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/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 529 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay).get(); 531 } 532 return E; 533 } 534 535 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 536 // Check to see if we are dereferencing a null pointer. If so, 537 // and if not volatile-qualified, this is undefined behavior that the 538 // optimizer will delete, so warn about it. People sometimes try to use this 539 // to get a deterministic trap and are surprised by clang's behavior. This 540 // only handles the pattern "*null", which is a very syntactic check. 541 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 542 if (UO && UO->getOpcode() == UO_Deref && 543 UO->getSubExpr()->getType()->isPointerType()) { 544 const LangAS AS = 545 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 546 if ((!isTargetAddressSpace(AS) || 547 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 548 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 549 S.Context, Expr::NPC_ValueDependentIsNotNull) && 550 !UO->getType().isVolatileQualified()) { 551 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 552 S.PDiag(diag::warn_indirection_through_null) 553 << UO->getSubExpr()->getSourceRange()); 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::note_indirection_through_null)); 556 } 557 } 558 } 559 560 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 561 SourceLocation AssignLoc, 562 const Expr* RHS) { 563 const ObjCIvarDecl *IV = OIRE->getDecl(); 564 if (!IV) 565 return; 566 567 DeclarationName MemberName = IV->getDeclName(); 568 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 569 if (!Member || !Member->isStr("isa")) 570 return; 571 572 const Expr *Base = OIRE->getBase(); 573 QualType BaseType = Base->getType(); 574 if (OIRE->isArrow()) 575 BaseType = BaseType->getPointeeType(); 576 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 577 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 578 ObjCInterfaceDecl *ClassDeclared = nullptr; 579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 580 if (!ClassDeclared->getSuperClass() 581 && (*ClassDeclared->ivar_begin()) == IV) { 582 if (RHS) { 583 NamedDecl *ObjectSetClass = 584 S.LookupSingleName(S.TUScope, 585 &S.Context.Idents.get("object_setClass"), 586 SourceLocation(), S.LookupOrdinaryName); 587 if (ObjectSetClass) { 588 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 589 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 590 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 591 "object_setClass(") 592 << FixItHint::CreateReplacement( 593 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 594 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 595 } 596 else 597 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 598 } else { 599 NamedDecl *ObjectGetClass = 600 S.LookupSingleName(S.TUScope, 601 &S.Context.Idents.get("object_getClass"), 602 SourceLocation(), S.LookupOrdinaryName); 603 if (ObjectGetClass) 604 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 605 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 606 "object_getClass(") 607 << FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 611 } 612 S.Diag(IV->getLocation(), diag::note_ivar_decl); 613 } 614 } 615 } 616 617 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 618 // Handle any placeholder expressions which made it here. 619 if (E->getType()->isPlaceholderType()) { 620 ExprResult result = CheckPlaceholderExpr(E); 621 if (result.isInvalid()) return ExprError(); 622 E = result.get(); 623 } 624 625 // C++ [conv.lval]p1: 626 // A glvalue of a non-function, non-array type T can be 627 // converted to a prvalue. 628 if (!E->isGLValue()) return E; 629 630 QualType T = E->getType(); 631 assert(!T.isNull() && "r-value conversion on typeless expression?"); 632 633 // lvalue-to-rvalue conversion cannot be applied to function or array types. 634 if (T->isFunctionType() || T->isArrayType()) 635 return E; 636 637 // We don't want to throw lvalue-to-rvalue casts on top of 638 // expressions of certain types in C++. 639 if (getLangOpts().CPlusPlus && 640 (E->getType() == Context.OverloadTy || 641 T->isDependentType() || 642 T->isRecordType())) 643 return E; 644 645 // The C standard is actually really unclear on this point, and 646 // DR106 tells us what the result should be but not why. It's 647 // generally best to say that void types just doesn't undergo 648 // lvalue-to-rvalue at all. Note that expressions of unqualified 649 // 'void' type are never l-values, but qualified void can be. 650 if (T->isVoidType()) 651 return E; 652 653 // OpenCL usually rejects direct accesses to values of 'half' type. 654 if (getLangOpts().OpenCL && 655 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 656 T->isHalfType()) { 657 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 658 << 0 << T; 659 return ExprError(); 660 } 661 662 CheckForNullPointerDereference(*this, E); 663 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 664 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 665 &Context.Idents.get("object_getClass"), 666 SourceLocation(), LookupOrdinaryName); 667 if (ObjectGetClass) 668 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 669 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 670 << FixItHint::CreateReplacement( 671 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 672 else 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 674 } 675 else if (const ObjCIvarRefExpr *OIRE = 676 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 677 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 678 679 // C++ [conv.lval]p1: 680 // [...] If T is a non-class type, the type of the prvalue is the 681 // cv-unqualified version of T. Otherwise, the type of the 682 // rvalue is T. 683 // 684 // C99 6.3.2.1p2: 685 // If the lvalue has qualified type, the value has the unqualified 686 // version of the type of the lvalue; otherwise, the value has the 687 // type of the lvalue. 688 if (T.hasQualifiers()) 689 T = T.getUnqualifiedType(); 690 691 // Under the MS ABI, lock down the inheritance model now. 692 if (T->isMemberPointerType() && 693 Context.getTargetInfo().getCXXABI().isMicrosoft()) 694 (void)isCompleteType(E->getExprLoc(), T); 695 696 ExprResult Res = CheckLValueToRValueConversionOperand(E); 697 if (Res.isInvalid()) 698 return Res; 699 E = Res.get(); 700 701 // Loading a __weak object implicitly retains the value, so we need a cleanup to 702 // balance that. 703 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 704 Cleanup.setExprNeedsCleanups(true); 705 706 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 707 Cleanup.setExprNeedsCleanups(true); 708 709 // C++ [conv.lval]p3: 710 // If T is cv std::nullptr_t, the result is a null pointer constant. 711 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 712 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 713 CurFPFeatureOverrides()); 714 715 // C11 6.3.2.1p2: 716 // ... if the lvalue has atomic type, the value has the non-atomic version 717 // of the type of the lvalue ... 718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 719 T = Atomic->getValueType().getUnqualifiedType(); 720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 721 nullptr, VK_PRValue, FPOptionsOverride()); 722 } 723 724 return Res; 725 } 726 727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 729 if (Res.isInvalid()) 730 return ExprError(); 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res; 735 } 736 737 /// CallExprUnaryConversions - a special case of an unary conversion 738 /// performed on a function designator of a call expression. 739 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 740 QualType Ty = E->getType(); 741 ExprResult Res = E; 742 // Only do implicit cast for a function type, but not for a pointer 743 // to function type. 744 if (Ty->isFunctionType()) { 745 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 746 CK_FunctionToPointerDecay); 747 if (Res.isInvalid()) 748 return ExprError(); 749 } 750 Res = DefaultLvalueConversion(Res.get()); 751 if (Res.isInvalid()) 752 return ExprError(); 753 return Res.get(); 754 } 755 756 /// UsualUnaryConversions - Performs various conversions that are common to most 757 /// operators (C99 6.3). The conversions of array and function types are 758 /// sometimes suppressed. For example, the array->pointer conversion doesn't 759 /// apply if the array is an argument to the sizeof or address (&) operators. 760 /// In these instances, this routine should *not* be called. 761 ExprResult Sema::UsualUnaryConversions(Expr *E) { 762 // First, convert to an r-value. 763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 764 if (Res.isInvalid()) 765 return ExprError(); 766 E = Res.get(); 767 768 QualType Ty = E->getType(); 769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 770 771 // Half FP have to be promoted to float unless it is natively supported 772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 774 775 // Try to perform integral promotions if the object has a theoretically 776 // promotable type. 777 if (Ty->isIntegralOrUnscopedEnumerationType()) { 778 // C99 6.3.1.1p2: 779 // 780 // The following may be used in an expression wherever an int or 781 // unsigned int may be used: 782 // - an object or expression with an integer type whose integer 783 // conversion rank is less than or equal to the rank of int 784 // and unsigned int. 785 // - A bit-field of type _Bool, int, signed int, or unsigned int. 786 // 787 // If an int can represent all values of the original type, the 788 // value is converted to an int; otherwise, it is converted to an 789 // unsigned int. These are called the integer promotions. All 790 // other types are unchanged by the integer promotions. 791 792 QualType PTy = Context.isPromotableBitField(E); 793 if (!PTy.isNull()) { 794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 795 return E; 796 } 797 if (Ty->isPromotableIntegerType()) { 798 QualType PT = Context.getPromotedIntegerType(Ty); 799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 800 return E; 801 } 802 } 803 return E; 804 } 805 806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 807 /// do not have a prototype. Arguments that have type float or __fp16 808 /// are promoted to double. All other argument types are converted by 809 /// UsualUnaryConversions(). 810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 811 QualType Ty = E->getType(); 812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 813 814 ExprResult Res = UsualUnaryConversions(E); 815 if (Res.isInvalid()) 816 return ExprError(); 817 E = Res.get(); 818 819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 820 // promote to double. 821 // Note that default argument promotion applies only to float (and 822 // half/fp16); it does not apply to _Float16. 823 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 824 if (BTy && (BTy->getKind() == BuiltinType::Half || 825 BTy->getKind() == BuiltinType::Float)) { 826 if (getLangOpts().OpenCL && 827 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 828 if (BTy->getKind() == BuiltinType::Half) { 829 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 830 } 831 } else { 832 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 833 } 834 } 835 if (BTy && 836 getLangOpts().getExtendIntArgs() == 837 LangOptions::ExtendArgsKind::ExtendTo64 && 838 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 839 Context.getTypeSizeInChars(BTy) < 840 Context.getTypeSizeInChars(Context.LongLongTy)) { 841 E = (Ty->isUnsignedIntegerType()) 842 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 843 .get() 844 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 845 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 846 "Unexpected typesize for LongLongTy"); 847 } 848 849 // C++ performs lvalue-to-rvalue conversion as a default argument 850 // promotion, even on class types, but note: 851 // C++11 [conv.lval]p2: 852 // When an lvalue-to-rvalue conversion occurs in an unevaluated 853 // operand or a subexpression thereof the value contained in the 854 // referenced object is not accessed. Otherwise, if the glvalue 855 // has a class type, the conversion copy-initializes a temporary 856 // of type T from the glvalue and the result of the conversion 857 // is a prvalue for the temporary. 858 // FIXME: add some way to gate this entire thing for correctness in 859 // potentially potentially evaluated contexts. 860 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 861 ExprResult Temp = PerformCopyInitialization( 862 InitializedEntity::InitializeTemporary(E->getType()), 863 E->getExprLoc(), E); 864 if (Temp.isInvalid()) 865 return ExprError(); 866 E = Temp.get(); 867 } 868 869 return E; 870 } 871 872 /// Determine the degree of POD-ness for an expression. 873 /// Incomplete types are considered POD, since this check can be performed 874 /// when we're in an unevaluated context. 875 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 876 if (Ty->isIncompleteType()) { 877 // C++11 [expr.call]p7: 878 // After these conversions, if the argument does not have arithmetic, 879 // enumeration, pointer, pointer to member, or class type, the program 880 // is ill-formed. 881 // 882 // Since we've already performed array-to-pointer and function-to-pointer 883 // decay, the only such type in C++ is cv void. This also handles 884 // initializer lists as variadic arguments. 885 if (Ty->isVoidType()) 886 return VAK_Invalid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 return VAK_Valid; 891 } 892 893 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 894 return VAK_Invalid; 895 896 if (Ty.isCXX98PODType(Context)) 897 return VAK_Valid; 898 899 // C++11 [expr.call]p7: 900 // Passing a potentially-evaluated argument of class type (Clause 9) 901 // having a non-trivial copy constructor, a non-trivial move constructor, 902 // or a non-trivial destructor, with no corresponding parameter, 903 // is conditionally-supported with implementation-defined semantics. 904 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 905 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 906 if (!Record->hasNonTrivialCopyConstructor() && 907 !Record->hasNonTrivialMoveConstructor() && 908 !Record->hasNonTrivialDestructor()) 909 return VAK_ValidInCXX11; 910 911 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 912 return VAK_Valid; 913 914 if (Ty->isObjCObjectType()) 915 return VAK_Invalid; 916 917 if (getLangOpts().MSVCCompat) 918 return VAK_MSVCUndefined; 919 920 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 921 // permitted to reject them. We should consider doing so. 922 return VAK_Undefined; 923 } 924 925 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 926 // Don't allow one to pass an Objective-C interface to a vararg. 927 const QualType &Ty = E->getType(); 928 VarArgKind VAK = isValidVarArgType(Ty); 929 930 // Complain about passing non-POD types through varargs. 931 switch (VAK) { 932 case VAK_ValidInCXX11: 933 DiagRuntimeBehavior( 934 E->getBeginLoc(), nullptr, 935 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 936 LLVM_FALLTHROUGH; 937 case VAK_Valid: 938 if (Ty->isRecordType()) { 939 // This is unlikely to be what the user intended. If the class has a 940 // 'c_str' member function, the user probably meant to call that. 941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 942 PDiag(diag::warn_pass_class_arg_to_vararg) 943 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 944 } 945 break; 946 947 case VAK_Undefined: 948 case VAK_MSVCUndefined: 949 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 950 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 951 << getLangOpts().CPlusPlus11 << Ty << CT); 952 break; 953 954 case VAK_Invalid: 955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 956 Diag(E->getBeginLoc(), 957 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 958 << Ty << CT; 959 else if (Ty->isObjCObjectType()) 960 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 961 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 962 << Ty << CT); 963 else 964 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 965 << isa<InitListExpr>(E) << Ty << CT; 966 break; 967 } 968 } 969 970 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 971 /// will create a trap if the resulting type is not a POD type. 972 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 973 FunctionDecl *FDecl) { 974 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 975 // Strip the unbridged-cast placeholder expression off, if applicable. 976 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 977 (CT == VariadicMethod || 978 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 979 E = stripARCUnbridgedCast(E); 980 981 // Otherwise, do normal placeholder checking. 982 } else { 983 ExprResult ExprRes = CheckPlaceholderExpr(E); 984 if (ExprRes.isInvalid()) 985 return ExprError(); 986 E = ExprRes.get(); 987 } 988 } 989 990 ExprResult ExprRes = DefaultArgumentPromotion(E); 991 if (ExprRes.isInvalid()) 992 return ExprError(); 993 994 // Copy blocks to the heap. 995 if (ExprRes.get()->getType()->isBlockPointerType()) 996 maybeExtendBlockObject(ExprRes); 997 998 E = ExprRes.get(); 999 1000 // Diagnostics regarding non-POD argument types are 1001 // emitted along with format string checking in Sema::CheckFunctionCall(). 1002 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1003 // Turn this into a trap. 1004 CXXScopeSpec SS; 1005 SourceLocation TemplateKWLoc; 1006 UnqualifiedId Name; 1007 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1008 E->getBeginLoc()); 1009 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1010 /*HasTrailingLParen=*/true, 1011 /*IsAddressOfOperand=*/false); 1012 if (TrapFn.isInvalid()) 1013 return ExprError(); 1014 1015 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1016 None, E->getEndLoc()); 1017 if (Call.isInvalid()) 1018 return ExprError(); 1019 1020 ExprResult Comma = 1021 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1022 if (Comma.isInvalid()) 1023 return ExprError(); 1024 return Comma.get(); 1025 } 1026 1027 if (!getLangOpts().CPlusPlus && 1028 RequireCompleteType(E->getExprLoc(), E->getType(), 1029 diag::err_call_incomplete_argument)) 1030 return ExprError(); 1031 1032 return E; 1033 } 1034 1035 /// Converts an integer to complex float type. Helper function of 1036 /// UsualArithmeticConversions() 1037 /// 1038 /// \return false if the integer expression is an integer type and is 1039 /// successfully converted to the complex type. 1040 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1041 ExprResult &ComplexExpr, 1042 QualType IntTy, 1043 QualType ComplexTy, 1044 bool SkipCast) { 1045 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1046 if (SkipCast) return false; 1047 if (IntTy->isIntegerType()) { 1048 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1049 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1050 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1051 CK_FloatingRealToComplex); 1052 } else { 1053 assert(IntTy->isComplexIntegerType()); 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1055 CK_IntegralComplexToFloatingComplex); 1056 } 1057 return false; 1058 } 1059 1060 /// Handle arithmetic conversion with complex types. Helper function of 1061 /// UsualArithmeticConversions() 1062 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1063 ExprResult &RHS, QualType LHSType, 1064 QualType RHSType, 1065 bool IsCompAssign) { 1066 // if we have an integer operand, the result is the complex type. 1067 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1068 /*skipCast*/false)) 1069 return LHSType; 1070 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1071 /*skipCast*/IsCompAssign)) 1072 return RHSType; 1073 1074 // This handles complex/complex, complex/float, or float/complex. 1075 // When both operands are complex, the shorter operand is converted to the 1076 // type of the longer, and that is the type of the result. This corresponds 1077 // to what is done when combining two real floating-point operands. 1078 // The fun begins when size promotion occur across type domains. 1079 // From H&S 6.3.4: When one operand is complex and the other is a real 1080 // floating-point type, the less precise type is converted, within it's 1081 // real or complex domain, to the precision of the other type. For example, 1082 // when combining a "long double" with a "double _Complex", the 1083 // "double _Complex" is promoted to "long double _Complex". 1084 1085 // Compute the rank of the two types, regardless of whether they are complex. 1086 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1087 1088 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1089 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1090 QualType LHSElementType = 1091 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1092 QualType RHSElementType = 1093 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1094 1095 QualType ResultType = S.Context.getComplexType(LHSElementType); 1096 if (Order < 0) { 1097 // Promote the precision of the LHS if not an assignment. 1098 ResultType = S.Context.getComplexType(RHSElementType); 1099 if (!IsCompAssign) { 1100 if (LHSComplexType) 1101 LHS = 1102 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1103 else 1104 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1105 } 1106 } else if (Order > 0) { 1107 // Promote the precision of the RHS. 1108 if (RHSComplexType) 1109 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1110 else 1111 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1112 } 1113 return ResultType; 1114 } 1115 1116 /// Handle arithmetic conversion from integer to float. Helper function 1117 /// of UsualArithmeticConversions() 1118 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1119 ExprResult &IntExpr, 1120 QualType FloatTy, QualType IntTy, 1121 bool ConvertFloat, bool ConvertInt) { 1122 if (IntTy->isIntegerType()) { 1123 if (ConvertInt) 1124 // Convert intExpr to the lhs floating point type. 1125 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1126 CK_IntegralToFloating); 1127 return FloatTy; 1128 } 1129 1130 // Convert both sides to the appropriate complex float. 1131 assert(IntTy->isComplexIntegerType()); 1132 QualType result = S.Context.getComplexType(FloatTy); 1133 1134 // _Complex int -> _Complex float 1135 if (ConvertInt) 1136 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1137 CK_IntegralComplexToFloatingComplex); 1138 1139 // float -> _Complex float 1140 if (ConvertFloat) 1141 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1142 CK_FloatingRealToComplex); 1143 1144 return result; 1145 } 1146 1147 /// Handle arithmethic conversion with floating point types. Helper 1148 /// function of UsualArithmeticConversions() 1149 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1150 ExprResult &RHS, QualType LHSType, 1151 QualType RHSType, bool IsCompAssign) { 1152 bool LHSFloat = LHSType->isRealFloatingType(); 1153 bool RHSFloat = RHSType->isRealFloatingType(); 1154 1155 // N1169 4.1.4: If one of the operands has a floating type and the other 1156 // operand has a fixed-point type, the fixed-point operand 1157 // is converted to the floating type [...] 1158 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1159 if (LHSFloat) 1160 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1161 else if (!IsCompAssign) 1162 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1163 return LHSFloat ? LHSType : RHSType; 1164 } 1165 1166 // If we have two real floating types, convert the smaller operand 1167 // to the bigger result. 1168 if (LHSFloat && RHSFloat) { 1169 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1170 if (order > 0) { 1171 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1172 return LHSType; 1173 } 1174 1175 assert(order < 0 && "illegal float comparison"); 1176 if (!IsCompAssign) 1177 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1178 return RHSType; 1179 } 1180 1181 if (LHSFloat) { 1182 // Half FP has to be promoted to float unless it is natively supported 1183 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1184 LHSType = S.Context.FloatTy; 1185 1186 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1187 /*ConvertFloat=*/!IsCompAssign, 1188 /*ConvertInt=*/ true); 1189 } 1190 assert(RHSFloat); 1191 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1192 /*ConvertFloat=*/ true, 1193 /*ConvertInt=*/!IsCompAssign); 1194 } 1195 1196 /// Diagnose attempts to convert between __float128 and long double if 1197 /// there is no support for such conversion. Helper function of 1198 /// UsualArithmeticConversions(). 1199 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1200 QualType RHSType) { 1201 /* No issue converting if at least one of the types is not a floating point 1202 type or the two types have the same rank. 1203 */ 1204 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1205 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1206 return false; 1207 1208 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1209 "The remaining types must be floating point types."); 1210 1211 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1212 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1213 1214 QualType LHSElemType = LHSComplex ? 1215 LHSComplex->getElementType() : LHSType; 1216 QualType RHSElemType = RHSComplex ? 1217 RHSComplex->getElementType() : RHSType; 1218 1219 // No issue if the two types have the same representation 1220 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1221 &S.Context.getFloatTypeSemantics(RHSElemType)) 1222 return false; 1223 1224 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1225 RHSElemType == S.Context.LongDoubleTy); 1226 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1227 RHSElemType == S.Context.Float128Ty); 1228 1229 // We've handled the situation where __float128 and long double have the same 1230 // representation. We allow all conversions for all possible long double types 1231 // except PPC's double double. 1232 return Float128AndLongDouble && 1233 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1234 &llvm::APFloat::PPCDoubleDouble()); 1235 } 1236 1237 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1238 1239 namespace { 1240 /// These helper callbacks are placed in an anonymous namespace to 1241 /// permit their use as function template parameters. 1242 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1243 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1244 } 1245 1246 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1247 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1248 CK_IntegralComplexCast); 1249 } 1250 } 1251 1252 /// Handle integer arithmetic conversions. Helper function of 1253 /// UsualArithmeticConversions() 1254 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1255 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1256 ExprResult &RHS, QualType LHSType, 1257 QualType RHSType, bool IsCompAssign) { 1258 // The rules for this case are in C99 6.3.1.8 1259 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1260 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1261 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1262 if (LHSSigned == RHSSigned) { 1263 // Same signedness; use the higher-ranked type 1264 if (order >= 0) { 1265 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1266 return LHSType; 1267 } else if (!IsCompAssign) 1268 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1269 return RHSType; 1270 } else if (order != (LHSSigned ? 1 : -1)) { 1271 // The unsigned type has greater than or equal rank to the 1272 // signed type, so use the unsigned type 1273 if (RHSSigned) { 1274 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1275 return LHSType; 1276 } else if (!IsCompAssign) 1277 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1278 return RHSType; 1279 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1280 // The two types are different widths; if we are here, that 1281 // means the signed type is larger than the unsigned type, so 1282 // use the signed type. 1283 if (LHSSigned) { 1284 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1285 return LHSType; 1286 } else if (!IsCompAssign) 1287 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1288 return RHSType; 1289 } else { 1290 // The signed type is higher-ranked than the unsigned type, 1291 // but isn't actually any bigger (like unsigned int and long 1292 // on most 32-bit systems). Use the unsigned type corresponding 1293 // to the signed type. 1294 QualType result = 1295 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1296 RHS = (*doRHSCast)(S, RHS.get(), result); 1297 if (!IsCompAssign) 1298 LHS = (*doLHSCast)(S, LHS.get(), result); 1299 return result; 1300 } 1301 } 1302 1303 /// Handle conversions with GCC complex int extension. Helper function 1304 /// of UsualArithmeticConversions() 1305 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1306 ExprResult &RHS, QualType LHSType, 1307 QualType RHSType, 1308 bool IsCompAssign) { 1309 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1310 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1311 1312 if (LHSComplexInt && RHSComplexInt) { 1313 QualType LHSEltType = LHSComplexInt->getElementType(); 1314 QualType RHSEltType = RHSComplexInt->getElementType(); 1315 QualType ScalarType = 1316 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1317 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1318 1319 return S.Context.getComplexType(ScalarType); 1320 } 1321 1322 if (LHSComplexInt) { 1323 QualType LHSEltType = LHSComplexInt->getElementType(); 1324 QualType ScalarType = 1325 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1326 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1327 QualType ComplexType = S.Context.getComplexType(ScalarType); 1328 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1329 CK_IntegralRealToComplex); 1330 1331 return ComplexType; 1332 } 1333 1334 assert(RHSComplexInt); 1335 1336 QualType RHSEltType = RHSComplexInt->getElementType(); 1337 QualType ScalarType = 1338 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1339 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1340 QualType ComplexType = S.Context.getComplexType(ScalarType); 1341 1342 if (!IsCompAssign) 1343 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1344 CK_IntegralRealToComplex); 1345 return ComplexType; 1346 } 1347 1348 /// Return the rank of a given fixed point or integer type. The value itself 1349 /// doesn't matter, but the values must be increasing with proper increasing 1350 /// rank as described in N1169 4.1.1. 1351 static unsigned GetFixedPointRank(QualType Ty) { 1352 const auto *BTy = Ty->getAs<BuiltinType>(); 1353 assert(BTy && "Expected a builtin type."); 1354 1355 switch (BTy->getKind()) { 1356 case BuiltinType::ShortFract: 1357 case BuiltinType::UShortFract: 1358 case BuiltinType::SatShortFract: 1359 case BuiltinType::SatUShortFract: 1360 return 1; 1361 case BuiltinType::Fract: 1362 case BuiltinType::UFract: 1363 case BuiltinType::SatFract: 1364 case BuiltinType::SatUFract: 1365 return 2; 1366 case BuiltinType::LongFract: 1367 case BuiltinType::ULongFract: 1368 case BuiltinType::SatLongFract: 1369 case BuiltinType::SatULongFract: 1370 return 3; 1371 case BuiltinType::ShortAccum: 1372 case BuiltinType::UShortAccum: 1373 case BuiltinType::SatShortAccum: 1374 case BuiltinType::SatUShortAccum: 1375 return 4; 1376 case BuiltinType::Accum: 1377 case BuiltinType::UAccum: 1378 case BuiltinType::SatAccum: 1379 case BuiltinType::SatUAccum: 1380 return 5; 1381 case BuiltinType::LongAccum: 1382 case BuiltinType::ULongAccum: 1383 case BuiltinType::SatLongAccum: 1384 case BuiltinType::SatULongAccum: 1385 return 6; 1386 default: 1387 if (BTy->isInteger()) 1388 return 0; 1389 llvm_unreachable("Unexpected fixed point or integer type"); 1390 } 1391 } 1392 1393 /// handleFixedPointConversion - Fixed point operations between fixed 1394 /// point types and integers or other fixed point types do not fall under 1395 /// usual arithmetic conversion since these conversions could result in loss 1396 /// of precsision (N1169 4.1.4). These operations should be calculated with 1397 /// the full precision of their result type (N1169 4.1.6.2.1). 1398 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1399 QualType RHSTy) { 1400 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1401 "Expected at least one of the operands to be a fixed point type"); 1402 assert((LHSTy->isFixedPointOrIntegerType() || 1403 RHSTy->isFixedPointOrIntegerType()) && 1404 "Special fixed point arithmetic operation conversions are only " 1405 "applied to ints or other fixed point types"); 1406 1407 // If one operand has signed fixed-point type and the other operand has 1408 // unsigned fixed-point type, then the unsigned fixed-point operand is 1409 // converted to its corresponding signed fixed-point type and the resulting 1410 // type is the type of the converted operand. 1411 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1412 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1413 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1414 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1415 1416 // The result type is the type with the highest rank, whereby a fixed-point 1417 // conversion rank is always greater than an integer conversion rank; if the 1418 // type of either of the operands is a saturating fixedpoint type, the result 1419 // type shall be the saturating fixed-point type corresponding to the type 1420 // with the highest rank; the resulting value is converted (taking into 1421 // account rounding and overflow) to the precision of the resulting type. 1422 // Same ranks between signed and unsigned types are resolved earlier, so both 1423 // types are either signed or both unsigned at this point. 1424 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1425 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1426 1427 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1428 1429 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1430 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1431 1432 return ResultTy; 1433 } 1434 1435 /// Check that the usual arithmetic conversions can be performed on this pair of 1436 /// expressions that might be of enumeration type. 1437 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1438 SourceLocation Loc, 1439 Sema::ArithConvKind ACK) { 1440 // C++2a [expr.arith.conv]p1: 1441 // If one operand is of enumeration type and the other operand is of a 1442 // different enumeration type or a floating-point type, this behavior is 1443 // deprecated ([depr.arith.conv.enum]). 1444 // 1445 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1446 // Eventually we will presumably reject these cases (in C++23 onwards?). 1447 QualType L = LHS->getType(), R = RHS->getType(); 1448 bool LEnum = L->isUnscopedEnumerationType(), 1449 REnum = R->isUnscopedEnumerationType(); 1450 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1451 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1452 (REnum && L->isFloatingType())) { 1453 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1454 ? diag::warn_arith_conv_enum_float_cxx20 1455 : diag::warn_arith_conv_enum_float) 1456 << LHS->getSourceRange() << RHS->getSourceRange() 1457 << (int)ACK << LEnum << L << R; 1458 } else if (!IsCompAssign && LEnum && REnum && 1459 !S.Context.hasSameUnqualifiedType(L, R)) { 1460 unsigned DiagID; 1461 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1462 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1463 // If either enumeration type is unnamed, it's less likely that the 1464 // user cares about this, but this situation is still deprecated in 1465 // C++2a. Use a different warning group. 1466 DiagID = S.getLangOpts().CPlusPlus20 1467 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1468 : diag::warn_arith_conv_mixed_anon_enum_types; 1469 } else if (ACK == Sema::ACK_Conditional) { 1470 // Conditional expressions are separated out because they have 1471 // historically had a different warning flag. 1472 DiagID = S.getLangOpts().CPlusPlus20 1473 ? diag::warn_conditional_mixed_enum_types_cxx20 1474 : diag::warn_conditional_mixed_enum_types; 1475 } else if (ACK == Sema::ACK_Comparison) { 1476 // Comparison expressions are separated out because they have 1477 // historically had a different warning flag. 1478 DiagID = S.getLangOpts().CPlusPlus20 1479 ? diag::warn_comparison_mixed_enum_types_cxx20 1480 : diag::warn_comparison_mixed_enum_types; 1481 } else { 1482 DiagID = S.getLangOpts().CPlusPlus20 1483 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1484 : diag::warn_arith_conv_mixed_enum_types; 1485 } 1486 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1487 << (int)ACK << L << R; 1488 } 1489 } 1490 1491 /// UsualArithmeticConversions - Performs various conversions that are common to 1492 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1493 /// routine returns the first non-arithmetic type found. The client is 1494 /// responsible for emitting appropriate error diagnostics. 1495 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1496 SourceLocation Loc, 1497 ArithConvKind ACK) { 1498 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1499 1500 if (ACK != ACK_CompAssign) { 1501 LHS = UsualUnaryConversions(LHS.get()); 1502 if (LHS.isInvalid()) 1503 return QualType(); 1504 } 1505 1506 RHS = UsualUnaryConversions(RHS.get()); 1507 if (RHS.isInvalid()) 1508 return QualType(); 1509 1510 // For conversion purposes, we ignore any qualifiers. 1511 // For example, "const float" and "float" are equivalent. 1512 QualType LHSType = 1513 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1514 QualType RHSType = 1515 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1516 1517 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1518 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1519 LHSType = AtomicLHS->getValueType(); 1520 1521 // If both types are identical, no conversion is needed. 1522 if (LHSType == RHSType) 1523 return LHSType; 1524 1525 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1526 // The caller can deal with this (e.g. pointer + int). 1527 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1528 return QualType(); 1529 1530 // Apply unary and bitfield promotions to the LHS's type. 1531 QualType LHSUnpromotedType = LHSType; 1532 if (LHSType->isPromotableIntegerType()) 1533 LHSType = Context.getPromotedIntegerType(LHSType); 1534 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1535 if (!LHSBitfieldPromoteTy.isNull()) 1536 LHSType = LHSBitfieldPromoteTy; 1537 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1538 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1539 1540 // If both types are identical, no conversion is needed. 1541 if (LHSType == RHSType) 1542 return LHSType; 1543 1544 // ExtInt types aren't subject to conversions between them or normal integers, 1545 // so this fails. 1546 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1547 return QualType(); 1548 1549 // At this point, we have two different arithmetic types. 1550 1551 // Diagnose attempts to convert between __float128 and long double where 1552 // such conversions currently can't be handled. 1553 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1554 return QualType(); 1555 1556 // Handle complex types first (C99 6.3.1.8p1). 1557 if (LHSType->isComplexType() || RHSType->isComplexType()) 1558 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1559 ACK == ACK_CompAssign); 1560 1561 // Now handle "real" floating types (i.e. float, double, long double). 1562 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1563 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1564 ACK == ACK_CompAssign); 1565 1566 // Handle GCC complex int extension. 1567 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1568 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1569 ACK == ACK_CompAssign); 1570 1571 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1572 return handleFixedPointConversion(*this, LHSType, RHSType); 1573 1574 // Finally, we have two differing integer types. 1575 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1576 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1577 } 1578 1579 //===----------------------------------------------------------------------===// 1580 // Semantic Analysis for various Expression Types 1581 //===----------------------------------------------------------------------===// 1582 1583 1584 ExprResult 1585 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1586 SourceLocation DefaultLoc, 1587 SourceLocation RParenLoc, 1588 Expr *ControllingExpr, 1589 ArrayRef<ParsedType> ArgTypes, 1590 ArrayRef<Expr *> ArgExprs) { 1591 unsigned NumAssocs = ArgTypes.size(); 1592 assert(NumAssocs == ArgExprs.size()); 1593 1594 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1595 for (unsigned i = 0; i < NumAssocs; ++i) { 1596 if (ArgTypes[i]) 1597 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1598 else 1599 Types[i] = nullptr; 1600 } 1601 1602 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1603 ControllingExpr, 1604 llvm::makeArrayRef(Types, NumAssocs), 1605 ArgExprs); 1606 delete [] Types; 1607 return ER; 1608 } 1609 1610 ExprResult 1611 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1612 SourceLocation DefaultLoc, 1613 SourceLocation RParenLoc, 1614 Expr *ControllingExpr, 1615 ArrayRef<TypeSourceInfo *> Types, 1616 ArrayRef<Expr *> Exprs) { 1617 unsigned NumAssocs = Types.size(); 1618 assert(NumAssocs == Exprs.size()); 1619 1620 // Decay and strip qualifiers for the controlling expression type, and handle 1621 // placeholder type replacement. See committee discussion from WG14 DR423. 1622 { 1623 EnterExpressionEvaluationContext Unevaluated( 1624 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1625 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1626 if (R.isInvalid()) 1627 return ExprError(); 1628 ControllingExpr = R.get(); 1629 } 1630 1631 // The controlling expression is an unevaluated operand, so side effects are 1632 // likely unintended. 1633 if (!inTemplateInstantiation() && 1634 ControllingExpr->HasSideEffects(Context, false)) 1635 Diag(ControllingExpr->getExprLoc(), 1636 diag::warn_side_effects_unevaluated_context); 1637 1638 bool TypeErrorFound = false, 1639 IsResultDependent = ControllingExpr->isTypeDependent(), 1640 ContainsUnexpandedParameterPack 1641 = ControllingExpr->containsUnexpandedParameterPack(); 1642 1643 for (unsigned i = 0; i < NumAssocs; ++i) { 1644 if (Exprs[i]->containsUnexpandedParameterPack()) 1645 ContainsUnexpandedParameterPack = true; 1646 1647 if (Types[i]) { 1648 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1649 ContainsUnexpandedParameterPack = true; 1650 1651 if (Types[i]->getType()->isDependentType()) { 1652 IsResultDependent = true; 1653 } else { 1654 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1655 // complete object type other than a variably modified type." 1656 unsigned D = 0; 1657 if (Types[i]->getType()->isIncompleteType()) 1658 D = diag::err_assoc_type_incomplete; 1659 else if (!Types[i]->getType()->isObjectType()) 1660 D = diag::err_assoc_type_nonobject; 1661 else if (Types[i]->getType()->isVariablyModifiedType()) 1662 D = diag::err_assoc_type_variably_modified; 1663 1664 if (D != 0) { 1665 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1666 << Types[i]->getTypeLoc().getSourceRange() 1667 << Types[i]->getType(); 1668 TypeErrorFound = true; 1669 } 1670 1671 // C11 6.5.1.1p2 "No two generic associations in the same generic 1672 // selection shall specify compatible types." 1673 for (unsigned j = i+1; j < NumAssocs; ++j) 1674 if (Types[j] && !Types[j]->getType()->isDependentType() && 1675 Context.typesAreCompatible(Types[i]->getType(), 1676 Types[j]->getType())) { 1677 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1678 diag::err_assoc_compatible_types) 1679 << Types[j]->getTypeLoc().getSourceRange() 1680 << Types[j]->getType() 1681 << Types[i]->getType(); 1682 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1683 diag::note_compat_assoc) 1684 << Types[i]->getTypeLoc().getSourceRange() 1685 << Types[i]->getType(); 1686 TypeErrorFound = true; 1687 } 1688 } 1689 } 1690 } 1691 if (TypeErrorFound) 1692 return ExprError(); 1693 1694 // If we determined that the generic selection is result-dependent, don't 1695 // try to compute the result expression. 1696 if (IsResultDependent) 1697 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1698 Exprs, DefaultLoc, RParenLoc, 1699 ContainsUnexpandedParameterPack); 1700 1701 SmallVector<unsigned, 1> CompatIndices; 1702 unsigned DefaultIndex = -1U; 1703 for (unsigned i = 0; i < NumAssocs; ++i) { 1704 if (!Types[i]) 1705 DefaultIndex = i; 1706 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1707 Types[i]->getType())) 1708 CompatIndices.push_back(i); 1709 } 1710 1711 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1712 // type compatible with at most one of the types named in its generic 1713 // association list." 1714 if (CompatIndices.size() > 1) { 1715 // We strip parens here because the controlling expression is typically 1716 // parenthesized in macro definitions. 1717 ControllingExpr = ControllingExpr->IgnoreParens(); 1718 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1719 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1720 << (unsigned)CompatIndices.size(); 1721 for (unsigned I : CompatIndices) { 1722 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1723 diag::note_compat_assoc) 1724 << Types[I]->getTypeLoc().getSourceRange() 1725 << Types[I]->getType(); 1726 } 1727 return ExprError(); 1728 } 1729 1730 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1731 // its controlling expression shall have type compatible with exactly one of 1732 // the types named in its generic association list." 1733 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1734 // We strip parens here because the controlling expression is typically 1735 // parenthesized in macro definitions. 1736 ControllingExpr = ControllingExpr->IgnoreParens(); 1737 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1738 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1739 return ExprError(); 1740 } 1741 1742 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1743 // type name that is compatible with the type of the controlling expression, 1744 // then the result expression of the generic selection is the expression 1745 // in that generic association. Otherwise, the result expression of the 1746 // generic selection is the expression in the default generic association." 1747 unsigned ResultIndex = 1748 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1749 1750 return GenericSelectionExpr::Create( 1751 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1752 ContainsUnexpandedParameterPack, ResultIndex); 1753 } 1754 1755 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1756 /// location of the token and the offset of the ud-suffix within it. 1757 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1758 unsigned Offset) { 1759 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1760 S.getLangOpts()); 1761 } 1762 1763 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1764 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1765 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1766 IdentifierInfo *UDSuffix, 1767 SourceLocation UDSuffixLoc, 1768 ArrayRef<Expr*> Args, 1769 SourceLocation LitEndLoc) { 1770 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1771 1772 QualType ArgTy[2]; 1773 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1774 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1775 if (ArgTy[ArgIdx]->isArrayType()) 1776 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1777 } 1778 1779 DeclarationName OpName = 1780 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1781 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1782 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1783 1784 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1785 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1786 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1787 /*AllowStringTemplatePack*/ false, 1788 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1789 return ExprError(); 1790 1791 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1792 } 1793 1794 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1795 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1796 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1797 /// multiple tokens. However, the common case is that StringToks points to one 1798 /// string. 1799 /// 1800 ExprResult 1801 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1802 assert(!StringToks.empty() && "Must have at least one string!"); 1803 1804 StringLiteralParser Literal(StringToks, PP); 1805 if (Literal.hadError) 1806 return ExprError(); 1807 1808 SmallVector<SourceLocation, 4> StringTokLocs; 1809 for (const Token &Tok : StringToks) 1810 StringTokLocs.push_back(Tok.getLocation()); 1811 1812 QualType CharTy = Context.CharTy; 1813 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1814 if (Literal.isWide()) { 1815 CharTy = Context.getWideCharType(); 1816 Kind = StringLiteral::Wide; 1817 } else if (Literal.isUTF8()) { 1818 if (getLangOpts().Char8) 1819 CharTy = Context.Char8Ty; 1820 Kind = StringLiteral::UTF8; 1821 } else if (Literal.isUTF16()) { 1822 CharTy = Context.Char16Ty; 1823 Kind = StringLiteral::UTF16; 1824 } else if (Literal.isUTF32()) { 1825 CharTy = Context.Char32Ty; 1826 Kind = StringLiteral::UTF32; 1827 } else if (Literal.isPascal()) { 1828 CharTy = Context.UnsignedCharTy; 1829 } 1830 1831 // Warn on initializing an array of char from a u8 string literal; this 1832 // becomes ill-formed in C++2a. 1833 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1834 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1835 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1836 1837 // Create removals for all 'u8' prefixes in the string literal(s). This 1838 // ensures C++2a compatibility (but may change the program behavior when 1839 // built by non-Clang compilers for which the execution character set is 1840 // not always UTF-8). 1841 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1842 SourceLocation RemovalDiagLoc; 1843 for (const Token &Tok : StringToks) { 1844 if (Tok.getKind() == tok::utf8_string_literal) { 1845 if (RemovalDiagLoc.isInvalid()) 1846 RemovalDiagLoc = Tok.getLocation(); 1847 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1848 Tok.getLocation(), 1849 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1850 getSourceManager(), getLangOpts()))); 1851 } 1852 } 1853 Diag(RemovalDiagLoc, RemovalDiag); 1854 } 1855 1856 QualType StrTy = 1857 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1858 1859 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1860 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1861 Kind, Literal.Pascal, StrTy, 1862 &StringTokLocs[0], 1863 StringTokLocs.size()); 1864 if (Literal.getUDSuffix().empty()) 1865 return Lit; 1866 1867 // We're building a user-defined literal. 1868 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1869 SourceLocation UDSuffixLoc = 1870 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1871 Literal.getUDSuffixOffset()); 1872 1873 // Make sure we're allowed user-defined literals here. 1874 if (!UDLScope) 1875 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1876 1877 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1878 // operator "" X (str, len) 1879 QualType SizeType = Context.getSizeType(); 1880 1881 DeclarationName OpName = 1882 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1883 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1884 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1885 1886 QualType ArgTy[] = { 1887 Context.getArrayDecayedType(StrTy), SizeType 1888 }; 1889 1890 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1891 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1892 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1893 /*AllowStringTemplatePack*/ true, 1894 /*DiagnoseMissing*/ true, Lit)) { 1895 1896 case LOLR_Cooked: { 1897 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1898 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1899 StringTokLocs[0]); 1900 Expr *Args[] = { Lit, LenArg }; 1901 1902 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1903 } 1904 1905 case LOLR_Template: { 1906 TemplateArgumentListInfo ExplicitArgs; 1907 TemplateArgument Arg(Lit); 1908 TemplateArgumentLocInfo ArgInfo(Lit); 1909 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1910 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1911 &ExplicitArgs); 1912 } 1913 1914 case LOLR_StringTemplatePack: { 1915 TemplateArgumentListInfo ExplicitArgs; 1916 1917 unsigned CharBits = Context.getIntWidth(CharTy); 1918 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1919 llvm::APSInt Value(CharBits, CharIsUnsigned); 1920 1921 TemplateArgument TypeArg(CharTy); 1922 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1923 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1924 1925 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1926 Value = Lit->getCodeUnit(I); 1927 TemplateArgument Arg(Context, Value, CharTy); 1928 TemplateArgumentLocInfo ArgInfo; 1929 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1930 } 1931 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1932 &ExplicitArgs); 1933 } 1934 case LOLR_Raw: 1935 case LOLR_ErrorNoDiagnostic: 1936 llvm_unreachable("unexpected literal operator lookup result"); 1937 case LOLR_Error: 1938 return ExprError(); 1939 } 1940 llvm_unreachable("unexpected literal operator lookup result"); 1941 } 1942 1943 DeclRefExpr * 1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1945 SourceLocation Loc, 1946 const CXXScopeSpec *SS) { 1947 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1948 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1949 } 1950 1951 DeclRefExpr * 1952 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1953 const DeclarationNameInfo &NameInfo, 1954 const CXXScopeSpec *SS, NamedDecl *FoundD, 1955 SourceLocation TemplateKWLoc, 1956 const TemplateArgumentListInfo *TemplateArgs) { 1957 NestedNameSpecifierLoc NNS = 1958 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1959 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1960 TemplateArgs); 1961 } 1962 1963 // CUDA/HIP: Check whether a captured reference variable is referencing a 1964 // host variable in a device or host device lambda. 1965 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1966 VarDecl *VD) { 1967 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1968 return false; 1969 assert(VD->getType()->isReferenceType()); 1970 1971 // Check whether the reference variable is referencing a host variable. 1972 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1973 if (!DRE) 1974 return false; 1975 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1976 if (!Referee || !Referee->hasGlobalStorage() || 1977 Referee->hasAttr<CUDADeviceAttr>()) 1978 return false; 1979 1980 // Check whether the current function is a device or host device lambda. 1981 // Check whether the reference variable is a capture by getDeclContext() 1982 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1983 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1984 if (MD && MD->getParent()->isLambda() && 1985 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1986 VD->getDeclContext() != MD) 1987 return true; 1988 1989 return false; 1990 } 1991 1992 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1993 // A declaration named in an unevaluated operand never constitutes an odr-use. 1994 if (isUnevaluatedContext()) 1995 return NOUR_Unevaluated; 1996 1997 // C++2a [basic.def.odr]p4: 1998 // A variable x whose name appears as a potentially-evaluated expression e 1999 // is odr-used by e unless [...] x is a reference that is usable in 2000 // constant expressions. 2001 // CUDA/HIP: 2002 // If a reference variable referencing a host variable is captured in a 2003 // device or host device lambda, the value of the referee must be copied 2004 // to the capture and the reference variable must be treated as odr-use 2005 // since the value of the referee is not known at compile time and must 2006 // be loaded from the captured. 2007 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2008 if (VD->getType()->isReferenceType() && 2009 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2010 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2011 VD->isUsableInConstantExpressions(Context)) 2012 return NOUR_Constant; 2013 } 2014 2015 // All remaining non-variable cases constitute an odr-use. For variables, we 2016 // need to wait and see how the expression is used. 2017 return NOUR_None; 2018 } 2019 2020 /// BuildDeclRefExpr - Build an expression that references a 2021 /// declaration that does not require a closure capture. 2022 DeclRefExpr * 2023 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2024 const DeclarationNameInfo &NameInfo, 2025 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2026 SourceLocation TemplateKWLoc, 2027 const TemplateArgumentListInfo *TemplateArgs) { 2028 bool RefersToCapturedVariable = 2029 isa<VarDecl>(D) && 2030 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2031 2032 DeclRefExpr *E = DeclRefExpr::Create( 2033 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2034 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2035 MarkDeclRefReferenced(E); 2036 2037 // C++ [except.spec]p17: 2038 // An exception-specification is considered to be needed when: 2039 // - in an expression, the function is the unique lookup result or 2040 // the selected member of a set of overloaded functions. 2041 // 2042 // We delay doing this until after we've built the function reference and 2043 // marked it as used so that: 2044 // a) if the function is defaulted, we get errors from defining it before / 2045 // instead of errors from computing its exception specification, and 2046 // b) if the function is a defaulted comparison, we can use the body we 2047 // build when defining it as input to the exception specification 2048 // computation rather than computing a new body. 2049 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2050 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2051 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2052 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2053 } 2054 } 2055 2056 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2057 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2058 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2059 getCurFunction()->recordUseOfWeak(E); 2060 2061 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2062 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2063 FD = IFD->getAnonField(); 2064 if (FD) { 2065 UnusedPrivateFields.remove(FD); 2066 // Just in case we're building an illegal pointer-to-member. 2067 if (FD->isBitField()) 2068 E->setObjectKind(OK_BitField); 2069 } 2070 2071 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2072 // designates a bit-field. 2073 if (auto *BD = dyn_cast<BindingDecl>(D)) 2074 if (auto *BE = BD->getBinding()) 2075 E->setObjectKind(BE->getObjectKind()); 2076 2077 return E; 2078 } 2079 2080 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2081 /// possibly a list of template arguments. 2082 /// 2083 /// If this produces template arguments, it is permitted to call 2084 /// DecomposeTemplateName. 2085 /// 2086 /// This actually loses a lot of source location information for 2087 /// non-standard name kinds; we should consider preserving that in 2088 /// some way. 2089 void 2090 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2091 TemplateArgumentListInfo &Buffer, 2092 DeclarationNameInfo &NameInfo, 2093 const TemplateArgumentListInfo *&TemplateArgs) { 2094 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2095 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2096 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2097 2098 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2099 Id.TemplateId->NumArgs); 2100 translateTemplateArguments(TemplateArgsPtr, Buffer); 2101 2102 TemplateName TName = Id.TemplateId->Template.get(); 2103 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2104 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2105 TemplateArgs = &Buffer; 2106 } else { 2107 NameInfo = GetNameFromUnqualifiedId(Id); 2108 TemplateArgs = nullptr; 2109 } 2110 } 2111 2112 static void emitEmptyLookupTypoDiagnostic( 2113 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2114 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2115 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2116 DeclContext *Ctx = 2117 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2118 if (!TC) { 2119 // Emit a special diagnostic for failed member lookups. 2120 // FIXME: computing the declaration context might fail here (?) 2121 if (Ctx) 2122 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2123 << SS.getRange(); 2124 else 2125 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2126 return; 2127 } 2128 2129 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2130 bool DroppedSpecifier = 2131 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2132 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2133 ? diag::note_implicit_param_decl 2134 : diag::note_previous_decl; 2135 if (!Ctx) 2136 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2137 SemaRef.PDiag(NoteID)); 2138 else 2139 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2140 << Typo << Ctx << DroppedSpecifier 2141 << SS.getRange(), 2142 SemaRef.PDiag(NoteID)); 2143 } 2144 2145 /// Diagnose a lookup that found results in an enclosing class during error 2146 /// recovery. This usually indicates that the results were found in a dependent 2147 /// base class that could not be searched as part of a template definition. 2148 /// Always issues a diagnostic (though this may be only a warning in MS 2149 /// compatibility mode). 2150 /// 2151 /// Return \c true if the error is unrecoverable, or \c false if the caller 2152 /// should attempt to recover using these lookup results. 2153 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2154 // During a default argument instantiation the CurContext points 2155 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2156 // function parameter list, hence add an explicit check. 2157 bool isDefaultArgument = 2158 !CodeSynthesisContexts.empty() && 2159 CodeSynthesisContexts.back().Kind == 2160 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2161 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2162 bool isInstance = CurMethod && CurMethod->isInstance() && 2163 R.getNamingClass() == CurMethod->getParent() && 2164 !isDefaultArgument; 2165 2166 // There are two ways we can find a class-scope declaration during template 2167 // instantiation that we did not find in the template definition: if it is a 2168 // member of a dependent base class, or if it is declared after the point of 2169 // use in the same class. Distinguish these by comparing the class in which 2170 // the member was found to the naming class of the lookup. 2171 unsigned DiagID = diag::err_found_in_dependent_base; 2172 unsigned NoteID = diag::note_member_declared_at; 2173 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2174 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2175 : diag::err_found_later_in_class; 2176 } else if (getLangOpts().MSVCCompat) { 2177 DiagID = diag::ext_found_in_dependent_base; 2178 NoteID = diag::note_dependent_member_use; 2179 } 2180 2181 if (isInstance) { 2182 // Give a code modification hint to insert 'this->'. 2183 Diag(R.getNameLoc(), DiagID) 2184 << R.getLookupName() 2185 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2186 CheckCXXThisCapture(R.getNameLoc()); 2187 } else { 2188 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2189 // they're not shadowed). 2190 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2191 } 2192 2193 for (NamedDecl *D : R) 2194 Diag(D->getLocation(), NoteID); 2195 2196 // Return true if we are inside a default argument instantiation 2197 // and the found name refers to an instance member function, otherwise 2198 // the caller will try to create an implicit member call and this is wrong 2199 // for default arguments. 2200 // 2201 // FIXME: Is this special case necessary? We could allow the caller to 2202 // diagnose this. 2203 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2204 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2205 return true; 2206 } 2207 2208 // Tell the callee to try to recover. 2209 return false; 2210 } 2211 2212 /// Diagnose an empty lookup. 2213 /// 2214 /// \return false if new lookup candidates were found 2215 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2216 CorrectionCandidateCallback &CCC, 2217 TemplateArgumentListInfo *ExplicitTemplateArgs, 2218 ArrayRef<Expr *> Args, TypoExpr **Out) { 2219 DeclarationName Name = R.getLookupName(); 2220 2221 unsigned diagnostic = diag::err_undeclared_var_use; 2222 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2223 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2224 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2225 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2226 diagnostic = diag::err_undeclared_use; 2227 diagnostic_suggest = diag::err_undeclared_use_suggest; 2228 } 2229 2230 // If the original lookup was an unqualified lookup, fake an 2231 // unqualified lookup. This is useful when (for example) the 2232 // original lookup would not have found something because it was a 2233 // dependent name. 2234 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2235 while (DC) { 2236 if (isa<CXXRecordDecl>(DC)) { 2237 LookupQualifiedName(R, DC); 2238 2239 if (!R.empty()) { 2240 // Don't give errors about ambiguities in this lookup. 2241 R.suppressDiagnostics(); 2242 2243 // If there's a best viable function among the results, only mention 2244 // that one in the notes. 2245 OverloadCandidateSet Candidates(R.getNameLoc(), 2246 OverloadCandidateSet::CSK_Normal); 2247 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2248 OverloadCandidateSet::iterator Best; 2249 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2250 OR_Success) { 2251 R.clear(); 2252 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2253 R.resolveKind(); 2254 } 2255 2256 return DiagnoseDependentMemberLookup(R); 2257 } 2258 2259 R.clear(); 2260 } 2261 2262 DC = DC->getLookupParent(); 2263 } 2264 2265 // We didn't find anything, so try to correct for a typo. 2266 TypoCorrection Corrected; 2267 if (S && Out) { 2268 SourceLocation TypoLoc = R.getNameLoc(); 2269 assert(!ExplicitTemplateArgs && 2270 "Diagnosing an empty lookup with explicit template args!"); 2271 *Out = CorrectTypoDelayed( 2272 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2273 [=](const TypoCorrection &TC) { 2274 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2275 diagnostic, diagnostic_suggest); 2276 }, 2277 nullptr, CTK_ErrorRecovery); 2278 if (*Out) 2279 return true; 2280 } else if (S && 2281 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2282 S, &SS, CCC, CTK_ErrorRecovery))) { 2283 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2284 bool DroppedSpecifier = 2285 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2286 R.setLookupName(Corrected.getCorrection()); 2287 2288 bool AcceptableWithRecovery = false; 2289 bool AcceptableWithoutRecovery = false; 2290 NamedDecl *ND = Corrected.getFoundDecl(); 2291 if (ND) { 2292 if (Corrected.isOverloaded()) { 2293 OverloadCandidateSet OCS(R.getNameLoc(), 2294 OverloadCandidateSet::CSK_Normal); 2295 OverloadCandidateSet::iterator Best; 2296 for (NamedDecl *CD : Corrected) { 2297 if (FunctionTemplateDecl *FTD = 2298 dyn_cast<FunctionTemplateDecl>(CD)) 2299 AddTemplateOverloadCandidate( 2300 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2301 Args, OCS); 2302 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2303 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2304 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2305 Args, OCS); 2306 } 2307 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2308 case OR_Success: 2309 ND = Best->FoundDecl; 2310 Corrected.setCorrectionDecl(ND); 2311 break; 2312 default: 2313 // FIXME: Arbitrarily pick the first declaration for the note. 2314 Corrected.setCorrectionDecl(ND); 2315 break; 2316 } 2317 } 2318 R.addDecl(ND); 2319 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2320 CXXRecordDecl *Record = nullptr; 2321 if (Corrected.getCorrectionSpecifier()) { 2322 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2323 Record = Ty->getAsCXXRecordDecl(); 2324 } 2325 if (!Record) 2326 Record = cast<CXXRecordDecl>( 2327 ND->getDeclContext()->getRedeclContext()); 2328 R.setNamingClass(Record); 2329 } 2330 2331 auto *UnderlyingND = ND->getUnderlyingDecl(); 2332 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2333 isa<FunctionTemplateDecl>(UnderlyingND); 2334 // FIXME: If we ended up with a typo for a type name or 2335 // Objective-C class name, we're in trouble because the parser 2336 // is in the wrong place to recover. Suggest the typo 2337 // correction, but don't make it a fix-it since we're not going 2338 // to recover well anyway. 2339 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2340 getAsTypeTemplateDecl(UnderlyingND) || 2341 isa<ObjCInterfaceDecl>(UnderlyingND); 2342 } else { 2343 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2344 // because we aren't able to recover. 2345 AcceptableWithoutRecovery = true; 2346 } 2347 2348 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2349 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2350 ? diag::note_implicit_param_decl 2351 : diag::note_previous_decl; 2352 if (SS.isEmpty()) 2353 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2354 PDiag(NoteID), AcceptableWithRecovery); 2355 else 2356 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2357 << Name << computeDeclContext(SS, false) 2358 << DroppedSpecifier << SS.getRange(), 2359 PDiag(NoteID), AcceptableWithRecovery); 2360 2361 // Tell the callee whether to try to recover. 2362 return !AcceptableWithRecovery; 2363 } 2364 } 2365 R.clear(); 2366 2367 // Emit a special diagnostic for failed member lookups. 2368 // FIXME: computing the declaration context might fail here (?) 2369 if (!SS.isEmpty()) { 2370 Diag(R.getNameLoc(), diag::err_no_member) 2371 << Name << computeDeclContext(SS, false) 2372 << SS.getRange(); 2373 return true; 2374 } 2375 2376 // Give up, we can't recover. 2377 Diag(R.getNameLoc(), diagnostic) << Name; 2378 return true; 2379 } 2380 2381 /// In Microsoft mode, if we are inside a template class whose parent class has 2382 /// dependent base classes, and we can't resolve an unqualified identifier, then 2383 /// assume the identifier is a member of a dependent base class. We can only 2384 /// recover successfully in static methods, instance methods, and other contexts 2385 /// where 'this' is available. This doesn't precisely match MSVC's 2386 /// instantiation model, but it's close enough. 2387 static Expr * 2388 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2389 DeclarationNameInfo &NameInfo, 2390 SourceLocation TemplateKWLoc, 2391 const TemplateArgumentListInfo *TemplateArgs) { 2392 // Only try to recover from lookup into dependent bases in static methods or 2393 // contexts where 'this' is available. 2394 QualType ThisType = S.getCurrentThisType(); 2395 const CXXRecordDecl *RD = nullptr; 2396 if (!ThisType.isNull()) 2397 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2398 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2399 RD = MD->getParent(); 2400 if (!RD || !RD->hasAnyDependentBases()) 2401 return nullptr; 2402 2403 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2404 // is available, suggest inserting 'this->' as a fixit. 2405 SourceLocation Loc = NameInfo.getLoc(); 2406 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2407 DB << NameInfo.getName() << RD; 2408 2409 if (!ThisType.isNull()) { 2410 DB << FixItHint::CreateInsertion(Loc, "this->"); 2411 return CXXDependentScopeMemberExpr::Create( 2412 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2413 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2414 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2415 } 2416 2417 // Synthesize a fake NNS that points to the derived class. This will 2418 // perform name lookup during template instantiation. 2419 CXXScopeSpec SS; 2420 auto *NNS = 2421 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2422 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2423 return DependentScopeDeclRefExpr::Create( 2424 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2425 TemplateArgs); 2426 } 2427 2428 ExprResult 2429 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2430 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2431 bool HasTrailingLParen, bool IsAddressOfOperand, 2432 CorrectionCandidateCallback *CCC, 2433 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2434 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2435 "cannot be direct & operand and have a trailing lparen"); 2436 if (SS.isInvalid()) 2437 return ExprError(); 2438 2439 TemplateArgumentListInfo TemplateArgsBuffer; 2440 2441 // Decompose the UnqualifiedId into the following data. 2442 DeclarationNameInfo NameInfo; 2443 const TemplateArgumentListInfo *TemplateArgs; 2444 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2445 2446 DeclarationName Name = NameInfo.getName(); 2447 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2448 SourceLocation NameLoc = NameInfo.getLoc(); 2449 2450 if (II && II->isEditorPlaceholder()) { 2451 // FIXME: When typed placeholders are supported we can create a typed 2452 // placeholder expression node. 2453 return ExprError(); 2454 } 2455 2456 // C++ [temp.dep.expr]p3: 2457 // An id-expression is type-dependent if it contains: 2458 // -- an identifier that was declared with a dependent type, 2459 // (note: handled after lookup) 2460 // -- a template-id that is dependent, 2461 // (note: handled in BuildTemplateIdExpr) 2462 // -- a conversion-function-id that specifies a dependent type, 2463 // -- a nested-name-specifier that contains a class-name that 2464 // names a dependent type. 2465 // Determine whether this is a member of an unknown specialization; 2466 // we need to handle these differently. 2467 bool DependentID = false; 2468 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2469 Name.getCXXNameType()->isDependentType()) { 2470 DependentID = true; 2471 } else if (SS.isSet()) { 2472 if (DeclContext *DC = computeDeclContext(SS, false)) { 2473 if (RequireCompleteDeclContext(SS, DC)) 2474 return ExprError(); 2475 } else { 2476 DependentID = true; 2477 } 2478 } 2479 2480 if (DependentID) 2481 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2482 IsAddressOfOperand, TemplateArgs); 2483 2484 // Perform the required lookup. 2485 LookupResult R(*this, NameInfo, 2486 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2487 ? LookupObjCImplicitSelfParam 2488 : LookupOrdinaryName); 2489 if (TemplateKWLoc.isValid() || TemplateArgs) { 2490 // Lookup the template name again to correctly establish the context in 2491 // which it was found. This is really unfortunate as we already did the 2492 // lookup to determine that it was a template name in the first place. If 2493 // this becomes a performance hit, we can work harder to preserve those 2494 // results until we get here but it's likely not worth it. 2495 bool MemberOfUnknownSpecialization; 2496 AssumedTemplateKind AssumedTemplate; 2497 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2498 MemberOfUnknownSpecialization, TemplateKWLoc, 2499 &AssumedTemplate)) 2500 return ExprError(); 2501 2502 if (MemberOfUnknownSpecialization || 2503 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2504 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2505 IsAddressOfOperand, TemplateArgs); 2506 } else { 2507 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2508 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2509 2510 // If the result might be in a dependent base class, this is a dependent 2511 // id-expression. 2512 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2513 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2514 IsAddressOfOperand, TemplateArgs); 2515 2516 // If this reference is in an Objective-C method, then we need to do 2517 // some special Objective-C lookup, too. 2518 if (IvarLookupFollowUp) { 2519 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2520 if (E.isInvalid()) 2521 return ExprError(); 2522 2523 if (Expr *Ex = E.getAs<Expr>()) 2524 return Ex; 2525 } 2526 } 2527 2528 if (R.isAmbiguous()) 2529 return ExprError(); 2530 2531 // This could be an implicitly declared function reference (legal in C90, 2532 // extension in C99, forbidden in C++). 2533 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2534 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2535 if (D) R.addDecl(D); 2536 } 2537 2538 // Determine whether this name might be a candidate for 2539 // argument-dependent lookup. 2540 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2541 2542 if (R.empty() && !ADL) { 2543 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2544 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2545 TemplateKWLoc, TemplateArgs)) 2546 return E; 2547 } 2548 2549 // Don't diagnose an empty lookup for inline assembly. 2550 if (IsInlineAsmIdentifier) 2551 return ExprError(); 2552 2553 // If this name wasn't predeclared and if this is not a function 2554 // call, diagnose the problem. 2555 TypoExpr *TE = nullptr; 2556 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2557 : nullptr); 2558 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2559 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2560 "Typo correction callback misconfigured"); 2561 if (CCC) { 2562 // Make sure the callback knows what the typo being diagnosed is. 2563 CCC->setTypoName(II); 2564 if (SS.isValid()) 2565 CCC->setTypoNNS(SS.getScopeRep()); 2566 } 2567 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2568 // a template name, but we happen to have always already looked up the name 2569 // before we get here if it must be a template name. 2570 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2571 None, &TE)) { 2572 if (TE && KeywordReplacement) { 2573 auto &State = getTypoExprState(TE); 2574 auto BestTC = State.Consumer->getNextCorrection(); 2575 if (BestTC.isKeyword()) { 2576 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2577 if (State.DiagHandler) 2578 State.DiagHandler(BestTC); 2579 KeywordReplacement->startToken(); 2580 KeywordReplacement->setKind(II->getTokenID()); 2581 KeywordReplacement->setIdentifierInfo(II); 2582 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2583 // Clean up the state associated with the TypoExpr, since it has 2584 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2585 clearDelayedTypo(TE); 2586 // Signal that a correction to a keyword was performed by returning a 2587 // valid-but-null ExprResult. 2588 return (Expr*)nullptr; 2589 } 2590 State.Consumer->resetCorrectionStream(); 2591 } 2592 return TE ? TE : ExprError(); 2593 } 2594 2595 assert(!R.empty() && 2596 "DiagnoseEmptyLookup returned false but added no results"); 2597 2598 // If we found an Objective-C instance variable, let 2599 // LookupInObjCMethod build the appropriate expression to 2600 // reference the ivar. 2601 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2602 R.clear(); 2603 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2604 // In a hopelessly buggy code, Objective-C instance variable 2605 // lookup fails and no expression will be built to reference it. 2606 if (!E.isInvalid() && !E.get()) 2607 return ExprError(); 2608 return E; 2609 } 2610 } 2611 2612 // This is guaranteed from this point on. 2613 assert(!R.empty() || ADL); 2614 2615 // Check whether this might be a C++ implicit instance member access. 2616 // C++ [class.mfct.non-static]p3: 2617 // When an id-expression that is not part of a class member access 2618 // syntax and not used to form a pointer to member is used in the 2619 // body of a non-static member function of class X, if name lookup 2620 // resolves the name in the id-expression to a non-static non-type 2621 // member of some class C, the id-expression is transformed into a 2622 // class member access expression using (*this) as the 2623 // postfix-expression to the left of the . operator. 2624 // 2625 // But we don't actually need to do this for '&' operands if R 2626 // resolved to a function or overloaded function set, because the 2627 // expression is ill-formed if it actually works out to be a 2628 // non-static member function: 2629 // 2630 // C++ [expr.ref]p4: 2631 // Otherwise, if E1.E2 refers to a non-static member function. . . 2632 // [t]he expression can be used only as the left-hand operand of a 2633 // member function call. 2634 // 2635 // There are other safeguards against such uses, but it's important 2636 // to get this right here so that we don't end up making a 2637 // spuriously dependent expression if we're inside a dependent 2638 // instance method. 2639 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2640 bool MightBeImplicitMember; 2641 if (!IsAddressOfOperand) 2642 MightBeImplicitMember = true; 2643 else if (!SS.isEmpty()) 2644 MightBeImplicitMember = false; 2645 else if (R.isOverloadedResult()) 2646 MightBeImplicitMember = false; 2647 else if (R.isUnresolvableResult()) 2648 MightBeImplicitMember = true; 2649 else 2650 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2651 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2652 isa<MSPropertyDecl>(R.getFoundDecl()); 2653 2654 if (MightBeImplicitMember) 2655 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2656 R, TemplateArgs, S); 2657 } 2658 2659 if (TemplateArgs || TemplateKWLoc.isValid()) { 2660 2661 // In C++1y, if this is a variable template id, then check it 2662 // in BuildTemplateIdExpr(). 2663 // The single lookup result must be a variable template declaration. 2664 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2665 Id.TemplateId->Kind == TNK_Var_template) { 2666 assert(R.getAsSingle<VarTemplateDecl>() && 2667 "There should only be one declaration found."); 2668 } 2669 2670 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2671 } 2672 2673 return BuildDeclarationNameExpr(SS, R, ADL); 2674 } 2675 2676 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2677 /// declaration name, generally during template instantiation. 2678 /// There's a large number of things which don't need to be done along 2679 /// this path. 2680 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2681 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2682 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2683 DeclContext *DC = computeDeclContext(SS, false); 2684 if (!DC) 2685 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2686 NameInfo, /*TemplateArgs=*/nullptr); 2687 2688 if (RequireCompleteDeclContext(SS, DC)) 2689 return ExprError(); 2690 2691 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2692 LookupQualifiedName(R, DC); 2693 2694 if (R.isAmbiguous()) 2695 return ExprError(); 2696 2697 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2698 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2699 NameInfo, /*TemplateArgs=*/nullptr); 2700 2701 if (R.empty()) { 2702 // Don't diagnose problems with invalid record decl, the secondary no_member 2703 // diagnostic during template instantiation is likely bogus, e.g. if a class 2704 // is invalid because it's derived from an invalid base class, then missing 2705 // members were likely supposed to be inherited. 2706 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2707 if (CD->isInvalidDecl()) 2708 return ExprError(); 2709 Diag(NameInfo.getLoc(), diag::err_no_member) 2710 << NameInfo.getName() << DC << SS.getRange(); 2711 return ExprError(); 2712 } 2713 2714 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2715 // Diagnose a missing typename if this resolved unambiguously to a type in 2716 // a dependent context. If we can recover with a type, downgrade this to 2717 // a warning in Microsoft compatibility mode. 2718 unsigned DiagID = diag::err_typename_missing; 2719 if (RecoveryTSI && getLangOpts().MSVCCompat) 2720 DiagID = diag::ext_typename_missing; 2721 SourceLocation Loc = SS.getBeginLoc(); 2722 auto D = Diag(Loc, DiagID); 2723 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2724 << SourceRange(Loc, NameInfo.getEndLoc()); 2725 2726 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2727 // context. 2728 if (!RecoveryTSI) 2729 return ExprError(); 2730 2731 // Only issue the fixit if we're prepared to recover. 2732 D << FixItHint::CreateInsertion(Loc, "typename "); 2733 2734 // Recover by pretending this was an elaborated type. 2735 QualType Ty = Context.getTypeDeclType(TD); 2736 TypeLocBuilder TLB; 2737 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2738 2739 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2740 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2741 QTL.setElaboratedKeywordLoc(SourceLocation()); 2742 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2743 2744 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2745 2746 return ExprEmpty(); 2747 } 2748 2749 // Defend against this resolving to an implicit member access. We usually 2750 // won't get here if this might be a legitimate a class member (we end up in 2751 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2752 // a pointer-to-member or in an unevaluated context in C++11. 2753 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2754 return BuildPossibleImplicitMemberExpr(SS, 2755 /*TemplateKWLoc=*/SourceLocation(), 2756 R, /*TemplateArgs=*/nullptr, S); 2757 2758 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2759 } 2760 2761 /// The parser has read a name in, and Sema has detected that we're currently 2762 /// inside an ObjC method. Perform some additional checks and determine if we 2763 /// should form a reference to an ivar. 2764 /// 2765 /// Ideally, most of this would be done by lookup, but there's 2766 /// actually quite a lot of extra work involved. 2767 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2768 IdentifierInfo *II) { 2769 SourceLocation Loc = Lookup.getNameLoc(); 2770 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2771 2772 // Check for error condition which is already reported. 2773 if (!CurMethod) 2774 return DeclResult(true); 2775 2776 // There are two cases to handle here. 1) scoped lookup could have failed, 2777 // in which case we should look for an ivar. 2) scoped lookup could have 2778 // found a decl, but that decl is outside the current instance method (i.e. 2779 // a global variable). In these two cases, we do a lookup for an ivar with 2780 // this name, if the lookup sucedes, we replace it our current decl. 2781 2782 // If we're in a class method, we don't normally want to look for 2783 // ivars. But if we don't find anything else, and there's an 2784 // ivar, that's an error. 2785 bool IsClassMethod = CurMethod->isClassMethod(); 2786 2787 bool LookForIvars; 2788 if (Lookup.empty()) 2789 LookForIvars = true; 2790 else if (IsClassMethod) 2791 LookForIvars = false; 2792 else 2793 LookForIvars = (Lookup.isSingleResult() && 2794 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2795 ObjCInterfaceDecl *IFace = nullptr; 2796 if (LookForIvars) { 2797 IFace = CurMethod->getClassInterface(); 2798 ObjCInterfaceDecl *ClassDeclared; 2799 ObjCIvarDecl *IV = nullptr; 2800 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2801 // Diagnose using an ivar in a class method. 2802 if (IsClassMethod) { 2803 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2804 return DeclResult(true); 2805 } 2806 2807 // Diagnose the use of an ivar outside of the declaring class. 2808 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2809 !declaresSameEntity(ClassDeclared, IFace) && 2810 !getLangOpts().DebuggerSupport) 2811 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2812 2813 // Success. 2814 return IV; 2815 } 2816 } else if (CurMethod->isInstanceMethod()) { 2817 // We should warn if a local variable hides an ivar. 2818 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2819 ObjCInterfaceDecl *ClassDeclared; 2820 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2821 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2822 declaresSameEntity(IFace, ClassDeclared)) 2823 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2824 } 2825 } 2826 } else if (Lookup.isSingleResult() && 2827 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2828 // If accessing a stand-alone ivar in a class method, this is an error. 2829 if (const ObjCIvarDecl *IV = 2830 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2831 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2832 return DeclResult(true); 2833 } 2834 } 2835 2836 // Didn't encounter an error, didn't find an ivar. 2837 return DeclResult(false); 2838 } 2839 2840 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2841 ObjCIvarDecl *IV) { 2842 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2843 assert(CurMethod && CurMethod->isInstanceMethod() && 2844 "should not reference ivar from this context"); 2845 2846 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2847 assert(IFace && "should not reference ivar from this context"); 2848 2849 // If we're referencing an invalid decl, just return this as a silent 2850 // error node. The error diagnostic was already emitted on the decl. 2851 if (IV->isInvalidDecl()) 2852 return ExprError(); 2853 2854 // Check if referencing a field with __attribute__((deprecated)). 2855 if (DiagnoseUseOfDecl(IV, Loc)) 2856 return ExprError(); 2857 2858 // FIXME: This should use a new expr for a direct reference, don't 2859 // turn this into Self->ivar, just return a BareIVarExpr or something. 2860 IdentifierInfo &II = Context.Idents.get("self"); 2861 UnqualifiedId SelfName; 2862 SelfName.setImplicitSelfParam(&II); 2863 CXXScopeSpec SelfScopeSpec; 2864 SourceLocation TemplateKWLoc; 2865 ExprResult SelfExpr = 2866 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2867 /*HasTrailingLParen=*/false, 2868 /*IsAddressOfOperand=*/false); 2869 if (SelfExpr.isInvalid()) 2870 return ExprError(); 2871 2872 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2873 if (SelfExpr.isInvalid()) 2874 return ExprError(); 2875 2876 MarkAnyDeclReferenced(Loc, IV, true); 2877 2878 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2879 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2880 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2881 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2882 2883 ObjCIvarRefExpr *Result = new (Context) 2884 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2885 IV->getLocation(), SelfExpr.get(), true, true); 2886 2887 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2888 if (!isUnevaluatedContext() && 2889 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2890 getCurFunction()->recordUseOfWeak(Result); 2891 } 2892 if (getLangOpts().ObjCAutoRefCount) 2893 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2894 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2895 2896 return Result; 2897 } 2898 2899 /// The parser has read a name in, and Sema has detected that we're currently 2900 /// inside an ObjC method. Perform some additional checks and determine if we 2901 /// should form a reference to an ivar. If so, build an expression referencing 2902 /// that ivar. 2903 ExprResult 2904 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2905 IdentifierInfo *II, bool AllowBuiltinCreation) { 2906 // FIXME: Integrate this lookup step into LookupParsedName. 2907 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2908 if (Ivar.isInvalid()) 2909 return ExprError(); 2910 if (Ivar.isUsable()) 2911 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2912 cast<ObjCIvarDecl>(Ivar.get())); 2913 2914 if (Lookup.empty() && II && AllowBuiltinCreation) 2915 LookupBuiltin(Lookup); 2916 2917 // Sentinel value saying that we didn't do anything special. 2918 return ExprResult(false); 2919 } 2920 2921 /// Cast a base object to a member's actual type. 2922 /// 2923 /// There are two relevant checks: 2924 /// 2925 /// C++ [class.access.base]p7: 2926 /// 2927 /// If a class member access operator [...] is used to access a non-static 2928 /// data member or non-static member function, the reference is ill-formed if 2929 /// the left operand [...] cannot be implicitly converted to a pointer to the 2930 /// naming class of the right operand. 2931 /// 2932 /// C++ [expr.ref]p7: 2933 /// 2934 /// If E2 is a non-static data member or a non-static member function, the 2935 /// program is ill-formed if the class of which E2 is directly a member is an 2936 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2937 /// 2938 /// Note that the latter check does not consider access; the access of the 2939 /// "real" base class is checked as appropriate when checking the access of the 2940 /// member name. 2941 ExprResult 2942 Sema::PerformObjectMemberConversion(Expr *From, 2943 NestedNameSpecifier *Qualifier, 2944 NamedDecl *FoundDecl, 2945 NamedDecl *Member) { 2946 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2947 if (!RD) 2948 return From; 2949 2950 QualType DestRecordType; 2951 QualType DestType; 2952 QualType FromRecordType; 2953 QualType FromType = From->getType(); 2954 bool PointerConversions = false; 2955 if (isa<FieldDecl>(Member)) { 2956 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2957 auto FromPtrType = FromType->getAs<PointerType>(); 2958 DestRecordType = Context.getAddrSpaceQualType( 2959 DestRecordType, FromPtrType 2960 ? FromType->getPointeeType().getAddressSpace() 2961 : FromType.getAddressSpace()); 2962 2963 if (FromPtrType) { 2964 DestType = Context.getPointerType(DestRecordType); 2965 FromRecordType = FromPtrType->getPointeeType(); 2966 PointerConversions = true; 2967 } else { 2968 DestType = DestRecordType; 2969 FromRecordType = FromType; 2970 } 2971 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2972 if (Method->isStatic()) 2973 return From; 2974 2975 DestType = Method->getThisType(); 2976 DestRecordType = DestType->getPointeeType(); 2977 2978 if (FromType->getAs<PointerType>()) { 2979 FromRecordType = FromType->getPointeeType(); 2980 PointerConversions = true; 2981 } else { 2982 FromRecordType = FromType; 2983 DestType = DestRecordType; 2984 } 2985 2986 LangAS FromAS = FromRecordType.getAddressSpace(); 2987 LangAS DestAS = DestRecordType.getAddressSpace(); 2988 if (FromAS != DestAS) { 2989 QualType FromRecordTypeWithoutAS = 2990 Context.removeAddrSpaceQualType(FromRecordType); 2991 QualType FromTypeWithDestAS = 2992 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2993 if (PointerConversions) 2994 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2995 From = ImpCastExprToType(From, FromTypeWithDestAS, 2996 CK_AddressSpaceConversion, From->getValueKind()) 2997 .get(); 2998 } 2999 } else { 3000 // No conversion necessary. 3001 return From; 3002 } 3003 3004 if (DestType->isDependentType() || FromType->isDependentType()) 3005 return From; 3006 3007 // If the unqualified types are the same, no conversion is necessary. 3008 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3009 return From; 3010 3011 SourceRange FromRange = From->getSourceRange(); 3012 SourceLocation FromLoc = FromRange.getBegin(); 3013 3014 ExprValueKind VK = From->getValueKind(); 3015 3016 // C++ [class.member.lookup]p8: 3017 // [...] Ambiguities can often be resolved by qualifying a name with its 3018 // class name. 3019 // 3020 // If the member was a qualified name and the qualified referred to a 3021 // specific base subobject type, we'll cast to that intermediate type 3022 // first and then to the object in which the member is declared. That allows 3023 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3024 // 3025 // class Base { public: int x; }; 3026 // class Derived1 : public Base { }; 3027 // class Derived2 : public Base { }; 3028 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3029 // 3030 // void VeryDerived::f() { 3031 // x = 17; // error: ambiguous base subobjects 3032 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3033 // } 3034 if (Qualifier && Qualifier->getAsType()) { 3035 QualType QType = QualType(Qualifier->getAsType(), 0); 3036 assert(QType->isRecordType() && "lookup done with non-record type"); 3037 3038 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3039 3040 // In C++98, the qualifier type doesn't actually have to be a base 3041 // type of the object type, in which case we just ignore it. 3042 // Otherwise build the appropriate casts. 3043 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3044 CXXCastPath BasePath; 3045 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3046 FromLoc, FromRange, &BasePath)) 3047 return ExprError(); 3048 3049 if (PointerConversions) 3050 QType = Context.getPointerType(QType); 3051 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3052 VK, &BasePath).get(); 3053 3054 FromType = QType; 3055 FromRecordType = QRecordType; 3056 3057 // If the qualifier type was the same as the destination type, 3058 // we're done. 3059 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3060 return From; 3061 } 3062 } 3063 3064 CXXCastPath BasePath; 3065 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3066 FromLoc, FromRange, &BasePath, 3067 /*IgnoreAccess=*/true)) 3068 return ExprError(); 3069 3070 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3071 VK, &BasePath); 3072 } 3073 3074 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3075 const LookupResult &R, 3076 bool HasTrailingLParen) { 3077 // Only when used directly as the postfix-expression of a call. 3078 if (!HasTrailingLParen) 3079 return false; 3080 3081 // Never if a scope specifier was provided. 3082 if (SS.isSet()) 3083 return false; 3084 3085 // Only in C++ or ObjC++. 3086 if (!getLangOpts().CPlusPlus) 3087 return false; 3088 3089 // Turn off ADL when we find certain kinds of declarations during 3090 // normal lookup: 3091 for (NamedDecl *D : R) { 3092 // C++0x [basic.lookup.argdep]p3: 3093 // -- a declaration of a class member 3094 // Since using decls preserve this property, we check this on the 3095 // original decl. 3096 if (D->isCXXClassMember()) 3097 return false; 3098 3099 // C++0x [basic.lookup.argdep]p3: 3100 // -- a block-scope function declaration that is not a 3101 // using-declaration 3102 // NOTE: we also trigger this for function templates (in fact, we 3103 // don't check the decl type at all, since all other decl types 3104 // turn off ADL anyway). 3105 if (isa<UsingShadowDecl>(D)) 3106 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3107 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3108 return false; 3109 3110 // C++0x [basic.lookup.argdep]p3: 3111 // -- a declaration that is neither a function or a function 3112 // template 3113 // And also for builtin functions. 3114 if (isa<FunctionDecl>(D)) { 3115 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3116 3117 // But also builtin functions. 3118 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3119 return false; 3120 } else if (!isa<FunctionTemplateDecl>(D)) 3121 return false; 3122 } 3123 3124 return true; 3125 } 3126 3127 3128 /// Diagnoses obvious problems with the use of the given declaration 3129 /// as an expression. This is only actually called for lookups that 3130 /// were not overloaded, and it doesn't promise that the declaration 3131 /// will in fact be used. 3132 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3133 if (D->isInvalidDecl()) 3134 return true; 3135 3136 if (isa<TypedefNameDecl>(D)) { 3137 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3138 return true; 3139 } 3140 3141 if (isa<ObjCInterfaceDecl>(D)) { 3142 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3143 return true; 3144 } 3145 3146 if (isa<NamespaceDecl>(D)) { 3147 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3148 return true; 3149 } 3150 3151 return false; 3152 } 3153 3154 // Certain multiversion types should be treated as overloaded even when there is 3155 // only one result. 3156 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3157 assert(R.isSingleResult() && "Expected only a single result"); 3158 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3159 return FD && 3160 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3161 } 3162 3163 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3164 LookupResult &R, bool NeedsADL, 3165 bool AcceptInvalidDecl) { 3166 // If this is a single, fully-resolved result and we don't need ADL, 3167 // just build an ordinary singleton decl ref. 3168 if (!NeedsADL && R.isSingleResult() && 3169 !R.getAsSingle<FunctionTemplateDecl>() && 3170 !ShouldLookupResultBeMultiVersionOverload(R)) 3171 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3172 R.getRepresentativeDecl(), nullptr, 3173 AcceptInvalidDecl); 3174 3175 // We only need to check the declaration if there's exactly one 3176 // result, because in the overloaded case the results can only be 3177 // functions and function templates. 3178 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3179 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3180 return ExprError(); 3181 3182 // Otherwise, just build an unresolved lookup expression. Suppress 3183 // any lookup-related diagnostics; we'll hash these out later, when 3184 // we've picked a target. 3185 R.suppressDiagnostics(); 3186 3187 UnresolvedLookupExpr *ULE 3188 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3189 SS.getWithLocInContext(Context), 3190 R.getLookupNameInfo(), 3191 NeedsADL, R.isOverloadedResult(), 3192 R.begin(), R.end()); 3193 3194 return ULE; 3195 } 3196 3197 static void 3198 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3199 ValueDecl *var, DeclContext *DC); 3200 3201 /// Complete semantic analysis for a reference to the given declaration. 3202 ExprResult Sema::BuildDeclarationNameExpr( 3203 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3204 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3205 bool AcceptInvalidDecl) { 3206 assert(D && "Cannot refer to a NULL declaration"); 3207 assert(!isa<FunctionTemplateDecl>(D) && 3208 "Cannot refer unambiguously to a function template"); 3209 3210 SourceLocation Loc = NameInfo.getLoc(); 3211 if (CheckDeclInExpr(*this, Loc, D)) 3212 return ExprError(); 3213 3214 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3215 // Specifically diagnose references to class templates that are missing 3216 // a template argument list. 3217 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3218 return ExprError(); 3219 } 3220 3221 // Make sure that we're referring to a value. 3222 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3223 Diag(Loc, diag::err_ref_non_value) 3224 << D << SS.getRange(); 3225 Diag(D->getLocation(), diag::note_declared_at); 3226 return ExprError(); 3227 } 3228 3229 // Check whether this declaration can be used. Note that we suppress 3230 // this check when we're going to perform argument-dependent lookup 3231 // on this function name, because this might not be the function 3232 // that overload resolution actually selects. 3233 if (DiagnoseUseOfDecl(D, Loc)) 3234 return ExprError(); 3235 3236 auto *VD = cast<ValueDecl>(D); 3237 3238 // Only create DeclRefExpr's for valid Decl's. 3239 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3240 return ExprError(); 3241 3242 // Handle members of anonymous structs and unions. If we got here, 3243 // and the reference is to a class member indirect field, then this 3244 // must be the subject of a pointer-to-member expression. 3245 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3246 if (!indirectField->isCXXClassMember()) 3247 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3248 indirectField); 3249 3250 { 3251 QualType type = VD->getType(); 3252 if (type.isNull()) 3253 return ExprError(); 3254 ExprValueKind valueKind = VK_PRValue; 3255 3256 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3257 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3258 // is expanded by some outer '...' in the context of the use. 3259 type = type.getNonPackExpansionType(); 3260 3261 switch (D->getKind()) { 3262 // Ignore all the non-ValueDecl kinds. 3263 #define ABSTRACT_DECL(kind) 3264 #define VALUE(type, base) 3265 #define DECL(type, base) \ 3266 case Decl::type: 3267 #include "clang/AST/DeclNodes.inc" 3268 llvm_unreachable("invalid value decl kind"); 3269 3270 // These shouldn't make it here. 3271 case Decl::ObjCAtDefsField: 3272 llvm_unreachable("forming non-member reference to ivar?"); 3273 3274 // Enum constants are always r-values and never references. 3275 // Unresolved using declarations are dependent. 3276 case Decl::EnumConstant: 3277 case Decl::UnresolvedUsingValue: 3278 case Decl::OMPDeclareReduction: 3279 case Decl::OMPDeclareMapper: 3280 valueKind = VK_PRValue; 3281 break; 3282 3283 // Fields and indirect fields that got here must be for 3284 // pointer-to-member expressions; we just call them l-values for 3285 // internal consistency, because this subexpression doesn't really 3286 // exist in the high-level semantics. 3287 case Decl::Field: 3288 case Decl::IndirectField: 3289 case Decl::ObjCIvar: 3290 assert(getLangOpts().CPlusPlus && 3291 "building reference to field in C?"); 3292 3293 // These can't have reference type in well-formed programs, but 3294 // for internal consistency we do this anyway. 3295 type = type.getNonReferenceType(); 3296 valueKind = VK_LValue; 3297 break; 3298 3299 // Non-type template parameters are either l-values or r-values 3300 // depending on the type. 3301 case Decl::NonTypeTemplateParm: { 3302 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3303 type = reftype->getPointeeType(); 3304 valueKind = VK_LValue; // even if the parameter is an r-value reference 3305 break; 3306 } 3307 3308 // [expr.prim.id.unqual]p2: 3309 // If the entity is a template parameter object for a template 3310 // parameter of type T, the type of the expression is const T. 3311 // [...] The expression is an lvalue if the entity is a [...] template 3312 // parameter object. 3313 if (type->isRecordType()) { 3314 type = type.getUnqualifiedType().withConst(); 3315 valueKind = VK_LValue; 3316 break; 3317 } 3318 3319 // For non-references, we need to strip qualifiers just in case 3320 // the template parameter was declared as 'const int' or whatever. 3321 valueKind = VK_PRValue; 3322 type = type.getUnqualifiedType(); 3323 break; 3324 } 3325 3326 case Decl::Var: 3327 case Decl::VarTemplateSpecialization: 3328 case Decl::VarTemplatePartialSpecialization: 3329 case Decl::Decomposition: 3330 case Decl::OMPCapturedExpr: 3331 // In C, "extern void blah;" is valid and is an r-value. 3332 if (!getLangOpts().CPlusPlus && 3333 !type.hasQualifiers() && 3334 type->isVoidType()) { 3335 valueKind = VK_PRValue; 3336 break; 3337 } 3338 LLVM_FALLTHROUGH; 3339 3340 case Decl::ImplicitParam: 3341 case Decl::ParmVar: { 3342 // These are always l-values. 3343 valueKind = VK_LValue; 3344 type = type.getNonReferenceType(); 3345 3346 // FIXME: Does the addition of const really only apply in 3347 // potentially-evaluated contexts? Since the variable isn't actually 3348 // captured in an unevaluated context, it seems that the answer is no. 3349 if (!isUnevaluatedContext()) { 3350 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3351 if (!CapturedType.isNull()) 3352 type = CapturedType; 3353 } 3354 3355 break; 3356 } 3357 3358 case Decl::Binding: { 3359 // These are always lvalues. 3360 valueKind = VK_LValue; 3361 type = type.getNonReferenceType(); 3362 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3363 // decides how that's supposed to work. 3364 auto *BD = cast<BindingDecl>(VD); 3365 if (BD->getDeclContext() != CurContext) { 3366 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3367 if (DD && DD->hasLocalStorage()) 3368 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3369 } 3370 break; 3371 } 3372 3373 case Decl::Function: { 3374 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3375 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3376 type = Context.BuiltinFnTy; 3377 valueKind = VK_PRValue; 3378 break; 3379 } 3380 } 3381 3382 const FunctionType *fty = type->castAs<FunctionType>(); 3383 3384 // If we're referring to a function with an __unknown_anytype 3385 // result type, make the entire expression __unknown_anytype. 3386 if (fty->getReturnType() == Context.UnknownAnyTy) { 3387 type = Context.UnknownAnyTy; 3388 valueKind = VK_PRValue; 3389 break; 3390 } 3391 3392 // Functions are l-values in C++. 3393 if (getLangOpts().CPlusPlus) { 3394 valueKind = VK_LValue; 3395 break; 3396 } 3397 3398 // C99 DR 316 says that, if a function type comes from a 3399 // function definition (without a prototype), that type is only 3400 // used for checking compatibility. Therefore, when referencing 3401 // the function, we pretend that we don't have the full function 3402 // type. 3403 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3404 isa<FunctionProtoType>(fty)) 3405 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3406 fty->getExtInfo()); 3407 3408 // Functions are r-values in C. 3409 valueKind = VK_PRValue; 3410 break; 3411 } 3412 3413 case Decl::CXXDeductionGuide: 3414 llvm_unreachable("building reference to deduction guide"); 3415 3416 case Decl::MSProperty: 3417 case Decl::MSGuid: 3418 case Decl::TemplateParamObject: 3419 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3420 // capture in OpenMP, or duplicated between host and device? 3421 valueKind = VK_LValue; 3422 break; 3423 3424 case Decl::CXXMethod: 3425 // If we're referring to a method with an __unknown_anytype 3426 // result type, make the entire expression __unknown_anytype. 3427 // This should only be possible with a type written directly. 3428 if (const FunctionProtoType *proto 3429 = dyn_cast<FunctionProtoType>(VD->getType())) 3430 if (proto->getReturnType() == Context.UnknownAnyTy) { 3431 type = Context.UnknownAnyTy; 3432 valueKind = VK_PRValue; 3433 break; 3434 } 3435 3436 // C++ methods are l-values if static, r-values if non-static. 3437 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3438 valueKind = VK_LValue; 3439 break; 3440 } 3441 LLVM_FALLTHROUGH; 3442 3443 case Decl::CXXConversion: 3444 case Decl::CXXDestructor: 3445 case Decl::CXXConstructor: 3446 valueKind = VK_PRValue; 3447 break; 3448 } 3449 3450 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3451 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3452 TemplateArgs); 3453 } 3454 } 3455 3456 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3457 SmallString<32> &Target) { 3458 Target.resize(CharByteWidth * (Source.size() + 1)); 3459 char *ResultPtr = &Target[0]; 3460 const llvm::UTF8 *ErrorPtr; 3461 bool success = 3462 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3463 (void)success; 3464 assert(success); 3465 Target.resize(ResultPtr - &Target[0]); 3466 } 3467 3468 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3469 PredefinedExpr::IdentKind IK) { 3470 // Pick the current block, lambda, captured statement or function. 3471 Decl *currentDecl = nullptr; 3472 if (const BlockScopeInfo *BSI = getCurBlock()) 3473 currentDecl = BSI->TheDecl; 3474 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3475 currentDecl = LSI->CallOperator; 3476 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3477 currentDecl = CSI->TheCapturedDecl; 3478 else 3479 currentDecl = getCurFunctionOrMethodDecl(); 3480 3481 if (!currentDecl) { 3482 Diag(Loc, diag::ext_predef_outside_function); 3483 currentDecl = Context.getTranslationUnitDecl(); 3484 } 3485 3486 QualType ResTy; 3487 StringLiteral *SL = nullptr; 3488 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3489 ResTy = Context.DependentTy; 3490 else { 3491 // Pre-defined identifiers are of type char[x], where x is the length of 3492 // the string. 3493 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3494 unsigned Length = Str.length(); 3495 3496 llvm::APInt LengthI(32, Length + 1); 3497 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3498 ResTy = 3499 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3500 SmallString<32> RawChars; 3501 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3502 Str, RawChars); 3503 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3504 ArrayType::Normal, 3505 /*IndexTypeQuals*/ 0); 3506 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3507 /*Pascal*/ false, ResTy, Loc); 3508 } else { 3509 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3510 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3511 ArrayType::Normal, 3512 /*IndexTypeQuals*/ 0); 3513 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3514 /*Pascal*/ false, ResTy, Loc); 3515 } 3516 } 3517 3518 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3519 } 3520 3521 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3522 SourceLocation LParen, 3523 SourceLocation RParen, 3524 TypeSourceInfo *TSI) { 3525 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3526 } 3527 3528 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3529 SourceLocation LParen, 3530 SourceLocation RParen, 3531 ParsedType ParsedTy) { 3532 TypeSourceInfo *TSI = nullptr; 3533 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3534 3535 if (Ty.isNull()) 3536 return ExprError(); 3537 if (!TSI) 3538 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3539 3540 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3541 } 3542 3543 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3544 PredefinedExpr::IdentKind IK; 3545 3546 switch (Kind) { 3547 default: llvm_unreachable("Unknown simple primary expr!"); 3548 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3549 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3550 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3551 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3552 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3553 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3554 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3555 } 3556 3557 return BuildPredefinedExpr(Loc, IK); 3558 } 3559 3560 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3561 SmallString<16> CharBuffer; 3562 bool Invalid = false; 3563 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3564 if (Invalid) 3565 return ExprError(); 3566 3567 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3568 PP, Tok.getKind()); 3569 if (Literal.hadError()) 3570 return ExprError(); 3571 3572 QualType Ty; 3573 if (Literal.isWide()) 3574 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3575 else if (Literal.isUTF8() && getLangOpts().Char8) 3576 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3577 else if (Literal.isUTF16()) 3578 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3579 else if (Literal.isUTF32()) 3580 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3581 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3582 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3583 else 3584 Ty = Context.CharTy; // 'x' -> char in C++ 3585 3586 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3587 if (Literal.isWide()) 3588 Kind = CharacterLiteral::Wide; 3589 else if (Literal.isUTF16()) 3590 Kind = CharacterLiteral::UTF16; 3591 else if (Literal.isUTF32()) 3592 Kind = CharacterLiteral::UTF32; 3593 else if (Literal.isUTF8()) 3594 Kind = CharacterLiteral::UTF8; 3595 3596 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3597 Tok.getLocation()); 3598 3599 if (Literal.getUDSuffix().empty()) 3600 return Lit; 3601 3602 // We're building a user-defined literal. 3603 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3604 SourceLocation UDSuffixLoc = 3605 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3606 3607 // Make sure we're allowed user-defined literals here. 3608 if (!UDLScope) 3609 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3610 3611 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3612 // operator "" X (ch) 3613 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3614 Lit, Tok.getLocation()); 3615 } 3616 3617 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3618 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3619 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3620 Context.IntTy, Loc); 3621 } 3622 3623 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3624 QualType Ty, SourceLocation Loc) { 3625 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3626 3627 using llvm::APFloat; 3628 APFloat Val(Format); 3629 3630 APFloat::opStatus result = Literal.GetFloatValue(Val); 3631 3632 // Overflow is always an error, but underflow is only an error if 3633 // we underflowed to zero (APFloat reports denormals as underflow). 3634 if ((result & APFloat::opOverflow) || 3635 ((result & APFloat::opUnderflow) && Val.isZero())) { 3636 unsigned diagnostic; 3637 SmallString<20> buffer; 3638 if (result & APFloat::opOverflow) { 3639 diagnostic = diag::warn_float_overflow; 3640 APFloat::getLargest(Format).toString(buffer); 3641 } else { 3642 diagnostic = diag::warn_float_underflow; 3643 APFloat::getSmallest(Format).toString(buffer); 3644 } 3645 3646 S.Diag(Loc, diagnostic) 3647 << Ty 3648 << StringRef(buffer.data(), buffer.size()); 3649 } 3650 3651 bool isExact = (result == APFloat::opOK); 3652 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3653 } 3654 3655 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3656 assert(E && "Invalid expression"); 3657 3658 if (E->isValueDependent()) 3659 return false; 3660 3661 QualType QT = E->getType(); 3662 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3663 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3664 return true; 3665 } 3666 3667 llvm::APSInt ValueAPS; 3668 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3669 3670 if (R.isInvalid()) 3671 return true; 3672 3673 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3674 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3675 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3676 << toString(ValueAPS, 10) << ValueIsPositive; 3677 return true; 3678 } 3679 3680 return false; 3681 } 3682 3683 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3684 // Fast path for a single digit (which is quite common). A single digit 3685 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3686 if (Tok.getLength() == 1) { 3687 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3688 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3689 } 3690 3691 SmallString<128> SpellingBuffer; 3692 // NumericLiteralParser wants to overread by one character. Add padding to 3693 // the buffer in case the token is copied to the buffer. If getSpelling() 3694 // returns a StringRef to the memory buffer, it should have a null char at 3695 // the EOF, so it is also safe. 3696 SpellingBuffer.resize(Tok.getLength() + 1); 3697 3698 // Get the spelling of the token, which eliminates trigraphs, etc. 3699 bool Invalid = false; 3700 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3701 if (Invalid) 3702 return ExprError(); 3703 3704 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3705 PP.getSourceManager(), PP.getLangOpts(), 3706 PP.getTargetInfo(), PP.getDiagnostics()); 3707 if (Literal.hadError) 3708 return ExprError(); 3709 3710 if (Literal.hasUDSuffix()) { 3711 // We're building a user-defined literal. 3712 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3713 SourceLocation UDSuffixLoc = 3714 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3715 3716 // Make sure we're allowed user-defined literals here. 3717 if (!UDLScope) 3718 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3719 3720 QualType CookedTy; 3721 if (Literal.isFloatingLiteral()) { 3722 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3723 // long double, the literal is treated as a call of the form 3724 // operator "" X (f L) 3725 CookedTy = Context.LongDoubleTy; 3726 } else { 3727 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3728 // unsigned long long, the literal is treated as a call of the form 3729 // operator "" X (n ULL) 3730 CookedTy = Context.UnsignedLongLongTy; 3731 } 3732 3733 DeclarationName OpName = 3734 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3735 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3736 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3737 3738 SourceLocation TokLoc = Tok.getLocation(); 3739 3740 // Perform literal operator lookup to determine if we're building a raw 3741 // literal or a cooked one. 3742 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3743 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3744 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3745 /*AllowStringTemplatePack*/ false, 3746 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3747 case LOLR_ErrorNoDiagnostic: 3748 // Lookup failure for imaginary constants isn't fatal, there's still the 3749 // GNU extension producing _Complex types. 3750 break; 3751 case LOLR_Error: 3752 return ExprError(); 3753 case LOLR_Cooked: { 3754 Expr *Lit; 3755 if (Literal.isFloatingLiteral()) { 3756 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3757 } else { 3758 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3759 if (Literal.GetIntegerValue(ResultVal)) 3760 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3761 << /* Unsigned */ 1; 3762 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3763 Tok.getLocation()); 3764 } 3765 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3766 } 3767 3768 case LOLR_Raw: { 3769 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3770 // literal is treated as a call of the form 3771 // operator "" X ("n") 3772 unsigned Length = Literal.getUDSuffixOffset(); 3773 QualType StrTy = Context.getConstantArrayType( 3774 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3775 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3776 Expr *Lit = StringLiteral::Create( 3777 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3778 /*Pascal*/false, StrTy, &TokLoc, 1); 3779 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3780 } 3781 3782 case LOLR_Template: { 3783 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3784 // template), L is treated as a call fo the form 3785 // operator "" X <'c1', 'c2', ... 'ck'>() 3786 // where n is the source character sequence c1 c2 ... ck. 3787 TemplateArgumentListInfo ExplicitArgs; 3788 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3789 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3790 llvm::APSInt Value(CharBits, CharIsUnsigned); 3791 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3792 Value = TokSpelling[I]; 3793 TemplateArgument Arg(Context, Value, Context.CharTy); 3794 TemplateArgumentLocInfo ArgInfo; 3795 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3796 } 3797 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3798 &ExplicitArgs); 3799 } 3800 case LOLR_StringTemplatePack: 3801 llvm_unreachable("unexpected literal operator lookup result"); 3802 } 3803 } 3804 3805 Expr *Res; 3806 3807 if (Literal.isFixedPointLiteral()) { 3808 QualType Ty; 3809 3810 if (Literal.isAccum) { 3811 if (Literal.isHalf) { 3812 Ty = Context.ShortAccumTy; 3813 } else if (Literal.isLong) { 3814 Ty = Context.LongAccumTy; 3815 } else { 3816 Ty = Context.AccumTy; 3817 } 3818 } else if (Literal.isFract) { 3819 if (Literal.isHalf) { 3820 Ty = Context.ShortFractTy; 3821 } else if (Literal.isLong) { 3822 Ty = Context.LongFractTy; 3823 } else { 3824 Ty = Context.FractTy; 3825 } 3826 } 3827 3828 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3829 3830 bool isSigned = !Literal.isUnsigned; 3831 unsigned scale = Context.getFixedPointScale(Ty); 3832 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3833 3834 llvm::APInt Val(bit_width, 0, isSigned); 3835 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3836 bool ValIsZero = Val.isNullValue() && !Overflowed; 3837 3838 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3839 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3840 // Clause 6.4.4 - The value of a constant shall be in the range of 3841 // representable values for its type, with exception for constants of a 3842 // fract type with a value of exactly 1; such a constant shall denote 3843 // the maximal value for the type. 3844 --Val; 3845 else if (Val.ugt(MaxVal) || Overflowed) 3846 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3847 3848 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3849 Tok.getLocation(), scale); 3850 } else if (Literal.isFloatingLiteral()) { 3851 QualType Ty; 3852 if (Literal.isHalf){ 3853 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3854 Ty = Context.HalfTy; 3855 else { 3856 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3857 return ExprError(); 3858 } 3859 } else if (Literal.isFloat) 3860 Ty = Context.FloatTy; 3861 else if (Literal.isLong) 3862 Ty = Context.LongDoubleTy; 3863 else if (Literal.isFloat16) 3864 Ty = Context.Float16Ty; 3865 else if (Literal.isFloat128) 3866 Ty = Context.Float128Ty; 3867 else 3868 Ty = Context.DoubleTy; 3869 3870 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3871 3872 if (Ty == Context.DoubleTy) { 3873 if (getLangOpts().SinglePrecisionConstants) { 3874 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3875 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3876 } 3877 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3878 "cl_khr_fp64", getLangOpts())) { 3879 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3880 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3881 << (getLangOpts().OpenCLVersion >= 300); 3882 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3883 } 3884 } 3885 } else if (!Literal.isIntegerLiteral()) { 3886 return ExprError(); 3887 } else { 3888 QualType Ty; 3889 3890 // 'long long' is a C99 or C++11 feature. 3891 if (!getLangOpts().C99 && Literal.isLongLong) { 3892 if (getLangOpts().CPlusPlus) 3893 Diag(Tok.getLocation(), 3894 getLangOpts().CPlusPlus11 ? 3895 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3896 else 3897 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3898 } 3899 3900 // 'z/uz' literals are a C++2b feature. 3901 if (Literal.isSizeT) 3902 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3903 ? getLangOpts().CPlusPlus2b 3904 ? diag::warn_cxx20_compat_size_t_suffix 3905 : diag::ext_cxx2b_size_t_suffix 3906 : diag::err_cxx2b_size_t_suffix); 3907 3908 // Get the value in the widest-possible width. 3909 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3910 llvm::APInt ResultVal(MaxWidth, 0); 3911 3912 if (Literal.GetIntegerValue(ResultVal)) { 3913 // If this value didn't fit into uintmax_t, error and force to ull. 3914 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3915 << /* Unsigned */ 1; 3916 Ty = Context.UnsignedLongLongTy; 3917 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3918 "long long is not intmax_t?"); 3919 } else { 3920 // If this value fits into a ULL, try to figure out what else it fits into 3921 // according to the rules of C99 6.4.4.1p5. 3922 3923 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3924 // be an unsigned int. 3925 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3926 3927 // Check from smallest to largest, picking the smallest type we can. 3928 unsigned Width = 0; 3929 3930 // Microsoft specific integer suffixes are explicitly sized. 3931 if (Literal.MicrosoftInteger) { 3932 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3933 Width = 8; 3934 Ty = Context.CharTy; 3935 } else { 3936 Width = Literal.MicrosoftInteger; 3937 Ty = Context.getIntTypeForBitwidth(Width, 3938 /*Signed=*/!Literal.isUnsigned); 3939 } 3940 } 3941 3942 // Check C++2b size_t literals. 3943 if (Literal.isSizeT) { 3944 assert(!Literal.MicrosoftInteger && 3945 "size_t literals can't be Microsoft literals"); 3946 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3947 Context.getTargetInfo().getSizeType()); 3948 3949 // Does it fit in size_t? 3950 if (ResultVal.isIntN(SizeTSize)) { 3951 // Does it fit in ssize_t? 3952 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3953 Ty = Context.getSignedSizeType(); 3954 else if (AllowUnsigned) 3955 Ty = Context.getSizeType(); 3956 Width = SizeTSize; 3957 } 3958 } 3959 3960 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3961 !Literal.isSizeT) { 3962 // Are int/unsigned possibilities? 3963 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3964 3965 // Does it fit in a unsigned int? 3966 if (ResultVal.isIntN(IntSize)) { 3967 // Does it fit in a signed int? 3968 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3969 Ty = Context.IntTy; 3970 else if (AllowUnsigned) 3971 Ty = Context.UnsignedIntTy; 3972 Width = IntSize; 3973 } 3974 } 3975 3976 // Are long/unsigned long possibilities? 3977 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3978 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3979 3980 // Does it fit in a unsigned long? 3981 if (ResultVal.isIntN(LongSize)) { 3982 // Does it fit in a signed long? 3983 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3984 Ty = Context.LongTy; 3985 else if (AllowUnsigned) 3986 Ty = Context.UnsignedLongTy; 3987 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3988 // is compatible. 3989 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3990 const unsigned LongLongSize = 3991 Context.getTargetInfo().getLongLongWidth(); 3992 Diag(Tok.getLocation(), 3993 getLangOpts().CPlusPlus 3994 ? Literal.isLong 3995 ? diag::warn_old_implicitly_unsigned_long_cxx 3996 : /*C++98 UB*/ diag:: 3997 ext_old_implicitly_unsigned_long_cxx 3998 : diag::warn_old_implicitly_unsigned_long) 3999 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4000 : /*will be ill-formed*/ 1); 4001 Ty = Context.UnsignedLongTy; 4002 } 4003 Width = LongSize; 4004 } 4005 } 4006 4007 // Check long long if needed. 4008 if (Ty.isNull() && !Literal.isSizeT) { 4009 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4010 4011 // Does it fit in a unsigned long long? 4012 if (ResultVal.isIntN(LongLongSize)) { 4013 // Does it fit in a signed long long? 4014 // To be compatible with MSVC, hex integer literals ending with the 4015 // LL or i64 suffix are always signed in Microsoft mode. 4016 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4017 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4018 Ty = Context.LongLongTy; 4019 else if (AllowUnsigned) 4020 Ty = Context.UnsignedLongLongTy; 4021 Width = LongLongSize; 4022 } 4023 } 4024 4025 // If we still couldn't decide a type, we either have 'size_t' literal 4026 // that is out of range, or a decimal literal that does not fit in a 4027 // signed long long and has no U suffix. 4028 if (Ty.isNull()) { 4029 if (Literal.isSizeT) 4030 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4031 << Literal.isUnsigned; 4032 else 4033 Diag(Tok.getLocation(), 4034 diag::ext_integer_literal_too_large_for_signed); 4035 Ty = Context.UnsignedLongLongTy; 4036 Width = Context.getTargetInfo().getLongLongWidth(); 4037 } 4038 4039 if (ResultVal.getBitWidth() != Width) 4040 ResultVal = ResultVal.trunc(Width); 4041 } 4042 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4043 } 4044 4045 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4046 if (Literal.isImaginary) { 4047 Res = new (Context) ImaginaryLiteral(Res, 4048 Context.getComplexType(Res->getType())); 4049 4050 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4051 } 4052 return Res; 4053 } 4054 4055 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4056 assert(E && "ActOnParenExpr() missing expr"); 4057 return new (Context) ParenExpr(L, R, E); 4058 } 4059 4060 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4061 SourceLocation Loc, 4062 SourceRange ArgRange) { 4063 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4064 // scalar or vector data type argument..." 4065 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4066 // type (C99 6.2.5p18) or void. 4067 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4068 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4069 << T << ArgRange; 4070 return true; 4071 } 4072 4073 assert((T->isVoidType() || !T->isIncompleteType()) && 4074 "Scalar types should always be complete"); 4075 return false; 4076 } 4077 4078 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4079 SourceLocation Loc, 4080 SourceRange ArgRange, 4081 UnaryExprOrTypeTrait TraitKind) { 4082 // Invalid types must be hard errors for SFINAE in C++. 4083 if (S.LangOpts.CPlusPlus) 4084 return true; 4085 4086 // C99 6.5.3.4p1: 4087 if (T->isFunctionType() && 4088 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4089 TraitKind == UETT_PreferredAlignOf)) { 4090 // sizeof(function)/alignof(function) is allowed as an extension. 4091 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4092 << getTraitSpelling(TraitKind) << ArgRange; 4093 return false; 4094 } 4095 4096 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4097 // this is an error (OpenCL v1.1 s6.3.k) 4098 if (T->isVoidType()) { 4099 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4100 : diag::ext_sizeof_alignof_void_type; 4101 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4102 return false; 4103 } 4104 4105 return true; 4106 } 4107 4108 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4109 SourceLocation Loc, 4110 SourceRange ArgRange, 4111 UnaryExprOrTypeTrait TraitKind) { 4112 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4113 // runtime doesn't allow it. 4114 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4115 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4116 << T << (TraitKind == UETT_SizeOf) 4117 << ArgRange; 4118 return true; 4119 } 4120 4121 return false; 4122 } 4123 4124 /// Check whether E is a pointer from a decayed array type (the decayed 4125 /// pointer type is equal to T) and emit a warning if it is. 4126 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4127 Expr *E) { 4128 // Don't warn if the operation changed the type. 4129 if (T != E->getType()) 4130 return; 4131 4132 // Now look for array decays. 4133 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4134 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4135 return; 4136 4137 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4138 << ICE->getType() 4139 << ICE->getSubExpr()->getType(); 4140 } 4141 4142 /// Check the constraints on expression operands to unary type expression 4143 /// and type traits. 4144 /// 4145 /// Completes any types necessary and validates the constraints on the operand 4146 /// expression. The logic mostly mirrors the type-based overload, but may modify 4147 /// the expression as it completes the type for that expression through template 4148 /// instantiation, etc. 4149 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4150 UnaryExprOrTypeTrait ExprKind) { 4151 QualType ExprTy = E->getType(); 4152 assert(!ExprTy->isReferenceType()); 4153 4154 bool IsUnevaluatedOperand = 4155 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4156 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4157 if (IsUnevaluatedOperand) { 4158 ExprResult Result = CheckUnevaluatedOperand(E); 4159 if (Result.isInvalid()) 4160 return true; 4161 E = Result.get(); 4162 } 4163 4164 // The operand for sizeof and alignof is in an unevaluated expression context, 4165 // so side effects could result in unintended consequences. 4166 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4167 // used to build SFINAE gadgets. 4168 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4169 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4170 !E->isInstantiationDependent() && 4171 E->HasSideEffects(Context, false)) 4172 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4173 4174 if (ExprKind == UETT_VecStep) 4175 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4176 E->getSourceRange()); 4177 4178 // Explicitly list some types as extensions. 4179 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4180 E->getSourceRange(), ExprKind)) 4181 return false; 4182 4183 // 'alignof' applied to an expression only requires the base element type of 4184 // the expression to be complete. 'sizeof' requires the expression's type to 4185 // be complete (and will attempt to complete it if it's an array of unknown 4186 // bound). 4187 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4188 if (RequireCompleteSizedType( 4189 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4190 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4191 getTraitSpelling(ExprKind), E->getSourceRange())) 4192 return true; 4193 } else { 4194 if (RequireCompleteSizedExprType( 4195 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4196 getTraitSpelling(ExprKind), E->getSourceRange())) 4197 return true; 4198 } 4199 4200 // Completing the expression's type may have changed it. 4201 ExprTy = E->getType(); 4202 assert(!ExprTy->isReferenceType()); 4203 4204 if (ExprTy->isFunctionType()) { 4205 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4206 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4207 return true; 4208 } 4209 4210 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4211 E->getSourceRange(), ExprKind)) 4212 return true; 4213 4214 if (ExprKind == UETT_SizeOf) { 4215 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4216 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4217 QualType OType = PVD->getOriginalType(); 4218 QualType Type = PVD->getType(); 4219 if (Type->isPointerType() && OType->isArrayType()) { 4220 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4221 << Type << OType; 4222 Diag(PVD->getLocation(), diag::note_declared_at); 4223 } 4224 } 4225 } 4226 4227 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4228 // decays into a pointer and returns an unintended result. This is most 4229 // likely a typo for "sizeof(array) op x". 4230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4231 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4232 BO->getLHS()); 4233 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4234 BO->getRHS()); 4235 } 4236 } 4237 4238 return false; 4239 } 4240 4241 /// Check the constraints on operands to unary expression and type 4242 /// traits. 4243 /// 4244 /// This will complete any types necessary, and validate the various constraints 4245 /// on those operands. 4246 /// 4247 /// The UsualUnaryConversions() function is *not* called by this routine. 4248 /// C99 6.3.2.1p[2-4] all state: 4249 /// Except when it is the operand of the sizeof operator ... 4250 /// 4251 /// C++ [expr.sizeof]p4 4252 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4253 /// standard conversions are not applied to the operand of sizeof. 4254 /// 4255 /// This policy is followed for all of the unary trait expressions. 4256 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4257 SourceLocation OpLoc, 4258 SourceRange ExprRange, 4259 UnaryExprOrTypeTrait ExprKind) { 4260 if (ExprType->isDependentType()) 4261 return false; 4262 4263 // C++ [expr.sizeof]p2: 4264 // When applied to a reference or a reference type, the result 4265 // is the size of the referenced type. 4266 // C++11 [expr.alignof]p3: 4267 // When alignof is applied to a reference type, the result 4268 // shall be the alignment of the referenced type. 4269 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4270 ExprType = Ref->getPointeeType(); 4271 4272 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4273 // When alignof or _Alignof is applied to an array type, the result 4274 // is the alignment of the element type. 4275 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4276 ExprKind == UETT_OpenMPRequiredSimdAlign) 4277 ExprType = Context.getBaseElementType(ExprType); 4278 4279 if (ExprKind == UETT_VecStep) 4280 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4281 4282 // Explicitly list some types as extensions. 4283 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4284 ExprKind)) 4285 return false; 4286 4287 if (RequireCompleteSizedType( 4288 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4289 getTraitSpelling(ExprKind), ExprRange)) 4290 return true; 4291 4292 if (ExprType->isFunctionType()) { 4293 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4294 << getTraitSpelling(ExprKind) << ExprRange; 4295 return true; 4296 } 4297 4298 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4299 ExprKind)) 4300 return true; 4301 4302 return false; 4303 } 4304 4305 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4306 // Cannot know anything else if the expression is dependent. 4307 if (E->isTypeDependent()) 4308 return false; 4309 4310 if (E->getObjectKind() == OK_BitField) { 4311 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4312 << 1 << E->getSourceRange(); 4313 return true; 4314 } 4315 4316 ValueDecl *D = nullptr; 4317 Expr *Inner = E->IgnoreParens(); 4318 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4319 D = DRE->getDecl(); 4320 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4321 D = ME->getMemberDecl(); 4322 } 4323 4324 // If it's a field, require the containing struct to have a 4325 // complete definition so that we can compute the layout. 4326 // 4327 // This can happen in C++11 onwards, either by naming the member 4328 // in a way that is not transformed into a member access expression 4329 // (in an unevaluated operand, for instance), or by naming the member 4330 // in a trailing-return-type. 4331 // 4332 // For the record, since __alignof__ on expressions is a GCC 4333 // extension, GCC seems to permit this but always gives the 4334 // nonsensical answer 0. 4335 // 4336 // We don't really need the layout here --- we could instead just 4337 // directly check for all the appropriate alignment-lowing 4338 // attributes --- but that would require duplicating a lot of 4339 // logic that just isn't worth duplicating for such a marginal 4340 // use-case. 4341 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4342 // Fast path this check, since we at least know the record has a 4343 // definition if we can find a member of it. 4344 if (!FD->getParent()->isCompleteDefinition()) { 4345 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4346 << E->getSourceRange(); 4347 return true; 4348 } 4349 4350 // Otherwise, if it's a field, and the field doesn't have 4351 // reference type, then it must have a complete type (or be a 4352 // flexible array member, which we explicitly want to 4353 // white-list anyway), which makes the following checks trivial. 4354 if (!FD->getType()->isReferenceType()) 4355 return false; 4356 } 4357 4358 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4359 } 4360 4361 bool Sema::CheckVecStepExpr(Expr *E) { 4362 E = E->IgnoreParens(); 4363 4364 // Cannot know anything else if the expression is dependent. 4365 if (E->isTypeDependent()) 4366 return false; 4367 4368 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4369 } 4370 4371 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4372 CapturingScopeInfo *CSI) { 4373 assert(T->isVariablyModifiedType()); 4374 assert(CSI != nullptr); 4375 4376 // We're going to walk down into the type and look for VLA expressions. 4377 do { 4378 const Type *Ty = T.getTypePtr(); 4379 switch (Ty->getTypeClass()) { 4380 #define TYPE(Class, Base) 4381 #define ABSTRACT_TYPE(Class, Base) 4382 #define NON_CANONICAL_TYPE(Class, Base) 4383 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4384 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4385 #include "clang/AST/TypeNodes.inc" 4386 T = QualType(); 4387 break; 4388 // These types are never variably-modified. 4389 case Type::Builtin: 4390 case Type::Complex: 4391 case Type::Vector: 4392 case Type::ExtVector: 4393 case Type::ConstantMatrix: 4394 case Type::Record: 4395 case Type::Enum: 4396 case Type::Elaborated: 4397 case Type::TemplateSpecialization: 4398 case Type::ObjCObject: 4399 case Type::ObjCInterface: 4400 case Type::ObjCObjectPointer: 4401 case Type::ObjCTypeParam: 4402 case Type::Pipe: 4403 case Type::ExtInt: 4404 llvm_unreachable("type class is never variably-modified!"); 4405 case Type::Adjusted: 4406 T = cast<AdjustedType>(Ty)->getOriginalType(); 4407 break; 4408 case Type::Decayed: 4409 T = cast<DecayedType>(Ty)->getPointeeType(); 4410 break; 4411 case Type::Pointer: 4412 T = cast<PointerType>(Ty)->getPointeeType(); 4413 break; 4414 case Type::BlockPointer: 4415 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4416 break; 4417 case Type::LValueReference: 4418 case Type::RValueReference: 4419 T = cast<ReferenceType>(Ty)->getPointeeType(); 4420 break; 4421 case Type::MemberPointer: 4422 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4423 break; 4424 case Type::ConstantArray: 4425 case Type::IncompleteArray: 4426 // Losing element qualification here is fine. 4427 T = cast<ArrayType>(Ty)->getElementType(); 4428 break; 4429 case Type::VariableArray: { 4430 // Losing element qualification here is fine. 4431 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4432 4433 // Unknown size indication requires no size computation. 4434 // Otherwise, evaluate and record it. 4435 auto Size = VAT->getSizeExpr(); 4436 if (Size && !CSI->isVLATypeCaptured(VAT) && 4437 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4438 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4439 4440 T = VAT->getElementType(); 4441 break; 4442 } 4443 case Type::FunctionProto: 4444 case Type::FunctionNoProto: 4445 T = cast<FunctionType>(Ty)->getReturnType(); 4446 break; 4447 case Type::Paren: 4448 case Type::TypeOf: 4449 case Type::UnaryTransform: 4450 case Type::Attributed: 4451 case Type::SubstTemplateTypeParm: 4452 case Type::MacroQualified: 4453 // Keep walking after single level desugaring. 4454 T = T.getSingleStepDesugaredType(Context); 4455 break; 4456 case Type::Typedef: 4457 T = cast<TypedefType>(Ty)->desugar(); 4458 break; 4459 case Type::Decltype: 4460 T = cast<DecltypeType>(Ty)->desugar(); 4461 break; 4462 case Type::Auto: 4463 case Type::DeducedTemplateSpecialization: 4464 T = cast<DeducedType>(Ty)->getDeducedType(); 4465 break; 4466 case Type::TypeOfExpr: 4467 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4468 break; 4469 case Type::Atomic: 4470 T = cast<AtomicType>(Ty)->getValueType(); 4471 break; 4472 } 4473 } while (!T.isNull() && T->isVariablyModifiedType()); 4474 } 4475 4476 /// Build a sizeof or alignof expression given a type operand. 4477 ExprResult 4478 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4479 SourceLocation OpLoc, 4480 UnaryExprOrTypeTrait ExprKind, 4481 SourceRange R) { 4482 if (!TInfo) 4483 return ExprError(); 4484 4485 QualType T = TInfo->getType(); 4486 4487 if (!T->isDependentType() && 4488 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4489 return ExprError(); 4490 4491 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4492 if (auto *TT = T->getAs<TypedefType>()) { 4493 for (auto I = FunctionScopes.rbegin(), 4494 E = std::prev(FunctionScopes.rend()); 4495 I != E; ++I) { 4496 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4497 if (CSI == nullptr) 4498 break; 4499 DeclContext *DC = nullptr; 4500 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4501 DC = LSI->CallOperator; 4502 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4503 DC = CRSI->TheCapturedDecl; 4504 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4505 DC = BSI->TheDecl; 4506 if (DC) { 4507 if (DC->containsDecl(TT->getDecl())) 4508 break; 4509 captureVariablyModifiedType(Context, T, CSI); 4510 } 4511 } 4512 } 4513 } 4514 4515 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4516 return new (Context) UnaryExprOrTypeTraitExpr( 4517 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4518 } 4519 4520 /// Build a sizeof or alignof expression given an expression 4521 /// operand. 4522 ExprResult 4523 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4524 UnaryExprOrTypeTrait ExprKind) { 4525 ExprResult PE = CheckPlaceholderExpr(E); 4526 if (PE.isInvalid()) 4527 return ExprError(); 4528 4529 E = PE.get(); 4530 4531 // Verify that the operand is valid. 4532 bool isInvalid = false; 4533 if (E->isTypeDependent()) { 4534 // Delay type-checking for type-dependent expressions. 4535 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4536 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4537 } else if (ExprKind == UETT_VecStep) { 4538 isInvalid = CheckVecStepExpr(E); 4539 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4540 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4541 isInvalid = true; 4542 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4543 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4544 isInvalid = true; 4545 } else { 4546 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4547 } 4548 4549 if (isInvalid) 4550 return ExprError(); 4551 4552 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4553 PE = TransformToPotentiallyEvaluated(E); 4554 if (PE.isInvalid()) return ExprError(); 4555 E = PE.get(); 4556 } 4557 4558 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4559 return new (Context) UnaryExprOrTypeTraitExpr( 4560 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4561 } 4562 4563 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4564 /// expr and the same for @c alignof and @c __alignof 4565 /// Note that the ArgRange is invalid if isType is false. 4566 ExprResult 4567 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4568 UnaryExprOrTypeTrait ExprKind, bool IsType, 4569 void *TyOrEx, SourceRange ArgRange) { 4570 // If error parsing type, ignore. 4571 if (!TyOrEx) return ExprError(); 4572 4573 if (IsType) { 4574 TypeSourceInfo *TInfo; 4575 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4576 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4577 } 4578 4579 Expr *ArgEx = (Expr *)TyOrEx; 4580 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4581 return Result; 4582 } 4583 4584 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4585 bool IsReal) { 4586 if (V.get()->isTypeDependent()) 4587 return S.Context.DependentTy; 4588 4589 // _Real and _Imag are only l-values for normal l-values. 4590 if (V.get()->getObjectKind() != OK_Ordinary) { 4591 V = S.DefaultLvalueConversion(V.get()); 4592 if (V.isInvalid()) 4593 return QualType(); 4594 } 4595 4596 // These operators return the element type of a complex type. 4597 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4598 return CT->getElementType(); 4599 4600 // Otherwise they pass through real integer and floating point types here. 4601 if (V.get()->getType()->isArithmeticType()) 4602 return V.get()->getType(); 4603 4604 // Test for placeholders. 4605 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4606 if (PR.isInvalid()) return QualType(); 4607 if (PR.get() != V.get()) { 4608 V = PR; 4609 return CheckRealImagOperand(S, V, Loc, IsReal); 4610 } 4611 4612 // Reject anything else. 4613 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4614 << (IsReal ? "__real" : "__imag"); 4615 return QualType(); 4616 } 4617 4618 4619 4620 ExprResult 4621 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4622 tok::TokenKind Kind, Expr *Input) { 4623 UnaryOperatorKind Opc; 4624 switch (Kind) { 4625 default: llvm_unreachable("Unknown unary op!"); 4626 case tok::plusplus: Opc = UO_PostInc; break; 4627 case tok::minusminus: Opc = UO_PostDec; break; 4628 } 4629 4630 // Since this might is a postfix expression, get rid of ParenListExprs. 4631 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4632 if (Result.isInvalid()) return ExprError(); 4633 Input = Result.get(); 4634 4635 return BuildUnaryOp(S, OpLoc, Opc, Input); 4636 } 4637 4638 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4639 /// 4640 /// \return true on error 4641 static bool checkArithmeticOnObjCPointer(Sema &S, 4642 SourceLocation opLoc, 4643 Expr *op) { 4644 assert(op->getType()->isObjCObjectPointerType()); 4645 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4646 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4647 return false; 4648 4649 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4650 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4651 << op->getSourceRange(); 4652 return true; 4653 } 4654 4655 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4656 auto *BaseNoParens = Base->IgnoreParens(); 4657 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4658 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4659 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4660 } 4661 4662 ExprResult 4663 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4664 Expr *idx, SourceLocation rbLoc) { 4665 if (base && !base->getType().isNull() && 4666 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4667 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4668 SourceLocation(), /*Length*/ nullptr, 4669 /*Stride=*/nullptr, rbLoc); 4670 4671 // Since this might be a postfix expression, get rid of ParenListExprs. 4672 if (isa<ParenListExpr>(base)) { 4673 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4674 if (result.isInvalid()) return ExprError(); 4675 base = result.get(); 4676 } 4677 4678 // Check if base and idx form a MatrixSubscriptExpr. 4679 // 4680 // Helper to check for comma expressions, which are not allowed as indices for 4681 // matrix subscript expressions. 4682 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4683 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4684 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4685 << SourceRange(base->getBeginLoc(), rbLoc); 4686 return true; 4687 } 4688 return false; 4689 }; 4690 // The matrix subscript operator ([][])is considered a single operator. 4691 // Separating the index expressions by parenthesis is not allowed. 4692 if (base->getType()->isSpecificPlaceholderType( 4693 BuiltinType::IncompleteMatrixIdx) && 4694 !isa<MatrixSubscriptExpr>(base)) { 4695 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4696 << SourceRange(base->getBeginLoc(), rbLoc); 4697 return ExprError(); 4698 } 4699 // If the base is a MatrixSubscriptExpr, try to create a new 4700 // MatrixSubscriptExpr. 4701 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4702 if (matSubscriptE) { 4703 if (CheckAndReportCommaError(idx)) 4704 return ExprError(); 4705 4706 assert(matSubscriptE->isIncomplete() && 4707 "base has to be an incomplete matrix subscript"); 4708 return CreateBuiltinMatrixSubscriptExpr( 4709 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4710 } 4711 4712 // Handle any non-overload placeholder types in the base and index 4713 // expressions. We can't handle overloads here because the other 4714 // operand might be an overloadable type, in which case the overload 4715 // resolution for the operator overload should get the first crack 4716 // at the overload. 4717 bool IsMSPropertySubscript = false; 4718 if (base->getType()->isNonOverloadPlaceholderType()) { 4719 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4720 if (!IsMSPropertySubscript) { 4721 ExprResult result = CheckPlaceholderExpr(base); 4722 if (result.isInvalid()) 4723 return ExprError(); 4724 base = result.get(); 4725 } 4726 } 4727 4728 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4729 if (base->getType()->isMatrixType()) { 4730 if (CheckAndReportCommaError(idx)) 4731 return ExprError(); 4732 4733 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4734 } 4735 4736 // A comma-expression as the index is deprecated in C++2a onwards. 4737 if (getLangOpts().CPlusPlus20 && 4738 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4739 (isa<CXXOperatorCallExpr>(idx) && 4740 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4741 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4742 << SourceRange(base->getBeginLoc(), rbLoc); 4743 } 4744 4745 if (idx->getType()->isNonOverloadPlaceholderType()) { 4746 ExprResult result = CheckPlaceholderExpr(idx); 4747 if (result.isInvalid()) return ExprError(); 4748 idx = result.get(); 4749 } 4750 4751 // Build an unanalyzed expression if either operand is type-dependent. 4752 if (getLangOpts().CPlusPlus && 4753 (base->isTypeDependent() || idx->isTypeDependent())) { 4754 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4755 VK_LValue, OK_Ordinary, rbLoc); 4756 } 4757 4758 // MSDN, property (C++) 4759 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4760 // This attribute can also be used in the declaration of an empty array in a 4761 // class or structure definition. For example: 4762 // __declspec(property(get=GetX, put=PutX)) int x[]; 4763 // The above statement indicates that x[] can be used with one or more array 4764 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4765 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4766 if (IsMSPropertySubscript) { 4767 // Build MS property subscript expression if base is MS property reference 4768 // or MS property subscript. 4769 return new (Context) MSPropertySubscriptExpr( 4770 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4771 } 4772 4773 // Use C++ overloaded-operator rules if either operand has record 4774 // type. The spec says to do this if either type is *overloadable*, 4775 // but enum types can't declare subscript operators or conversion 4776 // operators, so there's nothing interesting for overload resolution 4777 // to do if there aren't any record types involved. 4778 // 4779 // ObjC pointers have their own subscripting logic that is not tied 4780 // to overload resolution and so should not take this path. 4781 if (getLangOpts().CPlusPlus && 4782 (base->getType()->isRecordType() || 4783 (!base->getType()->isObjCObjectPointerType() && 4784 idx->getType()->isRecordType()))) { 4785 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4786 } 4787 4788 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4789 4790 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4791 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4792 4793 return Res; 4794 } 4795 4796 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4797 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4798 InitializationKind Kind = 4799 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4800 InitializationSequence InitSeq(*this, Entity, Kind, E); 4801 return InitSeq.Perform(*this, Entity, Kind, E); 4802 } 4803 4804 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4805 Expr *ColumnIdx, 4806 SourceLocation RBLoc) { 4807 ExprResult BaseR = CheckPlaceholderExpr(Base); 4808 if (BaseR.isInvalid()) 4809 return BaseR; 4810 Base = BaseR.get(); 4811 4812 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4813 if (RowR.isInvalid()) 4814 return RowR; 4815 RowIdx = RowR.get(); 4816 4817 if (!ColumnIdx) 4818 return new (Context) MatrixSubscriptExpr( 4819 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4820 4821 // Build an unanalyzed expression if any of the operands is type-dependent. 4822 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4823 ColumnIdx->isTypeDependent()) 4824 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4825 Context.DependentTy, RBLoc); 4826 4827 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4828 if (ColumnR.isInvalid()) 4829 return ColumnR; 4830 ColumnIdx = ColumnR.get(); 4831 4832 // Check that IndexExpr is an integer expression. If it is a constant 4833 // expression, check that it is less than Dim (= the number of elements in the 4834 // corresponding dimension). 4835 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4836 bool IsColumnIdx) -> Expr * { 4837 if (!IndexExpr->getType()->isIntegerType() && 4838 !IndexExpr->isTypeDependent()) { 4839 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4840 << IsColumnIdx; 4841 return nullptr; 4842 } 4843 4844 if (Optional<llvm::APSInt> Idx = 4845 IndexExpr->getIntegerConstantExpr(Context)) { 4846 if ((*Idx < 0 || *Idx >= Dim)) { 4847 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4848 << IsColumnIdx << Dim; 4849 return nullptr; 4850 } 4851 } 4852 4853 ExprResult ConvExpr = 4854 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4855 assert(!ConvExpr.isInvalid() && 4856 "should be able to convert any integer type to size type"); 4857 return ConvExpr.get(); 4858 }; 4859 4860 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4861 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4862 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4863 if (!RowIdx || !ColumnIdx) 4864 return ExprError(); 4865 4866 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4867 MTy->getElementType(), RBLoc); 4868 } 4869 4870 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4871 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4872 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4873 4874 // For expressions like `&(*s).b`, the base is recorded and what should be 4875 // checked. 4876 const MemberExpr *Member = nullptr; 4877 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4878 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4879 4880 LastRecord.PossibleDerefs.erase(StrippedExpr); 4881 } 4882 4883 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4884 if (isUnevaluatedContext()) 4885 return; 4886 4887 QualType ResultTy = E->getType(); 4888 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4889 4890 // Bail if the element is an array since it is not memory access. 4891 if (isa<ArrayType>(ResultTy)) 4892 return; 4893 4894 if (ResultTy->hasAttr(attr::NoDeref)) { 4895 LastRecord.PossibleDerefs.insert(E); 4896 return; 4897 } 4898 4899 // Check if the base type is a pointer to a member access of a struct 4900 // marked with noderef. 4901 const Expr *Base = E->getBase(); 4902 QualType BaseTy = Base->getType(); 4903 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4904 // Not a pointer access 4905 return; 4906 4907 const MemberExpr *Member = nullptr; 4908 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4909 Member->isArrow()) 4910 Base = Member->getBase(); 4911 4912 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4913 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4914 LastRecord.PossibleDerefs.insert(E); 4915 } 4916 } 4917 4918 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4919 Expr *LowerBound, 4920 SourceLocation ColonLocFirst, 4921 SourceLocation ColonLocSecond, 4922 Expr *Length, Expr *Stride, 4923 SourceLocation RBLoc) { 4924 if (Base->getType()->isPlaceholderType() && 4925 !Base->getType()->isSpecificPlaceholderType( 4926 BuiltinType::OMPArraySection)) { 4927 ExprResult Result = CheckPlaceholderExpr(Base); 4928 if (Result.isInvalid()) 4929 return ExprError(); 4930 Base = Result.get(); 4931 } 4932 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4933 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4934 if (Result.isInvalid()) 4935 return ExprError(); 4936 Result = DefaultLvalueConversion(Result.get()); 4937 if (Result.isInvalid()) 4938 return ExprError(); 4939 LowerBound = Result.get(); 4940 } 4941 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4942 ExprResult Result = CheckPlaceholderExpr(Length); 4943 if (Result.isInvalid()) 4944 return ExprError(); 4945 Result = DefaultLvalueConversion(Result.get()); 4946 if (Result.isInvalid()) 4947 return ExprError(); 4948 Length = Result.get(); 4949 } 4950 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4951 ExprResult Result = CheckPlaceholderExpr(Stride); 4952 if (Result.isInvalid()) 4953 return ExprError(); 4954 Result = DefaultLvalueConversion(Result.get()); 4955 if (Result.isInvalid()) 4956 return ExprError(); 4957 Stride = Result.get(); 4958 } 4959 4960 // Build an unanalyzed expression if either operand is type-dependent. 4961 if (Base->isTypeDependent() || 4962 (LowerBound && 4963 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4964 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4965 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4966 return new (Context) OMPArraySectionExpr( 4967 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4968 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4969 } 4970 4971 // Perform default conversions. 4972 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4973 QualType ResultTy; 4974 if (OriginalTy->isAnyPointerType()) { 4975 ResultTy = OriginalTy->getPointeeType(); 4976 } else if (OriginalTy->isArrayType()) { 4977 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4978 } else { 4979 return ExprError( 4980 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4981 << Base->getSourceRange()); 4982 } 4983 // C99 6.5.2.1p1 4984 if (LowerBound) { 4985 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4986 LowerBound); 4987 if (Res.isInvalid()) 4988 return ExprError(Diag(LowerBound->getExprLoc(), 4989 diag::err_omp_typecheck_section_not_integer) 4990 << 0 << LowerBound->getSourceRange()); 4991 LowerBound = Res.get(); 4992 4993 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4994 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4995 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4996 << 0 << LowerBound->getSourceRange(); 4997 } 4998 if (Length) { 4999 auto Res = 5000 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5001 if (Res.isInvalid()) 5002 return ExprError(Diag(Length->getExprLoc(), 5003 diag::err_omp_typecheck_section_not_integer) 5004 << 1 << Length->getSourceRange()); 5005 Length = Res.get(); 5006 5007 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5008 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5009 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5010 << 1 << Length->getSourceRange(); 5011 } 5012 if (Stride) { 5013 ExprResult Res = 5014 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5015 if (Res.isInvalid()) 5016 return ExprError(Diag(Stride->getExprLoc(), 5017 diag::err_omp_typecheck_section_not_integer) 5018 << 1 << Stride->getSourceRange()); 5019 Stride = Res.get(); 5020 5021 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5022 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5023 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5024 << 1 << Stride->getSourceRange(); 5025 } 5026 5027 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5028 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5029 // type. Note that functions are not objects, and that (in C99 parlance) 5030 // incomplete types are not object types. 5031 if (ResultTy->isFunctionType()) { 5032 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5033 << ResultTy << Base->getSourceRange(); 5034 return ExprError(); 5035 } 5036 5037 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5038 diag::err_omp_section_incomplete_type, Base)) 5039 return ExprError(); 5040 5041 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5042 Expr::EvalResult Result; 5043 if (LowerBound->EvaluateAsInt(Result, Context)) { 5044 // OpenMP 5.0, [2.1.5 Array Sections] 5045 // The array section must be a subset of the original array. 5046 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5047 if (LowerBoundValue.isNegative()) { 5048 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5049 << LowerBound->getSourceRange(); 5050 return ExprError(); 5051 } 5052 } 5053 } 5054 5055 if (Length) { 5056 Expr::EvalResult Result; 5057 if (Length->EvaluateAsInt(Result, Context)) { 5058 // OpenMP 5.0, [2.1.5 Array Sections] 5059 // The length must evaluate to non-negative integers. 5060 llvm::APSInt LengthValue = Result.Val.getInt(); 5061 if (LengthValue.isNegative()) { 5062 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5063 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5064 << Length->getSourceRange(); 5065 return ExprError(); 5066 } 5067 } 5068 } else if (ColonLocFirst.isValid() && 5069 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5070 !OriginalTy->isVariableArrayType()))) { 5071 // OpenMP 5.0, [2.1.5 Array Sections] 5072 // When the size of the array dimension is not known, the length must be 5073 // specified explicitly. 5074 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5075 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5076 return ExprError(); 5077 } 5078 5079 if (Stride) { 5080 Expr::EvalResult Result; 5081 if (Stride->EvaluateAsInt(Result, Context)) { 5082 // OpenMP 5.0, [2.1.5 Array Sections] 5083 // The stride must evaluate to a positive integer. 5084 llvm::APSInt StrideValue = Result.Val.getInt(); 5085 if (!StrideValue.isStrictlyPositive()) { 5086 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5087 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5088 << Stride->getSourceRange(); 5089 return ExprError(); 5090 } 5091 } 5092 } 5093 5094 if (!Base->getType()->isSpecificPlaceholderType( 5095 BuiltinType::OMPArraySection)) { 5096 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5097 if (Result.isInvalid()) 5098 return ExprError(); 5099 Base = Result.get(); 5100 } 5101 return new (Context) OMPArraySectionExpr( 5102 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5103 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5104 } 5105 5106 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5107 SourceLocation RParenLoc, 5108 ArrayRef<Expr *> Dims, 5109 ArrayRef<SourceRange> Brackets) { 5110 if (Base->getType()->isPlaceholderType()) { 5111 ExprResult Result = CheckPlaceholderExpr(Base); 5112 if (Result.isInvalid()) 5113 return ExprError(); 5114 Result = DefaultLvalueConversion(Result.get()); 5115 if (Result.isInvalid()) 5116 return ExprError(); 5117 Base = Result.get(); 5118 } 5119 QualType BaseTy = Base->getType(); 5120 // Delay analysis of the types/expressions if instantiation/specialization is 5121 // required. 5122 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5123 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5124 LParenLoc, RParenLoc, Dims, Brackets); 5125 if (!BaseTy->isPointerType() || 5126 (!Base->isTypeDependent() && 5127 BaseTy->getPointeeType()->isIncompleteType())) 5128 return ExprError(Diag(Base->getExprLoc(), 5129 diag::err_omp_non_pointer_type_array_shaping_base) 5130 << Base->getSourceRange()); 5131 5132 SmallVector<Expr *, 4> NewDims; 5133 bool ErrorFound = false; 5134 for (Expr *Dim : Dims) { 5135 if (Dim->getType()->isPlaceholderType()) { 5136 ExprResult Result = CheckPlaceholderExpr(Dim); 5137 if (Result.isInvalid()) { 5138 ErrorFound = true; 5139 continue; 5140 } 5141 Result = DefaultLvalueConversion(Result.get()); 5142 if (Result.isInvalid()) { 5143 ErrorFound = true; 5144 continue; 5145 } 5146 Dim = Result.get(); 5147 } 5148 if (!Dim->isTypeDependent()) { 5149 ExprResult Result = 5150 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5151 if (Result.isInvalid()) { 5152 ErrorFound = true; 5153 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5154 << Dim->getSourceRange(); 5155 continue; 5156 } 5157 Dim = Result.get(); 5158 Expr::EvalResult EvResult; 5159 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5160 // OpenMP 5.0, [2.1.4 Array Shaping] 5161 // Each si is an integral type expression that must evaluate to a 5162 // positive integer. 5163 llvm::APSInt Value = EvResult.Val.getInt(); 5164 if (!Value.isStrictlyPositive()) { 5165 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5166 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5167 << Dim->getSourceRange(); 5168 ErrorFound = true; 5169 continue; 5170 } 5171 } 5172 } 5173 NewDims.push_back(Dim); 5174 } 5175 if (ErrorFound) 5176 return ExprError(); 5177 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5178 LParenLoc, RParenLoc, NewDims, Brackets); 5179 } 5180 5181 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5182 SourceLocation LLoc, SourceLocation RLoc, 5183 ArrayRef<OMPIteratorData> Data) { 5184 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5185 bool IsCorrect = true; 5186 for (const OMPIteratorData &D : Data) { 5187 TypeSourceInfo *TInfo = nullptr; 5188 SourceLocation StartLoc; 5189 QualType DeclTy; 5190 if (!D.Type.getAsOpaquePtr()) { 5191 // OpenMP 5.0, 2.1.6 Iterators 5192 // In an iterator-specifier, if the iterator-type is not specified then 5193 // the type of that iterator is of int type. 5194 DeclTy = Context.IntTy; 5195 StartLoc = D.DeclIdentLoc; 5196 } else { 5197 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5198 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5199 } 5200 5201 bool IsDeclTyDependent = DeclTy->isDependentType() || 5202 DeclTy->containsUnexpandedParameterPack() || 5203 DeclTy->isInstantiationDependentType(); 5204 if (!IsDeclTyDependent) { 5205 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5206 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5207 // The iterator-type must be an integral or pointer type. 5208 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5209 << DeclTy; 5210 IsCorrect = false; 5211 continue; 5212 } 5213 if (DeclTy.isConstant(Context)) { 5214 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5215 // The iterator-type must not be const qualified. 5216 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5217 << DeclTy; 5218 IsCorrect = false; 5219 continue; 5220 } 5221 } 5222 5223 // Iterator declaration. 5224 assert(D.DeclIdent && "Identifier expected."); 5225 // Always try to create iterator declarator to avoid extra error messages 5226 // about unknown declarations use. 5227 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5228 D.DeclIdent, DeclTy, TInfo, SC_None); 5229 VD->setImplicit(); 5230 if (S) { 5231 // Check for conflicting previous declaration. 5232 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5233 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5234 ForVisibleRedeclaration); 5235 Previous.suppressDiagnostics(); 5236 LookupName(Previous, S); 5237 5238 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5239 /*AllowInlineNamespace=*/false); 5240 if (!Previous.empty()) { 5241 NamedDecl *Old = Previous.getRepresentativeDecl(); 5242 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5243 Diag(Old->getLocation(), diag::note_previous_definition); 5244 } else { 5245 PushOnScopeChains(VD, S); 5246 } 5247 } else { 5248 CurContext->addDecl(VD); 5249 } 5250 Expr *Begin = D.Range.Begin; 5251 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5252 ExprResult BeginRes = 5253 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5254 Begin = BeginRes.get(); 5255 } 5256 Expr *End = D.Range.End; 5257 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5258 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5259 End = EndRes.get(); 5260 } 5261 Expr *Step = D.Range.Step; 5262 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5263 if (!Step->getType()->isIntegralType(Context)) { 5264 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5265 << Step << Step->getSourceRange(); 5266 IsCorrect = false; 5267 continue; 5268 } 5269 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5270 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5271 // If the step expression of a range-specification equals zero, the 5272 // behavior is unspecified. 5273 if (Result && Result->isNullValue()) { 5274 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5275 << Step << Step->getSourceRange(); 5276 IsCorrect = false; 5277 continue; 5278 } 5279 } 5280 if (!Begin || !End || !IsCorrect) { 5281 IsCorrect = false; 5282 continue; 5283 } 5284 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5285 IDElem.IteratorDecl = VD; 5286 IDElem.AssignmentLoc = D.AssignLoc; 5287 IDElem.Range.Begin = Begin; 5288 IDElem.Range.End = End; 5289 IDElem.Range.Step = Step; 5290 IDElem.ColonLoc = D.ColonLoc; 5291 IDElem.SecondColonLoc = D.SecColonLoc; 5292 } 5293 if (!IsCorrect) { 5294 // Invalidate all created iterator declarations if error is found. 5295 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5296 if (Decl *ID = D.IteratorDecl) 5297 ID->setInvalidDecl(); 5298 } 5299 return ExprError(); 5300 } 5301 SmallVector<OMPIteratorHelperData, 4> Helpers; 5302 if (!CurContext->isDependentContext()) { 5303 // Build number of ityeration for each iteration range. 5304 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5305 // ((Begini-Stepi-1-Endi) / -Stepi); 5306 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5307 // (Endi - Begini) 5308 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5309 D.Range.Begin); 5310 if(!Res.isUsable()) { 5311 IsCorrect = false; 5312 continue; 5313 } 5314 ExprResult St, St1; 5315 if (D.Range.Step) { 5316 St = D.Range.Step; 5317 // (Endi - Begini) + Stepi 5318 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5319 if (!Res.isUsable()) { 5320 IsCorrect = false; 5321 continue; 5322 } 5323 // (Endi - Begini) + Stepi - 1 5324 Res = 5325 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5326 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5327 if (!Res.isUsable()) { 5328 IsCorrect = false; 5329 continue; 5330 } 5331 // ((Endi - Begini) + Stepi - 1) / Stepi 5332 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5333 if (!Res.isUsable()) { 5334 IsCorrect = false; 5335 continue; 5336 } 5337 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5338 // (Begini - Endi) 5339 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5340 D.Range.Begin, D.Range.End); 5341 if (!Res1.isUsable()) { 5342 IsCorrect = false; 5343 continue; 5344 } 5345 // (Begini - Endi) - Stepi 5346 Res1 = 5347 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5348 if (!Res1.isUsable()) { 5349 IsCorrect = false; 5350 continue; 5351 } 5352 // (Begini - Endi) - Stepi - 1 5353 Res1 = 5354 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5355 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5356 if (!Res1.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5361 Res1 = 5362 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5363 if (!Res1.isUsable()) { 5364 IsCorrect = false; 5365 continue; 5366 } 5367 // Stepi > 0. 5368 ExprResult CmpRes = 5369 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5370 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5371 if (!CmpRes.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5376 Res.get(), Res1.get()); 5377 if (!Res.isUsable()) { 5378 IsCorrect = false; 5379 continue; 5380 } 5381 } 5382 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5383 if (!Res.isUsable()) { 5384 IsCorrect = false; 5385 continue; 5386 } 5387 5388 // Build counter update. 5389 // Build counter. 5390 auto *CounterVD = 5391 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5392 D.IteratorDecl->getBeginLoc(), nullptr, 5393 Res.get()->getType(), nullptr, SC_None); 5394 CounterVD->setImplicit(); 5395 ExprResult RefRes = 5396 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5397 D.IteratorDecl->getBeginLoc()); 5398 // Build counter update. 5399 // I = Begini + counter * Stepi; 5400 ExprResult UpdateRes; 5401 if (D.Range.Step) { 5402 UpdateRes = CreateBuiltinBinOp( 5403 D.AssignmentLoc, BO_Mul, 5404 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5405 } else { 5406 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5407 } 5408 if (!UpdateRes.isUsable()) { 5409 IsCorrect = false; 5410 continue; 5411 } 5412 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5413 UpdateRes.get()); 5414 if (!UpdateRes.isUsable()) { 5415 IsCorrect = false; 5416 continue; 5417 } 5418 ExprResult VDRes = 5419 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5420 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5421 D.IteratorDecl->getBeginLoc()); 5422 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5423 UpdateRes.get()); 5424 if (!UpdateRes.isUsable()) { 5425 IsCorrect = false; 5426 continue; 5427 } 5428 UpdateRes = 5429 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5430 if (!UpdateRes.isUsable()) { 5431 IsCorrect = false; 5432 continue; 5433 } 5434 ExprResult CounterUpdateRes = 5435 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5436 if (!CounterUpdateRes.isUsable()) { 5437 IsCorrect = false; 5438 continue; 5439 } 5440 CounterUpdateRes = 5441 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5442 if (!CounterUpdateRes.isUsable()) { 5443 IsCorrect = false; 5444 continue; 5445 } 5446 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5447 HD.CounterVD = CounterVD; 5448 HD.Upper = Res.get(); 5449 HD.Update = UpdateRes.get(); 5450 HD.CounterUpdate = CounterUpdateRes.get(); 5451 } 5452 } else { 5453 Helpers.assign(ID.size(), {}); 5454 } 5455 if (!IsCorrect) { 5456 // Invalidate all created iterator declarations if error is found. 5457 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5458 if (Decl *ID = D.IteratorDecl) 5459 ID->setInvalidDecl(); 5460 } 5461 return ExprError(); 5462 } 5463 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5464 LLoc, RLoc, ID, Helpers); 5465 } 5466 5467 ExprResult 5468 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5469 Expr *Idx, SourceLocation RLoc) { 5470 Expr *LHSExp = Base; 5471 Expr *RHSExp = Idx; 5472 5473 ExprValueKind VK = VK_LValue; 5474 ExprObjectKind OK = OK_Ordinary; 5475 5476 // Per C++ core issue 1213, the result is an xvalue if either operand is 5477 // a non-lvalue array, and an lvalue otherwise. 5478 if (getLangOpts().CPlusPlus11) { 5479 for (auto *Op : {LHSExp, RHSExp}) { 5480 Op = Op->IgnoreImplicit(); 5481 if (Op->getType()->isArrayType() && !Op->isLValue()) 5482 VK = VK_XValue; 5483 } 5484 } 5485 5486 // Perform default conversions. 5487 if (!LHSExp->getType()->getAs<VectorType>()) { 5488 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5489 if (Result.isInvalid()) 5490 return ExprError(); 5491 LHSExp = Result.get(); 5492 } 5493 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5494 if (Result.isInvalid()) 5495 return ExprError(); 5496 RHSExp = Result.get(); 5497 5498 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5499 5500 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5501 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5502 // in the subscript position. As a result, we need to derive the array base 5503 // and index from the expression types. 5504 Expr *BaseExpr, *IndexExpr; 5505 QualType ResultType; 5506 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5507 BaseExpr = LHSExp; 5508 IndexExpr = RHSExp; 5509 ResultType = Context.DependentTy; 5510 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5511 BaseExpr = LHSExp; 5512 IndexExpr = RHSExp; 5513 ResultType = PTy->getPointeeType(); 5514 } else if (const ObjCObjectPointerType *PTy = 5515 LHSTy->getAs<ObjCObjectPointerType>()) { 5516 BaseExpr = LHSExp; 5517 IndexExpr = RHSExp; 5518 5519 // Use custom logic if this should be the pseudo-object subscript 5520 // expression. 5521 if (!LangOpts.isSubscriptPointerArithmetic()) 5522 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5523 nullptr); 5524 5525 ResultType = PTy->getPointeeType(); 5526 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5527 // Handle the uncommon case of "123[Ptr]". 5528 BaseExpr = RHSExp; 5529 IndexExpr = LHSExp; 5530 ResultType = PTy->getPointeeType(); 5531 } else if (const ObjCObjectPointerType *PTy = 5532 RHSTy->getAs<ObjCObjectPointerType>()) { 5533 // Handle the uncommon case of "123[Ptr]". 5534 BaseExpr = RHSExp; 5535 IndexExpr = LHSExp; 5536 ResultType = PTy->getPointeeType(); 5537 if (!LangOpts.isSubscriptPointerArithmetic()) { 5538 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5539 << ResultType << BaseExpr->getSourceRange(); 5540 return ExprError(); 5541 } 5542 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5543 BaseExpr = LHSExp; // vectors: V[123] 5544 IndexExpr = RHSExp; 5545 // We apply C++ DR1213 to vector subscripting too. 5546 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_PRValue) { 5547 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5548 if (Materialized.isInvalid()) 5549 return ExprError(); 5550 LHSExp = Materialized.get(); 5551 } 5552 VK = LHSExp->getValueKind(); 5553 if (VK != VK_PRValue) 5554 OK = OK_VectorComponent; 5555 5556 ResultType = VTy->getElementType(); 5557 QualType BaseType = BaseExpr->getType(); 5558 Qualifiers BaseQuals = BaseType.getQualifiers(); 5559 Qualifiers MemberQuals = ResultType.getQualifiers(); 5560 Qualifiers Combined = BaseQuals + MemberQuals; 5561 if (Combined != MemberQuals) 5562 ResultType = Context.getQualifiedType(ResultType, Combined); 5563 } else if (LHSTy->isArrayType()) { 5564 // If we see an array that wasn't promoted by 5565 // DefaultFunctionArrayLvalueConversion, it must be an array that 5566 // wasn't promoted because of the C90 rule that doesn't 5567 // allow promoting non-lvalue arrays. Warn, then 5568 // force the promotion here. 5569 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5570 << LHSExp->getSourceRange(); 5571 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5572 CK_ArrayToPointerDecay).get(); 5573 LHSTy = LHSExp->getType(); 5574 5575 BaseExpr = LHSExp; 5576 IndexExpr = RHSExp; 5577 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5578 } else if (RHSTy->isArrayType()) { 5579 // Same as previous, except for 123[f().a] case 5580 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5581 << RHSExp->getSourceRange(); 5582 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5583 CK_ArrayToPointerDecay).get(); 5584 RHSTy = RHSExp->getType(); 5585 5586 BaseExpr = RHSExp; 5587 IndexExpr = LHSExp; 5588 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5589 } else { 5590 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5591 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5592 } 5593 // C99 6.5.2.1p1 5594 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5595 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5596 << IndexExpr->getSourceRange()); 5597 5598 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5599 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5600 && !IndexExpr->isTypeDependent()) 5601 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5602 5603 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5604 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5605 // type. Note that Functions are not objects, and that (in C99 parlance) 5606 // incomplete types are not object types. 5607 if (ResultType->isFunctionType()) { 5608 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5609 << ResultType << BaseExpr->getSourceRange(); 5610 return ExprError(); 5611 } 5612 5613 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5614 // GNU extension: subscripting on pointer to void 5615 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5616 << BaseExpr->getSourceRange(); 5617 5618 // C forbids expressions of unqualified void type from being l-values. 5619 // See IsCForbiddenLValueType. 5620 if (!ResultType.hasQualifiers()) 5621 VK = VK_PRValue; 5622 } else if (!ResultType->isDependentType() && 5623 RequireCompleteSizedType( 5624 LLoc, ResultType, 5625 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5626 return ExprError(); 5627 5628 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5629 !ResultType.isCForbiddenLValueType()); 5630 5631 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5632 FunctionScopes.size() > 1) { 5633 if (auto *TT = 5634 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5635 for (auto I = FunctionScopes.rbegin(), 5636 E = std::prev(FunctionScopes.rend()); 5637 I != E; ++I) { 5638 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5639 if (CSI == nullptr) 5640 break; 5641 DeclContext *DC = nullptr; 5642 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5643 DC = LSI->CallOperator; 5644 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5645 DC = CRSI->TheCapturedDecl; 5646 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5647 DC = BSI->TheDecl; 5648 if (DC) { 5649 if (DC->containsDecl(TT->getDecl())) 5650 break; 5651 captureVariablyModifiedType( 5652 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5653 } 5654 } 5655 } 5656 } 5657 5658 return new (Context) 5659 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5660 } 5661 5662 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5663 ParmVarDecl *Param) { 5664 if (Param->hasUnparsedDefaultArg()) { 5665 // If we've already cleared out the location for the default argument, 5666 // that means we're parsing it right now. 5667 if (!UnparsedDefaultArgLocs.count(Param)) { 5668 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5669 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5670 Param->setInvalidDecl(); 5671 return true; 5672 } 5673 5674 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5675 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5676 Diag(UnparsedDefaultArgLocs[Param], 5677 diag::note_default_argument_declared_here); 5678 return true; 5679 } 5680 5681 if (Param->hasUninstantiatedDefaultArg() && 5682 InstantiateDefaultArgument(CallLoc, FD, Param)) 5683 return true; 5684 5685 assert(Param->hasInit() && "default argument but no initializer?"); 5686 5687 // If the default expression creates temporaries, we need to 5688 // push them to the current stack of expression temporaries so they'll 5689 // be properly destroyed. 5690 // FIXME: We should really be rebuilding the default argument with new 5691 // bound temporaries; see the comment in PR5810. 5692 // We don't need to do that with block decls, though, because 5693 // blocks in default argument expression can never capture anything. 5694 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5695 // Set the "needs cleanups" bit regardless of whether there are 5696 // any explicit objects. 5697 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5698 5699 // Append all the objects to the cleanup list. Right now, this 5700 // should always be a no-op, because blocks in default argument 5701 // expressions should never be able to capture anything. 5702 assert(!Init->getNumObjects() && 5703 "default argument expression has capturing blocks?"); 5704 } 5705 5706 // We already type-checked the argument, so we know it works. 5707 // Just mark all of the declarations in this potentially-evaluated expression 5708 // as being "referenced". 5709 EnterExpressionEvaluationContext EvalContext( 5710 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5711 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5712 /*SkipLocalVariables=*/true); 5713 return false; 5714 } 5715 5716 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5717 FunctionDecl *FD, ParmVarDecl *Param) { 5718 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5719 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5720 return ExprError(); 5721 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5722 } 5723 5724 Sema::VariadicCallType 5725 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5726 Expr *Fn) { 5727 if (Proto && Proto->isVariadic()) { 5728 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5729 return VariadicConstructor; 5730 else if (Fn && Fn->getType()->isBlockPointerType()) 5731 return VariadicBlock; 5732 else if (FDecl) { 5733 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5734 if (Method->isInstance()) 5735 return VariadicMethod; 5736 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5737 return VariadicMethod; 5738 return VariadicFunction; 5739 } 5740 return VariadicDoesNotApply; 5741 } 5742 5743 namespace { 5744 class FunctionCallCCC final : public FunctionCallFilterCCC { 5745 public: 5746 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5747 unsigned NumArgs, MemberExpr *ME) 5748 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5749 FunctionName(FuncName) {} 5750 5751 bool ValidateCandidate(const TypoCorrection &candidate) override { 5752 if (!candidate.getCorrectionSpecifier() || 5753 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5754 return false; 5755 } 5756 5757 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5758 } 5759 5760 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5761 return std::make_unique<FunctionCallCCC>(*this); 5762 } 5763 5764 private: 5765 const IdentifierInfo *const FunctionName; 5766 }; 5767 } 5768 5769 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5770 FunctionDecl *FDecl, 5771 ArrayRef<Expr *> Args) { 5772 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5773 DeclarationName FuncName = FDecl->getDeclName(); 5774 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5775 5776 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5777 if (TypoCorrection Corrected = S.CorrectTypo( 5778 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5779 S.getScopeForContext(S.CurContext), nullptr, CCC, 5780 Sema::CTK_ErrorRecovery)) { 5781 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5782 if (Corrected.isOverloaded()) { 5783 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5784 OverloadCandidateSet::iterator Best; 5785 for (NamedDecl *CD : Corrected) { 5786 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5787 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5788 OCS); 5789 } 5790 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5791 case OR_Success: 5792 ND = Best->FoundDecl; 5793 Corrected.setCorrectionDecl(ND); 5794 break; 5795 default: 5796 break; 5797 } 5798 } 5799 ND = ND->getUnderlyingDecl(); 5800 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5801 return Corrected; 5802 } 5803 } 5804 return TypoCorrection(); 5805 } 5806 5807 /// ConvertArgumentsForCall - Converts the arguments specified in 5808 /// Args/NumArgs to the parameter types of the function FDecl with 5809 /// function prototype Proto. Call is the call expression itself, and 5810 /// Fn is the function expression. For a C++ member function, this 5811 /// routine does not attempt to convert the object argument. Returns 5812 /// true if the call is ill-formed. 5813 bool 5814 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5815 FunctionDecl *FDecl, 5816 const FunctionProtoType *Proto, 5817 ArrayRef<Expr *> Args, 5818 SourceLocation RParenLoc, 5819 bool IsExecConfig) { 5820 // Bail out early if calling a builtin with custom typechecking. 5821 if (FDecl) 5822 if (unsigned ID = FDecl->getBuiltinID()) 5823 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5824 return false; 5825 5826 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5827 // assignment, to the types of the corresponding parameter, ... 5828 unsigned NumParams = Proto->getNumParams(); 5829 bool Invalid = false; 5830 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5831 unsigned FnKind = Fn->getType()->isBlockPointerType() 5832 ? 1 /* block */ 5833 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5834 : 0 /* function */); 5835 5836 // If too few arguments are available (and we don't have default 5837 // arguments for the remaining parameters), don't make the call. 5838 if (Args.size() < NumParams) { 5839 if (Args.size() < MinArgs) { 5840 TypoCorrection TC; 5841 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5842 unsigned diag_id = 5843 MinArgs == NumParams && !Proto->isVariadic() 5844 ? diag::err_typecheck_call_too_few_args_suggest 5845 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5846 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5847 << static_cast<unsigned>(Args.size()) 5848 << TC.getCorrectionRange()); 5849 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5850 Diag(RParenLoc, 5851 MinArgs == NumParams && !Proto->isVariadic() 5852 ? diag::err_typecheck_call_too_few_args_one 5853 : diag::err_typecheck_call_too_few_args_at_least_one) 5854 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5855 else 5856 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5857 ? diag::err_typecheck_call_too_few_args 5858 : diag::err_typecheck_call_too_few_args_at_least) 5859 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5860 << Fn->getSourceRange(); 5861 5862 // Emit the location of the prototype. 5863 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5864 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5865 5866 return true; 5867 } 5868 // We reserve space for the default arguments when we create 5869 // the call expression, before calling ConvertArgumentsForCall. 5870 assert((Call->getNumArgs() == NumParams) && 5871 "We should have reserved space for the default arguments before!"); 5872 } 5873 5874 // If too many are passed and not variadic, error on the extras and drop 5875 // them. 5876 if (Args.size() > NumParams) { 5877 if (!Proto->isVariadic()) { 5878 TypoCorrection TC; 5879 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5880 unsigned diag_id = 5881 MinArgs == NumParams && !Proto->isVariadic() 5882 ? diag::err_typecheck_call_too_many_args_suggest 5883 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5884 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5885 << static_cast<unsigned>(Args.size()) 5886 << TC.getCorrectionRange()); 5887 } else if (NumParams == 1 && FDecl && 5888 FDecl->getParamDecl(0)->getDeclName()) 5889 Diag(Args[NumParams]->getBeginLoc(), 5890 MinArgs == NumParams 5891 ? diag::err_typecheck_call_too_many_args_one 5892 : diag::err_typecheck_call_too_many_args_at_most_one) 5893 << FnKind << FDecl->getParamDecl(0) 5894 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5895 << SourceRange(Args[NumParams]->getBeginLoc(), 5896 Args.back()->getEndLoc()); 5897 else 5898 Diag(Args[NumParams]->getBeginLoc(), 5899 MinArgs == NumParams 5900 ? diag::err_typecheck_call_too_many_args 5901 : diag::err_typecheck_call_too_many_args_at_most) 5902 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5903 << Fn->getSourceRange() 5904 << SourceRange(Args[NumParams]->getBeginLoc(), 5905 Args.back()->getEndLoc()); 5906 5907 // Emit the location of the prototype. 5908 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5909 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5910 5911 // This deletes the extra arguments. 5912 Call->shrinkNumArgs(NumParams); 5913 return true; 5914 } 5915 } 5916 SmallVector<Expr *, 8> AllArgs; 5917 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5918 5919 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5920 AllArgs, CallType); 5921 if (Invalid) 5922 return true; 5923 unsigned TotalNumArgs = AllArgs.size(); 5924 for (unsigned i = 0; i < TotalNumArgs; ++i) 5925 Call->setArg(i, AllArgs[i]); 5926 5927 return false; 5928 } 5929 5930 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5931 const FunctionProtoType *Proto, 5932 unsigned FirstParam, ArrayRef<Expr *> Args, 5933 SmallVectorImpl<Expr *> &AllArgs, 5934 VariadicCallType CallType, bool AllowExplicit, 5935 bool IsListInitialization) { 5936 unsigned NumParams = Proto->getNumParams(); 5937 bool Invalid = false; 5938 size_t ArgIx = 0; 5939 // Continue to check argument types (even if we have too few/many args). 5940 for (unsigned i = FirstParam; i < NumParams; i++) { 5941 QualType ProtoArgType = Proto->getParamType(i); 5942 5943 Expr *Arg; 5944 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5945 if (ArgIx < Args.size()) { 5946 Arg = Args[ArgIx++]; 5947 5948 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5949 diag::err_call_incomplete_argument, Arg)) 5950 return true; 5951 5952 // Strip the unbridged-cast placeholder expression off, if applicable. 5953 bool CFAudited = false; 5954 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5955 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5956 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5957 Arg = stripARCUnbridgedCast(Arg); 5958 else if (getLangOpts().ObjCAutoRefCount && 5959 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5960 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5961 CFAudited = true; 5962 5963 if (Proto->getExtParameterInfo(i).isNoEscape() && 5964 ProtoArgType->isBlockPointerType()) 5965 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5966 BE->getBlockDecl()->setDoesNotEscape(); 5967 5968 InitializedEntity Entity = 5969 Param ? InitializedEntity::InitializeParameter(Context, Param, 5970 ProtoArgType) 5971 : InitializedEntity::InitializeParameter( 5972 Context, ProtoArgType, Proto->isParamConsumed(i)); 5973 5974 // Remember that parameter belongs to a CF audited API. 5975 if (CFAudited) 5976 Entity.setParameterCFAudited(); 5977 5978 ExprResult ArgE = PerformCopyInitialization( 5979 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5980 if (ArgE.isInvalid()) 5981 return true; 5982 5983 Arg = ArgE.getAs<Expr>(); 5984 } else { 5985 assert(Param && "can't use default arguments without a known callee"); 5986 5987 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5988 if (ArgExpr.isInvalid()) 5989 return true; 5990 5991 Arg = ArgExpr.getAs<Expr>(); 5992 } 5993 5994 // Check for array bounds violations for each argument to the call. This 5995 // check only triggers warnings when the argument isn't a more complex Expr 5996 // with its own checking, such as a BinaryOperator. 5997 CheckArrayAccess(Arg); 5998 5999 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6000 CheckStaticArrayArgument(CallLoc, Param, Arg); 6001 6002 AllArgs.push_back(Arg); 6003 } 6004 6005 // If this is a variadic call, handle args passed through "...". 6006 if (CallType != VariadicDoesNotApply) { 6007 // Assume that extern "C" functions with variadic arguments that 6008 // return __unknown_anytype aren't *really* variadic. 6009 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6010 FDecl->isExternC()) { 6011 for (Expr *A : Args.slice(ArgIx)) { 6012 QualType paramType; // ignored 6013 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6014 Invalid |= arg.isInvalid(); 6015 AllArgs.push_back(arg.get()); 6016 } 6017 6018 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6019 } else { 6020 for (Expr *A : Args.slice(ArgIx)) { 6021 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6022 Invalid |= Arg.isInvalid(); 6023 AllArgs.push_back(Arg.get()); 6024 } 6025 } 6026 6027 // Check for array bounds violations. 6028 for (Expr *A : Args.slice(ArgIx)) 6029 CheckArrayAccess(A); 6030 } 6031 return Invalid; 6032 } 6033 6034 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6035 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6036 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6037 TL = DTL.getOriginalLoc(); 6038 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6039 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6040 << ATL.getLocalSourceRange(); 6041 } 6042 6043 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6044 /// array parameter, check that it is non-null, and that if it is formed by 6045 /// array-to-pointer decay, the underlying array is sufficiently large. 6046 /// 6047 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6048 /// array type derivation, then for each call to the function, the value of the 6049 /// corresponding actual argument shall provide access to the first element of 6050 /// an array with at least as many elements as specified by the size expression. 6051 void 6052 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6053 ParmVarDecl *Param, 6054 const Expr *ArgExpr) { 6055 // Static array parameters are not supported in C++. 6056 if (!Param || getLangOpts().CPlusPlus) 6057 return; 6058 6059 QualType OrigTy = Param->getOriginalType(); 6060 6061 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6062 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6063 return; 6064 6065 if (ArgExpr->isNullPointerConstant(Context, 6066 Expr::NPC_NeverValueDependent)) { 6067 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6068 DiagnoseCalleeStaticArrayParam(*this, Param); 6069 return; 6070 } 6071 6072 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6073 if (!CAT) 6074 return; 6075 6076 const ConstantArrayType *ArgCAT = 6077 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6078 if (!ArgCAT) 6079 return; 6080 6081 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6082 ArgCAT->getElementType())) { 6083 if (ArgCAT->getSize().ult(CAT->getSize())) { 6084 Diag(CallLoc, diag::warn_static_array_too_small) 6085 << ArgExpr->getSourceRange() 6086 << (unsigned)ArgCAT->getSize().getZExtValue() 6087 << (unsigned)CAT->getSize().getZExtValue() << 0; 6088 DiagnoseCalleeStaticArrayParam(*this, Param); 6089 } 6090 return; 6091 } 6092 6093 Optional<CharUnits> ArgSize = 6094 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6095 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6096 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6097 Diag(CallLoc, diag::warn_static_array_too_small) 6098 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6099 << (unsigned)ParmSize->getQuantity() << 1; 6100 DiagnoseCalleeStaticArrayParam(*this, Param); 6101 } 6102 } 6103 6104 /// Given a function expression of unknown-any type, try to rebuild it 6105 /// to have a function type. 6106 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6107 6108 /// Is the given type a placeholder that we need to lower out 6109 /// immediately during argument processing? 6110 static bool isPlaceholderToRemoveAsArg(QualType type) { 6111 // Placeholders are never sugared. 6112 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6113 if (!placeholder) return false; 6114 6115 switch (placeholder->getKind()) { 6116 // Ignore all the non-placeholder types. 6117 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6118 case BuiltinType::Id: 6119 #include "clang/Basic/OpenCLImageTypes.def" 6120 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6121 case BuiltinType::Id: 6122 #include "clang/Basic/OpenCLExtensionTypes.def" 6123 // In practice we'll never use this, since all SVE types are sugared 6124 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6125 #define SVE_TYPE(Name, Id, SingletonId) \ 6126 case BuiltinType::Id: 6127 #include "clang/Basic/AArch64SVEACLETypes.def" 6128 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6129 case BuiltinType::Id: 6130 #include "clang/Basic/PPCTypes.def" 6131 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6132 #include "clang/Basic/RISCVVTypes.def" 6133 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6134 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6135 #include "clang/AST/BuiltinTypes.def" 6136 return false; 6137 6138 // We cannot lower out overload sets; they might validly be resolved 6139 // by the call machinery. 6140 case BuiltinType::Overload: 6141 return false; 6142 6143 // Unbridged casts in ARC can be handled in some call positions and 6144 // should be left in place. 6145 case BuiltinType::ARCUnbridgedCast: 6146 return false; 6147 6148 // Pseudo-objects should be converted as soon as possible. 6149 case BuiltinType::PseudoObject: 6150 return true; 6151 6152 // The debugger mode could theoretically but currently does not try 6153 // to resolve unknown-typed arguments based on known parameter types. 6154 case BuiltinType::UnknownAny: 6155 return true; 6156 6157 // These are always invalid as call arguments and should be reported. 6158 case BuiltinType::BoundMember: 6159 case BuiltinType::BuiltinFn: 6160 case BuiltinType::IncompleteMatrixIdx: 6161 case BuiltinType::OMPArraySection: 6162 case BuiltinType::OMPArrayShaping: 6163 case BuiltinType::OMPIterator: 6164 return true; 6165 6166 } 6167 llvm_unreachable("bad builtin type kind"); 6168 } 6169 6170 /// Check an argument list for placeholders that we won't try to 6171 /// handle later. 6172 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6173 // Apply this processing to all the arguments at once instead of 6174 // dying at the first failure. 6175 bool hasInvalid = false; 6176 for (size_t i = 0, e = args.size(); i != e; i++) { 6177 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6178 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6179 if (result.isInvalid()) hasInvalid = true; 6180 else args[i] = result.get(); 6181 } 6182 } 6183 return hasInvalid; 6184 } 6185 6186 /// If a builtin function has a pointer argument with no explicit address 6187 /// space, then it should be able to accept a pointer to any address 6188 /// space as input. In order to do this, we need to replace the 6189 /// standard builtin declaration with one that uses the same address space 6190 /// as the call. 6191 /// 6192 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6193 /// it does not contain any pointer arguments without 6194 /// an address space qualifer. Otherwise the rewritten 6195 /// FunctionDecl is returned. 6196 /// TODO: Handle pointer return types. 6197 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6198 FunctionDecl *FDecl, 6199 MultiExprArg ArgExprs) { 6200 6201 QualType DeclType = FDecl->getType(); 6202 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6203 6204 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6205 ArgExprs.size() < FT->getNumParams()) 6206 return nullptr; 6207 6208 bool NeedsNewDecl = false; 6209 unsigned i = 0; 6210 SmallVector<QualType, 8> OverloadParams; 6211 6212 for (QualType ParamType : FT->param_types()) { 6213 6214 // Convert array arguments to pointer to simplify type lookup. 6215 ExprResult ArgRes = 6216 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6217 if (ArgRes.isInvalid()) 6218 return nullptr; 6219 Expr *Arg = ArgRes.get(); 6220 QualType ArgType = Arg->getType(); 6221 if (!ParamType->isPointerType() || 6222 ParamType.hasAddressSpace() || 6223 !ArgType->isPointerType() || 6224 !ArgType->getPointeeType().hasAddressSpace()) { 6225 OverloadParams.push_back(ParamType); 6226 continue; 6227 } 6228 6229 QualType PointeeType = ParamType->getPointeeType(); 6230 if (PointeeType.hasAddressSpace()) 6231 continue; 6232 6233 NeedsNewDecl = true; 6234 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6235 6236 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6237 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6238 } 6239 6240 if (!NeedsNewDecl) 6241 return nullptr; 6242 6243 FunctionProtoType::ExtProtoInfo EPI; 6244 EPI.Variadic = FT->isVariadic(); 6245 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6246 OverloadParams, EPI); 6247 DeclContext *Parent = FDecl->getParent(); 6248 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6249 FDecl->getLocation(), 6250 FDecl->getLocation(), 6251 FDecl->getIdentifier(), 6252 OverloadTy, 6253 /*TInfo=*/nullptr, 6254 SC_Extern, false, 6255 /*hasPrototype=*/true); 6256 SmallVector<ParmVarDecl*, 16> Params; 6257 FT = cast<FunctionProtoType>(OverloadTy); 6258 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6259 QualType ParamType = FT->getParamType(i); 6260 ParmVarDecl *Parm = 6261 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6262 SourceLocation(), nullptr, ParamType, 6263 /*TInfo=*/nullptr, SC_None, nullptr); 6264 Parm->setScopeInfo(0, i); 6265 Params.push_back(Parm); 6266 } 6267 OverloadDecl->setParams(Params); 6268 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6269 return OverloadDecl; 6270 } 6271 6272 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6273 FunctionDecl *Callee, 6274 MultiExprArg ArgExprs) { 6275 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6276 // similar attributes) really don't like it when functions are called with an 6277 // invalid number of args. 6278 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6279 /*PartialOverloading=*/false) && 6280 !Callee->isVariadic()) 6281 return; 6282 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6283 return; 6284 6285 if (const EnableIfAttr *Attr = 6286 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6287 S.Diag(Fn->getBeginLoc(), 6288 isa<CXXMethodDecl>(Callee) 6289 ? diag::err_ovl_no_viable_member_function_in_call 6290 : diag::err_ovl_no_viable_function_in_call) 6291 << Callee << Callee->getSourceRange(); 6292 S.Diag(Callee->getLocation(), 6293 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6294 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6295 return; 6296 } 6297 } 6298 6299 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6300 const UnresolvedMemberExpr *const UME, Sema &S) { 6301 6302 const auto GetFunctionLevelDCIfCXXClass = 6303 [](Sema &S) -> const CXXRecordDecl * { 6304 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6305 if (!DC || !DC->getParent()) 6306 return nullptr; 6307 6308 // If the call to some member function was made from within a member 6309 // function body 'M' return return 'M's parent. 6310 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6311 return MD->getParent()->getCanonicalDecl(); 6312 // else the call was made from within a default member initializer of a 6313 // class, so return the class. 6314 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6315 return RD->getCanonicalDecl(); 6316 return nullptr; 6317 }; 6318 // If our DeclContext is neither a member function nor a class (in the 6319 // case of a lambda in a default member initializer), we can't have an 6320 // enclosing 'this'. 6321 6322 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6323 if (!CurParentClass) 6324 return false; 6325 6326 // The naming class for implicit member functions call is the class in which 6327 // name lookup starts. 6328 const CXXRecordDecl *const NamingClass = 6329 UME->getNamingClass()->getCanonicalDecl(); 6330 assert(NamingClass && "Must have naming class even for implicit access"); 6331 6332 // If the unresolved member functions were found in a 'naming class' that is 6333 // related (either the same or derived from) to the class that contains the 6334 // member function that itself contained the implicit member access. 6335 6336 return CurParentClass == NamingClass || 6337 CurParentClass->isDerivedFrom(NamingClass); 6338 } 6339 6340 static void 6341 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6342 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6343 6344 if (!UME) 6345 return; 6346 6347 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6348 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6349 // already been captured, or if this is an implicit member function call (if 6350 // it isn't, an attempt to capture 'this' should already have been made). 6351 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6352 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6353 return; 6354 6355 // Check if the naming class in which the unresolved members were found is 6356 // related (same as or is a base of) to the enclosing class. 6357 6358 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6359 return; 6360 6361 6362 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6363 // If the enclosing function is not dependent, then this lambda is 6364 // capture ready, so if we can capture this, do so. 6365 if (!EnclosingFunctionCtx->isDependentContext()) { 6366 // If the current lambda and all enclosing lambdas can capture 'this' - 6367 // then go ahead and capture 'this' (since our unresolved overload set 6368 // contains at least one non-static member function). 6369 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6370 S.CheckCXXThisCapture(CallLoc); 6371 } else if (S.CurContext->isDependentContext()) { 6372 // ... since this is an implicit member reference, that might potentially 6373 // involve a 'this' capture, mark 'this' for potential capture in 6374 // enclosing lambdas. 6375 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6376 CurLSI->addPotentialThisCapture(CallLoc); 6377 } 6378 } 6379 6380 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6381 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6382 Expr *ExecConfig) { 6383 ExprResult Call = 6384 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6385 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6386 if (Call.isInvalid()) 6387 return Call; 6388 6389 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6390 // language modes. 6391 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6392 if (ULE->hasExplicitTemplateArgs() && 6393 ULE->decls_begin() == ULE->decls_end()) { 6394 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6395 ? diag::warn_cxx17_compat_adl_only_template_id 6396 : diag::ext_adl_only_template_id) 6397 << ULE->getName(); 6398 } 6399 } 6400 6401 if (LangOpts.OpenMP) 6402 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6403 ExecConfig); 6404 6405 return Call; 6406 } 6407 6408 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6409 /// This provides the location of the left/right parens and a list of comma 6410 /// locations. 6411 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6412 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6413 Expr *ExecConfig, bool IsExecConfig, 6414 bool AllowRecovery) { 6415 // Since this might be a postfix expression, get rid of ParenListExprs. 6416 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6417 if (Result.isInvalid()) return ExprError(); 6418 Fn = Result.get(); 6419 6420 if (checkArgsForPlaceholders(*this, ArgExprs)) 6421 return ExprError(); 6422 6423 if (getLangOpts().CPlusPlus) { 6424 // If this is a pseudo-destructor expression, build the call immediately. 6425 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6426 if (!ArgExprs.empty()) { 6427 // Pseudo-destructor calls should not have any arguments. 6428 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6429 << FixItHint::CreateRemoval( 6430 SourceRange(ArgExprs.front()->getBeginLoc(), 6431 ArgExprs.back()->getEndLoc())); 6432 } 6433 6434 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6435 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6436 } 6437 if (Fn->getType() == Context.PseudoObjectTy) { 6438 ExprResult result = CheckPlaceholderExpr(Fn); 6439 if (result.isInvalid()) return ExprError(); 6440 Fn = result.get(); 6441 } 6442 6443 // Determine whether this is a dependent call inside a C++ template, 6444 // in which case we won't do any semantic analysis now. 6445 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6446 if (ExecConfig) { 6447 return CUDAKernelCallExpr::Create(Context, Fn, 6448 cast<CallExpr>(ExecConfig), ArgExprs, 6449 Context.DependentTy, VK_PRValue, 6450 RParenLoc, CurFPFeatureOverrides()); 6451 } else { 6452 6453 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6454 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6455 Fn->getBeginLoc()); 6456 6457 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6458 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6459 } 6460 } 6461 6462 // Determine whether this is a call to an object (C++ [over.call.object]). 6463 if (Fn->getType()->isRecordType()) 6464 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6465 RParenLoc); 6466 6467 if (Fn->getType() == Context.UnknownAnyTy) { 6468 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6469 if (result.isInvalid()) return ExprError(); 6470 Fn = result.get(); 6471 } 6472 6473 if (Fn->getType() == Context.BoundMemberTy) { 6474 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6475 RParenLoc, AllowRecovery); 6476 } 6477 } 6478 6479 // Check for overloaded calls. This can happen even in C due to extensions. 6480 if (Fn->getType() == Context.OverloadTy) { 6481 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6482 6483 // We aren't supposed to apply this logic if there's an '&' involved. 6484 if (!find.HasFormOfMemberPointer) { 6485 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6486 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6487 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6488 OverloadExpr *ovl = find.Expression; 6489 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6490 return BuildOverloadedCallExpr( 6491 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6492 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6493 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6494 RParenLoc, AllowRecovery); 6495 } 6496 } 6497 6498 // If we're directly calling a function, get the appropriate declaration. 6499 if (Fn->getType() == Context.UnknownAnyTy) { 6500 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6501 if (result.isInvalid()) return ExprError(); 6502 Fn = result.get(); 6503 } 6504 6505 Expr *NakedFn = Fn->IgnoreParens(); 6506 6507 bool CallingNDeclIndirectly = false; 6508 NamedDecl *NDecl = nullptr; 6509 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6510 if (UnOp->getOpcode() == UO_AddrOf) { 6511 CallingNDeclIndirectly = true; 6512 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6513 } 6514 } 6515 6516 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6517 NDecl = DRE->getDecl(); 6518 6519 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6520 if (FDecl && FDecl->getBuiltinID()) { 6521 // Rewrite the function decl for this builtin by replacing parameters 6522 // with no explicit address space with the address space of the arguments 6523 // in ArgExprs. 6524 if ((FDecl = 6525 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6526 NDecl = FDecl; 6527 Fn = DeclRefExpr::Create( 6528 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6529 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6530 nullptr, DRE->isNonOdrUse()); 6531 } 6532 } 6533 } else if (isa<MemberExpr>(NakedFn)) 6534 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6535 6536 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6537 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6538 FD, /*Complain=*/true, Fn->getBeginLoc())) 6539 return ExprError(); 6540 6541 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6542 } 6543 6544 if (Context.isDependenceAllowed() && 6545 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6546 assert(!getLangOpts().CPlusPlus); 6547 assert((Fn->containsErrors() || 6548 llvm::any_of(ArgExprs, 6549 [](clang::Expr *E) { return E->containsErrors(); })) && 6550 "should only occur in error-recovery path."); 6551 QualType ReturnType = 6552 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6553 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6554 : Context.DependentTy; 6555 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6556 Expr::getValueKindForType(ReturnType), RParenLoc, 6557 CurFPFeatureOverrides()); 6558 } 6559 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6560 ExecConfig, IsExecConfig); 6561 } 6562 6563 /// Parse a __builtin_astype expression. 6564 /// 6565 /// __builtin_astype( value, dst type ) 6566 /// 6567 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6568 SourceLocation BuiltinLoc, 6569 SourceLocation RParenLoc) { 6570 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6571 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6572 } 6573 6574 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6575 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6576 SourceLocation BuiltinLoc, 6577 SourceLocation RParenLoc) { 6578 ExprValueKind VK = VK_PRValue; 6579 ExprObjectKind OK = OK_Ordinary; 6580 QualType SrcTy = E->getType(); 6581 if (!SrcTy->isDependentType() && 6582 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6583 return ExprError( 6584 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6585 << DestTy << SrcTy << E->getSourceRange()); 6586 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6587 } 6588 6589 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6590 /// provided arguments. 6591 /// 6592 /// __builtin_convertvector( value, dst type ) 6593 /// 6594 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6595 SourceLocation BuiltinLoc, 6596 SourceLocation RParenLoc) { 6597 TypeSourceInfo *TInfo; 6598 GetTypeFromParser(ParsedDestTy, &TInfo); 6599 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6600 } 6601 6602 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6603 /// i.e. an expression not of \p OverloadTy. The expression should 6604 /// unary-convert to an expression of function-pointer or 6605 /// block-pointer type. 6606 /// 6607 /// \param NDecl the declaration being called, if available 6608 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6609 SourceLocation LParenLoc, 6610 ArrayRef<Expr *> Args, 6611 SourceLocation RParenLoc, Expr *Config, 6612 bool IsExecConfig, ADLCallKind UsesADL) { 6613 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6614 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6615 6616 // Functions with 'interrupt' attribute cannot be called directly. 6617 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6618 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6619 return ExprError(); 6620 } 6621 6622 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6623 // so there's some risk when calling out to non-interrupt handler functions 6624 // that the callee might not preserve them. This is easy to diagnose here, 6625 // but can be very challenging to debug. 6626 // Likewise, X86 interrupt handlers may only call routines with attribute 6627 // no_caller_saved_registers since there is no efficient way to 6628 // save and restore the non-GPR state. 6629 if (auto *Caller = getCurFunctionDecl()) { 6630 if (Caller->hasAttr<ARMInterruptAttr>()) { 6631 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6632 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6633 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6634 if (FDecl) 6635 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6636 } 6637 } 6638 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6639 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6640 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6641 if (FDecl) 6642 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6643 } 6644 } 6645 6646 // Promote the function operand. 6647 // We special-case function promotion here because we only allow promoting 6648 // builtin functions to function pointers in the callee of a call. 6649 ExprResult Result; 6650 QualType ResultTy; 6651 if (BuiltinID && 6652 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6653 // Extract the return type from the (builtin) function pointer type. 6654 // FIXME Several builtins still have setType in 6655 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6656 // Builtins.def to ensure they are correct before removing setType calls. 6657 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6658 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6659 ResultTy = FDecl->getCallResultType(); 6660 } else { 6661 Result = CallExprUnaryConversions(Fn); 6662 ResultTy = Context.BoolTy; 6663 } 6664 if (Result.isInvalid()) 6665 return ExprError(); 6666 Fn = Result.get(); 6667 6668 // Check for a valid function type, but only if it is not a builtin which 6669 // requires custom type checking. These will be handled by 6670 // CheckBuiltinFunctionCall below just after creation of the call expression. 6671 const FunctionType *FuncT = nullptr; 6672 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6673 retry: 6674 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6675 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6676 // have type pointer to function". 6677 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6678 if (!FuncT) 6679 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6680 << Fn->getType() << Fn->getSourceRange()); 6681 } else if (const BlockPointerType *BPT = 6682 Fn->getType()->getAs<BlockPointerType>()) { 6683 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6684 } else { 6685 // Handle calls to expressions of unknown-any type. 6686 if (Fn->getType() == Context.UnknownAnyTy) { 6687 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6688 if (rewrite.isInvalid()) 6689 return ExprError(); 6690 Fn = rewrite.get(); 6691 goto retry; 6692 } 6693 6694 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6695 << Fn->getType() << Fn->getSourceRange()); 6696 } 6697 } 6698 6699 // Get the number of parameters in the function prototype, if any. 6700 // We will allocate space for max(Args.size(), NumParams) arguments 6701 // in the call expression. 6702 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6703 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6704 6705 CallExpr *TheCall; 6706 if (Config) { 6707 assert(UsesADL == ADLCallKind::NotADL && 6708 "CUDAKernelCallExpr should not use ADL"); 6709 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6710 Args, ResultTy, VK_PRValue, RParenLoc, 6711 CurFPFeatureOverrides(), NumParams); 6712 } else { 6713 TheCall = 6714 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6715 CurFPFeatureOverrides(), NumParams, UsesADL); 6716 } 6717 6718 if (!Context.isDependenceAllowed()) { 6719 // Forget about the nulled arguments since typo correction 6720 // do not handle them well. 6721 TheCall->shrinkNumArgs(Args.size()); 6722 // C cannot always handle TypoExpr nodes in builtin calls and direct 6723 // function calls as their argument checking don't necessarily handle 6724 // dependent types properly, so make sure any TypoExprs have been 6725 // dealt with. 6726 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6727 if (!Result.isUsable()) return ExprError(); 6728 CallExpr *TheOldCall = TheCall; 6729 TheCall = dyn_cast<CallExpr>(Result.get()); 6730 bool CorrectedTypos = TheCall != TheOldCall; 6731 if (!TheCall) return Result; 6732 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6733 6734 // A new call expression node was created if some typos were corrected. 6735 // However it may not have been constructed with enough storage. In this 6736 // case, rebuild the node with enough storage. The waste of space is 6737 // immaterial since this only happens when some typos were corrected. 6738 if (CorrectedTypos && Args.size() < NumParams) { 6739 if (Config) 6740 TheCall = CUDAKernelCallExpr::Create( 6741 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6742 RParenLoc, CurFPFeatureOverrides(), NumParams); 6743 else 6744 TheCall = 6745 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6746 CurFPFeatureOverrides(), NumParams, UsesADL); 6747 } 6748 // We can now handle the nulled arguments for the default arguments. 6749 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6750 } 6751 6752 // Bail out early if calling a builtin with custom type checking. 6753 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6754 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6755 6756 if (getLangOpts().CUDA) { 6757 if (Config) { 6758 // CUDA: Kernel calls must be to global functions 6759 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6760 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6761 << FDecl << Fn->getSourceRange()); 6762 6763 // CUDA: Kernel function must have 'void' return type 6764 if (!FuncT->getReturnType()->isVoidType() && 6765 !FuncT->getReturnType()->getAs<AutoType>() && 6766 !FuncT->getReturnType()->isInstantiationDependentType()) 6767 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6768 << Fn->getType() << Fn->getSourceRange()); 6769 } else { 6770 // CUDA: Calls to global functions must be configured 6771 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6772 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6773 << FDecl << Fn->getSourceRange()); 6774 } 6775 } 6776 6777 // Check for a valid return type 6778 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6779 FDecl)) 6780 return ExprError(); 6781 6782 // We know the result type of the call, set it. 6783 TheCall->setType(FuncT->getCallResultType(Context)); 6784 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6785 6786 if (Proto) { 6787 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6788 IsExecConfig)) 6789 return ExprError(); 6790 } else { 6791 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6792 6793 if (FDecl) { 6794 // Check if we have too few/too many template arguments, based 6795 // on our knowledge of the function definition. 6796 const FunctionDecl *Def = nullptr; 6797 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6798 Proto = Def->getType()->getAs<FunctionProtoType>(); 6799 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6800 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6801 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6802 } 6803 6804 // If the function we're calling isn't a function prototype, but we have 6805 // a function prototype from a prior declaratiom, use that prototype. 6806 if (!FDecl->hasPrototype()) 6807 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6808 } 6809 6810 // Promote the arguments (C99 6.5.2.2p6). 6811 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6812 Expr *Arg = Args[i]; 6813 6814 if (Proto && i < Proto->getNumParams()) { 6815 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6816 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6817 ExprResult ArgE = 6818 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6819 if (ArgE.isInvalid()) 6820 return true; 6821 6822 Arg = ArgE.getAs<Expr>(); 6823 6824 } else { 6825 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6826 6827 if (ArgE.isInvalid()) 6828 return true; 6829 6830 Arg = ArgE.getAs<Expr>(); 6831 } 6832 6833 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6834 diag::err_call_incomplete_argument, Arg)) 6835 return ExprError(); 6836 6837 TheCall->setArg(i, Arg); 6838 } 6839 } 6840 6841 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6842 if (!Method->isStatic()) 6843 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6844 << Fn->getSourceRange()); 6845 6846 // Check for sentinels 6847 if (NDecl) 6848 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6849 6850 // Warn for unions passing across security boundary (CMSE). 6851 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6852 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6853 if (const auto *RT = 6854 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6855 if (RT->getDecl()->isOrContainsUnion()) 6856 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6857 << 0 << i; 6858 } 6859 } 6860 } 6861 6862 // Do special checking on direct calls to functions. 6863 if (FDecl) { 6864 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6865 return ExprError(); 6866 6867 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6868 6869 if (BuiltinID) 6870 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6871 } else if (NDecl) { 6872 if (CheckPointerCall(NDecl, TheCall, Proto)) 6873 return ExprError(); 6874 } else { 6875 if (CheckOtherCall(TheCall, Proto)) 6876 return ExprError(); 6877 } 6878 6879 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6880 } 6881 6882 ExprResult 6883 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6884 SourceLocation RParenLoc, Expr *InitExpr) { 6885 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6886 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6887 6888 TypeSourceInfo *TInfo; 6889 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6890 if (!TInfo) 6891 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6892 6893 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6894 } 6895 6896 ExprResult 6897 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6898 SourceLocation RParenLoc, Expr *LiteralExpr) { 6899 QualType literalType = TInfo->getType(); 6900 6901 if (literalType->isArrayType()) { 6902 if (RequireCompleteSizedType( 6903 LParenLoc, Context.getBaseElementType(literalType), 6904 diag::err_array_incomplete_or_sizeless_type, 6905 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6906 return ExprError(); 6907 if (literalType->isVariableArrayType()) { 6908 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6909 diag::err_variable_object_no_init)) { 6910 return ExprError(); 6911 } 6912 } 6913 } else if (!literalType->isDependentType() && 6914 RequireCompleteType(LParenLoc, literalType, 6915 diag::err_typecheck_decl_incomplete_type, 6916 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6917 return ExprError(); 6918 6919 InitializedEntity Entity 6920 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6921 InitializationKind Kind 6922 = InitializationKind::CreateCStyleCast(LParenLoc, 6923 SourceRange(LParenLoc, RParenLoc), 6924 /*InitList=*/true); 6925 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6926 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6927 &literalType); 6928 if (Result.isInvalid()) 6929 return ExprError(); 6930 LiteralExpr = Result.get(); 6931 6932 bool isFileScope = !CurContext->isFunctionOrMethod(); 6933 6934 // In C, compound literals are l-values for some reason. 6935 // For GCC compatibility, in C++, file-scope array compound literals with 6936 // constant initializers are also l-values, and compound literals are 6937 // otherwise prvalues. 6938 // 6939 // (GCC also treats C++ list-initialized file-scope array prvalues with 6940 // constant initializers as l-values, but that's non-conforming, so we don't 6941 // follow it there.) 6942 // 6943 // FIXME: It would be better to handle the lvalue cases as materializing and 6944 // lifetime-extending a temporary object, but our materialized temporaries 6945 // representation only supports lifetime extension from a variable, not "out 6946 // of thin air". 6947 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6948 // is bound to the result of applying array-to-pointer decay to the compound 6949 // literal. 6950 // FIXME: GCC supports compound literals of reference type, which should 6951 // obviously have a value kind derived from the kind of reference involved. 6952 ExprValueKind VK = 6953 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6954 ? VK_PRValue 6955 : VK_LValue; 6956 6957 if (isFileScope) 6958 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6959 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6960 Expr *Init = ILE->getInit(i); 6961 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6962 } 6963 6964 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6965 VK, LiteralExpr, isFileScope); 6966 if (isFileScope) { 6967 if (!LiteralExpr->isTypeDependent() && 6968 !LiteralExpr->isValueDependent() && 6969 !literalType->isDependentType()) // C99 6.5.2.5p3 6970 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6971 return ExprError(); 6972 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6973 literalType.getAddressSpace() != LangAS::Default) { 6974 // Embedded-C extensions to C99 6.5.2.5: 6975 // "If the compound literal occurs inside the body of a function, the 6976 // type name shall not be qualified by an address-space qualifier." 6977 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6978 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6979 return ExprError(); 6980 } 6981 6982 if (!isFileScope && !getLangOpts().CPlusPlus) { 6983 // Compound literals that have automatic storage duration are destroyed at 6984 // the end of the scope in C; in C++, they're just temporaries. 6985 6986 // Emit diagnostics if it is or contains a C union type that is non-trivial 6987 // to destruct. 6988 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6989 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6990 NTCUC_CompoundLiteral, NTCUK_Destruct); 6991 6992 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6993 if (literalType.isDestructedType()) { 6994 Cleanup.setExprNeedsCleanups(true); 6995 ExprCleanupObjects.push_back(E); 6996 getCurFunction()->setHasBranchProtectedScope(); 6997 } 6998 } 6999 7000 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7001 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7002 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7003 E->getInitializer()->getExprLoc()); 7004 7005 return MaybeBindToTemporary(E); 7006 } 7007 7008 ExprResult 7009 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7010 SourceLocation RBraceLoc) { 7011 // Only produce each kind of designated initialization diagnostic once. 7012 SourceLocation FirstDesignator; 7013 bool DiagnosedArrayDesignator = false; 7014 bool DiagnosedNestedDesignator = false; 7015 bool DiagnosedMixedDesignator = false; 7016 7017 // Check that any designated initializers are syntactically valid in the 7018 // current language mode. 7019 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7020 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7021 if (FirstDesignator.isInvalid()) 7022 FirstDesignator = DIE->getBeginLoc(); 7023 7024 if (!getLangOpts().CPlusPlus) 7025 break; 7026 7027 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7028 DiagnosedNestedDesignator = true; 7029 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7030 << DIE->getDesignatorsSourceRange(); 7031 } 7032 7033 for (auto &Desig : DIE->designators()) { 7034 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7035 DiagnosedArrayDesignator = true; 7036 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7037 << Desig.getSourceRange(); 7038 } 7039 } 7040 7041 if (!DiagnosedMixedDesignator && 7042 !isa<DesignatedInitExpr>(InitArgList[0])) { 7043 DiagnosedMixedDesignator = true; 7044 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7045 << DIE->getSourceRange(); 7046 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7047 << InitArgList[0]->getSourceRange(); 7048 } 7049 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7050 isa<DesignatedInitExpr>(InitArgList[0])) { 7051 DiagnosedMixedDesignator = true; 7052 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7053 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7054 << DIE->getSourceRange(); 7055 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7056 << InitArgList[I]->getSourceRange(); 7057 } 7058 } 7059 7060 if (FirstDesignator.isValid()) { 7061 // Only diagnose designated initiaization as a C++20 extension if we didn't 7062 // already diagnose use of (non-C++20) C99 designator syntax. 7063 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7064 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7065 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7066 ? diag::warn_cxx17_compat_designated_init 7067 : diag::ext_cxx_designated_init); 7068 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7069 Diag(FirstDesignator, diag::ext_designated_init); 7070 } 7071 } 7072 7073 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7074 } 7075 7076 ExprResult 7077 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7078 SourceLocation RBraceLoc) { 7079 // Semantic analysis for initializers is done by ActOnDeclarator() and 7080 // CheckInitializer() - it requires knowledge of the object being initialized. 7081 7082 // Immediately handle non-overload placeholders. Overloads can be 7083 // resolved contextually, but everything else here can't. 7084 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7085 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7086 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7087 7088 // Ignore failures; dropping the entire initializer list because 7089 // of one failure would be terrible for indexing/etc. 7090 if (result.isInvalid()) continue; 7091 7092 InitArgList[I] = result.get(); 7093 } 7094 } 7095 7096 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7097 RBraceLoc); 7098 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7099 return E; 7100 } 7101 7102 /// Do an explicit extend of the given block pointer if we're in ARC. 7103 void Sema::maybeExtendBlockObject(ExprResult &E) { 7104 assert(E.get()->getType()->isBlockPointerType()); 7105 assert(E.get()->isPRValue()); 7106 7107 // Only do this in an r-value context. 7108 if (!getLangOpts().ObjCAutoRefCount) return; 7109 7110 E = ImplicitCastExpr::Create( 7111 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7112 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7113 Cleanup.setExprNeedsCleanups(true); 7114 } 7115 7116 /// Prepare a conversion of the given expression to an ObjC object 7117 /// pointer type. 7118 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7119 QualType type = E.get()->getType(); 7120 if (type->isObjCObjectPointerType()) { 7121 return CK_BitCast; 7122 } else if (type->isBlockPointerType()) { 7123 maybeExtendBlockObject(E); 7124 return CK_BlockPointerToObjCPointerCast; 7125 } else { 7126 assert(type->isPointerType()); 7127 return CK_CPointerToObjCPointerCast; 7128 } 7129 } 7130 7131 /// Prepares for a scalar cast, performing all the necessary stages 7132 /// except the final cast and returning the kind required. 7133 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7134 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7135 // Also, callers should have filtered out the invalid cases with 7136 // pointers. Everything else should be possible. 7137 7138 QualType SrcTy = Src.get()->getType(); 7139 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7140 return CK_NoOp; 7141 7142 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7143 case Type::STK_MemberPointer: 7144 llvm_unreachable("member pointer type in C"); 7145 7146 case Type::STK_CPointer: 7147 case Type::STK_BlockPointer: 7148 case Type::STK_ObjCObjectPointer: 7149 switch (DestTy->getScalarTypeKind()) { 7150 case Type::STK_CPointer: { 7151 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7152 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7153 if (SrcAS != DestAS) 7154 return CK_AddressSpaceConversion; 7155 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7156 return CK_NoOp; 7157 return CK_BitCast; 7158 } 7159 case Type::STK_BlockPointer: 7160 return (SrcKind == Type::STK_BlockPointer 7161 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7162 case Type::STK_ObjCObjectPointer: 7163 if (SrcKind == Type::STK_ObjCObjectPointer) 7164 return CK_BitCast; 7165 if (SrcKind == Type::STK_CPointer) 7166 return CK_CPointerToObjCPointerCast; 7167 maybeExtendBlockObject(Src); 7168 return CK_BlockPointerToObjCPointerCast; 7169 case Type::STK_Bool: 7170 return CK_PointerToBoolean; 7171 case Type::STK_Integral: 7172 return CK_PointerToIntegral; 7173 case Type::STK_Floating: 7174 case Type::STK_FloatingComplex: 7175 case Type::STK_IntegralComplex: 7176 case Type::STK_MemberPointer: 7177 case Type::STK_FixedPoint: 7178 llvm_unreachable("illegal cast from pointer"); 7179 } 7180 llvm_unreachable("Should have returned before this"); 7181 7182 case Type::STK_FixedPoint: 7183 switch (DestTy->getScalarTypeKind()) { 7184 case Type::STK_FixedPoint: 7185 return CK_FixedPointCast; 7186 case Type::STK_Bool: 7187 return CK_FixedPointToBoolean; 7188 case Type::STK_Integral: 7189 return CK_FixedPointToIntegral; 7190 case Type::STK_Floating: 7191 return CK_FixedPointToFloating; 7192 case Type::STK_IntegralComplex: 7193 case Type::STK_FloatingComplex: 7194 Diag(Src.get()->getExprLoc(), 7195 diag::err_unimplemented_conversion_with_fixed_point_type) 7196 << DestTy; 7197 return CK_IntegralCast; 7198 case Type::STK_CPointer: 7199 case Type::STK_ObjCObjectPointer: 7200 case Type::STK_BlockPointer: 7201 case Type::STK_MemberPointer: 7202 llvm_unreachable("illegal cast to pointer type"); 7203 } 7204 llvm_unreachable("Should have returned before this"); 7205 7206 case Type::STK_Bool: // casting from bool is like casting from an integer 7207 case Type::STK_Integral: 7208 switch (DestTy->getScalarTypeKind()) { 7209 case Type::STK_CPointer: 7210 case Type::STK_ObjCObjectPointer: 7211 case Type::STK_BlockPointer: 7212 if (Src.get()->isNullPointerConstant(Context, 7213 Expr::NPC_ValueDependentIsNull)) 7214 return CK_NullToPointer; 7215 return CK_IntegralToPointer; 7216 case Type::STK_Bool: 7217 return CK_IntegralToBoolean; 7218 case Type::STK_Integral: 7219 return CK_IntegralCast; 7220 case Type::STK_Floating: 7221 return CK_IntegralToFloating; 7222 case Type::STK_IntegralComplex: 7223 Src = ImpCastExprToType(Src.get(), 7224 DestTy->castAs<ComplexType>()->getElementType(), 7225 CK_IntegralCast); 7226 return CK_IntegralRealToComplex; 7227 case Type::STK_FloatingComplex: 7228 Src = ImpCastExprToType(Src.get(), 7229 DestTy->castAs<ComplexType>()->getElementType(), 7230 CK_IntegralToFloating); 7231 return CK_FloatingRealToComplex; 7232 case Type::STK_MemberPointer: 7233 llvm_unreachable("member pointer type in C"); 7234 case Type::STK_FixedPoint: 7235 return CK_IntegralToFixedPoint; 7236 } 7237 llvm_unreachable("Should have returned before this"); 7238 7239 case Type::STK_Floating: 7240 switch (DestTy->getScalarTypeKind()) { 7241 case Type::STK_Floating: 7242 return CK_FloatingCast; 7243 case Type::STK_Bool: 7244 return CK_FloatingToBoolean; 7245 case Type::STK_Integral: 7246 return CK_FloatingToIntegral; 7247 case Type::STK_FloatingComplex: 7248 Src = ImpCastExprToType(Src.get(), 7249 DestTy->castAs<ComplexType>()->getElementType(), 7250 CK_FloatingCast); 7251 return CK_FloatingRealToComplex; 7252 case Type::STK_IntegralComplex: 7253 Src = ImpCastExprToType(Src.get(), 7254 DestTy->castAs<ComplexType>()->getElementType(), 7255 CK_FloatingToIntegral); 7256 return CK_IntegralRealToComplex; 7257 case Type::STK_CPointer: 7258 case Type::STK_ObjCObjectPointer: 7259 case Type::STK_BlockPointer: 7260 llvm_unreachable("valid float->pointer cast?"); 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("member pointer type in C"); 7263 case Type::STK_FixedPoint: 7264 return CK_FloatingToFixedPoint; 7265 } 7266 llvm_unreachable("Should have returned before this"); 7267 7268 case Type::STK_FloatingComplex: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_FloatingComplex: 7271 return CK_FloatingComplexCast; 7272 case Type::STK_IntegralComplex: 7273 return CK_FloatingComplexToIntegralComplex; 7274 case Type::STK_Floating: { 7275 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7276 if (Context.hasSameType(ET, DestTy)) 7277 return CK_FloatingComplexToReal; 7278 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7279 return CK_FloatingCast; 7280 } 7281 case Type::STK_Bool: 7282 return CK_FloatingComplexToBoolean; 7283 case Type::STK_Integral: 7284 Src = ImpCastExprToType(Src.get(), 7285 SrcTy->castAs<ComplexType>()->getElementType(), 7286 CK_FloatingComplexToReal); 7287 return CK_FloatingToIntegral; 7288 case Type::STK_CPointer: 7289 case Type::STK_ObjCObjectPointer: 7290 case Type::STK_BlockPointer: 7291 llvm_unreachable("valid complex float->pointer cast?"); 7292 case Type::STK_MemberPointer: 7293 llvm_unreachable("member pointer type in C"); 7294 case Type::STK_FixedPoint: 7295 Diag(Src.get()->getExprLoc(), 7296 diag::err_unimplemented_conversion_with_fixed_point_type) 7297 << SrcTy; 7298 return CK_IntegralCast; 7299 } 7300 llvm_unreachable("Should have returned before this"); 7301 7302 case Type::STK_IntegralComplex: 7303 switch (DestTy->getScalarTypeKind()) { 7304 case Type::STK_FloatingComplex: 7305 return CK_IntegralComplexToFloatingComplex; 7306 case Type::STK_IntegralComplex: 7307 return CK_IntegralComplexCast; 7308 case Type::STK_Integral: { 7309 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7310 if (Context.hasSameType(ET, DestTy)) 7311 return CK_IntegralComplexToReal; 7312 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7313 return CK_IntegralCast; 7314 } 7315 case Type::STK_Bool: 7316 return CK_IntegralComplexToBoolean; 7317 case Type::STK_Floating: 7318 Src = ImpCastExprToType(Src.get(), 7319 SrcTy->castAs<ComplexType>()->getElementType(), 7320 CK_IntegralComplexToReal); 7321 return CK_IntegralToFloating; 7322 case Type::STK_CPointer: 7323 case Type::STK_ObjCObjectPointer: 7324 case Type::STK_BlockPointer: 7325 llvm_unreachable("valid complex int->pointer cast?"); 7326 case Type::STK_MemberPointer: 7327 llvm_unreachable("member pointer type in C"); 7328 case Type::STK_FixedPoint: 7329 Diag(Src.get()->getExprLoc(), 7330 diag::err_unimplemented_conversion_with_fixed_point_type) 7331 << SrcTy; 7332 return CK_IntegralCast; 7333 } 7334 llvm_unreachable("Should have returned before this"); 7335 } 7336 7337 llvm_unreachable("Unhandled scalar cast"); 7338 } 7339 7340 static bool breakDownVectorType(QualType type, uint64_t &len, 7341 QualType &eltType) { 7342 // Vectors are simple. 7343 if (const VectorType *vecType = type->getAs<VectorType>()) { 7344 len = vecType->getNumElements(); 7345 eltType = vecType->getElementType(); 7346 assert(eltType->isScalarType()); 7347 return true; 7348 } 7349 7350 // We allow lax conversion to and from non-vector types, but only if 7351 // they're real types (i.e. non-complex, non-pointer scalar types). 7352 if (!type->isRealType()) return false; 7353 7354 len = 1; 7355 eltType = type; 7356 return true; 7357 } 7358 7359 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7360 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7361 /// allowed? 7362 /// 7363 /// This will also return false if the two given types do not make sense from 7364 /// the perspective of SVE bitcasts. 7365 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7366 assert(srcTy->isVectorType() || destTy->isVectorType()); 7367 7368 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7369 if (!FirstType->isSizelessBuiltinType()) 7370 return false; 7371 7372 const auto *VecTy = SecondType->getAs<VectorType>(); 7373 return VecTy && 7374 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7375 }; 7376 7377 return ValidScalableConversion(srcTy, destTy) || 7378 ValidScalableConversion(destTy, srcTy); 7379 } 7380 7381 /// Are the two types matrix types and do they have the same dimensions i.e. 7382 /// do they have the same number of rows and the same number of columns? 7383 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7384 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7385 return false; 7386 7387 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7388 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7389 7390 return matSrcType->getNumRows() == matDestType->getNumRows() && 7391 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7392 } 7393 7394 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7395 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7396 7397 uint64_t SrcLen, DestLen; 7398 QualType SrcEltTy, DestEltTy; 7399 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7400 return false; 7401 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7402 return false; 7403 7404 // ASTContext::getTypeSize will return the size rounded up to a 7405 // power of 2, so instead of using that, we need to use the raw 7406 // element size multiplied by the element count. 7407 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7408 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7409 7410 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7411 } 7412 7413 /// Are the two types lax-compatible vector types? That is, given 7414 /// that one of them is a vector, do they have equal storage sizes, 7415 /// where the storage size is the number of elements times the element 7416 /// size? 7417 /// 7418 /// This will also return false if either of the types is neither a 7419 /// vector nor a real type. 7420 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7421 assert(destTy->isVectorType() || srcTy->isVectorType()); 7422 7423 // Disallow lax conversions between scalars and ExtVectors (these 7424 // conversions are allowed for other vector types because common headers 7425 // depend on them). Most scalar OP ExtVector cases are handled by the 7426 // splat path anyway, which does what we want (convert, not bitcast). 7427 // What this rules out for ExtVectors is crazy things like char4*float. 7428 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7429 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7430 7431 return areVectorTypesSameSize(srcTy, destTy); 7432 } 7433 7434 /// Is this a legal conversion between two types, one of which is 7435 /// known to be a vector type? 7436 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7437 assert(destTy->isVectorType() || srcTy->isVectorType()); 7438 7439 switch (Context.getLangOpts().getLaxVectorConversions()) { 7440 case LangOptions::LaxVectorConversionKind::None: 7441 return false; 7442 7443 case LangOptions::LaxVectorConversionKind::Integer: 7444 if (!srcTy->isIntegralOrEnumerationType()) { 7445 auto *Vec = srcTy->getAs<VectorType>(); 7446 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7447 return false; 7448 } 7449 if (!destTy->isIntegralOrEnumerationType()) { 7450 auto *Vec = destTy->getAs<VectorType>(); 7451 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7452 return false; 7453 } 7454 // OK, integer (vector) -> integer (vector) bitcast. 7455 break; 7456 7457 case LangOptions::LaxVectorConversionKind::All: 7458 break; 7459 } 7460 7461 return areLaxCompatibleVectorTypes(srcTy, destTy); 7462 } 7463 7464 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7465 CastKind &Kind) { 7466 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7467 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7468 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7469 << DestTy << SrcTy << R; 7470 } 7471 } else if (SrcTy->isMatrixType()) { 7472 return Diag(R.getBegin(), 7473 diag::err_invalid_conversion_between_matrix_and_type) 7474 << SrcTy << DestTy << R; 7475 } else if (DestTy->isMatrixType()) { 7476 return Diag(R.getBegin(), 7477 diag::err_invalid_conversion_between_matrix_and_type) 7478 << DestTy << SrcTy << R; 7479 } 7480 7481 Kind = CK_MatrixCast; 7482 return false; 7483 } 7484 7485 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7486 CastKind &Kind) { 7487 assert(VectorTy->isVectorType() && "Not a vector type!"); 7488 7489 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7490 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7491 return Diag(R.getBegin(), 7492 Ty->isVectorType() ? 7493 diag::err_invalid_conversion_between_vectors : 7494 diag::err_invalid_conversion_between_vector_and_integer) 7495 << VectorTy << Ty << R; 7496 } else 7497 return Diag(R.getBegin(), 7498 diag::err_invalid_conversion_between_vector_and_scalar) 7499 << VectorTy << Ty << R; 7500 7501 Kind = CK_BitCast; 7502 return false; 7503 } 7504 7505 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7506 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7507 7508 if (DestElemTy == SplattedExpr->getType()) 7509 return SplattedExpr; 7510 7511 assert(DestElemTy->isFloatingType() || 7512 DestElemTy->isIntegralOrEnumerationType()); 7513 7514 CastKind CK; 7515 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7516 // OpenCL requires that we convert `true` boolean expressions to -1, but 7517 // only when splatting vectors. 7518 if (DestElemTy->isFloatingType()) { 7519 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7520 // in two steps: boolean to signed integral, then to floating. 7521 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7522 CK_BooleanToSignedIntegral); 7523 SplattedExpr = CastExprRes.get(); 7524 CK = CK_IntegralToFloating; 7525 } else { 7526 CK = CK_BooleanToSignedIntegral; 7527 } 7528 } else { 7529 ExprResult CastExprRes = SplattedExpr; 7530 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7531 if (CastExprRes.isInvalid()) 7532 return ExprError(); 7533 SplattedExpr = CastExprRes.get(); 7534 } 7535 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7536 } 7537 7538 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7539 Expr *CastExpr, CastKind &Kind) { 7540 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7541 7542 QualType SrcTy = CastExpr->getType(); 7543 7544 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7545 // an ExtVectorType. 7546 // In OpenCL, casts between vectors of different types are not allowed. 7547 // (See OpenCL 6.2). 7548 if (SrcTy->isVectorType()) { 7549 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7550 (getLangOpts().OpenCL && 7551 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7552 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7553 << DestTy << SrcTy << R; 7554 return ExprError(); 7555 } 7556 Kind = CK_BitCast; 7557 return CastExpr; 7558 } 7559 7560 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7561 // conversion will take place first from scalar to elt type, and then 7562 // splat from elt type to vector. 7563 if (SrcTy->isPointerType()) 7564 return Diag(R.getBegin(), 7565 diag::err_invalid_conversion_between_vector_and_scalar) 7566 << DestTy << SrcTy << R; 7567 7568 Kind = CK_VectorSplat; 7569 return prepareVectorSplat(DestTy, CastExpr); 7570 } 7571 7572 ExprResult 7573 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7574 Declarator &D, ParsedType &Ty, 7575 SourceLocation RParenLoc, Expr *CastExpr) { 7576 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7577 "ActOnCastExpr(): missing type or expr"); 7578 7579 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7580 if (D.isInvalidType()) 7581 return ExprError(); 7582 7583 if (getLangOpts().CPlusPlus) { 7584 // Check that there are no default arguments (C++ only). 7585 CheckExtraCXXDefaultArguments(D); 7586 } else { 7587 // Make sure any TypoExprs have been dealt with. 7588 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7589 if (!Res.isUsable()) 7590 return ExprError(); 7591 CastExpr = Res.get(); 7592 } 7593 7594 checkUnusedDeclAttributes(D); 7595 7596 QualType castType = castTInfo->getType(); 7597 Ty = CreateParsedType(castType, castTInfo); 7598 7599 bool isVectorLiteral = false; 7600 7601 // Check for an altivec or OpenCL literal, 7602 // i.e. all the elements are integer constants. 7603 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7604 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7605 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7606 && castType->isVectorType() && (PE || PLE)) { 7607 if (PLE && PLE->getNumExprs() == 0) { 7608 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7609 return ExprError(); 7610 } 7611 if (PE || PLE->getNumExprs() == 1) { 7612 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7613 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7614 isVectorLiteral = true; 7615 } 7616 else 7617 isVectorLiteral = true; 7618 } 7619 7620 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7621 // then handle it as such. 7622 if (isVectorLiteral) 7623 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7624 7625 // If the Expr being casted is a ParenListExpr, handle it specially. 7626 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7627 // sequence of BinOp comma operators. 7628 if (isa<ParenListExpr>(CastExpr)) { 7629 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7630 if (Result.isInvalid()) return ExprError(); 7631 CastExpr = Result.get(); 7632 } 7633 7634 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7635 !getSourceManager().isInSystemMacro(LParenLoc)) 7636 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7637 7638 CheckTollFreeBridgeCast(castType, CastExpr); 7639 7640 CheckObjCBridgeRelatedCast(castType, CastExpr); 7641 7642 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7643 7644 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7645 } 7646 7647 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7648 SourceLocation RParenLoc, Expr *E, 7649 TypeSourceInfo *TInfo) { 7650 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7651 "Expected paren or paren list expression"); 7652 7653 Expr **exprs; 7654 unsigned numExprs; 7655 Expr *subExpr; 7656 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7657 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7658 LiteralLParenLoc = PE->getLParenLoc(); 7659 LiteralRParenLoc = PE->getRParenLoc(); 7660 exprs = PE->getExprs(); 7661 numExprs = PE->getNumExprs(); 7662 } else { // isa<ParenExpr> by assertion at function entrance 7663 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7664 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7665 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7666 exprs = &subExpr; 7667 numExprs = 1; 7668 } 7669 7670 QualType Ty = TInfo->getType(); 7671 assert(Ty->isVectorType() && "Expected vector type"); 7672 7673 SmallVector<Expr *, 8> initExprs; 7674 const VectorType *VTy = Ty->castAs<VectorType>(); 7675 unsigned numElems = VTy->getNumElements(); 7676 7677 // '(...)' form of vector initialization in AltiVec: the number of 7678 // initializers must be one or must match the size of the vector. 7679 // If a single value is specified in the initializer then it will be 7680 // replicated to all the components of the vector 7681 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7682 // The number of initializers must be one or must match the size of the 7683 // vector. If a single value is specified in the initializer then it will 7684 // be replicated to all the components of the vector 7685 if (numExprs == 1) { 7686 QualType ElemTy = VTy->getElementType(); 7687 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7688 if (Literal.isInvalid()) 7689 return ExprError(); 7690 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7691 PrepareScalarCast(Literal, ElemTy)); 7692 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7693 } 7694 else if (numExprs < numElems) { 7695 Diag(E->getExprLoc(), 7696 diag::err_incorrect_number_of_vector_initializers); 7697 return ExprError(); 7698 } 7699 else 7700 initExprs.append(exprs, exprs + numExprs); 7701 } 7702 else { 7703 // For OpenCL, when the number of initializers is a single value, 7704 // it will be replicated to all components of the vector. 7705 if (getLangOpts().OpenCL && 7706 VTy->getVectorKind() == VectorType::GenericVector && 7707 numExprs == 1) { 7708 QualType ElemTy = VTy->getElementType(); 7709 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7710 if (Literal.isInvalid()) 7711 return ExprError(); 7712 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7713 PrepareScalarCast(Literal, ElemTy)); 7714 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7715 } 7716 7717 initExprs.append(exprs, exprs + numExprs); 7718 } 7719 // FIXME: This means that pretty-printing the final AST will produce curly 7720 // braces instead of the original commas. 7721 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7722 initExprs, LiteralRParenLoc); 7723 initE->setType(Ty); 7724 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7725 } 7726 7727 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7728 /// the ParenListExpr into a sequence of comma binary operators. 7729 ExprResult 7730 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7731 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7732 if (!E) 7733 return OrigExpr; 7734 7735 ExprResult Result(E->getExpr(0)); 7736 7737 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7738 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7739 E->getExpr(i)); 7740 7741 if (Result.isInvalid()) return ExprError(); 7742 7743 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7744 } 7745 7746 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7747 SourceLocation R, 7748 MultiExprArg Val) { 7749 return ParenListExpr::Create(Context, L, Val, R); 7750 } 7751 7752 /// Emit a specialized diagnostic when one expression is a null pointer 7753 /// constant and the other is not a pointer. Returns true if a diagnostic is 7754 /// emitted. 7755 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7756 SourceLocation QuestionLoc) { 7757 Expr *NullExpr = LHSExpr; 7758 Expr *NonPointerExpr = RHSExpr; 7759 Expr::NullPointerConstantKind NullKind = 7760 NullExpr->isNullPointerConstant(Context, 7761 Expr::NPC_ValueDependentIsNotNull); 7762 7763 if (NullKind == Expr::NPCK_NotNull) { 7764 NullExpr = RHSExpr; 7765 NonPointerExpr = LHSExpr; 7766 NullKind = 7767 NullExpr->isNullPointerConstant(Context, 7768 Expr::NPC_ValueDependentIsNotNull); 7769 } 7770 7771 if (NullKind == Expr::NPCK_NotNull) 7772 return false; 7773 7774 if (NullKind == Expr::NPCK_ZeroExpression) 7775 return false; 7776 7777 if (NullKind == Expr::NPCK_ZeroLiteral) { 7778 // In this case, check to make sure that we got here from a "NULL" 7779 // string in the source code. 7780 NullExpr = NullExpr->IgnoreParenImpCasts(); 7781 SourceLocation loc = NullExpr->getExprLoc(); 7782 if (!findMacroSpelling(loc, "NULL")) 7783 return false; 7784 } 7785 7786 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7787 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7788 << NonPointerExpr->getType() << DiagType 7789 << NonPointerExpr->getSourceRange(); 7790 return true; 7791 } 7792 7793 /// Return false if the condition expression is valid, true otherwise. 7794 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7795 QualType CondTy = Cond->getType(); 7796 7797 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7798 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7799 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7800 << CondTy << Cond->getSourceRange(); 7801 return true; 7802 } 7803 7804 // C99 6.5.15p2 7805 if (CondTy->isScalarType()) return false; 7806 7807 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7808 << CondTy << Cond->getSourceRange(); 7809 return true; 7810 } 7811 7812 /// Handle when one or both operands are void type. 7813 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7814 ExprResult &RHS) { 7815 Expr *LHSExpr = LHS.get(); 7816 Expr *RHSExpr = RHS.get(); 7817 7818 if (!LHSExpr->getType()->isVoidType()) 7819 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7820 << RHSExpr->getSourceRange(); 7821 if (!RHSExpr->getType()->isVoidType()) 7822 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7823 << LHSExpr->getSourceRange(); 7824 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7825 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7826 return S.Context.VoidTy; 7827 } 7828 7829 /// Return false if the NullExpr can be promoted to PointerTy, 7830 /// true otherwise. 7831 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7832 QualType PointerTy) { 7833 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7834 !NullExpr.get()->isNullPointerConstant(S.Context, 7835 Expr::NPC_ValueDependentIsNull)) 7836 return true; 7837 7838 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7839 return false; 7840 } 7841 7842 /// Checks compatibility between two pointers and return the resulting 7843 /// type. 7844 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7845 ExprResult &RHS, 7846 SourceLocation Loc) { 7847 QualType LHSTy = LHS.get()->getType(); 7848 QualType RHSTy = RHS.get()->getType(); 7849 7850 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7851 // Two identical pointers types are always compatible. 7852 return LHSTy; 7853 } 7854 7855 QualType lhptee, rhptee; 7856 7857 // Get the pointee types. 7858 bool IsBlockPointer = false; 7859 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7860 lhptee = LHSBTy->getPointeeType(); 7861 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7862 IsBlockPointer = true; 7863 } else { 7864 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7865 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7866 } 7867 7868 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7869 // differently qualified versions of compatible types, the result type is 7870 // a pointer to an appropriately qualified version of the composite 7871 // type. 7872 7873 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7874 // clause doesn't make sense for our extensions. E.g. address space 2 should 7875 // be incompatible with address space 3: they may live on different devices or 7876 // anything. 7877 Qualifiers lhQual = lhptee.getQualifiers(); 7878 Qualifiers rhQual = rhptee.getQualifiers(); 7879 7880 LangAS ResultAddrSpace = LangAS::Default; 7881 LangAS LAddrSpace = lhQual.getAddressSpace(); 7882 LangAS RAddrSpace = rhQual.getAddressSpace(); 7883 7884 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7885 // spaces is disallowed. 7886 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7887 ResultAddrSpace = LAddrSpace; 7888 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7889 ResultAddrSpace = RAddrSpace; 7890 else { 7891 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7892 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7893 << RHS.get()->getSourceRange(); 7894 return QualType(); 7895 } 7896 7897 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7898 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7899 lhQual.removeCVRQualifiers(); 7900 rhQual.removeCVRQualifiers(); 7901 7902 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7903 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7904 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7905 // qual types are compatible iff 7906 // * corresponded types are compatible 7907 // * CVR qualifiers are equal 7908 // * address spaces are equal 7909 // Thus for conditional operator we merge CVR and address space unqualified 7910 // pointees and if there is a composite type we return a pointer to it with 7911 // merged qualifiers. 7912 LHSCastKind = 7913 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7914 RHSCastKind = 7915 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7916 lhQual.removeAddressSpace(); 7917 rhQual.removeAddressSpace(); 7918 7919 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7920 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7921 7922 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7923 7924 if (CompositeTy.isNull()) { 7925 // In this situation, we assume void* type. No especially good 7926 // reason, but this is what gcc does, and we do have to pick 7927 // to get a consistent AST. 7928 QualType incompatTy; 7929 incompatTy = S.Context.getPointerType( 7930 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7931 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7932 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7933 7934 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7935 // for casts between types with incompatible address space qualifiers. 7936 // For the following code the compiler produces casts between global and 7937 // local address spaces of the corresponded innermost pointees: 7938 // local int *global *a; 7939 // global int *global *b; 7940 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7941 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7942 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7943 << RHS.get()->getSourceRange(); 7944 7945 return incompatTy; 7946 } 7947 7948 // The pointer types are compatible. 7949 // In case of OpenCL ResultTy should have the address space qualifier 7950 // which is a superset of address spaces of both the 2nd and the 3rd 7951 // operands of the conditional operator. 7952 QualType ResultTy = [&, ResultAddrSpace]() { 7953 if (S.getLangOpts().OpenCL) { 7954 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7955 CompositeQuals.setAddressSpace(ResultAddrSpace); 7956 return S.Context 7957 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7958 .withCVRQualifiers(MergedCVRQual); 7959 } 7960 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7961 }(); 7962 if (IsBlockPointer) 7963 ResultTy = S.Context.getBlockPointerType(ResultTy); 7964 else 7965 ResultTy = S.Context.getPointerType(ResultTy); 7966 7967 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7968 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7969 return ResultTy; 7970 } 7971 7972 /// Return the resulting type when the operands are both block pointers. 7973 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7974 ExprResult &LHS, 7975 ExprResult &RHS, 7976 SourceLocation Loc) { 7977 QualType LHSTy = LHS.get()->getType(); 7978 QualType RHSTy = RHS.get()->getType(); 7979 7980 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7981 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7982 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7983 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7984 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7985 return destType; 7986 } 7987 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7988 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7989 << RHS.get()->getSourceRange(); 7990 return QualType(); 7991 } 7992 7993 // We have 2 block pointer types. 7994 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7995 } 7996 7997 /// Return the resulting type when the operands are both pointers. 7998 static QualType 7999 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8000 ExprResult &RHS, 8001 SourceLocation Loc) { 8002 // get the pointer types 8003 QualType LHSTy = LHS.get()->getType(); 8004 QualType RHSTy = RHS.get()->getType(); 8005 8006 // get the "pointed to" types 8007 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8008 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8009 8010 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8011 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8012 // Figure out necessary qualifiers (C99 6.5.15p6) 8013 QualType destPointee 8014 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8015 QualType destType = S.Context.getPointerType(destPointee); 8016 // Add qualifiers if necessary. 8017 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8018 // Promote to void*. 8019 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8020 return destType; 8021 } 8022 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8023 QualType destPointee 8024 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8025 QualType destType = S.Context.getPointerType(destPointee); 8026 // Add qualifiers if necessary. 8027 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8028 // Promote to void*. 8029 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8030 return destType; 8031 } 8032 8033 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8034 } 8035 8036 /// Return false if the first expression is not an integer and the second 8037 /// expression is not a pointer, true otherwise. 8038 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8039 Expr* PointerExpr, SourceLocation Loc, 8040 bool IsIntFirstExpr) { 8041 if (!PointerExpr->getType()->isPointerType() || 8042 !Int.get()->getType()->isIntegerType()) 8043 return false; 8044 8045 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8046 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8047 8048 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8049 << Expr1->getType() << Expr2->getType() 8050 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8051 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8052 CK_IntegralToPointer); 8053 return true; 8054 } 8055 8056 /// Simple conversion between integer and floating point types. 8057 /// 8058 /// Used when handling the OpenCL conditional operator where the 8059 /// condition is a vector while the other operands are scalar. 8060 /// 8061 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8062 /// types are either integer or floating type. Between the two 8063 /// operands, the type with the higher rank is defined as the "result 8064 /// type". The other operand needs to be promoted to the same type. No 8065 /// other type promotion is allowed. We cannot use 8066 /// UsualArithmeticConversions() for this purpose, since it always 8067 /// promotes promotable types. 8068 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8069 ExprResult &RHS, 8070 SourceLocation QuestionLoc) { 8071 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8072 if (LHS.isInvalid()) 8073 return QualType(); 8074 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8075 if (RHS.isInvalid()) 8076 return QualType(); 8077 8078 // For conversion purposes, we ignore any qualifiers. 8079 // For example, "const float" and "float" are equivalent. 8080 QualType LHSType = 8081 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8082 QualType RHSType = 8083 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8084 8085 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8086 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8087 << LHSType << LHS.get()->getSourceRange(); 8088 return QualType(); 8089 } 8090 8091 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8092 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8093 << RHSType << RHS.get()->getSourceRange(); 8094 return QualType(); 8095 } 8096 8097 // If both types are identical, no conversion is needed. 8098 if (LHSType == RHSType) 8099 return LHSType; 8100 8101 // Now handle "real" floating types (i.e. float, double, long double). 8102 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8103 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8104 /*IsCompAssign = */ false); 8105 8106 // Finally, we have two differing integer types. 8107 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8108 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8109 } 8110 8111 /// Convert scalar operands to a vector that matches the 8112 /// condition in length. 8113 /// 8114 /// Used when handling the OpenCL conditional operator where the 8115 /// condition is a vector while the other operands are scalar. 8116 /// 8117 /// We first compute the "result type" for the scalar operands 8118 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8119 /// into a vector of that type where the length matches the condition 8120 /// vector type. s6.11.6 requires that the element types of the result 8121 /// and the condition must have the same number of bits. 8122 static QualType 8123 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8124 QualType CondTy, SourceLocation QuestionLoc) { 8125 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8126 if (ResTy.isNull()) return QualType(); 8127 8128 const VectorType *CV = CondTy->getAs<VectorType>(); 8129 assert(CV); 8130 8131 // Determine the vector result type 8132 unsigned NumElements = CV->getNumElements(); 8133 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8134 8135 // Ensure that all types have the same number of bits 8136 if (S.Context.getTypeSize(CV->getElementType()) 8137 != S.Context.getTypeSize(ResTy)) { 8138 // Since VectorTy is created internally, it does not pretty print 8139 // with an OpenCL name. Instead, we just print a description. 8140 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8141 SmallString<64> Str; 8142 llvm::raw_svector_ostream OS(Str); 8143 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8144 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8145 << CondTy << OS.str(); 8146 return QualType(); 8147 } 8148 8149 // Convert operands to the vector result type 8150 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8151 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8152 8153 return VectorTy; 8154 } 8155 8156 /// Return false if this is a valid OpenCL condition vector 8157 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8158 SourceLocation QuestionLoc) { 8159 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8160 // integral type. 8161 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8162 assert(CondTy); 8163 QualType EleTy = CondTy->getElementType(); 8164 if (EleTy->isIntegerType()) return false; 8165 8166 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8167 << Cond->getType() << Cond->getSourceRange(); 8168 return true; 8169 } 8170 8171 /// Return false if the vector condition type and the vector 8172 /// result type are compatible. 8173 /// 8174 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8175 /// number of elements, and their element types have the same number 8176 /// of bits. 8177 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8178 SourceLocation QuestionLoc) { 8179 const VectorType *CV = CondTy->getAs<VectorType>(); 8180 const VectorType *RV = VecResTy->getAs<VectorType>(); 8181 assert(CV && RV); 8182 8183 if (CV->getNumElements() != RV->getNumElements()) { 8184 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8185 << CondTy << VecResTy; 8186 return true; 8187 } 8188 8189 QualType CVE = CV->getElementType(); 8190 QualType RVE = RV->getElementType(); 8191 8192 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8193 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8194 << CondTy << VecResTy; 8195 return true; 8196 } 8197 8198 return false; 8199 } 8200 8201 /// Return the resulting type for the conditional operator in 8202 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8203 /// s6.3.i) when the condition is a vector type. 8204 static QualType 8205 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8206 ExprResult &LHS, ExprResult &RHS, 8207 SourceLocation QuestionLoc) { 8208 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8209 if (Cond.isInvalid()) 8210 return QualType(); 8211 QualType CondTy = Cond.get()->getType(); 8212 8213 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8214 return QualType(); 8215 8216 // If either operand is a vector then find the vector type of the 8217 // result as specified in OpenCL v1.1 s6.3.i. 8218 if (LHS.get()->getType()->isVectorType() || 8219 RHS.get()->getType()->isVectorType()) { 8220 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8221 /*isCompAssign*/false, 8222 /*AllowBothBool*/true, 8223 /*AllowBoolConversions*/false); 8224 if (VecResTy.isNull()) return QualType(); 8225 // The result type must match the condition type as specified in 8226 // OpenCL v1.1 s6.11.6. 8227 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8228 return QualType(); 8229 return VecResTy; 8230 } 8231 8232 // Both operands are scalar. 8233 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8234 } 8235 8236 /// Return true if the Expr is block type 8237 static bool checkBlockType(Sema &S, const Expr *E) { 8238 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8239 QualType Ty = CE->getCallee()->getType(); 8240 if (Ty->isBlockPointerType()) { 8241 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8242 return true; 8243 } 8244 } 8245 return false; 8246 } 8247 8248 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8249 /// In that case, LHS = cond. 8250 /// C99 6.5.15 8251 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8252 ExprResult &RHS, ExprValueKind &VK, 8253 ExprObjectKind &OK, 8254 SourceLocation QuestionLoc) { 8255 8256 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8257 if (!LHSResult.isUsable()) return QualType(); 8258 LHS = LHSResult; 8259 8260 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8261 if (!RHSResult.isUsable()) return QualType(); 8262 RHS = RHSResult; 8263 8264 // C++ is sufficiently different to merit its own checker. 8265 if (getLangOpts().CPlusPlus) 8266 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8267 8268 VK = VK_PRValue; 8269 OK = OK_Ordinary; 8270 8271 if (Context.isDependenceAllowed() && 8272 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8273 RHS.get()->isTypeDependent())) { 8274 assert(!getLangOpts().CPlusPlus); 8275 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8276 RHS.get()->containsErrors()) && 8277 "should only occur in error-recovery path."); 8278 return Context.DependentTy; 8279 } 8280 8281 // The OpenCL operator with a vector condition is sufficiently 8282 // different to merit its own checker. 8283 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8284 Cond.get()->getType()->isExtVectorType()) 8285 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8286 8287 // First, check the condition. 8288 Cond = UsualUnaryConversions(Cond.get()); 8289 if (Cond.isInvalid()) 8290 return QualType(); 8291 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8292 return QualType(); 8293 8294 // Now check the two expressions. 8295 if (LHS.get()->getType()->isVectorType() || 8296 RHS.get()->getType()->isVectorType()) 8297 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8298 /*AllowBothBool*/true, 8299 /*AllowBoolConversions*/false); 8300 8301 QualType ResTy = 8302 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8303 if (LHS.isInvalid() || RHS.isInvalid()) 8304 return QualType(); 8305 8306 QualType LHSTy = LHS.get()->getType(); 8307 QualType RHSTy = RHS.get()->getType(); 8308 8309 // Diagnose attempts to convert between __float128 and long double where 8310 // such conversions currently can't be handled. 8311 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8312 Diag(QuestionLoc, 8313 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8315 return QualType(); 8316 } 8317 8318 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8319 // selection operator (?:). 8320 if (getLangOpts().OpenCL && 8321 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8322 return QualType(); 8323 } 8324 8325 // If both operands have arithmetic type, do the usual arithmetic conversions 8326 // to find a common type: C99 6.5.15p3,5. 8327 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8328 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8329 // different sizes, or between ExtInts and other types. 8330 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8331 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8332 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8333 << RHS.get()->getSourceRange(); 8334 return QualType(); 8335 } 8336 8337 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8338 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8339 8340 return ResTy; 8341 } 8342 8343 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8344 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8345 return LHSTy; 8346 } 8347 8348 // If both operands are the same structure or union type, the result is that 8349 // type. 8350 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8351 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8352 if (LHSRT->getDecl() == RHSRT->getDecl()) 8353 // "If both the operands have structure or union type, the result has 8354 // that type." This implies that CV qualifiers are dropped. 8355 return LHSTy.getUnqualifiedType(); 8356 // FIXME: Type of conditional expression must be complete in C mode. 8357 } 8358 8359 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8360 // The following || allows only one side to be void (a GCC-ism). 8361 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8362 return checkConditionalVoidType(*this, LHS, RHS); 8363 } 8364 8365 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8366 // the type of the other operand." 8367 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8368 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8369 8370 // All objective-c pointer type analysis is done here. 8371 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8372 QuestionLoc); 8373 if (LHS.isInvalid() || RHS.isInvalid()) 8374 return QualType(); 8375 if (!compositeType.isNull()) 8376 return compositeType; 8377 8378 8379 // Handle block pointer types. 8380 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8381 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8382 QuestionLoc); 8383 8384 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8385 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8386 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8387 QuestionLoc); 8388 8389 // GCC compatibility: soften pointer/integer mismatch. Note that 8390 // null pointers have been filtered out by this point. 8391 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8392 /*IsIntFirstExpr=*/true)) 8393 return RHSTy; 8394 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8395 /*IsIntFirstExpr=*/false)) 8396 return LHSTy; 8397 8398 // Allow ?: operations in which both operands have the same 8399 // built-in sizeless type. 8400 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8401 return LHSTy; 8402 8403 // Emit a better diagnostic if one of the expressions is a null pointer 8404 // constant and the other is not a pointer type. In this case, the user most 8405 // likely forgot to take the address of the other expression. 8406 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8407 return QualType(); 8408 8409 // Otherwise, the operands are not compatible. 8410 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8411 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8412 << RHS.get()->getSourceRange(); 8413 return QualType(); 8414 } 8415 8416 /// FindCompositeObjCPointerType - Helper method to find composite type of 8417 /// two objective-c pointer types of the two input expressions. 8418 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8419 SourceLocation QuestionLoc) { 8420 QualType LHSTy = LHS.get()->getType(); 8421 QualType RHSTy = RHS.get()->getType(); 8422 8423 // Handle things like Class and struct objc_class*. Here we case the result 8424 // to the pseudo-builtin, because that will be implicitly cast back to the 8425 // redefinition type if an attempt is made to access its fields. 8426 if (LHSTy->isObjCClassType() && 8427 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8428 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8429 return LHSTy; 8430 } 8431 if (RHSTy->isObjCClassType() && 8432 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8433 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8434 return RHSTy; 8435 } 8436 // And the same for struct objc_object* / id 8437 if (LHSTy->isObjCIdType() && 8438 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8439 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8440 return LHSTy; 8441 } 8442 if (RHSTy->isObjCIdType() && 8443 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8444 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8445 return RHSTy; 8446 } 8447 // And the same for struct objc_selector* / SEL 8448 if (Context.isObjCSelType(LHSTy) && 8449 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8450 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8451 return LHSTy; 8452 } 8453 if (Context.isObjCSelType(RHSTy) && 8454 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8455 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8456 return RHSTy; 8457 } 8458 // Check constraints for Objective-C object pointers types. 8459 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8460 8461 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8462 // Two identical object pointer types are always compatible. 8463 return LHSTy; 8464 } 8465 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8466 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8467 QualType compositeType = LHSTy; 8468 8469 // If both operands are interfaces and either operand can be 8470 // assigned to the other, use that type as the composite 8471 // type. This allows 8472 // xxx ? (A*) a : (B*) b 8473 // where B is a subclass of A. 8474 // 8475 // Additionally, as for assignment, if either type is 'id' 8476 // allow silent coercion. Finally, if the types are 8477 // incompatible then make sure to use 'id' as the composite 8478 // type so the result is acceptable for sending messages to. 8479 8480 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8481 // It could return the composite type. 8482 if (!(compositeType = 8483 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8484 // Nothing more to do. 8485 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8486 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8487 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8488 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8489 } else if ((LHSOPT->isObjCQualifiedIdType() || 8490 RHSOPT->isObjCQualifiedIdType()) && 8491 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8492 true)) { 8493 // Need to handle "id<xx>" explicitly. 8494 // GCC allows qualified id and any Objective-C type to devolve to 8495 // id. Currently localizing to here until clear this should be 8496 // part of ObjCQualifiedIdTypesAreCompatible. 8497 compositeType = Context.getObjCIdType(); 8498 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8499 compositeType = Context.getObjCIdType(); 8500 } else { 8501 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8502 << LHSTy << RHSTy 8503 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8504 QualType incompatTy = Context.getObjCIdType(); 8505 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8506 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8507 return incompatTy; 8508 } 8509 // The object pointer types are compatible. 8510 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8511 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8512 return compositeType; 8513 } 8514 // Check Objective-C object pointer types and 'void *' 8515 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8516 if (getLangOpts().ObjCAutoRefCount) { 8517 // ARC forbids the implicit conversion of object pointers to 'void *', 8518 // so these types are not compatible. 8519 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8520 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8521 LHS = RHS = true; 8522 return QualType(); 8523 } 8524 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8525 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8526 QualType destPointee 8527 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8528 QualType destType = Context.getPointerType(destPointee); 8529 // Add qualifiers if necessary. 8530 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8531 // Promote to void*. 8532 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8533 return destType; 8534 } 8535 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8536 if (getLangOpts().ObjCAutoRefCount) { 8537 // ARC forbids the implicit conversion of object pointers to 'void *', 8538 // so these types are not compatible. 8539 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8541 LHS = RHS = true; 8542 return QualType(); 8543 } 8544 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8545 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8546 QualType destPointee 8547 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8548 QualType destType = Context.getPointerType(destPointee); 8549 // Add qualifiers if necessary. 8550 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8551 // Promote to void*. 8552 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8553 return destType; 8554 } 8555 return QualType(); 8556 } 8557 8558 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8559 /// ParenRange in parentheses. 8560 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8561 const PartialDiagnostic &Note, 8562 SourceRange ParenRange) { 8563 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8564 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8565 EndLoc.isValid()) { 8566 Self.Diag(Loc, Note) 8567 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8568 << FixItHint::CreateInsertion(EndLoc, ")"); 8569 } else { 8570 // We can't display the parentheses, so just show the bare note. 8571 Self.Diag(Loc, Note) << ParenRange; 8572 } 8573 } 8574 8575 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8576 return BinaryOperator::isAdditiveOp(Opc) || 8577 BinaryOperator::isMultiplicativeOp(Opc) || 8578 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8579 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8580 // not any of the logical operators. Bitwise-xor is commonly used as a 8581 // logical-xor because there is no logical-xor operator. The logical 8582 // operators, including uses of xor, have a high false positive rate for 8583 // precedence warnings. 8584 } 8585 8586 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8587 /// expression, either using a built-in or overloaded operator, 8588 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8589 /// expression. 8590 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8591 Expr **RHSExprs) { 8592 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8593 E = E->IgnoreImpCasts(); 8594 E = E->IgnoreConversionOperatorSingleStep(); 8595 E = E->IgnoreImpCasts(); 8596 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8597 E = MTE->getSubExpr(); 8598 E = E->IgnoreImpCasts(); 8599 } 8600 8601 // Built-in binary operator. 8602 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8603 if (IsArithmeticOp(OP->getOpcode())) { 8604 *Opcode = OP->getOpcode(); 8605 *RHSExprs = OP->getRHS(); 8606 return true; 8607 } 8608 } 8609 8610 // Overloaded operator. 8611 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8612 if (Call->getNumArgs() != 2) 8613 return false; 8614 8615 // Make sure this is really a binary operator that is safe to pass into 8616 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8617 OverloadedOperatorKind OO = Call->getOperator(); 8618 if (OO < OO_Plus || OO > OO_Arrow || 8619 OO == OO_PlusPlus || OO == OO_MinusMinus) 8620 return false; 8621 8622 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8623 if (IsArithmeticOp(OpKind)) { 8624 *Opcode = OpKind; 8625 *RHSExprs = Call->getArg(1); 8626 return true; 8627 } 8628 } 8629 8630 return false; 8631 } 8632 8633 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8634 /// or is a logical expression such as (x==y) which has int type, but is 8635 /// commonly interpreted as boolean. 8636 static bool ExprLooksBoolean(Expr *E) { 8637 E = E->IgnoreParenImpCasts(); 8638 8639 if (E->getType()->isBooleanType()) 8640 return true; 8641 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8642 return OP->isComparisonOp() || OP->isLogicalOp(); 8643 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8644 return OP->getOpcode() == UO_LNot; 8645 if (E->getType()->isPointerType()) 8646 return true; 8647 // FIXME: What about overloaded operator calls returning "unspecified boolean 8648 // type"s (commonly pointer-to-members)? 8649 8650 return false; 8651 } 8652 8653 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8654 /// and binary operator are mixed in a way that suggests the programmer assumed 8655 /// the conditional operator has higher precedence, for example: 8656 /// "int x = a + someBinaryCondition ? 1 : 2". 8657 static void DiagnoseConditionalPrecedence(Sema &Self, 8658 SourceLocation OpLoc, 8659 Expr *Condition, 8660 Expr *LHSExpr, 8661 Expr *RHSExpr) { 8662 BinaryOperatorKind CondOpcode; 8663 Expr *CondRHS; 8664 8665 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8666 return; 8667 if (!ExprLooksBoolean(CondRHS)) 8668 return; 8669 8670 // The condition is an arithmetic binary expression, with a right- 8671 // hand side that looks boolean, so warn. 8672 8673 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8674 ? diag::warn_precedence_bitwise_conditional 8675 : diag::warn_precedence_conditional; 8676 8677 Self.Diag(OpLoc, DiagID) 8678 << Condition->getSourceRange() 8679 << BinaryOperator::getOpcodeStr(CondOpcode); 8680 8681 SuggestParentheses( 8682 Self, OpLoc, 8683 Self.PDiag(diag::note_precedence_silence) 8684 << BinaryOperator::getOpcodeStr(CondOpcode), 8685 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8686 8687 SuggestParentheses(Self, OpLoc, 8688 Self.PDiag(diag::note_precedence_conditional_first), 8689 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8690 } 8691 8692 /// Compute the nullability of a conditional expression. 8693 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8694 QualType LHSTy, QualType RHSTy, 8695 ASTContext &Ctx) { 8696 if (!ResTy->isAnyPointerType()) 8697 return ResTy; 8698 8699 auto GetNullability = [&Ctx](QualType Ty) { 8700 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8701 if (Kind) { 8702 // For our purposes, treat _Nullable_result as _Nullable. 8703 if (*Kind == NullabilityKind::NullableResult) 8704 return NullabilityKind::Nullable; 8705 return *Kind; 8706 } 8707 return NullabilityKind::Unspecified; 8708 }; 8709 8710 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8711 NullabilityKind MergedKind; 8712 8713 // Compute nullability of a binary conditional expression. 8714 if (IsBin) { 8715 if (LHSKind == NullabilityKind::NonNull) 8716 MergedKind = NullabilityKind::NonNull; 8717 else 8718 MergedKind = RHSKind; 8719 // Compute nullability of a normal conditional expression. 8720 } else { 8721 if (LHSKind == NullabilityKind::Nullable || 8722 RHSKind == NullabilityKind::Nullable) 8723 MergedKind = NullabilityKind::Nullable; 8724 else if (LHSKind == NullabilityKind::NonNull) 8725 MergedKind = RHSKind; 8726 else if (RHSKind == NullabilityKind::NonNull) 8727 MergedKind = LHSKind; 8728 else 8729 MergedKind = NullabilityKind::Unspecified; 8730 } 8731 8732 // Return if ResTy already has the correct nullability. 8733 if (GetNullability(ResTy) == MergedKind) 8734 return ResTy; 8735 8736 // Strip all nullability from ResTy. 8737 while (ResTy->getNullability(Ctx)) 8738 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8739 8740 // Create a new AttributedType with the new nullability kind. 8741 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8742 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8743 } 8744 8745 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8746 /// in the case of a the GNU conditional expr extension. 8747 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8748 SourceLocation ColonLoc, 8749 Expr *CondExpr, Expr *LHSExpr, 8750 Expr *RHSExpr) { 8751 if (!Context.isDependenceAllowed()) { 8752 // C cannot handle TypoExpr nodes in the condition because it 8753 // doesn't handle dependent types properly, so make sure any TypoExprs have 8754 // been dealt with before checking the operands. 8755 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8756 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8757 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8758 8759 if (!CondResult.isUsable()) 8760 return ExprError(); 8761 8762 if (LHSExpr) { 8763 if (!LHSResult.isUsable()) 8764 return ExprError(); 8765 } 8766 8767 if (!RHSResult.isUsable()) 8768 return ExprError(); 8769 8770 CondExpr = CondResult.get(); 8771 LHSExpr = LHSResult.get(); 8772 RHSExpr = RHSResult.get(); 8773 } 8774 8775 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8776 // was the condition. 8777 OpaqueValueExpr *opaqueValue = nullptr; 8778 Expr *commonExpr = nullptr; 8779 if (!LHSExpr) { 8780 commonExpr = CondExpr; 8781 // Lower out placeholder types first. This is important so that we don't 8782 // try to capture a placeholder. This happens in few cases in C++; such 8783 // as Objective-C++'s dictionary subscripting syntax. 8784 if (commonExpr->hasPlaceholderType()) { 8785 ExprResult result = CheckPlaceholderExpr(commonExpr); 8786 if (!result.isUsable()) return ExprError(); 8787 commonExpr = result.get(); 8788 } 8789 // We usually want to apply unary conversions *before* saving, except 8790 // in the special case of a C++ l-value conditional. 8791 if (!(getLangOpts().CPlusPlus 8792 && !commonExpr->isTypeDependent() 8793 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8794 && commonExpr->isGLValue() 8795 && commonExpr->isOrdinaryOrBitFieldObject() 8796 && RHSExpr->isOrdinaryOrBitFieldObject() 8797 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8798 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8799 if (commonRes.isInvalid()) 8800 return ExprError(); 8801 commonExpr = commonRes.get(); 8802 } 8803 8804 // If the common expression is a class or array prvalue, materialize it 8805 // so that we can safely refer to it multiple times. 8806 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8807 commonExpr->getType()->isArrayType())) { 8808 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8809 if (MatExpr.isInvalid()) 8810 return ExprError(); 8811 commonExpr = MatExpr.get(); 8812 } 8813 8814 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8815 commonExpr->getType(), 8816 commonExpr->getValueKind(), 8817 commonExpr->getObjectKind(), 8818 commonExpr); 8819 LHSExpr = CondExpr = opaqueValue; 8820 } 8821 8822 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8823 ExprValueKind VK = VK_PRValue; 8824 ExprObjectKind OK = OK_Ordinary; 8825 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8826 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8827 VK, OK, QuestionLoc); 8828 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8829 RHS.isInvalid()) 8830 return ExprError(); 8831 8832 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8833 RHS.get()); 8834 8835 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8836 8837 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8838 Context); 8839 8840 if (!commonExpr) 8841 return new (Context) 8842 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8843 RHS.get(), result, VK, OK); 8844 8845 return new (Context) BinaryConditionalOperator( 8846 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8847 ColonLoc, result, VK, OK); 8848 } 8849 8850 // Check if we have a conversion between incompatible cmse function pointer 8851 // types, that is, a conversion between a function pointer with the 8852 // cmse_nonsecure_call attribute and one without. 8853 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8854 QualType ToType) { 8855 if (const auto *ToFn = 8856 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8857 if (const auto *FromFn = 8858 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8859 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8860 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8861 8862 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8863 } 8864 } 8865 return false; 8866 } 8867 8868 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8869 // being closely modeled after the C99 spec:-). The odd characteristic of this 8870 // routine is it effectively iqnores the qualifiers on the top level pointee. 8871 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8872 // FIXME: add a couple examples in this comment. 8873 static Sema::AssignConvertType 8874 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8875 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8876 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8877 8878 // get the "pointed to" type (ignoring qualifiers at the top level) 8879 const Type *lhptee, *rhptee; 8880 Qualifiers lhq, rhq; 8881 std::tie(lhptee, lhq) = 8882 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8883 std::tie(rhptee, rhq) = 8884 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8885 8886 Sema::AssignConvertType ConvTy = Sema::Compatible; 8887 8888 // C99 6.5.16.1p1: This following citation is common to constraints 8889 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8890 // qualifiers of the type *pointed to* by the right; 8891 8892 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8893 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8894 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8895 // Ignore lifetime for further calculation. 8896 lhq.removeObjCLifetime(); 8897 rhq.removeObjCLifetime(); 8898 } 8899 8900 if (!lhq.compatiblyIncludes(rhq)) { 8901 // Treat address-space mismatches as fatal. 8902 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8903 return Sema::IncompatiblePointerDiscardsQualifiers; 8904 8905 // It's okay to add or remove GC or lifetime qualifiers when converting to 8906 // and from void*. 8907 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8908 .compatiblyIncludes( 8909 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8910 && (lhptee->isVoidType() || rhptee->isVoidType())) 8911 ; // keep old 8912 8913 // Treat lifetime mismatches as fatal. 8914 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8915 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8916 8917 // For GCC/MS compatibility, other qualifier mismatches are treated 8918 // as still compatible in C. 8919 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8920 } 8921 8922 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8923 // incomplete type and the other is a pointer to a qualified or unqualified 8924 // version of void... 8925 if (lhptee->isVoidType()) { 8926 if (rhptee->isIncompleteOrObjectType()) 8927 return ConvTy; 8928 8929 // As an extension, we allow cast to/from void* to function pointer. 8930 assert(rhptee->isFunctionType()); 8931 return Sema::FunctionVoidPointer; 8932 } 8933 8934 if (rhptee->isVoidType()) { 8935 if (lhptee->isIncompleteOrObjectType()) 8936 return ConvTy; 8937 8938 // As an extension, we allow cast to/from void* to function pointer. 8939 assert(lhptee->isFunctionType()); 8940 return Sema::FunctionVoidPointer; 8941 } 8942 8943 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8944 // unqualified versions of compatible types, ... 8945 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8946 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8947 // Check if the pointee types are compatible ignoring the sign. 8948 // We explicitly check for char so that we catch "char" vs 8949 // "unsigned char" on systems where "char" is unsigned. 8950 if (lhptee->isCharType()) 8951 ltrans = S.Context.UnsignedCharTy; 8952 else if (lhptee->hasSignedIntegerRepresentation()) 8953 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8954 8955 if (rhptee->isCharType()) 8956 rtrans = S.Context.UnsignedCharTy; 8957 else if (rhptee->hasSignedIntegerRepresentation()) 8958 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8959 8960 if (ltrans == rtrans) { 8961 // Types are compatible ignoring the sign. Qualifier incompatibility 8962 // takes priority over sign incompatibility because the sign 8963 // warning can be disabled. 8964 if (ConvTy != Sema::Compatible) 8965 return ConvTy; 8966 8967 return Sema::IncompatiblePointerSign; 8968 } 8969 8970 // If we are a multi-level pointer, it's possible that our issue is simply 8971 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8972 // the eventual target type is the same and the pointers have the same 8973 // level of indirection, this must be the issue. 8974 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8975 do { 8976 std::tie(lhptee, lhq) = 8977 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8978 std::tie(rhptee, rhq) = 8979 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8980 8981 // Inconsistent address spaces at this point is invalid, even if the 8982 // address spaces would be compatible. 8983 // FIXME: This doesn't catch address space mismatches for pointers of 8984 // different nesting levels, like: 8985 // __local int *** a; 8986 // int ** b = a; 8987 // It's not clear how to actually determine when such pointers are 8988 // invalidly incompatible. 8989 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8990 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8991 8992 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8993 8994 if (lhptee == rhptee) 8995 return Sema::IncompatibleNestedPointerQualifiers; 8996 } 8997 8998 // General pointer incompatibility takes priority over qualifiers. 8999 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9000 return Sema::IncompatibleFunctionPointer; 9001 return Sema::IncompatiblePointer; 9002 } 9003 if (!S.getLangOpts().CPlusPlus && 9004 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9005 return Sema::IncompatibleFunctionPointer; 9006 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9007 return Sema::IncompatibleFunctionPointer; 9008 return ConvTy; 9009 } 9010 9011 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9012 /// block pointer types are compatible or whether a block and normal pointer 9013 /// are compatible. It is more restrict than comparing two function pointer 9014 // types. 9015 static Sema::AssignConvertType 9016 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9017 QualType RHSType) { 9018 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9019 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9020 9021 QualType lhptee, rhptee; 9022 9023 // get the "pointed to" type (ignoring qualifiers at the top level) 9024 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9025 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9026 9027 // In C++, the types have to match exactly. 9028 if (S.getLangOpts().CPlusPlus) 9029 return Sema::IncompatibleBlockPointer; 9030 9031 Sema::AssignConvertType ConvTy = Sema::Compatible; 9032 9033 // For blocks we enforce that qualifiers are identical. 9034 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9035 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9036 if (S.getLangOpts().OpenCL) { 9037 LQuals.removeAddressSpace(); 9038 RQuals.removeAddressSpace(); 9039 } 9040 if (LQuals != RQuals) 9041 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9042 9043 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9044 // assignment. 9045 // The current behavior is similar to C++ lambdas. A block might be 9046 // assigned to a variable iff its return type and parameters are compatible 9047 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9048 // an assignment. Presumably it should behave in way that a function pointer 9049 // assignment does in C, so for each parameter and return type: 9050 // * CVR and address space of LHS should be a superset of CVR and address 9051 // space of RHS. 9052 // * unqualified types should be compatible. 9053 if (S.getLangOpts().OpenCL) { 9054 if (!S.Context.typesAreBlockPointerCompatible( 9055 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9056 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9057 return Sema::IncompatibleBlockPointer; 9058 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9059 return Sema::IncompatibleBlockPointer; 9060 9061 return ConvTy; 9062 } 9063 9064 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9065 /// for assignment compatibility. 9066 static Sema::AssignConvertType 9067 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9068 QualType RHSType) { 9069 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9070 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9071 9072 if (LHSType->isObjCBuiltinType()) { 9073 // Class is not compatible with ObjC object pointers. 9074 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9075 !RHSType->isObjCQualifiedClassType()) 9076 return Sema::IncompatiblePointer; 9077 return Sema::Compatible; 9078 } 9079 if (RHSType->isObjCBuiltinType()) { 9080 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9081 !LHSType->isObjCQualifiedClassType()) 9082 return Sema::IncompatiblePointer; 9083 return Sema::Compatible; 9084 } 9085 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9086 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9087 9088 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9089 // make an exception for id<P> 9090 !LHSType->isObjCQualifiedIdType()) 9091 return Sema::CompatiblePointerDiscardsQualifiers; 9092 9093 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9094 return Sema::Compatible; 9095 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9096 return Sema::IncompatibleObjCQualifiedId; 9097 return Sema::IncompatiblePointer; 9098 } 9099 9100 Sema::AssignConvertType 9101 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9102 QualType LHSType, QualType RHSType) { 9103 // Fake up an opaque expression. We don't actually care about what 9104 // cast operations are required, so if CheckAssignmentConstraints 9105 // adds casts to this they'll be wasted, but fortunately that doesn't 9106 // usually happen on valid code. 9107 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9108 ExprResult RHSPtr = &RHSExpr; 9109 CastKind K; 9110 9111 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9112 } 9113 9114 /// This helper function returns true if QT is a vector type that has element 9115 /// type ElementType. 9116 static bool isVector(QualType QT, QualType ElementType) { 9117 if (const VectorType *VT = QT->getAs<VectorType>()) 9118 return VT->getElementType().getCanonicalType() == ElementType; 9119 return false; 9120 } 9121 9122 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9123 /// has code to accommodate several GCC extensions when type checking 9124 /// pointers. Here are some objectionable examples that GCC considers warnings: 9125 /// 9126 /// int a, *pint; 9127 /// short *pshort; 9128 /// struct foo *pfoo; 9129 /// 9130 /// pint = pshort; // warning: assignment from incompatible pointer type 9131 /// a = pint; // warning: assignment makes integer from pointer without a cast 9132 /// pint = a; // warning: assignment makes pointer from integer without a cast 9133 /// pint = pfoo; // warning: assignment from incompatible pointer type 9134 /// 9135 /// As a result, the code for dealing with pointers is more complex than the 9136 /// C99 spec dictates. 9137 /// 9138 /// Sets 'Kind' for any result kind except Incompatible. 9139 Sema::AssignConvertType 9140 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9141 CastKind &Kind, bool ConvertRHS) { 9142 QualType RHSType = RHS.get()->getType(); 9143 QualType OrigLHSType = LHSType; 9144 9145 // Get canonical types. We're not formatting these types, just comparing 9146 // them. 9147 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9148 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9149 9150 // Common case: no conversion required. 9151 if (LHSType == RHSType) { 9152 Kind = CK_NoOp; 9153 return Compatible; 9154 } 9155 9156 // If we have an atomic type, try a non-atomic assignment, then just add an 9157 // atomic qualification step. 9158 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9159 Sema::AssignConvertType result = 9160 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9161 if (result != Compatible) 9162 return result; 9163 if (Kind != CK_NoOp && ConvertRHS) 9164 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9165 Kind = CK_NonAtomicToAtomic; 9166 return Compatible; 9167 } 9168 9169 // If the left-hand side is a reference type, then we are in a 9170 // (rare!) case where we've allowed the use of references in C, 9171 // e.g., as a parameter type in a built-in function. In this case, 9172 // just make sure that the type referenced is compatible with the 9173 // right-hand side type. The caller is responsible for adjusting 9174 // LHSType so that the resulting expression does not have reference 9175 // type. 9176 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9177 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9178 Kind = CK_LValueBitCast; 9179 return Compatible; 9180 } 9181 return Incompatible; 9182 } 9183 9184 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9185 // to the same ExtVector type. 9186 if (LHSType->isExtVectorType()) { 9187 if (RHSType->isExtVectorType()) 9188 return Incompatible; 9189 if (RHSType->isArithmeticType()) { 9190 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9191 if (ConvertRHS) 9192 RHS = prepareVectorSplat(LHSType, RHS.get()); 9193 Kind = CK_VectorSplat; 9194 return Compatible; 9195 } 9196 } 9197 9198 // Conversions to or from vector type. 9199 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9200 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9201 // Allow assignments of an AltiVec vector type to an equivalent GCC 9202 // vector type and vice versa 9203 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9204 Kind = CK_BitCast; 9205 return Compatible; 9206 } 9207 9208 // If we are allowing lax vector conversions, and LHS and RHS are both 9209 // vectors, the total size only needs to be the same. This is a bitcast; 9210 // no bits are changed but the result type is different. 9211 if (isLaxVectorConversion(RHSType, LHSType)) { 9212 Kind = CK_BitCast; 9213 return IncompatibleVectors; 9214 } 9215 } 9216 9217 // When the RHS comes from another lax conversion (e.g. binops between 9218 // scalars and vectors) the result is canonicalized as a vector. When the 9219 // LHS is also a vector, the lax is allowed by the condition above. Handle 9220 // the case where LHS is a scalar. 9221 if (LHSType->isScalarType()) { 9222 const VectorType *VecType = RHSType->getAs<VectorType>(); 9223 if (VecType && VecType->getNumElements() == 1 && 9224 isLaxVectorConversion(RHSType, LHSType)) { 9225 ExprResult *VecExpr = &RHS; 9226 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9227 Kind = CK_BitCast; 9228 return Compatible; 9229 } 9230 } 9231 9232 // Allow assignments between fixed-length and sizeless SVE vectors. 9233 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9234 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9235 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9236 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9237 Kind = CK_BitCast; 9238 return Compatible; 9239 } 9240 9241 return Incompatible; 9242 } 9243 9244 // Diagnose attempts to convert between __float128 and long double where 9245 // such conversions currently can't be handled. 9246 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9247 return Incompatible; 9248 9249 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9250 // discards the imaginary part. 9251 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9252 !LHSType->getAs<ComplexType>()) 9253 return Incompatible; 9254 9255 // Arithmetic conversions. 9256 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9257 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9258 if (ConvertRHS) 9259 Kind = PrepareScalarCast(RHS, LHSType); 9260 return Compatible; 9261 } 9262 9263 // Conversions to normal pointers. 9264 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9265 // U* -> T* 9266 if (isa<PointerType>(RHSType)) { 9267 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9268 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9269 if (AddrSpaceL != AddrSpaceR) 9270 Kind = CK_AddressSpaceConversion; 9271 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9272 Kind = CK_NoOp; 9273 else 9274 Kind = CK_BitCast; 9275 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9276 } 9277 9278 // int -> T* 9279 if (RHSType->isIntegerType()) { 9280 Kind = CK_IntegralToPointer; // FIXME: null? 9281 return IntToPointer; 9282 } 9283 9284 // C pointers are not compatible with ObjC object pointers, 9285 // with two exceptions: 9286 if (isa<ObjCObjectPointerType>(RHSType)) { 9287 // - conversions to void* 9288 if (LHSPointer->getPointeeType()->isVoidType()) { 9289 Kind = CK_BitCast; 9290 return Compatible; 9291 } 9292 9293 // - conversions from 'Class' to the redefinition type 9294 if (RHSType->isObjCClassType() && 9295 Context.hasSameType(LHSType, 9296 Context.getObjCClassRedefinitionType())) { 9297 Kind = CK_BitCast; 9298 return Compatible; 9299 } 9300 9301 Kind = CK_BitCast; 9302 return IncompatiblePointer; 9303 } 9304 9305 // U^ -> void* 9306 if (RHSType->getAs<BlockPointerType>()) { 9307 if (LHSPointer->getPointeeType()->isVoidType()) { 9308 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9309 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9310 ->getPointeeType() 9311 .getAddressSpace(); 9312 Kind = 9313 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9314 return Compatible; 9315 } 9316 } 9317 9318 return Incompatible; 9319 } 9320 9321 // Conversions to block pointers. 9322 if (isa<BlockPointerType>(LHSType)) { 9323 // U^ -> T^ 9324 if (RHSType->isBlockPointerType()) { 9325 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9326 ->getPointeeType() 9327 .getAddressSpace(); 9328 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9329 ->getPointeeType() 9330 .getAddressSpace(); 9331 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9332 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9333 } 9334 9335 // int or null -> T^ 9336 if (RHSType->isIntegerType()) { 9337 Kind = CK_IntegralToPointer; // FIXME: null 9338 return IntToBlockPointer; 9339 } 9340 9341 // id -> T^ 9342 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9343 Kind = CK_AnyPointerToBlockPointerCast; 9344 return Compatible; 9345 } 9346 9347 // void* -> T^ 9348 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9349 if (RHSPT->getPointeeType()->isVoidType()) { 9350 Kind = CK_AnyPointerToBlockPointerCast; 9351 return Compatible; 9352 } 9353 9354 return Incompatible; 9355 } 9356 9357 // Conversions to Objective-C pointers. 9358 if (isa<ObjCObjectPointerType>(LHSType)) { 9359 // A* -> B* 9360 if (RHSType->isObjCObjectPointerType()) { 9361 Kind = CK_BitCast; 9362 Sema::AssignConvertType result = 9363 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9364 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9365 result == Compatible && 9366 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9367 result = IncompatibleObjCWeakRef; 9368 return result; 9369 } 9370 9371 // int or null -> A* 9372 if (RHSType->isIntegerType()) { 9373 Kind = CK_IntegralToPointer; // FIXME: null 9374 return IntToPointer; 9375 } 9376 9377 // In general, C pointers are not compatible with ObjC object pointers, 9378 // with two exceptions: 9379 if (isa<PointerType>(RHSType)) { 9380 Kind = CK_CPointerToObjCPointerCast; 9381 9382 // - conversions from 'void*' 9383 if (RHSType->isVoidPointerType()) { 9384 return Compatible; 9385 } 9386 9387 // - conversions to 'Class' from its redefinition type 9388 if (LHSType->isObjCClassType() && 9389 Context.hasSameType(RHSType, 9390 Context.getObjCClassRedefinitionType())) { 9391 return Compatible; 9392 } 9393 9394 return IncompatiblePointer; 9395 } 9396 9397 // Only under strict condition T^ is compatible with an Objective-C pointer. 9398 if (RHSType->isBlockPointerType() && 9399 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9400 if (ConvertRHS) 9401 maybeExtendBlockObject(RHS); 9402 Kind = CK_BlockPointerToObjCPointerCast; 9403 return Compatible; 9404 } 9405 9406 return Incompatible; 9407 } 9408 9409 // Conversions from pointers that are not covered by the above. 9410 if (isa<PointerType>(RHSType)) { 9411 // T* -> _Bool 9412 if (LHSType == Context.BoolTy) { 9413 Kind = CK_PointerToBoolean; 9414 return Compatible; 9415 } 9416 9417 // T* -> int 9418 if (LHSType->isIntegerType()) { 9419 Kind = CK_PointerToIntegral; 9420 return PointerToInt; 9421 } 9422 9423 return Incompatible; 9424 } 9425 9426 // Conversions from Objective-C pointers that are not covered by the above. 9427 if (isa<ObjCObjectPointerType>(RHSType)) { 9428 // T* -> _Bool 9429 if (LHSType == Context.BoolTy) { 9430 Kind = CK_PointerToBoolean; 9431 return Compatible; 9432 } 9433 9434 // T* -> int 9435 if (LHSType->isIntegerType()) { 9436 Kind = CK_PointerToIntegral; 9437 return PointerToInt; 9438 } 9439 9440 return Incompatible; 9441 } 9442 9443 // struct A -> struct B 9444 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9445 if (Context.typesAreCompatible(LHSType, RHSType)) { 9446 Kind = CK_NoOp; 9447 return Compatible; 9448 } 9449 } 9450 9451 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9452 Kind = CK_IntToOCLSampler; 9453 return Compatible; 9454 } 9455 9456 return Incompatible; 9457 } 9458 9459 /// Constructs a transparent union from an expression that is 9460 /// used to initialize the transparent union. 9461 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9462 ExprResult &EResult, QualType UnionType, 9463 FieldDecl *Field) { 9464 // Build an initializer list that designates the appropriate member 9465 // of the transparent union. 9466 Expr *E = EResult.get(); 9467 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9468 E, SourceLocation()); 9469 Initializer->setType(UnionType); 9470 Initializer->setInitializedFieldInUnion(Field); 9471 9472 // Build a compound literal constructing a value of the transparent 9473 // union type from this initializer list. 9474 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9475 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9476 VK_PRValue, Initializer, false); 9477 } 9478 9479 Sema::AssignConvertType 9480 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9481 ExprResult &RHS) { 9482 QualType RHSType = RHS.get()->getType(); 9483 9484 // If the ArgType is a Union type, we want to handle a potential 9485 // transparent_union GCC extension. 9486 const RecordType *UT = ArgType->getAsUnionType(); 9487 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9488 return Incompatible; 9489 9490 // The field to initialize within the transparent union. 9491 RecordDecl *UD = UT->getDecl(); 9492 FieldDecl *InitField = nullptr; 9493 // It's compatible if the expression matches any of the fields. 9494 for (auto *it : UD->fields()) { 9495 if (it->getType()->isPointerType()) { 9496 // If the transparent union contains a pointer type, we allow: 9497 // 1) void pointer 9498 // 2) null pointer constant 9499 if (RHSType->isPointerType()) 9500 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9501 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9502 InitField = it; 9503 break; 9504 } 9505 9506 if (RHS.get()->isNullPointerConstant(Context, 9507 Expr::NPC_ValueDependentIsNull)) { 9508 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9509 CK_NullToPointer); 9510 InitField = it; 9511 break; 9512 } 9513 } 9514 9515 CastKind Kind; 9516 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9517 == Compatible) { 9518 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9519 InitField = it; 9520 break; 9521 } 9522 } 9523 9524 if (!InitField) 9525 return Incompatible; 9526 9527 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9528 return Compatible; 9529 } 9530 9531 Sema::AssignConvertType 9532 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9533 bool Diagnose, 9534 bool DiagnoseCFAudited, 9535 bool ConvertRHS) { 9536 // We need to be able to tell the caller whether we diagnosed a problem, if 9537 // they ask us to issue diagnostics. 9538 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9539 9540 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9541 // we can't avoid *all* modifications at the moment, so we need some somewhere 9542 // to put the updated value. 9543 ExprResult LocalRHS = CallerRHS; 9544 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9545 9546 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9547 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9548 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9549 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9550 Diag(RHS.get()->getExprLoc(), 9551 diag::warn_noderef_to_dereferenceable_pointer) 9552 << RHS.get()->getSourceRange(); 9553 } 9554 } 9555 } 9556 9557 if (getLangOpts().CPlusPlus) { 9558 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9559 // C++ 5.17p3: If the left operand is not of class type, the 9560 // expression is implicitly converted (C++ 4) to the 9561 // cv-unqualified type of the left operand. 9562 QualType RHSType = RHS.get()->getType(); 9563 if (Diagnose) { 9564 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9565 AA_Assigning); 9566 } else { 9567 ImplicitConversionSequence ICS = 9568 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9569 /*SuppressUserConversions=*/false, 9570 AllowedExplicit::None, 9571 /*InOverloadResolution=*/false, 9572 /*CStyle=*/false, 9573 /*AllowObjCWritebackConversion=*/false); 9574 if (ICS.isFailure()) 9575 return Incompatible; 9576 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9577 ICS, AA_Assigning); 9578 } 9579 if (RHS.isInvalid()) 9580 return Incompatible; 9581 Sema::AssignConvertType result = Compatible; 9582 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9583 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9584 result = IncompatibleObjCWeakRef; 9585 return result; 9586 } 9587 9588 // FIXME: Currently, we fall through and treat C++ classes like C 9589 // structures. 9590 // FIXME: We also fall through for atomics; not sure what should 9591 // happen there, though. 9592 } else if (RHS.get()->getType() == Context.OverloadTy) { 9593 // As a set of extensions to C, we support overloading on functions. These 9594 // functions need to be resolved here. 9595 DeclAccessPair DAP; 9596 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9597 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9598 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9599 else 9600 return Incompatible; 9601 } 9602 9603 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9604 // a null pointer constant. 9605 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9606 LHSType->isBlockPointerType()) && 9607 RHS.get()->isNullPointerConstant(Context, 9608 Expr::NPC_ValueDependentIsNull)) { 9609 if (Diagnose || ConvertRHS) { 9610 CastKind Kind; 9611 CXXCastPath Path; 9612 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9613 /*IgnoreBaseAccess=*/false, Diagnose); 9614 if (ConvertRHS) 9615 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9616 } 9617 return Compatible; 9618 } 9619 9620 // OpenCL queue_t type assignment. 9621 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9622 Context, Expr::NPC_ValueDependentIsNull)) { 9623 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9624 return Compatible; 9625 } 9626 9627 // This check seems unnatural, however it is necessary to ensure the proper 9628 // conversion of functions/arrays. If the conversion were done for all 9629 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9630 // expressions that suppress this implicit conversion (&, sizeof). 9631 // 9632 // Suppress this for references: C++ 8.5.3p5. 9633 if (!LHSType->isReferenceType()) { 9634 // FIXME: We potentially allocate here even if ConvertRHS is false. 9635 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9636 if (RHS.isInvalid()) 9637 return Incompatible; 9638 } 9639 CastKind Kind; 9640 Sema::AssignConvertType result = 9641 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9642 9643 // C99 6.5.16.1p2: The value of the right operand is converted to the 9644 // type of the assignment expression. 9645 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9646 // so that we can use references in built-in functions even in C. 9647 // The getNonReferenceType() call makes sure that the resulting expression 9648 // does not have reference type. 9649 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9650 QualType Ty = LHSType.getNonLValueExprType(Context); 9651 Expr *E = RHS.get(); 9652 9653 // Check for various Objective-C errors. If we are not reporting 9654 // diagnostics and just checking for errors, e.g., during overload 9655 // resolution, return Incompatible to indicate the failure. 9656 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9657 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9658 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9659 if (!Diagnose) 9660 return Incompatible; 9661 } 9662 if (getLangOpts().ObjC && 9663 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9664 E->getType(), E, Diagnose) || 9665 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9666 if (!Diagnose) 9667 return Incompatible; 9668 // Replace the expression with a corrected version and continue so we 9669 // can find further errors. 9670 RHS = E; 9671 return Compatible; 9672 } 9673 9674 if (ConvertRHS) 9675 RHS = ImpCastExprToType(E, Ty, Kind); 9676 } 9677 9678 return result; 9679 } 9680 9681 namespace { 9682 /// The original operand to an operator, prior to the application of the usual 9683 /// arithmetic conversions and converting the arguments of a builtin operator 9684 /// candidate. 9685 struct OriginalOperand { 9686 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9687 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9688 Op = MTE->getSubExpr(); 9689 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9690 Op = BTE->getSubExpr(); 9691 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9692 Orig = ICE->getSubExprAsWritten(); 9693 Conversion = ICE->getConversionFunction(); 9694 } 9695 } 9696 9697 QualType getType() const { return Orig->getType(); } 9698 9699 Expr *Orig; 9700 NamedDecl *Conversion; 9701 }; 9702 } 9703 9704 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9705 ExprResult &RHS) { 9706 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9707 9708 Diag(Loc, diag::err_typecheck_invalid_operands) 9709 << OrigLHS.getType() << OrigRHS.getType() 9710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9711 9712 // If a user-defined conversion was applied to either of the operands prior 9713 // to applying the built-in operator rules, tell the user about it. 9714 if (OrigLHS.Conversion) { 9715 Diag(OrigLHS.Conversion->getLocation(), 9716 diag::note_typecheck_invalid_operands_converted) 9717 << 0 << LHS.get()->getType(); 9718 } 9719 if (OrigRHS.Conversion) { 9720 Diag(OrigRHS.Conversion->getLocation(), 9721 diag::note_typecheck_invalid_operands_converted) 9722 << 1 << RHS.get()->getType(); 9723 } 9724 9725 return QualType(); 9726 } 9727 9728 // Diagnose cases where a scalar was implicitly converted to a vector and 9729 // diagnose the underlying types. Otherwise, diagnose the error 9730 // as invalid vector logical operands for non-C++ cases. 9731 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9732 ExprResult &RHS) { 9733 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9734 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9735 9736 bool LHSNatVec = LHSType->isVectorType(); 9737 bool RHSNatVec = RHSType->isVectorType(); 9738 9739 if (!(LHSNatVec && RHSNatVec)) { 9740 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9741 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9742 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9743 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9744 << Vector->getSourceRange(); 9745 return QualType(); 9746 } 9747 9748 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9749 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9750 << RHS.get()->getSourceRange(); 9751 9752 return QualType(); 9753 } 9754 9755 /// Try to convert a value of non-vector type to a vector type by converting 9756 /// the type to the element type of the vector and then performing a splat. 9757 /// If the language is OpenCL, we only use conversions that promote scalar 9758 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9759 /// for float->int. 9760 /// 9761 /// OpenCL V2.0 6.2.6.p2: 9762 /// An error shall occur if any scalar operand type has greater rank 9763 /// than the type of the vector element. 9764 /// 9765 /// \param scalar - if non-null, actually perform the conversions 9766 /// \return true if the operation fails (but without diagnosing the failure) 9767 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9768 QualType scalarTy, 9769 QualType vectorEltTy, 9770 QualType vectorTy, 9771 unsigned &DiagID) { 9772 // The conversion to apply to the scalar before splatting it, 9773 // if necessary. 9774 CastKind scalarCast = CK_NoOp; 9775 9776 if (vectorEltTy->isIntegralType(S.Context)) { 9777 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9778 (scalarTy->isIntegerType() && 9779 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9780 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9781 return true; 9782 } 9783 if (!scalarTy->isIntegralType(S.Context)) 9784 return true; 9785 scalarCast = CK_IntegralCast; 9786 } else if (vectorEltTy->isRealFloatingType()) { 9787 if (scalarTy->isRealFloatingType()) { 9788 if (S.getLangOpts().OpenCL && 9789 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9790 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9791 return true; 9792 } 9793 scalarCast = CK_FloatingCast; 9794 } 9795 else if (scalarTy->isIntegralType(S.Context)) 9796 scalarCast = CK_IntegralToFloating; 9797 else 9798 return true; 9799 } else { 9800 return true; 9801 } 9802 9803 // Adjust scalar if desired. 9804 if (scalar) { 9805 if (scalarCast != CK_NoOp) 9806 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9807 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9808 } 9809 return false; 9810 } 9811 9812 /// Convert vector E to a vector with the same number of elements but different 9813 /// element type. 9814 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9815 const auto *VecTy = E->getType()->getAs<VectorType>(); 9816 assert(VecTy && "Expression E must be a vector"); 9817 QualType NewVecTy = S.Context.getVectorType(ElementType, 9818 VecTy->getNumElements(), 9819 VecTy->getVectorKind()); 9820 9821 // Look through the implicit cast. Return the subexpression if its type is 9822 // NewVecTy. 9823 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9824 if (ICE->getSubExpr()->getType() == NewVecTy) 9825 return ICE->getSubExpr(); 9826 9827 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9828 return S.ImpCastExprToType(E, NewVecTy, Cast); 9829 } 9830 9831 /// Test if a (constant) integer Int can be casted to another integer type 9832 /// IntTy without losing precision. 9833 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9834 QualType OtherIntTy) { 9835 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9836 9837 // Reject cases where the value of the Int is unknown as that would 9838 // possibly cause truncation, but accept cases where the scalar can be 9839 // demoted without loss of precision. 9840 Expr::EvalResult EVResult; 9841 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9842 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9843 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9844 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9845 9846 if (CstInt) { 9847 // If the scalar is constant and is of a higher order and has more active 9848 // bits that the vector element type, reject it. 9849 llvm::APSInt Result = EVResult.Val.getInt(); 9850 unsigned NumBits = IntSigned 9851 ? (Result.isNegative() ? Result.getMinSignedBits() 9852 : Result.getActiveBits()) 9853 : Result.getActiveBits(); 9854 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9855 return true; 9856 9857 // If the signedness of the scalar type and the vector element type 9858 // differs and the number of bits is greater than that of the vector 9859 // element reject it. 9860 return (IntSigned != OtherIntSigned && 9861 NumBits > S.Context.getIntWidth(OtherIntTy)); 9862 } 9863 9864 // Reject cases where the value of the scalar is not constant and it's 9865 // order is greater than that of the vector element type. 9866 return (Order < 0); 9867 } 9868 9869 /// Test if a (constant) integer Int can be casted to floating point type 9870 /// FloatTy without losing precision. 9871 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9872 QualType FloatTy) { 9873 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9874 9875 // Determine if the integer constant can be expressed as a floating point 9876 // number of the appropriate type. 9877 Expr::EvalResult EVResult; 9878 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9879 9880 uint64_t Bits = 0; 9881 if (CstInt) { 9882 // Reject constants that would be truncated if they were converted to 9883 // the floating point type. Test by simple to/from conversion. 9884 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9885 // could be avoided if there was a convertFromAPInt method 9886 // which could signal back if implicit truncation occurred. 9887 llvm::APSInt Result = EVResult.Val.getInt(); 9888 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9889 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9890 llvm::APFloat::rmTowardZero); 9891 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9892 !IntTy->hasSignedIntegerRepresentation()); 9893 bool Ignored = false; 9894 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9895 &Ignored); 9896 if (Result != ConvertBack) 9897 return true; 9898 } else { 9899 // Reject types that cannot be fully encoded into the mantissa of 9900 // the float. 9901 Bits = S.Context.getTypeSize(IntTy); 9902 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9903 S.Context.getFloatTypeSemantics(FloatTy)); 9904 if (Bits > FloatPrec) 9905 return true; 9906 } 9907 9908 return false; 9909 } 9910 9911 /// Attempt to convert and splat Scalar into a vector whose types matches 9912 /// Vector following GCC conversion rules. The rule is that implicit 9913 /// conversion can occur when Scalar can be casted to match Vector's element 9914 /// type without causing truncation of Scalar. 9915 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9916 ExprResult *Vector) { 9917 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9918 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9919 const VectorType *VT = VectorTy->getAs<VectorType>(); 9920 9921 assert(!isa<ExtVectorType>(VT) && 9922 "ExtVectorTypes should not be handled here!"); 9923 9924 QualType VectorEltTy = VT->getElementType(); 9925 9926 // Reject cases where the vector element type or the scalar element type are 9927 // not integral or floating point types. 9928 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9929 return true; 9930 9931 // The conversion to apply to the scalar before splatting it, 9932 // if necessary. 9933 CastKind ScalarCast = CK_NoOp; 9934 9935 // Accept cases where the vector elements are integers and the scalar is 9936 // an integer. 9937 // FIXME: Notionally if the scalar was a floating point value with a precise 9938 // integral representation, we could cast it to an appropriate integer 9939 // type and then perform the rest of the checks here. GCC will perform 9940 // this conversion in some cases as determined by the input language. 9941 // We should accept it on a language independent basis. 9942 if (VectorEltTy->isIntegralType(S.Context) && 9943 ScalarTy->isIntegralType(S.Context) && 9944 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9945 9946 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9947 return true; 9948 9949 ScalarCast = CK_IntegralCast; 9950 } else if (VectorEltTy->isIntegralType(S.Context) && 9951 ScalarTy->isRealFloatingType()) { 9952 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9953 ScalarCast = CK_FloatingToIntegral; 9954 else 9955 return true; 9956 } else if (VectorEltTy->isRealFloatingType()) { 9957 if (ScalarTy->isRealFloatingType()) { 9958 9959 // Reject cases where the scalar type is not a constant and has a higher 9960 // Order than the vector element type. 9961 llvm::APFloat Result(0.0); 9962 9963 // Determine whether this is a constant scalar. In the event that the 9964 // value is dependent (and thus cannot be evaluated by the constant 9965 // evaluator), skip the evaluation. This will then diagnose once the 9966 // expression is instantiated. 9967 bool CstScalar = Scalar->get()->isValueDependent() || 9968 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9969 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9970 if (!CstScalar && Order < 0) 9971 return true; 9972 9973 // If the scalar cannot be safely casted to the vector element type, 9974 // reject it. 9975 if (CstScalar) { 9976 bool Truncated = false; 9977 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9978 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9979 if (Truncated) 9980 return true; 9981 } 9982 9983 ScalarCast = CK_FloatingCast; 9984 } else if (ScalarTy->isIntegralType(S.Context)) { 9985 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9986 return true; 9987 9988 ScalarCast = CK_IntegralToFloating; 9989 } else 9990 return true; 9991 } else if (ScalarTy->isEnumeralType()) 9992 return true; 9993 9994 // Adjust scalar if desired. 9995 if (Scalar) { 9996 if (ScalarCast != CK_NoOp) 9997 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9998 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9999 } 10000 return false; 10001 } 10002 10003 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10004 SourceLocation Loc, bool IsCompAssign, 10005 bool AllowBothBool, 10006 bool AllowBoolConversions) { 10007 if (!IsCompAssign) { 10008 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10009 if (LHS.isInvalid()) 10010 return QualType(); 10011 } 10012 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10013 if (RHS.isInvalid()) 10014 return QualType(); 10015 10016 // For conversion purposes, we ignore any qualifiers. 10017 // For example, "const float" and "float" are equivalent. 10018 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10019 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10020 10021 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10022 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10023 assert(LHSVecType || RHSVecType); 10024 10025 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10026 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10027 return InvalidOperands(Loc, LHS, RHS); 10028 10029 // AltiVec-style "vector bool op vector bool" combinations are allowed 10030 // for some operators but not others. 10031 if (!AllowBothBool && 10032 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10033 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10034 return InvalidOperands(Loc, LHS, RHS); 10035 10036 // If the vector types are identical, return. 10037 if (Context.hasSameType(LHSType, RHSType)) 10038 return LHSType; 10039 10040 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10041 if (LHSVecType && RHSVecType && 10042 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10043 if (isa<ExtVectorType>(LHSVecType)) { 10044 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10045 return LHSType; 10046 } 10047 10048 if (!IsCompAssign) 10049 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10050 return RHSType; 10051 } 10052 10053 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10054 // can be mixed, with the result being the non-bool type. The non-bool 10055 // operand must have integer element type. 10056 if (AllowBoolConversions && LHSVecType && RHSVecType && 10057 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10058 (Context.getTypeSize(LHSVecType->getElementType()) == 10059 Context.getTypeSize(RHSVecType->getElementType()))) { 10060 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10061 LHSVecType->getElementType()->isIntegerType() && 10062 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10063 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10064 return LHSType; 10065 } 10066 if (!IsCompAssign && 10067 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10068 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10069 RHSVecType->getElementType()->isIntegerType()) { 10070 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10071 return RHSType; 10072 } 10073 } 10074 10075 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10076 // since the ambiguity can affect the ABI. 10077 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10078 const VectorType *VecType = SecondType->getAs<VectorType>(); 10079 return FirstType->isSizelessBuiltinType() && VecType && 10080 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10081 VecType->getVectorKind() == 10082 VectorType::SveFixedLengthPredicateVector); 10083 }; 10084 10085 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10086 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10087 return QualType(); 10088 } 10089 10090 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10091 // since the ambiguity can affect the ABI. 10092 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10093 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10094 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10095 10096 if (FirstVecType && SecondVecType) 10097 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10098 (SecondVecType->getVectorKind() == 10099 VectorType::SveFixedLengthDataVector || 10100 SecondVecType->getVectorKind() == 10101 VectorType::SveFixedLengthPredicateVector); 10102 10103 return FirstType->isSizelessBuiltinType() && SecondVecType && 10104 SecondVecType->getVectorKind() == VectorType::GenericVector; 10105 }; 10106 10107 if (IsSveGnuConversion(LHSType, RHSType) || 10108 IsSveGnuConversion(RHSType, LHSType)) { 10109 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10110 return QualType(); 10111 } 10112 10113 // If there's a vector type and a scalar, try to convert the scalar to 10114 // the vector element type and splat. 10115 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10116 if (!RHSVecType) { 10117 if (isa<ExtVectorType>(LHSVecType)) { 10118 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10119 LHSVecType->getElementType(), LHSType, 10120 DiagID)) 10121 return LHSType; 10122 } else { 10123 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10124 return LHSType; 10125 } 10126 } 10127 if (!LHSVecType) { 10128 if (isa<ExtVectorType>(RHSVecType)) { 10129 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10130 LHSType, RHSVecType->getElementType(), 10131 RHSType, DiagID)) 10132 return RHSType; 10133 } else { 10134 if (LHS.get()->getValueKind() == VK_LValue || 10135 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10136 return RHSType; 10137 } 10138 } 10139 10140 // FIXME: The code below also handles conversion between vectors and 10141 // non-scalars, we should break this down into fine grained specific checks 10142 // and emit proper diagnostics. 10143 QualType VecType = LHSVecType ? LHSType : RHSType; 10144 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10145 QualType OtherType = LHSVecType ? RHSType : LHSType; 10146 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10147 if (isLaxVectorConversion(OtherType, VecType)) { 10148 // If we're allowing lax vector conversions, only the total (data) size 10149 // needs to be the same. For non compound assignment, if one of the types is 10150 // scalar, the result is always the vector type. 10151 if (!IsCompAssign) { 10152 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10153 return VecType; 10154 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10155 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10156 // type. Note that this is already done by non-compound assignments in 10157 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10158 // <1 x T> -> T. The result is also a vector type. 10159 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10160 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10161 ExprResult *RHSExpr = &RHS; 10162 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10163 return VecType; 10164 } 10165 } 10166 10167 // Okay, the expression is invalid. 10168 10169 // If there's a non-vector, non-real operand, diagnose that. 10170 if ((!RHSVecType && !RHSType->isRealType()) || 10171 (!LHSVecType && !LHSType->isRealType())) { 10172 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10173 << LHSType << RHSType 10174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10175 return QualType(); 10176 } 10177 10178 // OpenCL V1.1 6.2.6.p1: 10179 // If the operands are of more than one vector type, then an error shall 10180 // occur. Implicit conversions between vector types are not permitted, per 10181 // section 6.2.1. 10182 if (getLangOpts().OpenCL && 10183 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10184 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10185 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10186 << RHSType; 10187 return QualType(); 10188 } 10189 10190 10191 // If there is a vector type that is not a ExtVector and a scalar, we reach 10192 // this point if scalar could not be converted to the vector's element type 10193 // without truncation. 10194 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10195 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10196 QualType Scalar = LHSVecType ? RHSType : LHSType; 10197 QualType Vector = LHSVecType ? LHSType : RHSType; 10198 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10199 Diag(Loc, 10200 diag::err_typecheck_vector_not_convertable_implict_truncation) 10201 << ScalarOrVector << Scalar << Vector; 10202 10203 return QualType(); 10204 } 10205 10206 // Otherwise, use the generic diagnostic. 10207 Diag(Loc, DiagID) 10208 << LHSType << RHSType 10209 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10210 return QualType(); 10211 } 10212 10213 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10214 // expression. These are mainly cases where the null pointer is used as an 10215 // integer instead of a pointer. 10216 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10217 SourceLocation Loc, bool IsCompare) { 10218 // The canonical way to check for a GNU null is with isNullPointerConstant, 10219 // but we use a bit of a hack here for speed; this is a relatively 10220 // hot path, and isNullPointerConstant is slow. 10221 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10222 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10223 10224 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10225 10226 // Avoid analyzing cases where the result will either be invalid (and 10227 // diagnosed as such) or entirely valid and not something to warn about. 10228 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10229 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10230 return; 10231 10232 // Comparison operations would not make sense with a null pointer no matter 10233 // what the other expression is. 10234 if (!IsCompare) { 10235 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10236 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10237 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10238 return; 10239 } 10240 10241 // The rest of the operations only make sense with a null pointer 10242 // if the other expression is a pointer. 10243 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10244 NonNullType->canDecayToPointerType()) 10245 return; 10246 10247 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10248 << LHSNull /* LHS is NULL */ << NonNullType 10249 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10250 } 10251 10252 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10253 SourceLocation Loc) { 10254 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10255 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10256 if (!LUE || !RUE) 10257 return; 10258 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10259 RUE->getKind() != UETT_SizeOf) 10260 return; 10261 10262 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10263 QualType LHSTy = LHSArg->getType(); 10264 QualType RHSTy; 10265 10266 if (RUE->isArgumentType()) 10267 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10268 else 10269 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10270 10271 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10272 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10273 return; 10274 10275 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10276 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10277 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10278 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10279 << LHSArgDecl; 10280 } 10281 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10282 QualType ArrayElemTy = ArrayTy->getElementType(); 10283 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10284 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10285 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10286 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10287 return; 10288 S.Diag(Loc, diag::warn_division_sizeof_array) 10289 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10290 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10291 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10292 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10293 << LHSArgDecl; 10294 } 10295 10296 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10297 } 10298 } 10299 10300 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10301 ExprResult &RHS, 10302 SourceLocation Loc, bool IsDiv) { 10303 // Check for division/remainder by zero. 10304 Expr::EvalResult RHSValue; 10305 if (!RHS.get()->isValueDependent() && 10306 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10307 RHSValue.Val.getInt() == 0) 10308 S.DiagRuntimeBehavior(Loc, RHS.get(), 10309 S.PDiag(diag::warn_remainder_division_by_zero) 10310 << IsDiv << RHS.get()->getSourceRange()); 10311 } 10312 10313 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10314 SourceLocation Loc, 10315 bool IsCompAssign, bool IsDiv) { 10316 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10317 10318 QualType LHSTy = LHS.get()->getType(); 10319 QualType RHSTy = RHS.get()->getType(); 10320 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10321 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10322 /*AllowBothBool*/getLangOpts().AltiVec, 10323 /*AllowBoolConversions*/false); 10324 if (!IsDiv && 10325 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10326 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10327 // For division, only matrix-by-scalar is supported. Other combinations with 10328 // matrix types are invalid. 10329 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10330 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10331 10332 QualType compType = UsualArithmeticConversions( 10333 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10334 if (LHS.isInvalid() || RHS.isInvalid()) 10335 return QualType(); 10336 10337 10338 if (compType.isNull() || !compType->isArithmeticType()) 10339 return InvalidOperands(Loc, LHS, RHS); 10340 if (IsDiv) { 10341 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10342 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10343 } 10344 return compType; 10345 } 10346 10347 QualType Sema::CheckRemainderOperands( 10348 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10349 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10350 10351 if (LHS.get()->getType()->isVectorType() || 10352 RHS.get()->getType()->isVectorType()) { 10353 if (LHS.get()->getType()->hasIntegerRepresentation() && 10354 RHS.get()->getType()->hasIntegerRepresentation()) 10355 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10356 /*AllowBothBool*/getLangOpts().AltiVec, 10357 /*AllowBoolConversions*/false); 10358 return InvalidOperands(Loc, LHS, RHS); 10359 } 10360 10361 QualType compType = UsualArithmeticConversions( 10362 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10363 if (LHS.isInvalid() || RHS.isInvalid()) 10364 return QualType(); 10365 10366 if (compType.isNull() || !compType->isIntegerType()) 10367 return InvalidOperands(Loc, LHS, RHS); 10368 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10369 return compType; 10370 } 10371 10372 /// Diagnose invalid arithmetic on two void pointers. 10373 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10374 Expr *LHSExpr, Expr *RHSExpr) { 10375 S.Diag(Loc, S.getLangOpts().CPlusPlus 10376 ? diag::err_typecheck_pointer_arith_void_type 10377 : diag::ext_gnu_void_ptr) 10378 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10379 << RHSExpr->getSourceRange(); 10380 } 10381 10382 /// Diagnose invalid arithmetic on a void pointer. 10383 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10384 Expr *Pointer) { 10385 S.Diag(Loc, S.getLangOpts().CPlusPlus 10386 ? diag::err_typecheck_pointer_arith_void_type 10387 : diag::ext_gnu_void_ptr) 10388 << 0 /* one pointer */ << Pointer->getSourceRange(); 10389 } 10390 10391 /// Diagnose invalid arithmetic on a null pointer. 10392 /// 10393 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10394 /// idiom, which we recognize as a GNU extension. 10395 /// 10396 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10397 Expr *Pointer, bool IsGNUIdiom) { 10398 if (IsGNUIdiom) 10399 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10400 << Pointer->getSourceRange(); 10401 else 10402 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10403 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10404 } 10405 10406 /// Diagnose invalid arithmetic on two function pointers. 10407 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10408 Expr *LHS, Expr *RHS) { 10409 assert(LHS->getType()->isAnyPointerType()); 10410 assert(RHS->getType()->isAnyPointerType()); 10411 S.Diag(Loc, S.getLangOpts().CPlusPlus 10412 ? diag::err_typecheck_pointer_arith_function_type 10413 : diag::ext_gnu_ptr_func_arith) 10414 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10415 // We only show the second type if it differs from the first. 10416 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10417 RHS->getType()) 10418 << RHS->getType()->getPointeeType() 10419 << LHS->getSourceRange() << RHS->getSourceRange(); 10420 } 10421 10422 /// Diagnose invalid arithmetic on a function pointer. 10423 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10424 Expr *Pointer) { 10425 assert(Pointer->getType()->isAnyPointerType()); 10426 S.Diag(Loc, S.getLangOpts().CPlusPlus 10427 ? diag::err_typecheck_pointer_arith_function_type 10428 : diag::ext_gnu_ptr_func_arith) 10429 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10430 << 0 /* one pointer, so only one type */ 10431 << Pointer->getSourceRange(); 10432 } 10433 10434 /// Emit error if Operand is incomplete pointer type 10435 /// 10436 /// \returns True if pointer has incomplete type 10437 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10438 Expr *Operand) { 10439 QualType ResType = Operand->getType(); 10440 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10441 ResType = ResAtomicType->getValueType(); 10442 10443 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10444 QualType PointeeTy = ResType->getPointeeType(); 10445 return S.RequireCompleteSizedType( 10446 Loc, PointeeTy, 10447 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10448 Operand->getSourceRange()); 10449 } 10450 10451 /// Check the validity of an arithmetic pointer operand. 10452 /// 10453 /// If the operand has pointer type, this code will check for pointer types 10454 /// which are invalid in arithmetic operations. These will be diagnosed 10455 /// appropriately, including whether or not the use is supported as an 10456 /// extension. 10457 /// 10458 /// \returns True when the operand is valid to use (even if as an extension). 10459 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10460 Expr *Operand) { 10461 QualType ResType = Operand->getType(); 10462 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10463 ResType = ResAtomicType->getValueType(); 10464 10465 if (!ResType->isAnyPointerType()) return true; 10466 10467 QualType PointeeTy = ResType->getPointeeType(); 10468 if (PointeeTy->isVoidType()) { 10469 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10470 return !S.getLangOpts().CPlusPlus; 10471 } 10472 if (PointeeTy->isFunctionType()) { 10473 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10474 return !S.getLangOpts().CPlusPlus; 10475 } 10476 10477 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10478 10479 return true; 10480 } 10481 10482 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10483 /// operands. 10484 /// 10485 /// This routine will diagnose any invalid arithmetic on pointer operands much 10486 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10487 /// for emitting a single diagnostic even for operations where both LHS and RHS 10488 /// are (potentially problematic) pointers. 10489 /// 10490 /// \returns True when the operand is valid to use (even if as an extension). 10491 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10492 Expr *LHSExpr, Expr *RHSExpr) { 10493 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10494 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10495 if (!isLHSPointer && !isRHSPointer) return true; 10496 10497 QualType LHSPointeeTy, RHSPointeeTy; 10498 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10499 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10500 10501 // if both are pointers check if operation is valid wrt address spaces 10502 if (isLHSPointer && isRHSPointer) { 10503 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10504 S.Diag(Loc, 10505 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10506 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10507 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10508 return false; 10509 } 10510 } 10511 10512 // Check for arithmetic on pointers to incomplete types. 10513 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10514 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10515 if (isLHSVoidPtr || isRHSVoidPtr) { 10516 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10517 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10518 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10519 10520 return !S.getLangOpts().CPlusPlus; 10521 } 10522 10523 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10524 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10525 if (isLHSFuncPtr || isRHSFuncPtr) { 10526 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10527 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10528 RHSExpr); 10529 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10530 10531 return !S.getLangOpts().CPlusPlus; 10532 } 10533 10534 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10535 return false; 10536 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10537 return false; 10538 10539 return true; 10540 } 10541 10542 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10543 /// literal. 10544 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10545 Expr *LHSExpr, Expr *RHSExpr) { 10546 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10547 Expr* IndexExpr = RHSExpr; 10548 if (!StrExpr) { 10549 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10550 IndexExpr = LHSExpr; 10551 } 10552 10553 bool IsStringPlusInt = StrExpr && 10554 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10555 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10556 return; 10557 10558 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10559 Self.Diag(OpLoc, diag::warn_string_plus_int) 10560 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10561 10562 // Only print a fixit for "str" + int, not for int + "str". 10563 if (IndexExpr == RHSExpr) { 10564 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10565 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10566 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10567 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10568 << FixItHint::CreateInsertion(EndLoc, "]"); 10569 } else 10570 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10571 } 10572 10573 /// Emit a warning when adding a char literal to a string. 10574 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10575 Expr *LHSExpr, Expr *RHSExpr) { 10576 const Expr *StringRefExpr = LHSExpr; 10577 const CharacterLiteral *CharExpr = 10578 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10579 10580 if (!CharExpr) { 10581 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10582 StringRefExpr = RHSExpr; 10583 } 10584 10585 if (!CharExpr || !StringRefExpr) 10586 return; 10587 10588 const QualType StringType = StringRefExpr->getType(); 10589 10590 // Return if not a PointerType. 10591 if (!StringType->isAnyPointerType()) 10592 return; 10593 10594 // Return if not a CharacterType. 10595 if (!StringType->getPointeeType()->isAnyCharacterType()) 10596 return; 10597 10598 ASTContext &Ctx = Self.getASTContext(); 10599 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10600 10601 const QualType CharType = CharExpr->getType(); 10602 if (!CharType->isAnyCharacterType() && 10603 CharType->isIntegerType() && 10604 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10605 Self.Diag(OpLoc, diag::warn_string_plus_char) 10606 << DiagRange << Ctx.CharTy; 10607 } else { 10608 Self.Diag(OpLoc, diag::warn_string_plus_char) 10609 << DiagRange << CharExpr->getType(); 10610 } 10611 10612 // Only print a fixit for str + char, not for char + str. 10613 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10614 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10615 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10616 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10617 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10618 << FixItHint::CreateInsertion(EndLoc, "]"); 10619 } else { 10620 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10621 } 10622 } 10623 10624 /// Emit error when two pointers are incompatible. 10625 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10626 Expr *LHSExpr, Expr *RHSExpr) { 10627 assert(LHSExpr->getType()->isAnyPointerType()); 10628 assert(RHSExpr->getType()->isAnyPointerType()); 10629 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10630 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10631 << RHSExpr->getSourceRange(); 10632 } 10633 10634 // C99 6.5.6 10635 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10636 SourceLocation Loc, BinaryOperatorKind Opc, 10637 QualType* CompLHSTy) { 10638 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10639 10640 if (LHS.get()->getType()->isVectorType() || 10641 RHS.get()->getType()->isVectorType()) { 10642 QualType compType = CheckVectorOperands( 10643 LHS, RHS, Loc, CompLHSTy, 10644 /*AllowBothBool*/getLangOpts().AltiVec, 10645 /*AllowBoolConversions*/getLangOpts().ZVector); 10646 if (CompLHSTy) *CompLHSTy = compType; 10647 return compType; 10648 } 10649 10650 if (LHS.get()->getType()->isConstantMatrixType() || 10651 RHS.get()->getType()->isConstantMatrixType()) { 10652 QualType compType = 10653 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10654 if (CompLHSTy) 10655 *CompLHSTy = compType; 10656 return compType; 10657 } 10658 10659 QualType compType = UsualArithmeticConversions( 10660 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10661 if (LHS.isInvalid() || RHS.isInvalid()) 10662 return QualType(); 10663 10664 // Diagnose "string literal" '+' int and string '+' "char literal". 10665 if (Opc == BO_Add) { 10666 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10667 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10668 } 10669 10670 // handle the common case first (both operands are arithmetic). 10671 if (!compType.isNull() && compType->isArithmeticType()) { 10672 if (CompLHSTy) *CompLHSTy = compType; 10673 return compType; 10674 } 10675 10676 // Type-checking. Ultimately the pointer's going to be in PExp; 10677 // note that we bias towards the LHS being the pointer. 10678 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10679 10680 bool isObjCPointer; 10681 if (PExp->getType()->isPointerType()) { 10682 isObjCPointer = false; 10683 } else if (PExp->getType()->isObjCObjectPointerType()) { 10684 isObjCPointer = true; 10685 } else { 10686 std::swap(PExp, IExp); 10687 if (PExp->getType()->isPointerType()) { 10688 isObjCPointer = false; 10689 } else if (PExp->getType()->isObjCObjectPointerType()) { 10690 isObjCPointer = true; 10691 } else { 10692 return InvalidOperands(Loc, LHS, RHS); 10693 } 10694 } 10695 assert(PExp->getType()->isAnyPointerType()); 10696 10697 if (!IExp->getType()->isIntegerType()) 10698 return InvalidOperands(Loc, LHS, RHS); 10699 10700 // Adding to a null pointer results in undefined behavior. 10701 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10702 Context, Expr::NPC_ValueDependentIsNotNull)) { 10703 // In C++ adding zero to a null pointer is defined. 10704 Expr::EvalResult KnownVal; 10705 if (!getLangOpts().CPlusPlus || 10706 (!IExp->isValueDependent() && 10707 (!IExp->EvaluateAsInt(KnownVal, Context) || 10708 KnownVal.Val.getInt() != 0))) { 10709 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10710 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10711 Context, BO_Add, PExp, IExp); 10712 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10713 } 10714 } 10715 10716 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10717 return QualType(); 10718 10719 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10720 return QualType(); 10721 10722 // Check array bounds for pointer arithemtic 10723 CheckArrayAccess(PExp, IExp); 10724 10725 if (CompLHSTy) { 10726 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10727 if (LHSTy.isNull()) { 10728 LHSTy = LHS.get()->getType(); 10729 if (LHSTy->isPromotableIntegerType()) 10730 LHSTy = Context.getPromotedIntegerType(LHSTy); 10731 } 10732 *CompLHSTy = LHSTy; 10733 } 10734 10735 return PExp->getType(); 10736 } 10737 10738 // C99 6.5.6 10739 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10740 SourceLocation Loc, 10741 QualType* CompLHSTy) { 10742 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10743 10744 if (LHS.get()->getType()->isVectorType() || 10745 RHS.get()->getType()->isVectorType()) { 10746 QualType compType = CheckVectorOperands( 10747 LHS, RHS, Loc, CompLHSTy, 10748 /*AllowBothBool*/getLangOpts().AltiVec, 10749 /*AllowBoolConversions*/getLangOpts().ZVector); 10750 if (CompLHSTy) *CompLHSTy = compType; 10751 return compType; 10752 } 10753 10754 if (LHS.get()->getType()->isConstantMatrixType() || 10755 RHS.get()->getType()->isConstantMatrixType()) { 10756 QualType compType = 10757 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10758 if (CompLHSTy) 10759 *CompLHSTy = compType; 10760 return compType; 10761 } 10762 10763 QualType compType = UsualArithmeticConversions( 10764 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10765 if (LHS.isInvalid() || RHS.isInvalid()) 10766 return QualType(); 10767 10768 // Enforce type constraints: C99 6.5.6p3. 10769 10770 // Handle the common case first (both operands are arithmetic). 10771 if (!compType.isNull() && compType->isArithmeticType()) { 10772 if (CompLHSTy) *CompLHSTy = compType; 10773 return compType; 10774 } 10775 10776 // Either ptr - int or ptr - ptr. 10777 if (LHS.get()->getType()->isAnyPointerType()) { 10778 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10779 10780 // Diagnose bad cases where we step over interface counts. 10781 if (LHS.get()->getType()->isObjCObjectPointerType() && 10782 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10783 return QualType(); 10784 10785 // The result type of a pointer-int computation is the pointer type. 10786 if (RHS.get()->getType()->isIntegerType()) { 10787 // Subtracting from a null pointer should produce a warning. 10788 // The last argument to the diagnose call says this doesn't match the 10789 // GNU int-to-pointer idiom. 10790 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10791 Expr::NPC_ValueDependentIsNotNull)) { 10792 // In C++ adding zero to a null pointer is defined. 10793 Expr::EvalResult KnownVal; 10794 if (!getLangOpts().CPlusPlus || 10795 (!RHS.get()->isValueDependent() && 10796 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10797 KnownVal.Val.getInt() != 0))) { 10798 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10799 } 10800 } 10801 10802 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10803 return QualType(); 10804 10805 // Check array bounds for pointer arithemtic 10806 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10807 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10808 10809 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10810 return LHS.get()->getType(); 10811 } 10812 10813 // Handle pointer-pointer subtractions. 10814 if (const PointerType *RHSPTy 10815 = RHS.get()->getType()->getAs<PointerType>()) { 10816 QualType rpointee = RHSPTy->getPointeeType(); 10817 10818 if (getLangOpts().CPlusPlus) { 10819 // Pointee types must be the same: C++ [expr.add] 10820 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10821 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10822 } 10823 } else { 10824 // Pointee types must be compatible C99 6.5.6p3 10825 if (!Context.typesAreCompatible( 10826 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10827 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10828 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10829 return QualType(); 10830 } 10831 } 10832 10833 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10834 LHS.get(), RHS.get())) 10835 return QualType(); 10836 10837 // FIXME: Add warnings for nullptr - ptr. 10838 10839 // The pointee type may have zero size. As an extension, a structure or 10840 // union may have zero size or an array may have zero length. In this 10841 // case subtraction does not make sense. 10842 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10843 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10844 if (ElementSize.isZero()) { 10845 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10846 << rpointee.getUnqualifiedType() 10847 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10848 } 10849 } 10850 10851 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10852 return Context.getPointerDiffType(); 10853 } 10854 } 10855 10856 return InvalidOperands(Loc, LHS, RHS); 10857 } 10858 10859 static bool isScopedEnumerationType(QualType T) { 10860 if (const EnumType *ET = T->getAs<EnumType>()) 10861 return ET->getDecl()->isScoped(); 10862 return false; 10863 } 10864 10865 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10866 SourceLocation Loc, BinaryOperatorKind Opc, 10867 QualType LHSType) { 10868 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10869 // so skip remaining warnings as we don't want to modify values within Sema. 10870 if (S.getLangOpts().OpenCL) 10871 return; 10872 10873 // Check right/shifter operand 10874 Expr::EvalResult RHSResult; 10875 if (RHS.get()->isValueDependent() || 10876 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10877 return; 10878 llvm::APSInt Right = RHSResult.Val.getInt(); 10879 10880 if (Right.isNegative()) { 10881 S.DiagRuntimeBehavior(Loc, RHS.get(), 10882 S.PDiag(diag::warn_shift_negative) 10883 << RHS.get()->getSourceRange()); 10884 return; 10885 } 10886 10887 QualType LHSExprType = LHS.get()->getType(); 10888 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10889 if (LHSExprType->isExtIntType()) 10890 LeftSize = S.Context.getIntWidth(LHSExprType); 10891 else if (LHSExprType->isFixedPointType()) { 10892 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10893 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10894 } 10895 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10896 if (Right.uge(LeftBits)) { 10897 S.DiagRuntimeBehavior(Loc, RHS.get(), 10898 S.PDiag(diag::warn_shift_gt_typewidth) 10899 << RHS.get()->getSourceRange()); 10900 return; 10901 } 10902 10903 // FIXME: We probably need to handle fixed point types specially here. 10904 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10905 return; 10906 10907 // When left shifting an ICE which is signed, we can check for overflow which 10908 // according to C++ standards prior to C++2a has undefined behavior 10909 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10910 // more than the maximum value representable in the result type, so never 10911 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10912 // expression is still probably a bug.) 10913 Expr::EvalResult LHSResult; 10914 if (LHS.get()->isValueDependent() || 10915 LHSType->hasUnsignedIntegerRepresentation() || 10916 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10917 return; 10918 llvm::APSInt Left = LHSResult.Val.getInt(); 10919 10920 // If LHS does not have a signed type and non-negative value 10921 // then, the behavior is undefined before C++2a. Warn about it. 10922 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10923 !S.getLangOpts().CPlusPlus20) { 10924 S.DiagRuntimeBehavior(Loc, LHS.get(), 10925 S.PDiag(diag::warn_shift_lhs_negative) 10926 << LHS.get()->getSourceRange()); 10927 return; 10928 } 10929 10930 llvm::APInt ResultBits = 10931 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10932 if (LeftBits.uge(ResultBits)) 10933 return; 10934 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10935 Result = Result.shl(Right); 10936 10937 // Print the bit representation of the signed integer as an unsigned 10938 // hexadecimal number. 10939 SmallString<40> HexResult; 10940 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10941 10942 // If we are only missing a sign bit, this is less likely to result in actual 10943 // bugs -- if the result is cast back to an unsigned type, it will have the 10944 // expected value. Thus we place this behind a different warning that can be 10945 // turned off separately if needed. 10946 if (LeftBits == ResultBits - 1) { 10947 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10948 << HexResult << LHSType 10949 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10950 return; 10951 } 10952 10953 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10954 << HexResult.str() << Result.getMinSignedBits() << LHSType 10955 << Left.getBitWidth() << LHS.get()->getSourceRange() 10956 << RHS.get()->getSourceRange(); 10957 } 10958 10959 /// Return the resulting type when a vector is shifted 10960 /// by a scalar or vector shift amount. 10961 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10962 SourceLocation Loc, bool IsCompAssign) { 10963 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10964 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10965 !LHS.get()->getType()->isVectorType()) { 10966 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10967 << RHS.get()->getType() << LHS.get()->getType() 10968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10969 return QualType(); 10970 } 10971 10972 if (!IsCompAssign) { 10973 LHS = S.UsualUnaryConversions(LHS.get()); 10974 if (LHS.isInvalid()) return QualType(); 10975 } 10976 10977 RHS = S.UsualUnaryConversions(RHS.get()); 10978 if (RHS.isInvalid()) return QualType(); 10979 10980 QualType LHSType = LHS.get()->getType(); 10981 // Note that LHS might be a scalar because the routine calls not only in 10982 // OpenCL case. 10983 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10984 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10985 10986 // Note that RHS might not be a vector. 10987 QualType RHSType = RHS.get()->getType(); 10988 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10989 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10990 10991 // The operands need to be integers. 10992 if (!LHSEleType->isIntegerType()) { 10993 S.Diag(Loc, diag::err_typecheck_expect_int) 10994 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10995 return QualType(); 10996 } 10997 10998 if (!RHSEleType->isIntegerType()) { 10999 S.Diag(Loc, diag::err_typecheck_expect_int) 11000 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11001 return QualType(); 11002 } 11003 11004 if (!LHSVecTy) { 11005 assert(RHSVecTy); 11006 if (IsCompAssign) 11007 return RHSType; 11008 if (LHSEleType != RHSEleType) { 11009 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11010 LHSEleType = RHSEleType; 11011 } 11012 QualType VecTy = 11013 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11014 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11015 LHSType = VecTy; 11016 } else if (RHSVecTy) { 11017 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11018 // are applied component-wise. So if RHS is a vector, then ensure 11019 // that the number of elements is the same as LHS... 11020 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11021 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11022 << LHS.get()->getType() << RHS.get()->getType() 11023 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11024 return QualType(); 11025 } 11026 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11027 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11028 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11029 if (LHSBT != RHSBT && 11030 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11031 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11032 << LHS.get()->getType() << RHS.get()->getType() 11033 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11034 } 11035 } 11036 } else { 11037 // ...else expand RHS to match the number of elements in LHS. 11038 QualType VecTy = 11039 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11040 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11041 } 11042 11043 return LHSType; 11044 } 11045 11046 // C99 6.5.7 11047 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11048 SourceLocation Loc, BinaryOperatorKind Opc, 11049 bool IsCompAssign) { 11050 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11051 11052 // Vector shifts promote their scalar inputs to vector type. 11053 if (LHS.get()->getType()->isVectorType() || 11054 RHS.get()->getType()->isVectorType()) { 11055 if (LangOpts.ZVector) { 11056 // The shift operators for the z vector extensions work basically 11057 // like general shifts, except that neither the LHS nor the RHS is 11058 // allowed to be a "vector bool". 11059 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11060 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11061 return InvalidOperands(Loc, LHS, RHS); 11062 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11063 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11064 return InvalidOperands(Loc, LHS, RHS); 11065 } 11066 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11067 } 11068 11069 // Shifts don't perform usual arithmetic conversions, they just do integer 11070 // promotions on each operand. C99 6.5.7p3 11071 11072 // For the LHS, do usual unary conversions, but then reset them away 11073 // if this is a compound assignment. 11074 ExprResult OldLHS = LHS; 11075 LHS = UsualUnaryConversions(LHS.get()); 11076 if (LHS.isInvalid()) 11077 return QualType(); 11078 QualType LHSType = LHS.get()->getType(); 11079 if (IsCompAssign) LHS = OldLHS; 11080 11081 // The RHS is simpler. 11082 RHS = UsualUnaryConversions(RHS.get()); 11083 if (RHS.isInvalid()) 11084 return QualType(); 11085 QualType RHSType = RHS.get()->getType(); 11086 11087 // C99 6.5.7p2: Each of the operands shall have integer type. 11088 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11089 if ((!LHSType->isFixedPointOrIntegerType() && 11090 !LHSType->hasIntegerRepresentation()) || 11091 !RHSType->hasIntegerRepresentation()) 11092 return InvalidOperands(Loc, LHS, RHS); 11093 11094 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11095 // hasIntegerRepresentation() above instead of this. 11096 if (isScopedEnumerationType(LHSType) || 11097 isScopedEnumerationType(RHSType)) { 11098 return InvalidOperands(Loc, LHS, RHS); 11099 } 11100 // Sanity-check shift operands 11101 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11102 11103 // "The type of the result is that of the promoted left operand." 11104 return LHSType; 11105 } 11106 11107 /// Diagnose bad pointer comparisons. 11108 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11109 ExprResult &LHS, ExprResult &RHS, 11110 bool IsError) { 11111 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11112 : diag::ext_typecheck_comparison_of_distinct_pointers) 11113 << LHS.get()->getType() << RHS.get()->getType() 11114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11115 } 11116 11117 /// Returns false if the pointers are converted to a composite type, 11118 /// true otherwise. 11119 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11120 ExprResult &LHS, ExprResult &RHS) { 11121 // C++ [expr.rel]p2: 11122 // [...] Pointer conversions (4.10) and qualification 11123 // conversions (4.4) are performed on pointer operands (or on 11124 // a pointer operand and a null pointer constant) to bring 11125 // them to their composite pointer type. [...] 11126 // 11127 // C++ [expr.eq]p1 uses the same notion for (in)equality 11128 // comparisons of pointers. 11129 11130 QualType LHSType = LHS.get()->getType(); 11131 QualType RHSType = RHS.get()->getType(); 11132 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11133 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11134 11135 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11136 if (T.isNull()) { 11137 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11138 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11139 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11140 else 11141 S.InvalidOperands(Loc, LHS, RHS); 11142 return true; 11143 } 11144 11145 return false; 11146 } 11147 11148 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11149 ExprResult &LHS, 11150 ExprResult &RHS, 11151 bool IsError) { 11152 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11153 : diag::ext_typecheck_comparison_of_fptr_to_void) 11154 << LHS.get()->getType() << RHS.get()->getType() 11155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11156 } 11157 11158 static bool isObjCObjectLiteral(ExprResult &E) { 11159 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11160 case Stmt::ObjCArrayLiteralClass: 11161 case Stmt::ObjCDictionaryLiteralClass: 11162 case Stmt::ObjCStringLiteralClass: 11163 case Stmt::ObjCBoxedExprClass: 11164 return true; 11165 default: 11166 // Note that ObjCBoolLiteral is NOT an object literal! 11167 return false; 11168 } 11169 } 11170 11171 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11172 const ObjCObjectPointerType *Type = 11173 LHS->getType()->getAs<ObjCObjectPointerType>(); 11174 11175 // If this is not actually an Objective-C object, bail out. 11176 if (!Type) 11177 return false; 11178 11179 // Get the LHS object's interface type. 11180 QualType InterfaceType = Type->getPointeeType(); 11181 11182 // If the RHS isn't an Objective-C object, bail out. 11183 if (!RHS->getType()->isObjCObjectPointerType()) 11184 return false; 11185 11186 // Try to find the -isEqual: method. 11187 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11188 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11189 InterfaceType, 11190 /*IsInstance=*/true); 11191 if (!Method) { 11192 if (Type->isObjCIdType()) { 11193 // For 'id', just check the global pool. 11194 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11195 /*receiverId=*/true); 11196 } else { 11197 // Check protocols. 11198 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11199 /*IsInstance=*/true); 11200 } 11201 } 11202 11203 if (!Method) 11204 return false; 11205 11206 QualType T = Method->parameters()[0]->getType(); 11207 if (!T->isObjCObjectPointerType()) 11208 return false; 11209 11210 QualType R = Method->getReturnType(); 11211 if (!R->isScalarType()) 11212 return false; 11213 11214 return true; 11215 } 11216 11217 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11218 FromE = FromE->IgnoreParenImpCasts(); 11219 switch (FromE->getStmtClass()) { 11220 default: 11221 break; 11222 case Stmt::ObjCStringLiteralClass: 11223 // "string literal" 11224 return LK_String; 11225 case Stmt::ObjCArrayLiteralClass: 11226 // "array literal" 11227 return LK_Array; 11228 case Stmt::ObjCDictionaryLiteralClass: 11229 // "dictionary literal" 11230 return LK_Dictionary; 11231 case Stmt::BlockExprClass: 11232 return LK_Block; 11233 case Stmt::ObjCBoxedExprClass: { 11234 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11235 switch (Inner->getStmtClass()) { 11236 case Stmt::IntegerLiteralClass: 11237 case Stmt::FloatingLiteralClass: 11238 case Stmt::CharacterLiteralClass: 11239 case Stmt::ObjCBoolLiteralExprClass: 11240 case Stmt::CXXBoolLiteralExprClass: 11241 // "numeric literal" 11242 return LK_Numeric; 11243 case Stmt::ImplicitCastExprClass: { 11244 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11245 // Boolean literals can be represented by implicit casts. 11246 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11247 return LK_Numeric; 11248 break; 11249 } 11250 default: 11251 break; 11252 } 11253 return LK_Boxed; 11254 } 11255 } 11256 return LK_None; 11257 } 11258 11259 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11260 ExprResult &LHS, ExprResult &RHS, 11261 BinaryOperator::Opcode Opc){ 11262 Expr *Literal; 11263 Expr *Other; 11264 if (isObjCObjectLiteral(LHS)) { 11265 Literal = LHS.get(); 11266 Other = RHS.get(); 11267 } else { 11268 Literal = RHS.get(); 11269 Other = LHS.get(); 11270 } 11271 11272 // Don't warn on comparisons against nil. 11273 Other = Other->IgnoreParenCasts(); 11274 if (Other->isNullPointerConstant(S.getASTContext(), 11275 Expr::NPC_ValueDependentIsNotNull)) 11276 return; 11277 11278 // This should be kept in sync with warn_objc_literal_comparison. 11279 // LK_String should always be after the other literals, since it has its own 11280 // warning flag. 11281 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11282 assert(LiteralKind != Sema::LK_Block); 11283 if (LiteralKind == Sema::LK_None) { 11284 llvm_unreachable("Unknown Objective-C object literal kind"); 11285 } 11286 11287 if (LiteralKind == Sema::LK_String) 11288 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11289 << Literal->getSourceRange(); 11290 else 11291 S.Diag(Loc, diag::warn_objc_literal_comparison) 11292 << LiteralKind << Literal->getSourceRange(); 11293 11294 if (BinaryOperator::isEqualityOp(Opc) && 11295 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11296 SourceLocation Start = LHS.get()->getBeginLoc(); 11297 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11298 CharSourceRange OpRange = 11299 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11300 11301 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11302 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11303 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11304 << FixItHint::CreateInsertion(End, "]"); 11305 } 11306 } 11307 11308 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11309 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11310 ExprResult &RHS, SourceLocation Loc, 11311 BinaryOperatorKind Opc) { 11312 // Check that left hand side is !something. 11313 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11314 if (!UO || UO->getOpcode() != UO_LNot) return; 11315 11316 // Only check if the right hand side is non-bool arithmetic type. 11317 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11318 11319 // Make sure that the something in !something is not bool. 11320 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11321 if (SubExpr->isKnownToHaveBooleanValue()) return; 11322 11323 // Emit warning. 11324 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11325 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11326 << Loc << IsBitwiseOp; 11327 11328 // First note suggest !(x < y) 11329 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11330 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11331 FirstClose = S.getLocForEndOfToken(FirstClose); 11332 if (FirstClose.isInvalid()) 11333 FirstOpen = SourceLocation(); 11334 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11335 << IsBitwiseOp 11336 << FixItHint::CreateInsertion(FirstOpen, "(") 11337 << FixItHint::CreateInsertion(FirstClose, ")"); 11338 11339 // Second note suggests (!x) < y 11340 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11341 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11342 SecondClose = S.getLocForEndOfToken(SecondClose); 11343 if (SecondClose.isInvalid()) 11344 SecondOpen = SourceLocation(); 11345 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11346 << FixItHint::CreateInsertion(SecondOpen, "(") 11347 << FixItHint::CreateInsertion(SecondClose, ")"); 11348 } 11349 11350 // Returns true if E refers to a non-weak array. 11351 static bool checkForArray(const Expr *E) { 11352 const ValueDecl *D = nullptr; 11353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11354 D = DR->getDecl(); 11355 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11356 if (Mem->isImplicitAccess()) 11357 D = Mem->getMemberDecl(); 11358 } 11359 if (!D) 11360 return false; 11361 return D->getType()->isArrayType() && !D->isWeak(); 11362 } 11363 11364 /// Diagnose some forms of syntactically-obvious tautological comparison. 11365 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11366 Expr *LHS, Expr *RHS, 11367 BinaryOperatorKind Opc) { 11368 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11369 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11370 11371 QualType LHSType = LHS->getType(); 11372 QualType RHSType = RHS->getType(); 11373 if (LHSType->hasFloatingRepresentation() || 11374 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11375 S.inTemplateInstantiation()) 11376 return; 11377 11378 // Comparisons between two array types are ill-formed for operator<=>, so 11379 // we shouldn't emit any additional warnings about it. 11380 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11381 return; 11382 11383 // For non-floating point types, check for self-comparisons of the form 11384 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11385 // often indicate logic errors in the program. 11386 // 11387 // NOTE: Don't warn about comparison expressions resulting from macro 11388 // expansion. Also don't warn about comparisons which are only self 11389 // comparisons within a template instantiation. The warnings should catch 11390 // obvious cases in the definition of the template anyways. The idea is to 11391 // warn when the typed comparison operator will always evaluate to the same 11392 // result. 11393 11394 // Used for indexing into %select in warn_comparison_always 11395 enum { 11396 AlwaysConstant, 11397 AlwaysTrue, 11398 AlwaysFalse, 11399 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11400 }; 11401 11402 // C++2a [depr.array.comp]: 11403 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11404 // operands of array type are deprecated. 11405 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11406 RHSStripped->getType()->isArrayType()) { 11407 S.Diag(Loc, diag::warn_depr_array_comparison) 11408 << LHS->getSourceRange() << RHS->getSourceRange() 11409 << LHSStripped->getType() << RHSStripped->getType(); 11410 // Carry on to produce the tautological comparison warning, if this 11411 // expression is potentially-evaluated, we can resolve the array to a 11412 // non-weak declaration, and so on. 11413 } 11414 11415 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11416 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11417 unsigned Result; 11418 switch (Opc) { 11419 case BO_EQ: 11420 case BO_LE: 11421 case BO_GE: 11422 Result = AlwaysTrue; 11423 break; 11424 case BO_NE: 11425 case BO_LT: 11426 case BO_GT: 11427 Result = AlwaysFalse; 11428 break; 11429 case BO_Cmp: 11430 Result = AlwaysEqual; 11431 break; 11432 default: 11433 Result = AlwaysConstant; 11434 break; 11435 } 11436 S.DiagRuntimeBehavior(Loc, nullptr, 11437 S.PDiag(diag::warn_comparison_always) 11438 << 0 /*self-comparison*/ 11439 << Result); 11440 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11441 // What is it always going to evaluate to? 11442 unsigned Result; 11443 switch (Opc) { 11444 case BO_EQ: // e.g. array1 == array2 11445 Result = AlwaysFalse; 11446 break; 11447 case BO_NE: // e.g. array1 != array2 11448 Result = AlwaysTrue; 11449 break; 11450 default: // e.g. array1 <= array2 11451 // The best we can say is 'a constant' 11452 Result = AlwaysConstant; 11453 break; 11454 } 11455 S.DiagRuntimeBehavior(Loc, nullptr, 11456 S.PDiag(diag::warn_comparison_always) 11457 << 1 /*array comparison*/ 11458 << Result); 11459 } 11460 } 11461 11462 if (isa<CastExpr>(LHSStripped)) 11463 LHSStripped = LHSStripped->IgnoreParenCasts(); 11464 if (isa<CastExpr>(RHSStripped)) 11465 RHSStripped = RHSStripped->IgnoreParenCasts(); 11466 11467 // Warn about comparisons against a string constant (unless the other 11468 // operand is null); the user probably wants string comparison function. 11469 Expr *LiteralString = nullptr; 11470 Expr *LiteralStringStripped = nullptr; 11471 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11472 !RHSStripped->isNullPointerConstant(S.Context, 11473 Expr::NPC_ValueDependentIsNull)) { 11474 LiteralString = LHS; 11475 LiteralStringStripped = LHSStripped; 11476 } else if ((isa<StringLiteral>(RHSStripped) || 11477 isa<ObjCEncodeExpr>(RHSStripped)) && 11478 !LHSStripped->isNullPointerConstant(S.Context, 11479 Expr::NPC_ValueDependentIsNull)) { 11480 LiteralString = RHS; 11481 LiteralStringStripped = RHSStripped; 11482 } 11483 11484 if (LiteralString) { 11485 S.DiagRuntimeBehavior(Loc, nullptr, 11486 S.PDiag(diag::warn_stringcompare) 11487 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11488 << LiteralString->getSourceRange()); 11489 } 11490 } 11491 11492 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11493 switch (CK) { 11494 default: { 11495 #ifndef NDEBUG 11496 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11497 << "\n"; 11498 #endif 11499 llvm_unreachable("unhandled cast kind"); 11500 } 11501 case CK_UserDefinedConversion: 11502 return ICK_Identity; 11503 case CK_LValueToRValue: 11504 return ICK_Lvalue_To_Rvalue; 11505 case CK_ArrayToPointerDecay: 11506 return ICK_Array_To_Pointer; 11507 case CK_FunctionToPointerDecay: 11508 return ICK_Function_To_Pointer; 11509 case CK_IntegralCast: 11510 return ICK_Integral_Conversion; 11511 case CK_FloatingCast: 11512 return ICK_Floating_Conversion; 11513 case CK_IntegralToFloating: 11514 case CK_FloatingToIntegral: 11515 return ICK_Floating_Integral; 11516 case CK_IntegralComplexCast: 11517 case CK_FloatingComplexCast: 11518 case CK_FloatingComplexToIntegralComplex: 11519 case CK_IntegralComplexToFloatingComplex: 11520 return ICK_Complex_Conversion; 11521 case CK_FloatingComplexToReal: 11522 case CK_FloatingRealToComplex: 11523 case CK_IntegralComplexToReal: 11524 case CK_IntegralRealToComplex: 11525 return ICK_Complex_Real; 11526 } 11527 } 11528 11529 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11530 QualType FromType, 11531 SourceLocation Loc) { 11532 // Check for a narrowing implicit conversion. 11533 StandardConversionSequence SCS; 11534 SCS.setAsIdentityConversion(); 11535 SCS.setToType(0, FromType); 11536 SCS.setToType(1, ToType); 11537 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11538 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11539 11540 APValue PreNarrowingValue; 11541 QualType PreNarrowingType; 11542 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11543 PreNarrowingType, 11544 /*IgnoreFloatToIntegralConversion*/ true)) { 11545 case NK_Dependent_Narrowing: 11546 // Implicit conversion to a narrower type, but the expression is 11547 // value-dependent so we can't tell whether it's actually narrowing. 11548 case NK_Not_Narrowing: 11549 return false; 11550 11551 case NK_Constant_Narrowing: 11552 // Implicit conversion to a narrower type, and the value is not a constant 11553 // expression. 11554 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11555 << /*Constant*/ 1 11556 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11557 return true; 11558 11559 case NK_Variable_Narrowing: 11560 // Implicit conversion to a narrower type, and the value is not a constant 11561 // expression. 11562 case NK_Type_Narrowing: 11563 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11564 << /*Constant*/ 0 << FromType << ToType; 11565 // TODO: It's not a constant expression, but what if the user intended it 11566 // to be? Can we produce notes to help them figure out why it isn't? 11567 return true; 11568 } 11569 llvm_unreachable("unhandled case in switch"); 11570 } 11571 11572 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11573 ExprResult &LHS, 11574 ExprResult &RHS, 11575 SourceLocation Loc) { 11576 QualType LHSType = LHS.get()->getType(); 11577 QualType RHSType = RHS.get()->getType(); 11578 // Dig out the original argument type and expression before implicit casts 11579 // were applied. These are the types/expressions we need to check the 11580 // [expr.spaceship] requirements against. 11581 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11582 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11583 QualType LHSStrippedType = LHSStripped.get()->getType(); 11584 QualType RHSStrippedType = RHSStripped.get()->getType(); 11585 11586 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11587 // other is not, the program is ill-formed. 11588 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11589 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11590 return QualType(); 11591 } 11592 11593 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11594 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11595 RHSStrippedType->isEnumeralType(); 11596 if (NumEnumArgs == 1) { 11597 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11598 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11599 if (OtherTy->hasFloatingRepresentation()) { 11600 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11601 return QualType(); 11602 } 11603 } 11604 if (NumEnumArgs == 2) { 11605 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11606 // type E, the operator yields the result of converting the operands 11607 // to the underlying type of E and applying <=> to the converted operands. 11608 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11609 S.InvalidOperands(Loc, LHS, RHS); 11610 return QualType(); 11611 } 11612 QualType IntType = 11613 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11614 assert(IntType->isArithmeticType()); 11615 11616 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11617 // promote the boolean type, and all other promotable integer types, to 11618 // avoid this. 11619 if (IntType->isPromotableIntegerType()) 11620 IntType = S.Context.getPromotedIntegerType(IntType); 11621 11622 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11623 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11624 LHSType = RHSType = IntType; 11625 } 11626 11627 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11628 // usual arithmetic conversions are applied to the operands. 11629 QualType Type = 11630 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11631 if (LHS.isInvalid() || RHS.isInvalid()) 11632 return QualType(); 11633 if (Type.isNull()) 11634 return S.InvalidOperands(Loc, LHS, RHS); 11635 11636 Optional<ComparisonCategoryType> CCT = 11637 getComparisonCategoryForBuiltinCmp(Type); 11638 if (!CCT) 11639 return S.InvalidOperands(Loc, LHS, RHS); 11640 11641 bool HasNarrowing = checkThreeWayNarrowingConversion( 11642 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11643 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11644 RHS.get()->getBeginLoc()); 11645 if (HasNarrowing) 11646 return QualType(); 11647 11648 assert(!Type.isNull() && "composite type for <=> has not been set"); 11649 11650 return S.CheckComparisonCategoryType( 11651 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11652 } 11653 11654 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11655 ExprResult &RHS, 11656 SourceLocation Loc, 11657 BinaryOperatorKind Opc) { 11658 if (Opc == BO_Cmp) 11659 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11660 11661 // C99 6.5.8p3 / C99 6.5.9p4 11662 QualType Type = 11663 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11664 if (LHS.isInvalid() || RHS.isInvalid()) 11665 return QualType(); 11666 if (Type.isNull()) 11667 return S.InvalidOperands(Loc, LHS, RHS); 11668 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11669 11670 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11671 return S.InvalidOperands(Loc, LHS, RHS); 11672 11673 // Check for comparisons of floating point operands using != and ==. 11674 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11675 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11676 11677 // The result of comparisons is 'bool' in C++, 'int' in C. 11678 return S.Context.getLogicalOperationType(); 11679 } 11680 11681 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11682 if (!NullE.get()->getType()->isAnyPointerType()) 11683 return; 11684 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11685 if (!E.get()->getType()->isAnyPointerType() && 11686 E.get()->isNullPointerConstant(Context, 11687 Expr::NPC_ValueDependentIsNotNull) == 11688 Expr::NPCK_ZeroExpression) { 11689 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11690 if (CL->getValue() == 0) 11691 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11692 << NullValue 11693 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11694 NullValue ? "NULL" : "(void *)0"); 11695 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11696 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11697 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11698 if (T == Context.CharTy) 11699 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11700 << NullValue 11701 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11702 NullValue ? "NULL" : "(void *)0"); 11703 } 11704 } 11705 } 11706 11707 // C99 6.5.8, C++ [expr.rel] 11708 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11709 SourceLocation Loc, 11710 BinaryOperatorKind Opc) { 11711 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11712 bool IsThreeWay = Opc == BO_Cmp; 11713 bool IsOrdered = IsRelational || IsThreeWay; 11714 auto IsAnyPointerType = [](ExprResult E) { 11715 QualType Ty = E.get()->getType(); 11716 return Ty->isPointerType() || Ty->isMemberPointerType(); 11717 }; 11718 11719 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11720 // type, array-to-pointer, ..., conversions are performed on both operands to 11721 // bring them to their composite type. 11722 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11723 // any type-related checks. 11724 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11725 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11726 if (LHS.isInvalid()) 11727 return QualType(); 11728 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11729 if (RHS.isInvalid()) 11730 return QualType(); 11731 } else { 11732 LHS = DefaultLvalueConversion(LHS.get()); 11733 if (LHS.isInvalid()) 11734 return QualType(); 11735 RHS = DefaultLvalueConversion(RHS.get()); 11736 if (RHS.isInvalid()) 11737 return QualType(); 11738 } 11739 11740 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11741 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11742 CheckPtrComparisonWithNullChar(LHS, RHS); 11743 CheckPtrComparisonWithNullChar(RHS, LHS); 11744 } 11745 11746 // Handle vector comparisons separately. 11747 if (LHS.get()->getType()->isVectorType() || 11748 RHS.get()->getType()->isVectorType()) 11749 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11750 11751 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11752 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11753 11754 QualType LHSType = LHS.get()->getType(); 11755 QualType RHSType = RHS.get()->getType(); 11756 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11757 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11758 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11759 11760 const Expr::NullPointerConstantKind LHSNullKind = 11761 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11762 const Expr::NullPointerConstantKind RHSNullKind = 11763 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11764 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11765 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11766 11767 auto computeResultTy = [&]() { 11768 if (Opc != BO_Cmp) 11769 return Context.getLogicalOperationType(); 11770 assert(getLangOpts().CPlusPlus); 11771 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11772 11773 QualType CompositeTy = LHS.get()->getType(); 11774 assert(!CompositeTy->isReferenceType()); 11775 11776 Optional<ComparisonCategoryType> CCT = 11777 getComparisonCategoryForBuiltinCmp(CompositeTy); 11778 if (!CCT) 11779 return InvalidOperands(Loc, LHS, RHS); 11780 11781 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11782 // P0946R0: Comparisons between a null pointer constant and an object 11783 // pointer result in std::strong_equality, which is ill-formed under 11784 // P1959R0. 11785 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11786 << (LHSIsNull ? LHS.get()->getSourceRange() 11787 : RHS.get()->getSourceRange()); 11788 return QualType(); 11789 } 11790 11791 return CheckComparisonCategoryType( 11792 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11793 }; 11794 11795 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11796 bool IsEquality = Opc == BO_EQ; 11797 if (RHSIsNull) 11798 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11799 RHS.get()->getSourceRange()); 11800 else 11801 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11802 LHS.get()->getSourceRange()); 11803 } 11804 11805 if ((LHSType->isIntegerType() && !LHSIsNull) || 11806 (RHSType->isIntegerType() && !RHSIsNull)) { 11807 // Skip normal pointer conversion checks in this case; we have better 11808 // diagnostics for this below. 11809 } else if (getLangOpts().CPlusPlus) { 11810 // Equality comparison of a function pointer to a void pointer is invalid, 11811 // but we allow it as an extension. 11812 // FIXME: If we really want to allow this, should it be part of composite 11813 // pointer type computation so it works in conditionals too? 11814 if (!IsOrdered && 11815 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11816 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11817 // This is a gcc extension compatibility comparison. 11818 // In a SFINAE context, we treat this as a hard error to maintain 11819 // conformance with the C++ standard. 11820 diagnoseFunctionPointerToVoidComparison( 11821 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11822 11823 if (isSFINAEContext()) 11824 return QualType(); 11825 11826 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11827 return computeResultTy(); 11828 } 11829 11830 // C++ [expr.eq]p2: 11831 // If at least one operand is a pointer [...] bring them to their 11832 // composite pointer type. 11833 // C++ [expr.spaceship]p6 11834 // If at least one of the operands is of pointer type, [...] bring them 11835 // to their composite pointer type. 11836 // C++ [expr.rel]p2: 11837 // If both operands are pointers, [...] bring them to their composite 11838 // pointer type. 11839 // For <=>, the only valid non-pointer types are arrays and functions, and 11840 // we already decayed those, so this is really the same as the relational 11841 // comparison rule. 11842 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11843 (IsOrdered ? 2 : 1) && 11844 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11845 RHSType->isObjCObjectPointerType()))) { 11846 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11847 return QualType(); 11848 return computeResultTy(); 11849 } 11850 } else if (LHSType->isPointerType() && 11851 RHSType->isPointerType()) { // C99 6.5.8p2 11852 // All of the following pointer-related warnings are GCC extensions, except 11853 // when handling null pointer constants. 11854 QualType LCanPointeeTy = 11855 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11856 QualType RCanPointeeTy = 11857 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11858 11859 // C99 6.5.9p2 and C99 6.5.8p2 11860 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11861 RCanPointeeTy.getUnqualifiedType())) { 11862 if (IsRelational) { 11863 // Pointers both need to point to complete or incomplete types 11864 if ((LCanPointeeTy->isIncompleteType() != 11865 RCanPointeeTy->isIncompleteType()) && 11866 !getLangOpts().C11) { 11867 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11868 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11869 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11870 << RCanPointeeTy->isIncompleteType(); 11871 } 11872 if (LCanPointeeTy->isFunctionType()) { 11873 // Valid unless a relational comparison of function pointers 11874 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11875 << LHSType << RHSType << LHS.get()->getSourceRange() 11876 << RHS.get()->getSourceRange(); 11877 } 11878 } 11879 } else if (!IsRelational && 11880 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11881 // Valid unless comparison between non-null pointer and function pointer 11882 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11883 && !LHSIsNull && !RHSIsNull) 11884 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11885 /*isError*/false); 11886 } else { 11887 // Invalid 11888 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11889 } 11890 if (LCanPointeeTy != RCanPointeeTy) { 11891 // Treat NULL constant as a special case in OpenCL. 11892 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11893 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11894 Diag(Loc, 11895 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11896 << LHSType << RHSType << 0 /* comparison */ 11897 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11898 } 11899 } 11900 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11901 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11902 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11903 : CK_BitCast; 11904 if (LHSIsNull && !RHSIsNull) 11905 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11906 else 11907 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11908 } 11909 return computeResultTy(); 11910 } 11911 11912 if (getLangOpts().CPlusPlus) { 11913 // C++ [expr.eq]p4: 11914 // Two operands of type std::nullptr_t or one operand of type 11915 // std::nullptr_t and the other a null pointer constant compare equal. 11916 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11917 if (LHSType->isNullPtrType()) { 11918 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11919 return computeResultTy(); 11920 } 11921 if (RHSType->isNullPtrType()) { 11922 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11923 return computeResultTy(); 11924 } 11925 } 11926 11927 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11928 // These aren't covered by the composite pointer type rules. 11929 if (!IsOrdered && RHSType->isNullPtrType() && 11930 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11931 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11932 return computeResultTy(); 11933 } 11934 if (!IsOrdered && LHSType->isNullPtrType() && 11935 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11936 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11937 return computeResultTy(); 11938 } 11939 11940 if (IsRelational && 11941 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11942 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11943 // HACK: Relational comparison of nullptr_t against a pointer type is 11944 // invalid per DR583, but we allow it within std::less<> and friends, 11945 // since otherwise common uses of it break. 11946 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11947 // friends to have std::nullptr_t overload candidates. 11948 DeclContext *DC = CurContext; 11949 if (isa<FunctionDecl>(DC)) 11950 DC = DC->getParent(); 11951 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11952 if (CTSD->isInStdNamespace() && 11953 llvm::StringSwitch<bool>(CTSD->getName()) 11954 .Cases("less", "less_equal", "greater", "greater_equal", true) 11955 .Default(false)) { 11956 if (RHSType->isNullPtrType()) 11957 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11958 else 11959 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11960 return computeResultTy(); 11961 } 11962 } 11963 } 11964 11965 // C++ [expr.eq]p2: 11966 // If at least one operand is a pointer to member, [...] bring them to 11967 // their composite pointer type. 11968 if (!IsOrdered && 11969 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11970 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11971 return QualType(); 11972 else 11973 return computeResultTy(); 11974 } 11975 } 11976 11977 // Handle block pointer types. 11978 if (!IsOrdered && LHSType->isBlockPointerType() && 11979 RHSType->isBlockPointerType()) { 11980 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11981 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11982 11983 if (!LHSIsNull && !RHSIsNull && 11984 !Context.typesAreCompatible(lpointee, rpointee)) { 11985 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11986 << LHSType << RHSType << LHS.get()->getSourceRange() 11987 << RHS.get()->getSourceRange(); 11988 } 11989 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11990 return computeResultTy(); 11991 } 11992 11993 // Allow block pointers to be compared with null pointer constants. 11994 if (!IsOrdered 11995 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11996 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11997 if (!LHSIsNull && !RHSIsNull) { 11998 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11999 ->getPointeeType()->isVoidType()) 12000 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12001 ->getPointeeType()->isVoidType()))) 12002 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12003 << LHSType << RHSType << LHS.get()->getSourceRange() 12004 << RHS.get()->getSourceRange(); 12005 } 12006 if (LHSIsNull && !RHSIsNull) 12007 LHS = ImpCastExprToType(LHS.get(), RHSType, 12008 RHSType->isPointerType() ? CK_BitCast 12009 : CK_AnyPointerToBlockPointerCast); 12010 else 12011 RHS = ImpCastExprToType(RHS.get(), LHSType, 12012 LHSType->isPointerType() ? CK_BitCast 12013 : CK_AnyPointerToBlockPointerCast); 12014 return computeResultTy(); 12015 } 12016 12017 if (LHSType->isObjCObjectPointerType() || 12018 RHSType->isObjCObjectPointerType()) { 12019 const PointerType *LPT = LHSType->getAs<PointerType>(); 12020 const PointerType *RPT = RHSType->getAs<PointerType>(); 12021 if (LPT || RPT) { 12022 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12023 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12024 12025 if (!LPtrToVoid && !RPtrToVoid && 12026 !Context.typesAreCompatible(LHSType, RHSType)) { 12027 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12028 /*isError*/false); 12029 } 12030 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12031 // the RHS, but we have test coverage for this behavior. 12032 // FIXME: Consider using convertPointersToCompositeType in C++. 12033 if (LHSIsNull && !RHSIsNull) { 12034 Expr *E = LHS.get(); 12035 if (getLangOpts().ObjCAutoRefCount) 12036 CheckObjCConversion(SourceRange(), RHSType, E, 12037 CCK_ImplicitConversion); 12038 LHS = ImpCastExprToType(E, RHSType, 12039 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12040 } 12041 else { 12042 Expr *E = RHS.get(); 12043 if (getLangOpts().ObjCAutoRefCount) 12044 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12045 /*Diagnose=*/true, 12046 /*DiagnoseCFAudited=*/false, Opc); 12047 RHS = ImpCastExprToType(E, LHSType, 12048 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12049 } 12050 return computeResultTy(); 12051 } 12052 if (LHSType->isObjCObjectPointerType() && 12053 RHSType->isObjCObjectPointerType()) { 12054 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12055 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12056 /*isError*/false); 12057 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12058 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12059 12060 if (LHSIsNull && !RHSIsNull) 12061 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12062 else 12063 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12064 return computeResultTy(); 12065 } 12066 12067 if (!IsOrdered && LHSType->isBlockPointerType() && 12068 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12069 LHS = ImpCastExprToType(LHS.get(), RHSType, 12070 CK_BlockPointerToObjCPointerCast); 12071 return computeResultTy(); 12072 } else if (!IsOrdered && 12073 LHSType->isBlockCompatibleObjCPointerType(Context) && 12074 RHSType->isBlockPointerType()) { 12075 RHS = ImpCastExprToType(RHS.get(), LHSType, 12076 CK_BlockPointerToObjCPointerCast); 12077 return computeResultTy(); 12078 } 12079 } 12080 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12081 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12082 unsigned DiagID = 0; 12083 bool isError = false; 12084 if (LangOpts.DebuggerSupport) { 12085 // Under a debugger, allow the comparison of pointers to integers, 12086 // since users tend to want to compare addresses. 12087 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12088 (RHSIsNull && RHSType->isIntegerType())) { 12089 if (IsOrdered) { 12090 isError = getLangOpts().CPlusPlus; 12091 DiagID = 12092 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12093 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12094 } 12095 } else if (getLangOpts().CPlusPlus) { 12096 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12097 isError = true; 12098 } else if (IsOrdered) 12099 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12100 else 12101 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12102 12103 if (DiagID) { 12104 Diag(Loc, DiagID) 12105 << LHSType << RHSType << LHS.get()->getSourceRange() 12106 << RHS.get()->getSourceRange(); 12107 if (isError) 12108 return QualType(); 12109 } 12110 12111 if (LHSType->isIntegerType()) 12112 LHS = ImpCastExprToType(LHS.get(), RHSType, 12113 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12114 else 12115 RHS = ImpCastExprToType(RHS.get(), LHSType, 12116 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12117 return computeResultTy(); 12118 } 12119 12120 // Handle block pointers. 12121 if (!IsOrdered && RHSIsNull 12122 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12124 return computeResultTy(); 12125 } 12126 if (!IsOrdered && LHSIsNull 12127 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12128 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12129 return computeResultTy(); 12130 } 12131 12132 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12133 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12134 return computeResultTy(); 12135 } 12136 12137 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12138 return computeResultTy(); 12139 } 12140 12141 if (LHSIsNull && RHSType->isQueueT()) { 12142 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12143 return computeResultTy(); 12144 } 12145 12146 if (LHSType->isQueueT() && RHSIsNull) { 12147 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12148 return computeResultTy(); 12149 } 12150 } 12151 12152 return InvalidOperands(Loc, LHS, RHS); 12153 } 12154 12155 // Return a signed ext_vector_type that is of identical size and number of 12156 // elements. For floating point vectors, return an integer type of identical 12157 // size and number of elements. In the non ext_vector_type case, search from 12158 // the largest type to the smallest type to avoid cases where long long == long, 12159 // where long gets picked over long long. 12160 QualType Sema::GetSignedVectorType(QualType V) { 12161 const VectorType *VTy = V->castAs<VectorType>(); 12162 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12163 12164 if (isa<ExtVectorType>(VTy)) { 12165 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12166 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12167 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12168 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12169 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12170 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12171 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12172 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12173 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12174 "Unhandled vector element size in vector compare"); 12175 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12176 } 12177 12178 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12179 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12180 VectorType::GenericVector); 12181 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12182 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12183 VectorType::GenericVector); 12184 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12185 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12186 VectorType::GenericVector); 12187 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12188 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12189 VectorType::GenericVector); 12190 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12191 "Unhandled vector element size in vector compare"); 12192 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12193 VectorType::GenericVector); 12194 } 12195 12196 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12197 /// operates on extended vector types. Instead of producing an IntTy result, 12198 /// like a scalar comparison, a vector comparison produces a vector of integer 12199 /// types. 12200 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12201 SourceLocation Loc, 12202 BinaryOperatorKind Opc) { 12203 if (Opc == BO_Cmp) { 12204 Diag(Loc, diag::err_three_way_vector_comparison); 12205 return QualType(); 12206 } 12207 12208 // Check to make sure we're operating on vectors of the same type and width, 12209 // Allowing one side to be a scalar of element type. 12210 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12211 /*AllowBothBool*/true, 12212 /*AllowBoolConversions*/getLangOpts().ZVector); 12213 if (vType.isNull()) 12214 return vType; 12215 12216 QualType LHSType = LHS.get()->getType(); 12217 12218 // If AltiVec, the comparison results in a numeric type, i.e. 12219 // bool for C++, int for C 12220 if (getLangOpts().AltiVec && 12221 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12222 return Context.getLogicalOperationType(); 12223 12224 // For non-floating point types, check for self-comparisons of the form 12225 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12226 // often indicate logic errors in the program. 12227 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12228 12229 // Check for comparisons of floating point operands using != and ==. 12230 if (BinaryOperator::isEqualityOp(Opc) && 12231 LHSType->hasFloatingRepresentation()) { 12232 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12233 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12234 } 12235 12236 // Return a signed type for the vector. 12237 return GetSignedVectorType(vType); 12238 } 12239 12240 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12241 const ExprResult &XorRHS, 12242 const SourceLocation Loc) { 12243 // Do not diagnose macros. 12244 if (Loc.isMacroID()) 12245 return; 12246 12247 // Do not diagnose if both LHS and RHS are macros. 12248 if (XorLHS.get()->getExprLoc().isMacroID() && 12249 XorRHS.get()->getExprLoc().isMacroID()) 12250 return; 12251 12252 bool Negative = false; 12253 bool ExplicitPlus = false; 12254 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12255 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12256 12257 if (!LHSInt) 12258 return; 12259 if (!RHSInt) { 12260 // Check negative literals. 12261 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12262 UnaryOperatorKind Opc = UO->getOpcode(); 12263 if (Opc != UO_Minus && Opc != UO_Plus) 12264 return; 12265 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12266 if (!RHSInt) 12267 return; 12268 Negative = (Opc == UO_Minus); 12269 ExplicitPlus = !Negative; 12270 } else { 12271 return; 12272 } 12273 } 12274 12275 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12276 llvm::APInt RightSideValue = RHSInt->getValue(); 12277 if (LeftSideValue != 2 && LeftSideValue != 10) 12278 return; 12279 12280 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12281 return; 12282 12283 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12284 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12285 llvm::StringRef ExprStr = 12286 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12287 12288 CharSourceRange XorRange = 12289 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12290 llvm::StringRef XorStr = 12291 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12292 // Do not diagnose if xor keyword/macro is used. 12293 if (XorStr == "xor") 12294 return; 12295 12296 std::string LHSStr = std::string(Lexer::getSourceText( 12297 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12298 S.getSourceManager(), S.getLangOpts())); 12299 std::string RHSStr = std::string(Lexer::getSourceText( 12300 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12301 S.getSourceManager(), S.getLangOpts())); 12302 12303 if (Negative) { 12304 RightSideValue = -RightSideValue; 12305 RHSStr = "-" + RHSStr; 12306 } else if (ExplicitPlus) { 12307 RHSStr = "+" + RHSStr; 12308 } 12309 12310 StringRef LHSStrRef = LHSStr; 12311 StringRef RHSStrRef = RHSStr; 12312 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12313 // literals. 12314 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12315 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12316 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12317 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12318 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12319 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12320 LHSStrRef.find('\'') != StringRef::npos || 12321 RHSStrRef.find('\'') != StringRef::npos) 12322 return; 12323 12324 bool SuggestXor = 12325 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12326 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12327 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12328 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12329 std::string SuggestedExpr = "1 << " + RHSStr; 12330 bool Overflow = false; 12331 llvm::APInt One = (LeftSideValue - 1); 12332 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12333 if (Overflow) { 12334 if (RightSideIntValue < 64) 12335 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12336 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12337 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12338 else if (RightSideIntValue == 64) 12339 S.Diag(Loc, diag::warn_xor_used_as_pow) 12340 << ExprStr << toString(XorValue, 10, true); 12341 else 12342 return; 12343 } else { 12344 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12345 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12346 << toString(PowValue, 10, true) 12347 << FixItHint::CreateReplacement( 12348 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12349 } 12350 12351 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12352 << ("0x2 ^ " + RHSStr) << SuggestXor; 12353 } else if (LeftSideValue == 10) { 12354 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12355 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12356 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12357 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12358 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12359 << ("0xA ^ " + RHSStr) << SuggestXor; 12360 } 12361 } 12362 12363 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12364 SourceLocation Loc) { 12365 // Ensure that either both operands are of the same vector type, or 12366 // one operand is of a vector type and the other is of its element type. 12367 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12368 /*AllowBothBool*/true, 12369 /*AllowBoolConversions*/false); 12370 if (vType.isNull()) 12371 return InvalidOperands(Loc, LHS, RHS); 12372 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12373 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12374 return InvalidOperands(Loc, LHS, RHS); 12375 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12376 // usage of the logical operators && and || with vectors in C. This 12377 // check could be notionally dropped. 12378 if (!getLangOpts().CPlusPlus && 12379 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12380 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12381 12382 return GetSignedVectorType(LHS.get()->getType()); 12383 } 12384 12385 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12386 SourceLocation Loc, 12387 bool IsCompAssign) { 12388 if (!IsCompAssign) { 12389 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12390 if (LHS.isInvalid()) 12391 return QualType(); 12392 } 12393 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12394 if (RHS.isInvalid()) 12395 return QualType(); 12396 12397 // For conversion purposes, we ignore any qualifiers. 12398 // For example, "const float" and "float" are equivalent. 12399 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12400 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12401 12402 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12403 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12404 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12405 12406 if (Context.hasSameType(LHSType, RHSType)) 12407 return LHSType; 12408 12409 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12410 // case we have to return InvalidOperands. 12411 ExprResult OriginalLHS = LHS; 12412 ExprResult OriginalRHS = RHS; 12413 if (LHSMatType && !RHSMatType) { 12414 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12415 if (!RHS.isInvalid()) 12416 return LHSType; 12417 12418 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12419 } 12420 12421 if (!LHSMatType && RHSMatType) { 12422 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12423 if (!LHS.isInvalid()) 12424 return RHSType; 12425 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12426 } 12427 12428 return InvalidOperands(Loc, LHS, RHS); 12429 } 12430 12431 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12432 SourceLocation Loc, 12433 bool IsCompAssign) { 12434 if (!IsCompAssign) { 12435 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12436 if (LHS.isInvalid()) 12437 return QualType(); 12438 } 12439 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12440 if (RHS.isInvalid()) 12441 return QualType(); 12442 12443 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12444 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12445 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12446 12447 if (LHSMatType && RHSMatType) { 12448 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12449 return InvalidOperands(Loc, LHS, RHS); 12450 12451 if (!Context.hasSameType(LHSMatType->getElementType(), 12452 RHSMatType->getElementType())) 12453 return InvalidOperands(Loc, LHS, RHS); 12454 12455 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12456 LHSMatType->getNumRows(), 12457 RHSMatType->getNumColumns()); 12458 } 12459 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12460 } 12461 12462 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12463 SourceLocation Loc, 12464 BinaryOperatorKind Opc) { 12465 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12466 12467 bool IsCompAssign = 12468 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12469 12470 if (LHS.get()->getType()->isVectorType() || 12471 RHS.get()->getType()->isVectorType()) { 12472 if (LHS.get()->getType()->hasIntegerRepresentation() && 12473 RHS.get()->getType()->hasIntegerRepresentation()) 12474 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12475 /*AllowBothBool*/true, 12476 /*AllowBoolConversions*/getLangOpts().ZVector); 12477 return InvalidOperands(Loc, LHS, RHS); 12478 } 12479 12480 if (Opc == BO_And) 12481 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12482 12483 if (LHS.get()->getType()->hasFloatingRepresentation() || 12484 RHS.get()->getType()->hasFloatingRepresentation()) 12485 return InvalidOperands(Loc, LHS, RHS); 12486 12487 ExprResult LHSResult = LHS, RHSResult = RHS; 12488 QualType compType = UsualArithmeticConversions( 12489 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12490 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12491 return QualType(); 12492 LHS = LHSResult.get(); 12493 RHS = RHSResult.get(); 12494 12495 if (Opc == BO_Xor) 12496 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12497 12498 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12499 return compType; 12500 return InvalidOperands(Loc, LHS, RHS); 12501 } 12502 12503 // C99 6.5.[13,14] 12504 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12505 SourceLocation Loc, 12506 BinaryOperatorKind Opc) { 12507 // Check vector operands differently. 12508 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12509 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12510 12511 bool EnumConstantInBoolContext = false; 12512 for (const ExprResult &HS : {LHS, RHS}) { 12513 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12514 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12515 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12516 EnumConstantInBoolContext = true; 12517 } 12518 } 12519 12520 if (EnumConstantInBoolContext) 12521 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12522 12523 // Diagnose cases where the user write a logical and/or but probably meant a 12524 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12525 // is a constant. 12526 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12527 !LHS.get()->getType()->isBooleanType() && 12528 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12529 // Don't warn in macros or template instantiations. 12530 !Loc.isMacroID() && !inTemplateInstantiation()) { 12531 // If the RHS can be constant folded, and if it constant folds to something 12532 // that isn't 0 or 1 (which indicate a potential logical operation that 12533 // happened to fold to true/false) then warn. 12534 // Parens on the RHS are ignored. 12535 Expr::EvalResult EVResult; 12536 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12537 llvm::APSInt Result = EVResult.Val.getInt(); 12538 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12539 !RHS.get()->getExprLoc().isMacroID()) || 12540 (Result != 0 && Result != 1)) { 12541 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12542 << RHS.get()->getSourceRange() 12543 << (Opc == BO_LAnd ? "&&" : "||"); 12544 // Suggest replacing the logical operator with the bitwise version 12545 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12546 << (Opc == BO_LAnd ? "&" : "|") 12547 << FixItHint::CreateReplacement(SourceRange( 12548 Loc, getLocForEndOfToken(Loc)), 12549 Opc == BO_LAnd ? "&" : "|"); 12550 if (Opc == BO_LAnd) 12551 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12552 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12553 << FixItHint::CreateRemoval( 12554 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12555 RHS.get()->getEndLoc())); 12556 } 12557 } 12558 } 12559 12560 if (!Context.getLangOpts().CPlusPlus) { 12561 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12562 // not operate on the built-in scalar and vector float types. 12563 if (Context.getLangOpts().OpenCL && 12564 Context.getLangOpts().OpenCLVersion < 120) { 12565 if (LHS.get()->getType()->isFloatingType() || 12566 RHS.get()->getType()->isFloatingType()) 12567 return InvalidOperands(Loc, LHS, RHS); 12568 } 12569 12570 LHS = UsualUnaryConversions(LHS.get()); 12571 if (LHS.isInvalid()) 12572 return QualType(); 12573 12574 RHS = UsualUnaryConversions(RHS.get()); 12575 if (RHS.isInvalid()) 12576 return QualType(); 12577 12578 if (!LHS.get()->getType()->isScalarType() || 12579 !RHS.get()->getType()->isScalarType()) 12580 return InvalidOperands(Loc, LHS, RHS); 12581 12582 return Context.IntTy; 12583 } 12584 12585 // The following is safe because we only use this method for 12586 // non-overloadable operands. 12587 12588 // C++ [expr.log.and]p1 12589 // C++ [expr.log.or]p1 12590 // The operands are both contextually converted to type bool. 12591 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12592 if (LHSRes.isInvalid()) 12593 return InvalidOperands(Loc, LHS, RHS); 12594 LHS = LHSRes; 12595 12596 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12597 if (RHSRes.isInvalid()) 12598 return InvalidOperands(Loc, LHS, RHS); 12599 RHS = RHSRes; 12600 12601 // C++ [expr.log.and]p2 12602 // C++ [expr.log.or]p2 12603 // The result is a bool. 12604 return Context.BoolTy; 12605 } 12606 12607 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12608 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12609 if (!ME) return false; 12610 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12611 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12612 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12613 if (!Base) return false; 12614 return Base->getMethodDecl() != nullptr; 12615 } 12616 12617 /// Is the given expression (which must be 'const') a reference to a 12618 /// variable which was originally non-const, but which has become 12619 /// 'const' due to being captured within a block? 12620 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12621 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12622 assert(E->isLValue() && E->getType().isConstQualified()); 12623 E = E->IgnoreParens(); 12624 12625 // Must be a reference to a declaration from an enclosing scope. 12626 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12627 if (!DRE) return NCCK_None; 12628 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12629 12630 // The declaration must be a variable which is not declared 'const'. 12631 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12632 if (!var) return NCCK_None; 12633 if (var->getType().isConstQualified()) return NCCK_None; 12634 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12635 12636 // Decide whether the first capture was for a block or a lambda. 12637 DeclContext *DC = S.CurContext, *Prev = nullptr; 12638 // Decide whether the first capture was for a block or a lambda. 12639 while (DC) { 12640 // For init-capture, it is possible that the variable belongs to the 12641 // template pattern of the current context. 12642 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12643 if (var->isInitCapture() && 12644 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12645 break; 12646 if (DC == var->getDeclContext()) 12647 break; 12648 Prev = DC; 12649 DC = DC->getParent(); 12650 } 12651 // Unless we have an init-capture, we've gone one step too far. 12652 if (!var->isInitCapture()) 12653 DC = Prev; 12654 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12655 } 12656 12657 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12658 Ty = Ty.getNonReferenceType(); 12659 if (IsDereference && Ty->isPointerType()) 12660 Ty = Ty->getPointeeType(); 12661 return !Ty.isConstQualified(); 12662 } 12663 12664 // Update err_typecheck_assign_const and note_typecheck_assign_const 12665 // when this enum is changed. 12666 enum { 12667 ConstFunction, 12668 ConstVariable, 12669 ConstMember, 12670 ConstMethod, 12671 NestedConstMember, 12672 ConstUnknown, // Keep as last element 12673 }; 12674 12675 /// Emit the "read-only variable not assignable" error and print notes to give 12676 /// more information about why the variable is not assignable, such as pointing 12677 /// to the declaration of a const variable, showing that a method is const, or 12678 /// that the function is returning a const reference. 12679 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12680 SourceLocation Loc) { 12681 SourceRange ExprRange = E->getSourceRange(); 12682 12683 // Only emit one error on the first const found. All other consts will emit 12684 // a note to the error. 12685 bool DiagnosticEmitted = false; 12686 12687 // Track if the current expression is the result of a dereference, and if the 12688 // next checked expression is the result of a dereference. 12689 bool IsDereference = false; 12690 bool NextIsDereference = false; 12691 12692 // Loop to process MemberExpr chains. 12693 while (true) { 12694 IsDereference = NextIsDereference; 12695 12696 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12697 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12698 NextIsDereference = ME->isArrow(); 12699 const ValueDecl *VD = ME->getMemberDecl(); 12700 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12701 // Mutable fields can be modified even if the class is const. 12702 if (Field->isMutable()) { 12703 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12704 break; 12705 } 12706 12707 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12708 if (!DiagnosticEmitted) { 12709 S.Diag(Loc, diag::err_typecheck_assign_const) 12710 << ExprRange << ConstMember << false /*static*/ << Field 12711 << Field->getType(); 12712 DiagnosticEmitted = true; 12713 } 12714 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12715 << ConstMember << false /*static*/ << Field << Field->getType() 12716 << Field->getSourceRange(); 12717 } 12718 E = ME->getBase(); 12719 continue; 12720 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12721 if (VDecl->getType().isConstQualified()) { 12722 if (!DiagnosticEmitted) { 12723 S.Diag(Loc, diag::err_typecheck_assign_const) 12724 << ExprRange << ConstMember << true /*static*/ << VDecl 12725 << VDecl->getType(); 12726 DiagnosticEmitted = true; 12727 } 12728 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12729 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12730 << VDecl->getSourceRange(); 12731 } 12732 // Static fields do not inherit constness from parents. 12733 break; 12734 } 12735 break; // End MemberExpr 12736 } else if (const ArraySubscriptExpr *ASE = 12737 dyn_cast<ArraySubscriptExpr>(E)) { 12738 E = ASE->getBase()->IgnoreParenImpCasts(); 12739 continue; 12740 } else if (const ExtVectorElementExpr *EVE = 12741 dyn_cast<ExtVectorElementExpr>(E)) { 12742 E = EVE->getBase()->IgnoreParenImpCasts(); 12743 continue; 12744 } 12745 break; 12746 } 12747 12748 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12749 // Function calls 12750 const FunctionDecl *FD = CE->getDirectCallee(); 12751 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12752 if (!DiagnosticEmitted) { 12753 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12754 << ConstFunction << FD; 12755 DiagnosticEmitted = true; 12756 } 12757 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12758 diag::note_typecheck_assign_const) 12759 << ConstFunction << FD << FD->getReturnType() 12760 << FD->getReturnTypeSourceRange(); 12761 } 12762 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12763 // Point to variable declaration. 12764 if (const ValueDecl *VD = DRE->getDecl()) { 12765 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12766 if (!DiagnosticEmitted) { 12767 S.Diag(Loc, diag::err_typecheck_assign_const) 12768 << ExprRange << ConstVariable << VD << VD->getType(); 12769 DiagnosticEmitted = true; 12770 } 12771 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12772 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12773 } 12774 } 12775 } else if (isa<CXXThisExpr>(E)) { 12776 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12778 if (MD->isConst()) { 12779 if (!DiagnosticEmitted) { 12780 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12781 << ConstMethod << MD; 12782 DiagnosticEmitted = true; 12783 } 12784 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12785 << ConstMethod << MD << MD->getSourceRange(); 12786 } 12787 } 12788 } 12789 } 12790 12791 if (DiagnosticEmitted) 12792 return; 12793 12794 // Can't determine a more specific message, so display the generic error. 12795 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12796 } 12797 12798 enum OriginalExprKind { 12799 OEK_Variable, 12800 OEK_Member, 12801 OEK_LValue 12802 }; 12803 12804 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12805 const RecordType *Ty, 12806 SourceLocation Loc, SourceRange Range, 12807 OriginalExprKind OEK, 12808 bool &DiagnosticEmitted) { 12809 std::vector<const RecordType *> RecordTypeList; 12810 RecordTypeList.push_back(Ty); 12811 unsigned NextToCheckIndex = 0; 12812 // We walk the record hierarchy breadth-first to ensure that we print 12813 // diagnostics in field nesting order. 12814 while (RecordTypeList.size() > NextToCheckIndex) { 12815 bool IsNested = NextToCheckIndex > 0; 12816 for (const FieldDecl *Field : 12817 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12818 // First, check every field for constness. 12819 QualType FieldTy = Field->getType(); 12820 if (FieldTy.isConstQualified()) { 12821 if (!DiagnosticEmitted) { 12822 S.Diag(Loc, diag::err_typecheck_assign_const) 12823 << Range << NestedConstMember << OEK << VD 12824 << IsNested << Field; 12825 DiagnosticEmitted = true; 12826 } 12827 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12828 << NestedConstMember << IsNested << Field 12829 << FieldTy << Field->getSourceRange(); 12830 } 12831 12832 // Then we append it to the list to check next in order. 12833 FieldTy = FieldTy.getCanonicalType(); 12834 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12835 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12836 RecordTypeList.push_back(FieldRecTy); 12837 } 12838 } 12839 ++NextToCheckIndex; 12840 } 12841 } 12842 12843 /// Emit an error for the case where a record we are trying to assign to has a 12844 /// const-qualified field somewhere in its hierarchy. 12845 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12846 SourceLocation Loc) { 12847 QualType Ty = E->getType(); 12848 assert(Ty->isRecordType() && "lvalue was not record?"); 12849 SourceRange Range = E->getSourceRange(); 12850 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12851 bool DiagEmitted = false; 12852 12853 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12854 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12855 Range, OEK_Member, DiagEmitted); 12856 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12857 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12858 Range, OEK_Variable, DiagEmitted); 12859 else 12860 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12861 Range, OEK_LValue, DiagEmitted); 12862 if (!DiagEmitted) 12863 DiagnoseConstAssignment(S, E, Loc); 12864 } 12865 12866 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12867 /// emit an error and return true. If so, return false. 12868 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12869 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12870 12871 S.CheckShadowingDeclModification(E, Loc); 12872 12873 SourceLocation OrigLoc = Loc; 12874 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12875 &Loc); 12876 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12877 IsLV = Expr::MLV_InvalidMessageExpression; 12878 if (IsLV == Expr::MLV_Valid) 12879 return false; 12880 12881 unsigned DiagID = 0; 12882 bool NeedType = false; 12883 switch (IsLV) { // C99 6.5.16p2 12884 case Expr::MLV_ConstQualified: 12885 // Use a specialized diagnostic when we're assigning to an object 12886 // from an enclosing function or block. 12887 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12888 if (NCCK == NCCK_Block) 12889 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12890 else 12891 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12892 break; 12893 } 12894 12895 // In ARC, use some specialized diagnostics for occasions where we 12896 // infer 'const'. These are always pseudo-strong variables. 12897 if (S.getLangOpts().ObjCAutoRefCount) { 12898 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12899 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12900 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12901 12902 // Use the normal diagnostic if it's pseudo-__strong but the 12903 // user actually wrote 'const'. 12904 if (var->isARCPseudoStrong() && 12905 (!var->getTypeSourceInfo() || 12906 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12907 // There are three pseudo-strong cases: 12908 // - self 12909 ObjCMethodDecl *method = S.getCurMethodDecl(); 12910 if (method && var == method->getSelfDecl()) { 12911 DiagID = method->isClassMethod() 12912 ? diag::err_typecheck_arc_assign_self_class_method 12913 : diag::err_typecheck_arc_assign_self; 12914 12915 // - Objective-C externally_retained attribute. 12916 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12917 isa<ParmVarDecl>(var)) { 12918 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12919 12920 // - fast enumeration variables 12921 } else { 12922 DiagID = diag::err_typecheck_arr_assign_enumeration; 12923 } 12924 12925 SourceRange Assign; 12926 if (Loc != OrigLoc) 12927 Assign = SourceRange(OrigLoc, OrigLoc); 12928 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12929 // We need to preserve the AST regardless, so migration tool 12930 // can do its job. 12931 return false; 12932 } 12933 } 12934 } 12935 12936 // If none of the special cases above are triggered, then this is a 12937 // simple const assignment. 12938 if (DiagID == 0) { 12939 DiagnoseConstAssignment(S, E, Loc); 12940 return true; 12941 } 12942 12943 break; 12944 case Expr::MLV_ConstAddrSpace: 12945 DiagnoseConstAssignment(S, E, Loc); 12946 return true; 12947 case Expr::MLV_ConstQualifiedField: 12948 DiagnoseRecursiveConstFields(S, E, Loc); 12949 return true; 12950 case Expr::MLV_ArrayType: 12951 case Expr::MLV_ArrayTemporary: 12952 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12953 NeedType = true; 12954 break; 12955 case Expr::MLV_NotObjectType: 12956 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12957 NeedType = true; 12958 break; 12959 case Expr::MLV_LValueCast: 12960 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12961 break; 12962 case Expr::MLV_Valid: 12963 llvm_unreachable("did not take early return for MLV_Valid"); 12964 case Expr::MLV_InvalidExpression: 12965 case Expr::MLV_MemberFunction: 12966 case Expr::MLV_ClassTemporary: 12967 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12968 break; 12969 case Expr::MLV_IncompleteType: 12970 case Expr::MLV_IncompleteVoidType: 12971 return S.RequireCompleteType(Loc, E->getType(), 12972 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12973 case Expr::MLV_DuplicateVectorComponents: 12974 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12975 break; 12976 case Expr::MLV_NoSetterProperty: 12977 llvm_unreachable("readonly properties should be processed differently"); 12978 case Expr::MLV_InvalidMessageExpression: 12979 DiagID = diag::err_readonly_message_assignment; 12980 break; 12981 case Expr::MLV_SubObjCPropertySetting: 12982 DiagID = diag::err_no_subobject_property_setting; 12983 break; 12984 } 12985 12986 SourceRange Assign; 12987 if (Loc != OrigLoc) 12988 Assign = SourceRange(OrigLoc, OrigLoc); 12989 if (NeedType) 12990 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12991 else 12992 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12993 return true; 12994 } 12995 12996 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12997 SourceLocation Loc, 12998 Sema &Sema) { 12999 if (Sema.inTemplateInstantiation()) 13000 return; 13001 if (Sema.isUnevaluatedContext()) 13002 return; 13003 if (Loc.isInvalid() || Loc.isMacroID()) 13004 return; 13005 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13006 return; 13007 13008 // C / C++ fields 13009 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13010 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13011 if (ML && MR) { 13012 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13013 return; 13014 const ValueDecl *LHSDecl = 13015 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13016 const ValueDecl *RHSDecl = 13017 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13018 if (LHSDecl != RHSDecl) 13019 return; 13020 if (LHSDecl->getType().isVolatileQualified()) 13021 return; 13022 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13023 if (RefTy->getPointeeType().isVolatileQualified()) 13024 return; 13025 13026 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13027 } 13028 13029 // Objective-C instance variables 13030 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13031 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13032 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13033 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13034 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13035 if (RL && RR && RL->getDecl() == RR->getDecl()) 13036 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13037 } 13038 } 13039 13040 // C99 6.5.16.1 13041 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13042 SourceLocation Loc, 13043 QualType CompoundType) { 13044 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13045 13046 // Verify that LHS is a modifiable lvalue, and emit error if not. 13047 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13048 return QualType(); 13049 13050 QualType LHSType = LHSExpr->getType(); 13051 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13052 CompoundType; 13053 // OpenCL v1.2 s6.1.1.1 p2: 13054 // The half data type can only be used to declare a pointer to a buffer that 13055 // contains half values 13056 if (getLangOpts().OpenCL && 13057 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13058 LHSType->isHalfType()) { 13059 Diag(Loc, diag::err_opencl_half_load_store) << 1 13060 << LHSType.getUnqualifiedType(); 13061 return QualType(); 13062 } 13063 13064 AssignConvertType ConvTy; 13065 if (CompoundType.isNull()) { 13066 Expr *RHSCheck = RHS.get(); 13067 13068 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13069 13070 QualType LHSTy(LHSType); 13071 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13072 if (RHS.isInvalid()) 13073 return QualType(); 13074 // Special case of NSObject attributes on c-style pointer types. 13075 if (ConvTy == IncompatiblePointer && 13076 ((Context.isObjCNSObjectType(LHSType) && 13077 RHSType->isObjCObjectPointerType()) || 13078 (Context.isObjCNSObjectType(RHSType) && 13079 LHSType->isObjCObjectPointerType()))) 13080 ConvTy = Compatible; 13081 13082 if (ConvTy == Compatible && 13083 LHSType->isObjCObjectType()) 13084 Diag(Loc, diag::err_objc_object_assignment) 13085 << LHSType; 13086 13087 // If the RHS is a unary plus or minus, check to see if they = and + are 13088 // right next to each other. If so, the user may have typo'd "x =+ 4" 13089 // instead of "x += 4". 13090 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13091 RHSCheck = ICE->getSubExpr(); 13092 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13093 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13094 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13095 // Only if the two operators are exactly adjacent. 13096 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13097 // And there is a space or other character before the subexpr of the 13098 // unary +/-. We don't want to warn on "x=-1". 13099 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13100 UO->getSubExpr()->getBeginLoc().isFileID()) { 13101 Diag(Loc, diag::warn_not_compound_assign) 13102 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13103 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13104 } 13105 } 13106 13107 if (ConvTy == Compatible) { 13108 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13109 // Warn about retain cycles where a block captures the LHS, but 13110 // not if the LHS is a simple variable into which the block is 13111 // being stored...unless that variable can be captured by reference! 13112 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13113 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13114 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13115 checkRetainCycles(LHSExpr, RHS.get()); 13116 } 13117 13118 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13119 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13120 // It is safe to assign a weak reference into a strong variable. 13121 // Although this code can still have problems: 13122 // id x = self.weakProp; 13123 // id y = self.weakProp; 13124 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13125 // paths through the function. This should be revisited if 13126 // -Wrepeated-use-of-weak is made flow-sensitive. 13127 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13128 // variable, which will be valid for the current autorelease scope. 13129 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13130 RHS.get()->getBeginLoc())) 13131 getCurFunction()->markSafeWeakUse(RHS.get()); 13132 13133 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13134 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13135 } 13136 } 13137 } else { 13138 // Compound assignment "x += y" 13139 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13140 } 13141 13142 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13143 RHS.get(), AA_Assigning)) 13144 return QualType(); 13145 13146 CheckForNullPointerDereference(*this, LHSExpr); 13147 13148 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13149 if (CompoundType.isNull()) { 13150 // C++2a [expr.ass]p5: 13151 // A simple-assignment whose left operand is of a volatile-qualified 13152 // type is deprecated unless the assignment is either a discarded-value 13153 // expression or an unevaluated operand 13154 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13155 } else { 13156 // C++2a [expr.ass]p6: 13157 // [Compound-assignment] expressions are deprecated if E1 has 13158 // volatile-qualified type 13159 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13160 } 13161 } 13162 13163 // C99 6.5.16p3: The type of an assignment expression is the type of the 13164 // left operand unless the left operand has qualified type, in which case 13165 // it is the unqualified version of the type of the left operand. 13166 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13167 // is converted to the type of the assignment expression (above). 13168 // C++ 5.17p1: the type of the assignment expression is that of its left 13169 // operand. 13170 return (getLangOpts().CPlusPlus 13171 ? LHSType : LHSType.getUnqualifiedType()); 13172 } 13173 13174 // Only ignore explicit casts to void. 13175 static bool IgnoreCommaOperand(const Expr *E) { 13176 E = E->IgnoreParens(); 13177 13178 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13179 if (CE->getCastKind() == CK_ToVoid) { 13180 return true; 13181 } 13182 13183 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13184 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13185 CE->getSubExpr()->getType()->isDependentType()) { 13186 return true; 13187 } 13188 } 13189 13190 return false; 13191 } 13192 13193 // Look for instances where it is likely the comma operator is confused with 13194 // another operator. There is an explicit list of acceptable expressions for 13195 // the left hand side of the comma operator, otherwise emit a warning. 13196 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13197 // No warnings in macros 13198 if (Loc.isMacroID()) 13199 return; 13200 13201 // Don't warn in template instantiations. 13202 if (inTemplateInstantiation()) 13203 return; 13204 13205 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13206 // instead, skip more than needed, then call back into here with the 13207 // CommaVisitor in SemaStmt.cpp. 13208 // The listed locations are the initialization and increment portions 13209 // of a for loop. The additional checks are on the condition of 13210 // if statements, do/while loops, and for loops. 13211 // Differences in scope flags for C89 mode requires the extra logic. 13212 const unsigned ForIncrementFlags = 13213 getLangOpts().C99 || getLangOpts().CPlusPlus 13214 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13215 : Scope::ContinueScope | Scope::BreakScope; 13216 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13217 const unsigned ScopeFlags = getCurScope()->getFlags(); 13218 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13219 (ScopeFlags & ForInitFlags) == ForInitFlags) 13220 return; 13221 13222 // If there are multiple comma operators used together, get the RHS of the 13223 // of the comma operator as the LHS. 13224 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13225 if (BO->getOpcode() != BO_Comma) 13226 break; 13227 LHS = BO->getRHS(); 13228 } 13229 13230 // Only allow some expressions on LHS to not warn. 13231 if (IgnoreCommaOperand(LHS)) 13232 return; 13233 13234 Diag(Loc, diag::warn_comma_operator); 13235 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13236 << LHS->getSourceRange() 13237 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13238 LangOpts.CPlusPlus ? "static_cast<void>(" 13239 : "(void)(") 13240 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13241 ")"); 13242 } 13243 13244 // C99 6.5.17 13245 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13246 SourceLocation Loc) { 13247 LHS = S.CheckPlaceholderExpr(LHS.get()); 13248 RHS = S.CheckPlaceholderExpr(RHS.get()); 13249 if (LHS.isInvalid() || RHS.isInvalid()) 13250 return QualType(); 13251 13252 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13253 // operands, but not unary promotions. 13254 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13255 13256 // So we treat the LHS as a ignored value, and in C++ we allow the 13257 // containing site to determine what should be done with the RHS. 13258 LHS = S.IgnoredValueConversions(LHS.get()); 13259 if (LHS.isInvalid()) 13260 return QualType(); 13261 13262 S.DiagnoseUnusedExprResult(LHS.get()); 13263 13264 if (!S.getLangOpts().CPlusPlus) { 13265 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13266 if (RHS.isInvalid()) 13267 return QualType(); 13268 if (!RHS.get()->getType()->isVoidType()) 13269 S.RequireCompleteType(Loc, RHS.get()->getType(), 13270 diag::err_incomplete_type); 13271 } 13272 13273 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13274 S.DiagnoseCommaOperator(LHS.get(), Loc); 13275 13276 return RHS.get()->getType(); 13277 } 13278 13279 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13280 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13281 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13282 ExprValueKind &VK, 13283 ExprObjectKind &OK, 13284 SourceLocation OpLoc, 13285 bool IsInc, bool IsPrefix) { 13286 if (Op->isTypeDependent()) 13287 return S.Context.DependentTy; 13288 13289 QualType ResType = Op->getType(); 13290 // Atomic types can be used for increment / decrement where the non-atomic 13291 // versions can, so ignore the _Atomic() specifier for the purpose of 13292 // checking. 13293 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13294 ResType = ResAtomicType->getValueType(); 13295 13296 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13297 13298 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13299 // Decrement of bool is not allowed. 13300 if (!IsInc) { 13301 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13302 return QualType(); 13303 } 13304 // Increment of bool sets it to true, but is deprecated. 13305 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13306 : diag::warn_increment_bool) 13307 << Op->getSourceRange(); 13308 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13309 // Error on enum increments and decrements in C++ mode 13310 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13311 return QualType(); 13312 } else if (ResType->isRealType()) { 13313 // OK! 13314 } else if (ResType->isPointerType()) { 13315 // C99 6.5.2.4p2, 6.5.6p2 13316 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13317 return QualType(); 13318 } else if (ResType->isObjCObjectPointerType()) { 13319 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13320 // Otherwise, we just need a complete type. 13321 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13322 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13323 return QualType(); 13324 } else if (ResType->isAnyComplexType()) { 13325 // C99 does not support ++/-- on complex types, we allow as an extension. 13326 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13327 << ResType << Op->getSourceRange(); 13328 } else if (ResType->isPlaceholderType()) { 13329 ExprResult PR = S.CheckPlaceholderExpr(Op); 13330 if (PR.isInvalid()) return QualType(); 13331 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13332 IsInc, IsPrefix); 13333 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13334 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13335 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13336 (ResType->castAs<VectorType>()->getVectorKind() != 13337 VectorType::AltiVecBool)) { 13338 // The z vector extensions allow ++ and -- for non-bool vectors. 13339 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13340 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13341 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13342 } else { 13343 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13344 << ResType << int(IsInc) << Op->getSourceRange(); 13345 return QualType(); 13346 } 13347 // At this point, we know we have a real, complex or pointer type. 13348 // Now make sure the operand is a modifiable lvalue. 13349 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13350 return QualType(); 13351 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13352 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13353 // An operand with volatile-qualified type is deprecated 13354 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13355 << IsInc << ResType; 13356 } 13357 // In C++, a prefix increment is the same type as the operand. Otherwise 13358 // (in C or with postfix), the increment is the unqualified type of the 13359 // operand. 13360 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13361 VK = VK_LValue; 13362 OK = Op->getObjectKind(); 13363 return ResType; 13364 } else { 13365 VK = VK_PRValue; 13366 return ResType.getUnqualifiedType(); 13367 } 13368 } 13369 13370 13371 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13372 /// This routine allows us to typecheck complex/recursive expressions 13373 /// where the declaration is needed for type checking. We only need to 13374 /// handle cases when the expression references a function designator 13375 /// or is an lvalue. Here are some examples: 13376 /// - &(x) => x 13377 /// - &*****f => f for f a function designator. 13378 /// - &s.xx => s 13379 /// - &s.zz[1].yy -> s, if zz is an array 13380 /// - *(x + 1) -> x, if x is an array 13381 /// - &"123"[2] -> 0 13382 /// - & __real__ x -> x 13383 /// 13384 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13385 /// members. 13386 static ValueDecl *getPrimaryDecl(Expr *E) { 13387 switch (E->getStmtClass()) { 13388 case Stmt::DeclRefExprClass: 13389 return cast<DeclRefExpr>(E)->getDecl(); 13390 case Stmt::MemberExprClass: 13391 // If this is an arrow operator, the address is an offset from 13392 // the base's value, so the object the base refers to is 13393 // irrelevant. 13394 if (cast<MemberExpr>(E)->isArrow()) 13395 return nullptr; 13396 // Otherwise, the expression refers to a part of the base 13397 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13398 case Stmt::ArraySubscriptExprClass: { 13399 // FIXME: This code shouldn't be necessary! We should catch the implicit 13400 // promotion of register arrays earlier. 13401 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13402 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13403 if (ICE->getSubExpr()->getType()->isArrayType()) 13404 return getPrimaryDecl(ICE->getSubExpr()); 13405 } 13406 return nullptr; 13407 } 13408 case Stmt::UnaryOperatorClass: { 13409 UnaryOperator *UO = cast<UnaryOperator>(E); 13410 13411 switch(UO->getOpcode()) { 13412 case UO_Real: 13413 case UO_Imag: 13414 case UO_Extension: 13415 return getPrimaryDecl(UO->getSubExpr()); 13416 default: 13417 return nullptr; 13418 } 13419 } 13420 case Stmt::ParenExprClass: 13421 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13422 case Stmt::ImplicitCastExprClass: 13423 // If the result of an implicit cast is an l-value, we care about 13424 // the sub-expression; otherwise, the result here doesn't matter. 13425 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13426 case Stmt::CXXUuidofExprClass: 13427 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13428 default: 13429 return nullptr; 13430 } 13431 } 13432 13433 namespace { 13434 enum { 13435 AO_Bit_Field = 0, 13436 AO_Vector_Element = 1, 13437 AO_Property_Expansion = 2, 13438 AO_Register_Variable = 3, 13439 AO_Matrix_Element = 4, 13440 AO_No_Error = 5 13441 }; 13442 } 13443 /// Diagnose invalid operand for address of operations. 13444 /// 13445 /// \param Type The type of operand which cannot have its address taken. 13446 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13447 Expr *E, unsigned Type) { 13448 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13449 } 13450 13451 /// CheckAddressOfOperand - The operand of & must be either a function 13452 /// designator or an lvalue designating an object. If it is an lvalue, the 13453 /// object cannot be declared with storage class register or be a bit field. 13454 /// Note: The usual conversions are *not* applied to the operand of the & 13455 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13456 /// In C++, the operand might be an overloaded function name, in which case 13457 /// we allow the '&' but retain the overloaded-function type. 13458 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13459 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13460 if (PTy->getKind() == BuiltinType::Overload) { 13461 Expr *E = OrigOp.get()->IgnoreParens(); 13462 if (!isa<OverloadExpr>(E)) { 13463 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13464 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13465 << OrigOp.get()->getSourceRange(); 13466 return QualType(); 13467 } 13468 13469 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13470 if (isa<UnresolvedMemberExpr>(Ovl)) 13471 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13472 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13473 << OrigOp.get()->getSourceRange(); 13474 return QualType(); 13475 } 13476 13477 return Context.OverloadTy; 13478 } 13479 13480 if (PTy->getKind() == BuiltinType::UnknownAny) 13481 return Context.UnknownAnyTy; 13482 13483 if (PTy->getKind() == BuiltinType::BoundMember) { 13484 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13485 << OrigOp.get()->getSourceRange(); 13486 return QualType(); 13487 } 13488 13489 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13490 if (OrigOp.isInvalid()) return QualType(); 13491 } 13492 13493 if (OrigOp.get()->isTypeDependent()) 13494 return Context.DependentTy; 13495 13496 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13497 13498 // Make sure to ignore parentheses in subsequent checks 13499 Expr *op = OrigOp.get()->IgnoreParens(); 13500 13501 // In OpenCL captures for blocks called as lambda functions 13502 // are located in the private address space. Blocks used in 13503 // enqueue_kernel can be located in a different address space 13504 // depending on a vendor implementation. Thus preventing 13505 // taking an address of the capture to avoid invalid AS casts. 13506 if (LangOpts.OpenCL) { 13507 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13508 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13509 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13510 return QualType(); 13511 } 13512 } 13513 13514 if (getLangOpts().C99) { 13515 // Implement C99-only parts of addressof rules. 13516 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13517 if (uOp->getOpcode() == UO_Deref) 13518 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13519 // (assuming the deref expression is valid). 13520 return uOp->getSubExpr()->getType(); 13521 } 13522 // Technically, there should be a check for array subscript 13523 // expressions here, but the result of one is always an lvalue anyway. 13524 } 13525 ValueDecl *dcl = getPrimaryDecl(op); 13526 13527 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13528 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13529 op->getBeginLoc())) 13530 return QualType(); 13531 13532 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13533 unsigned AddressOfError = AO_No_Error; 13534 13535 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13536 bool sfinae = (bool)isSFINAEContext(); 13537 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13538 : diag::ext_typecheck_addrof_temporary) 13539 << op->getType() << op->getSourceRange(); 13540 if (sfinae) 13541 return QualType(); 13542 // Materialize the temporary as an lvalue so that we can take its address. 13543 OrigOp = op = 13544 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13545 } else if (isa<ObjCSelectorExpr>(op)) { 13546 return Context.getPointerType(op->getType()); 13547 } else if (lval == Expr::LV_MemberFunction) { 13548 // If it's an instance method, make a member pointer. 13549 // The expression must have exactly the form &A::foo. 13550 13551 // If the underlying expression isn't a decl ref, give up. 13552 if (!isa<DeclRefExpr>(op)) { 13553 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13554 << OrigOp.get()->getSourceRange(); 13555 return QualType(); 13556 } 13557 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13558 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13559 13560 // The id-expression was parenthesized. 13561 if (OrigOp.get() != DRE) { 13562 Diag(OpLoc, diag::err_parens_pointer_member_function) 13563 << OrigOp.get()->getSourceRange(); 13564 13565 // The method was named without a qualifier. 13566 } else if (!DRE->getQualifier()) { 13567 if (MD->getParent()->getName().empty()) 13568 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13569 << op->getSourceRange(); 13570 else { 13571 SmallString<32> Str; 13572 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13573 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13574 << op->getSourceRange() 13575 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13576 } 13577 } 13578 13579 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13580 if (isa<CXXDestructorDecl>(MD)) 13581 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13582 13583 QualType MPTy = Context.getMemberPointerType( 13584 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13585 // Under the MS ABI, lock down the inheritance model now. 13586 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13587 (void)isCompleteType(OpLoc, MPTy); 13588 return MPTy; 13589 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13590 // C99 6.5.3.2p1 13591 // The operand must be either an l-value or a function designator 13592 if (!op->getType()->isFunctionType()) { 13593 // Use a special diagnostic for loads from property references. 13594 if (isa<PseudoObjectExpr>(op)) { 13595 AddressOfError = AO_Property_Expansion; 13596 } else { 13597 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13598 << op->getType() << op->getSourceRange(); 13599 return QualType(); 13600 } 13601 } 13602 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13603 // The operand cannot be a bit-field 13604 AddressOfError = AO_Bit_Field; 13605 } else if (op->getObjectKind() == OK_VectorComponent) { 13606 // The operand cannot be an element of a vector 13607 AddressOfError = AO_Vector_Element; 13608 } else if (op->getObjectKind() == OK_MatrixComponent) { 13609 // The operand cannot be an element of a matrix. 13610 AddressOfError = AO_Matrix_Element; 13611 } else if (dcl) { // C99 6.5.3.2p1 13612 // We have an lvalue with a decl. Make sure the decl is not declared 13613 // with the register storage-class specifier. 13614 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13615 // in C++ it is not error to take address of a register 13616 // variable (c++03 7.1.1P3) 13617 if (vd->getStorageClass() == SC_Register && 13618 !getLangOpts().CPlusPlus) { 13619 AddressOfError = AO_Register_Variable; 13620 } 13621 } else if (isa<MSPropertyDecl>(dcl)) { 13622 AddressOfError = AO_Property_Expansion; 13623 } else if (isa<FunctionTemplateDecl>(dcl)) { 13624 return Context.OverloadTy; 13625 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13626 // Okay: we can take the address of a field. 13627 // Could be a pointer to member, though, if there is an explicit 13628 // scope qualifier for the class. 13629 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13630 DeclContext *Ctx = dcl->getDeclContext(); 13631 if (Ctx && Ctx->isRecord()) { 13632 if (dcl->getType()->isReferenceType()) { 13633 Diag(OpLoc, 13634 diag::err_cannot_form_pointer_to_member_of_reference_type) 13635 << dcl->getDeclName() << dcl->getType(); 13636 return QualType(); 13637 } 13638 13639 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13640 Ctx = Ctx->getParent(); 13641 13642 QualType MPTy = Context.getMemberPointerType( 13643 op->getType(), 13644 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13645 // Under the MS ABI, lock down the inheritance model now. 13646 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13647 (void)isCompleteType(OpLoc, MPTy); 13648 return MPTy; 13649 } 13650 } 13651 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13652 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13653 llvm_unreachable("Unknown/unexpected decl type"); 13654 } 13655 13656 if (AddressOfError != AO_No_Error) { 13657 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13658 return QualType(); 13659 } 13660 13661 if (lval == Expr::LV_IncompleteVoidType) { 13662 // Taking the address of a void variable is technically illegal, but we 13663 // allow it in cases which are otherwise valid. 13664 // Example: "extern void x; void* y = &x;". 13665 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13666 } 13667 13668 // If the operand has type "type", the result has type "pointer to type". 13669 if (op->getType()->isObjCObjectType()) 13670 return Context.getObjCObjectPointerType(op->getType()); 13671 13672 CheckAddressOfPackedMember(op); 13673 13674 return Context.getPointerType(op->getType()); 13675 } 13676 13677 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13678 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13679 if (!DRE) 13680 return; 13681 const Decl *D = DRE->getDecl(); 13682 if (!D) 13683 return; 13684 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13685 if (!Param) 13686 return; 13687 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13688 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13689 return; 13690 if (FunctionScopeInfo *FD = S.getCurFunction()) 13691 if (!FD->ModifiedNonNullParams.count(Param)) 13692 FD->ModifiedNonNullParams.insert(Param); 13693 } 13694 13695 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13696 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13697 SourceLocation OpLoc) { 13698 if (Op->isTypeDependent()) 13699 return S.Context.DependentTy; 13700 13701 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13702 if (ConvResult.isInvalid()) 13703 return QualType(); 13704 Op = ConvResult.get(); 13705 QualType OpTy = Op->getType(); 13706 QualType Result; 13707 13708 if (isa<CXXReinterpretCastExpr>(Op)) { 13709 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13710 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13711 Op->getSourceRange()); 13712 } 13713 13714 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13715 { 13716 Result = PT->getPointeeType(); 13717 } 13718 else if (const ObjCObjectPointerType *OPT = 13719 OpTy->getAs<ObjCObjectPointerType>()) 13720 Result = OPT->getPointeeType(); 13721 else { 13722 ExprResult PR = S.CheckPlaceholderExpr(Op); 13723 if (PR.isInvalid()) return QualType(); 13724 if (PR.get() != Op) 13725 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13726 } 13727 13728 if (Result.isNull()) { 13729 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13730 << OpTy << Op->getSourceRange(); 13731 return QualType(); 13732 } 13733 13734 // Note that per both C89 and C99, indirection is always legal, even if Result 13735 // is an incomplete type or void. It would be possible to warn about 13736 // dereferencing a void pointer, but it's completely well-defined, and such a 13737 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13738 // for pointers to 'void' but is fine for any other pointer type: 13739 // 13740 // C++ [expr.unary.op]p1: 13741 // [...] the expression to which [the unary * operator] is applied shall 13742 // be a pointer to an object type, or a pointer to a function type 13743 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13744 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13745 << OpTy << Op->getSourceRange(); 13746 13747 // Dereferences are usually l-values... 13748 VK = VK_LValue; 13749 13750 // ...except that certain expressions are never l-values in C. 13751 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13752 VK = VK_PRValue; 13753 13754 return Result; 13755 } 13756 13757 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13758 BinaryOperatorKind Opc; 13759 switch (Kind) { 13760 default: llvm_unreachable("Unknown binop!"); 13761 case tok::periodstar: Opc = BO_PtrMemD; break; 13762 case tok::arrowstar: Opc = BO_PtrMemI; break; 13763 case tok::star: Opc = BO_Mul; break; 13764 case tok::slash: Opc = BO_Div; break; 13765 case tok::percent: Opc = BO_Rem; break; 13766 case tok::plus: Opc = BO_Add; break; 13767 case tok::minus: Opc = BO_Sub; break; 13768 case tok::lessless: Opc = BO_Shl; break; 13769 case tok::greatergreater: Opc = BO_Shr; break; 13770 case tok::lessequal: Opc = BO_LE; break; 13771 case tok::less: Opc = BO_LT; break; 13772 case tok::greaterequal: Opc = BO_GE; break; 13773 case tok::greater: Opc = BO_GT; break; 13774 case tok::exclaimequal: Opc = BO_NE; break; 13775 case tok::equalequal: Opc = BO_EQ; break; 13776 case tok::spaceship: Opc = BO_Cmp; break; 13777 case tok::amp: Opc = BO_And; break; 13778 case tok::caret: Opc = BO_Xor; break; 13779 case tok::pipe: Opc = BO_Or; break; 13780 case tok::ampamp: Opc = BO_LAnd; break; 13781 case tok::pipepipe: Opc = BO_LOr; break; 13782 case tok::equal: Opc = BO_Assign; break; 13783 case tok::starequal: Opc = BO_MulAssign; break; 13784 case tok::slashequal: Opc = BO_DivAssign; break; 13785 case tok::percentequal: Opc = BO_RemAssign; break; 13786 case tok::plusequal: Opc = BO_AddAssign; break; 13787 case tok::minusequal: Opc = BO_SubAssign; break; 13788 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13789 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13790 case tok::ampequal: Opc = BO_AndAssign; break; 13791 case tok::caretequal: Opc = BO_XorAssign; break; 13792 case tok::pipeequal: Opc = BO_OrAssign; break; 13793 case tok::comma: Opc = BO_Comma; break; 13794 } 13795 return Opc; 13796 } 13797 13798 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13799 tok::TokenKind Kind) { 13800 UnaryOperatorKind Opc; 13801 switch (Kind) { 13802 default: llvm_unreachable("Unknown unary op!"); 13803 case tok::plusplus: Opc = UO_PreInc; break; 13804 case tok::minusminus: Opc = UO_PreDec; break; 13805 case tok::amp: Opc = UO_AddrOf; break; 13806 case tok::star: Opc = UO_Deref; break; 13807 case tok::plus: Opc = UO_Plus; break; 13808 case tok::minus: Opc = UO_Minus; break; 13809 case tok::tilde: Opc = UO_Not; break; 13810 case tok::exclaim: Opc = UO_LNot; break; 13811 case tok::kw___real: Opc = UO_Real; break; 13812 case tok::kw___imag: Opc = UO_Imag; break; 13813 case tok::kw___extension__: Opc = UO_Extension; break; 13814 } 13815 return Opc; 13816 } 13817 13818 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13819 /// This warning suppressed in the event of macro expansions. 13820 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13821 SourceLocation OpLoc, bool IsBuiltin) { 13822 if (S.inTemplateInstantiation()) 13823 return; 13824 if (S.isUnevaluatedContext()) 13825 return; 13826 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13827 return; 13828 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13829 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13830 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13831 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13832 if (!LHSDeclRef || !RHSDeclRef || 13833 LHSDeclRef->getLocation().isMacroID() || 13834 RHSDeclRef->getLocation().isMacroID()) 13835 return; 13836 const ValueDecl *LHSDecl = 13837 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13838 const ValueDecl *RHSDecl = 13839 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13840 if (LHSDecl != RHSDecl) 13841 return; 13842 if (LHSDecl->getType().isVolatileQualified()) 13843 return; 13844 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13845 if (RefTy->getPointeeType().isVolatileQualified()) 13846 return; 13847 13848 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13849 : diag::warn_self_assignment_overloaded) 13850 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13851 << RHSExpr->getSourceRange(); 13852 } 13853 13854 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13855 /// is usually indicative of introspection within the Objective-C pointer. 13856 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13857 SourceLocation OpLoc) { 13858 if (!S.getLangOpts().ObjC) 13859 return; 13860 13861 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13862 const Expr *LHS = L.get(); 13863 const Expr *RHS = R.get(); 13864 13865 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13866 ObjCPointerExpr = LHS; 13867 OtherExpr = RHS; 13868 } 13869 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13870 ObjCPointerExpr = RHS; 13871 OtherExpr = LHS; 13872 } 13873 13874 // This warning is deliberately made very specific to reduce false 13875 // positives with logic that uses '&' for hashing. This logic mainly 13876 // looks for code trying to introspect into tagged pointers, which 13877 // code should generally never do. 13878 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13879 unsigned Diag = diag::warn_objc_pointer_masking; 13880 // Determine if we are introspecting the result of performSelectorXXX. 13881 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13882 // Special case messages to -performSelector and friends, which 13883 // can return non-pointer values boxed in a pointer value. 13884 // Some clients may wish to silence warnings in this subcase. 13885 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13886 Selector S = ME->getSelector(); 13887 StringRef SelArg0 = S.getNameForSlot(0); 13888 if (SelArg0.startswith("performSelector")) 13889 Diag = diag::warn_objc_pointer_masking_performSelector; 13890 } 13891 13892 S.Diag(OpLoc, Diag) 13893 << ObjCPointerExpr->getSourceRange(); 13894 } 13895 } 13896 13897 static NamedDecl *getDeclFromExpr(Expr *E) { 13898 if (!E) 13899 return nullptr; 13900 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13901 return DRE->getDecl(); 13902 if (auto *ME = dyn_cast<MemberExpr>(E)) 13903 return ME->getMemberDecl(); 13904 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13905 return IRE->getDecl(); 13906 return nullptr; 13907 } 13908 13909 // This helper function promotes a binary operator's operands (which are of a 13910 // half vector type) to a vector of floats and then truncates the result to 13911 // a vector of either half or short. 13912 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13913 BinaryOperatorKind Opc, QualType ResultTy, 13914 ExprValueKind VK, ExprObjectKind OK, 13915 bool IsCompAssign, SourceLocation OpLoc, 13916 FPOptionsOverride FPFeatures) { 13917 auto &Context = S.getASTContext(); 13918 assert((isVector(ResultTy, Context.HalfTy) || 13919 isVector(ResultTy, Context.ShortTy)) && 13920 "Result must be a vector of half or short"); 13921 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13922 isVector(RHS.get()->getType(), Context.HalfTy) && 13923 "both operands expected to be a half vector"); 13924 13925 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13926 QualType BinOpResTy = RHS.get()->getType(); 13927 13928 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13929 // change BinOpResTy to a vector of ints. 13930 if (isVector(ResultTy, Context.ShortTy)) 13931 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13932 13933 if (IsCompAssign) 13934 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13935 ResultTy, VK, OK, OpLoc, FPFeatures, 13936 BinOpResTy, BinOpResTy); 13937 13938 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13939 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13940 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13941 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13942 } 13943 13944 static std::pair<ExprResult, ExprResult> 13945 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13946 Expr *RHSExpr) { 13947 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13948 if (!S.Context.isDependenceAllowed()) { 13949 // C cannot handle TypoExpr nodes on either side of a binop because it 13950 // doesn't handle dependent types properly, so make sure any TypoExprs have 13951 // been dealt with before checking the operands. 13952 LHS = S.CorrectDelayedTyposInExpr(LHS); 13953 RHS = S.CorrectDelayedTyposInExpr( 13954 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13955 [Opc, LHS](Expr *E) { 13956 if (Opc != BO_Assign) 13957 return ExprResult(E); 13958 // Avoid correcting the RHS to the same Expr as the LHS. 13959 Decl *D = getDeclFromExpr(E); 13960 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13961 }); 13962 } 13963 return std::make_pair(LHS, RHS); 13964 } 13965 13966 /// Returns true if conversion between vectors of halfs and vectors of floats 13967 /// is needed. 13968 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13969 Expr *E0, Expr *E1 = nullptr) { 13970 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13971 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13972 return false; 13973 13974 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13975 QualType Ty = E->IgnoreImplicit()->getType(); 13976 13977 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13978 // to vectors of floats. Although the element type of the vectors is __fp16, 13979 // the vectors shouldn't be treated as storage-only types. See the 13980 // discussion here: https://reviews.llvm.org/rG825235c140e7 13981 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13982 if (VT->getVectorKind() == VectorType::NeonVector) 13983 return false; 13984 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13985 } 13986 return false; 13987 }; 13988 13989 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13990 } 13991 13992 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13993 /// operator @p Opc at location @c TokLoc. This routine only supports 13994 /// built-in operations; ActOnBinOp handles overloaded operators. 13995 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13996 BinaryOperatorKind Opc, 13997 Expr *LHSExpr, Expr *RHSExpr) { 13998 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13999 // The syntax only allows initializer lists on the RHS of assignment, 14000 // so we don't need to worry about accepting invalid code for 14001 // non-assignment operators. 14002 // C++11 5.17p9: 14003 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14004 // of x = {} is x = T(). 14005 InitializationKind Kind = InitializationKind::CreateDirectList( 14006 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14007 InitializedEntity Entity = 14008 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14009 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14010 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14011 if (Init.isInvalid()) 14012 return Init; 14013 RHSExpr = Init.get(); 14014 } 14015 14016 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14017 QualType ResultTy; // Result type of the binary operator. 14018 // The following two variables are used for compound assignment operators 14019 QualType CompLHSTy; // Type of LHS after promotions for computation 14020 QualType CompResultTy; // Type of computation result 14021 ExprValueKind VK = VK_PRValue; 14022 ExprObjectKind OK = OK_Ordinary; 14023 bool ConvertHalfVec = false; 14024 14025 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14026 if (!LHS.isUsable() || !RHS.isUsable()) 14027 return ExprError(); 14028 14029 if (getLangOpts().OpenCL) { 14030 QualType LHSTy = LHSExpr->getType(); 14031 QualType RHSTy = RHSExpr->getType(); 14032 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14033 // the ATOMIC_VAR_INIT macro. 14034 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14035 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14036 if (BO_Assign == Opc) 14037 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14038 else 14039 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14040 return ExprError(); 14041 } 14042 14043 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14044 // only with a builtin functions and therefore should be disallowed here. 14045 if (LHSTy->isImageType() || RHSTy->isImageType() || 14046 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14047 LHSTy->isPipeType() || RHSTy->isPipeType() || 14048 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14049 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14050 return ExprError(); 14051 } 14052 } 14053 14054 switch (Opc) { 14055 case BO_Assign: 14056 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14057 if (getLangOpts().CPlusPlus && 14058 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14059 VK = LHS.get()->getValueKind(); 14060 OK = LHS.get()->getObjectKind(); 14061 } 14062 if (!ResultTy.isNull()) { 14063 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14064 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14065 14066 // Avoid copying a block to the heap if the block is assigned to a local 14067 // auto variable that is declared in the same scope as the block. This 14068 // optimization is unsafe if the local variable is declared in an outer 14069 // scope. For example: 14070 // 14071 // BlockTy b; 14072 // { 14073 // b = ^{...}; 14074 // } 14075 // // It is unsafe to invoke the block here if it wasn't copied to the 14076 // // heap. 14077 // b(); 14078 14079 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14080 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14081 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14082 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14083 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14084 14085 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14086 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14087 NTCUC_Assignment, NTCUK_Copy); 14088 } 14089 RecordModifiableNonNullParam(*this, LHS.get()); 14090 break; 14091 case BO_PtrMemD: 14092 case BO_PtrMemI: 14093 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14094 Opc == BO_PtrMemI); 14095 break; 14096 case BO_Mul: 14097 case BO_Div: 14098 ConvertHalfVec = true; 14099 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14100 Opc == BO_Div); 14101 break; 14102 case BO_Rem: 14103 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14104 break; 14105 case BO_Add: 14106 ConvertHalfVec = true; 14107 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14108 break; 14109 case BO_Sub: 14110 ConvertHalfVec = true; 14111 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14112 break; 14113 case BO_Shl: 14114 case BO_Shr: 14115 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14116 break; 14117 case BO_LE: 14118 case BO_LT: 14119 case BO_GE: 14120 case BO_GT: 14121 ConvertHalfVec = true; 14122 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14123 break; 14124 case BO_EQ: 14125 case BO_NE: 14126 ConvertHalfVec = true; 14127 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14128 break; 14129 case BO_Cmp: 14130 ConvertHalfVec = true; 14131 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14132 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14133 break; 14134 case BO_And: 14135 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14136 LLVM_FALLTHROUGH; 14137 case BO_Xor: 14138 case BO_Or: 14139 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14140 break; 14141 case BO_LAnd: 14142 case BO_LOr: 14143 ConvertHalfVec = true; 14144 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14145 break; 14146 case BO_MulAssign: 14147 case BO_DivAssign: 14148 ConvertHalfVec = true; 14149 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14150 Opc == BO_DivAssign); 14151 CompLHSTy = CompResultTy; 14152 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14153 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14154 break; 14155 case BO_RemAssign: 14156 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14157 CompLHSTy = CompResultTy; 14158 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14159 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14160 break; 14161 case BO_AddAssign: 14162 ConvertHalfVec = true; 14163 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14164 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14165 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14166 break; 14167 case BO_SubAssign: 14168 ConvertHalfVec = true; 14169 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14170 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14171 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14172 break; 14173 case BO_ShlAssign: 14174 case BO_ShrAssign: 14175 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14176 CompLHSTy = CompResultTy; 14177 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14178 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14179 break; 14180 case BO_AndAssign: 14181 case BO_OrAssign: // fallthrough 14182 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14183 LLVM_FALLTHROUGH; 14184 case BO_XorAssign: 14185 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14186 CompLHSTy = CompResultTy; 14187 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14188 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14189 break; 14190 case BO_Comma: 14191 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14192 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14193 VK = RHS.get()->getValueKind(); 14194 OK = RHS.get()->getObjectKind(); 14195 } 14196 break; 14197 } 14198 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14199 return ExprError(); 14200 14201 // Some of the binary operations require promoting operands of half vector to 14202 // float vectors and truncating the result back to half vector. For now, we do 14203 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14204 // arm64). 14205 assert( 14206 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14207 isVector(LHS.get()->getType(), Context.HalfTy)) && 14208 "both sides are half vectors or neither sides are"); 14209 ConvertHalfVec = 14210 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14211 14212 // Check for array bounds violations for both sides of the BinaryOperator 14213 CheckArrayAccess(LHS.get()); 14214 CheckArrayAccess(RHS.get()); 14215 14216 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14217 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14218 &Context.Idents.get("object_setClass"), 14219 SourceLocation(), LookupOrdinaryName); 14220 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14221 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14222 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14223 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14224 "object_setClass(") 14225 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14226 ",") 14227 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14228 } 14229 else 14230 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14231 } 14232 else if (const ObjCIvarRefExpr *OIRE = 14233 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14234 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14235 14236 // Opc is not a compound assignment if CompResultTy is null. 14237 if (CompResultTy.isNull()) { 14238 if (ConvertHalfVec) 14239 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14240 OpLoc, CurFPFeatureOverrides()); 14241 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14242 VK, OK, OpLoc, CurFPFeatureOverrides()); 14243 } 14244 14245 // Handle compound assignments. 14246 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14247 OK_ObjCProperty) { 14248 VK = VK_LValue; 14249 OK = LHS.get()->getObjectKind(); 14250 } 14251 14252 // The LHS is not converted to the result type for fixed-point compound 14253 // assignment as the common type is computed on demand. Reset the CompLHSTy 14254 // to the LHS type we would have gotten after unary conversions. 14255 if (CompResultTy->isFixedPointType()) 14256 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14257 14258 if (ConvertHalfVec) 14259 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14260 OpLoc, CurFPFeatureOverrides()); 14261 14262 return CompoundAssignOperator::Create( 14263 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14264 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14265 } 14266 14267 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14268 /// operators are mixed in a way that suggests that the programmer forgot that 14269 /// comparison operators have higher precedence. The most typical example of 14270 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14271 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14272 SourceLocation OpLoc, Expr *LHSExpr, 14273 Expr *RHSExpr) { 14274 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14275 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14276 14277 // Check that one of the sides is a comparison operator and the other isn't. 14278 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14279 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14280 if (isLeftComp == isRightComp) 14281 return; 14282 14283 // Bitwise operations are sometimes used as eager logical ops. 14284 // Don't diagnose this. 14285 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14286 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14287 if (isLeftBitwise || isRightBitwise) 14288 return; 14289 14290 SourceRange DiagRange = isLeftComp 14291 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14292 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14293 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14294 SourceRange ParensRange = 14295 isLeftComp 14296 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14297 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14298 14299 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14300 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14301 SuggestParentheses(Self, OpLoc, 14302 Self.PDiag(diag::note_precedence_silence) << OpStr, 14303 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14304 SuggestParentheses(Self, OpLoc, 14305 Self.PDiag(diag::note_precedence_bitwise_first) 14306 << BinaryOperator::getOpcodeStr(Opc), 14307 ParensRange); 14308 } 14309 14310 /// It accepts a '&&' expr that is inside a '||' one. 14311 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14312 /// in parentheses. 14313 static void 14314 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14315 BinaryOperator *Bop) { 14316 assert(Bop->getOpcode() == BO_LAnd); 14317 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14318 << Bop->getSourceRange() << OpLoc; 14319 SuggestParentheses(Self, Bop->getOperatorLoc(), 14320 Self.PDiag(diag::note_precedence_silence) 14321 << Bop->getOpcodeStr(), 14322 Bop->getSourceRange()); 14323 } 14324 14325 /// Returns true if the given expression can be evaluated as a constant 14326 /// 'true'. 14327 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14328 bool Res; 14329 return !E->isValueDependent() && 14330 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14331 } 14332 14333 /// Returns true if the given expression can be evaluated as a constant 14334 /// 'false'. 14335 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14336 bool Res; 14337 return !E->isValueDependent() && 14338 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14339 } 14340 14341 /// Look for '&&' in the left hand of a '||' expr. 14342 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14343 Expr *LHSExpr, Expr *RHSExpr) { 14344 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14345 if (Bop->getOpcode() == BO_LAnd) { 14346 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14347 if (EvaluatesAsFalse(S, RHSExpr)) 14348 return; 14349 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14350 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14351 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14352 } else if (Bop->getOpcode() == BO_LOr) { 14353 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14354 // If it's "a || b && 1 || c" we didn't warn earlier for 14355 // "a || b && 1", but warn now. 14356 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14357 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14358 } 14359 } 14360 } 14361 } 14362 14363 /// Look for '&&' in the right hand of a '||' expr. 14364 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14365 Expr *LHSExpr, Expr *RHSExpr) { 14366 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14367 if (Bop->getOpcode() == BO_LAnd) { 14368 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14369 if (EvaluatesAsFalse(S, LHSExpr)) 14370 return; 14371 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14372 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14373 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14374 } 14375 } 14376 } 14377 14378 /// Look for bitwise op in the left or right hand of a bitwise op with 14379 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14380 /// the '&' expression in parentheses. 14381 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14382 SourceLocation OpLoc, Expr *SubExpr) { 14383 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14384 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14385 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14386 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14387 << Bop->getSourceRange() << OpLoc; 14388 SuggestParentheses(S, Bop->getOperatorLoc(), 14389 S.PDiag(diag::note_precedence_silence) 14390 << Bop->getOpcodeStr(), 14391 Bop->getSourceRange()); 14392 } 14393 } 14394 } 14395 14396 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14397 Expr *SubExpr, StringRef Shift) { 14398 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14399 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14400 StringRef Op = Bop->getOpcodeStr(); 14401 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14402 << Bop->getSourceRange() << OpLoc << Shift << Op; 14403 SuggestParentheses(S, Bop->getOperatorLoc(), 14404 S.PDiag(diag::note_precedence_silence) << Op, 14405 Bop->getSourceRange()); 14406 } 14407 } 14408 } 14409 14410 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14411 Expr *LHSExpr, Expr *RHSExpr) { 14412 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14413 if (!OCE) 14414 return; 14415 14416 FunctionDecl *FD = OCE->getDirectCallee(); 14417 if (!FD || !FD->isOverloadedOperator()) 14418 return; 14419 14420 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14421 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14422 return; 14423 14424 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14425 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14426 << (Kind == OO_LessLess); 14427 SuggestParentheses(S, OCE->getOperatorLoc(), 14428 S.PDiag(diag::note_precedence_silence) 14429 << (Kind == OO_LessLess ? "<<" : ">>"), 14430 OCE->getSourceRange()); 14431 SuggestParentheses( 14432 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14433 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14434 } 14435 14436 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14437 /// precedence. 14438 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14439 SourceLocation OpLoc, Expr *LHSExpr, 14440 Expr *RHSExpr){ 14441 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14442 if (BinaryOperator::isBitwiseOp(Opc)) 14443 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14444 14445 // Diagnose "arg1 & arg2 | arg3" 14446 if ((Opc == BO_Or || Opc == BO_Xor) && 14447 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14448 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14449 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14450 } 14451 14452 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14453 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14454 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14455 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14456 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14457 } 14458 14459 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14460 || Opc == BO_Shr) { 14461 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14462 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14463 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14464 } 14465 14466 // Warn on overloaded shift operators and comparisons, such as: 14467 // cout << 5 == 4; 14468 if (BinaryOperator::isComparisonOp(Opc)) 14469 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14470 } 14471 14472 // Binary Operators. 'Tok' is the token for the operator. 14473 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14474 tok::TokenKind Kind, 14475 Expr *LHSExpr, Expr *RHSExpr) { 14476 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14477 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14478 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14479 14480 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14481 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14482 14483 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14484 } 14485 14486 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14487 UnresolvedSetImpl &Functions) { 14488 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14489 if (OverOp != OO_None && OverOp != OO_Equal) 14490 LookupOverloadedOperatorName(OverOp, S, Functions); 14491 14492 // In C++20 onwards, we may have a second operator to look up. 14493 if (getLangOpts().CPlusPlus20) { 14494 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14495 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14496 } 14497 } 14498 14499 /// Build an overloaded binary operator expression in the given scope. 14500 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14501 BinaryOperatorKind Opc, 14502 Expr *LHS, Expr *RHS) { 14503 switch (Opc) { 14504 case BO_Assign: 14505 case BO_DivAssign: 14506 case BO_RemAssign: 14507 case BO_SubAssign: 14508 case BO_AndAssign: 14509 case BO_OrAssign: 14510 case BO_XorAssign: 14511 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14512 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14513 break; 14514 default: 14515 break; 14516 } 14517 14518 // Find all of the overloaded operators visible from this point. 14519 UnresolvedSet<16> Functions; 14520 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14521 14522 // Build the (potentially-overloaded, potentially-dependent) 14523 // binary operation. 14524 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14525 } 14526 14527 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14528 BinaryOperatorKind Opc, 14529 Expr *LHSExpr, Expr *RHSExpr) { 14530 ExprResult LHS, RHS; 14531 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14532 if (!LHS.isUsable() || !RHS.isUsable()) 14533 return ExprError(); 14534 LHSExpr = LHS.get(); 14535 RHSExpr = RHS.get(); 14536 14537 // We want to end up calling one of checkPseudoObjectAssignment 14538 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14539 // both expressions are overloadable or either is type-dependent), 14540 // or CreateBuiltinBinOp (in any other case). We also want to get 14541 // any placeholder types out of the way. 14542 14543 // Handle pseudo-objects in the LHS. 14544 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14545 // Assignments with a pseudo-object l-value need special analysis. 14546 if (pty->getKind() == BuiltinType::PseudoObject && 14547 BinaryOperator::isAssignmentOp(Opc)) 14548 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14549 14550 // Don't resolve overloads if the other type is overloadable. 14551 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14552 // We can't actually test that if we still have a placeholder, 14553 // though. Fortunately, none of the exceptions we see in that 14554 // code below are valid when the LHS is an overload set. Note 14555 // that an overload set can be dependently-typed, but it never 14556 // instantiates to having an overloadable type. 14557 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14558 if (resolvedRHS.isInvalid()) return ExprError(); 14559 RHSExpr = resolvedRHS.get(); 14560 14561 if (RHSExpr->isTypeDependent() || 14562 RHSExpr->getType()->isOverloadableType()) 14563 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14564 } 14565 14566 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14567 // template, diagnose the missing 'template' keyword instead of diagnosing 14568 // an invalid use of a bound member function. 14569 // 14570 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14571 // to C++1z [over.over]/1.4, but we already checked for that case above. 14572 if (Opc == BO_LT && inTemplateInstantiation() && 14573 (pty->getKind() == BuiltinType::BoundMember || 14574 pty->getKind() == BuiltinType::Overload)) { 14575 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14576 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14577 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14578 return isa<FunctionTemplateDecl>(ND); 14579 })) { 14580 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14581 : OE->getNameLoc(), 14582 diag::err_template_kw_missing) 14583 << OE->getName().getAsString() << ""; 14584 return ExprError(); 14585 } 14586 } 14587 14588 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14589 if (LHS.isInvalid()) return ExprError(); 14590 LHSExpr = LHS.get(); 14591 } 14592 14593 // Handle pseudo-objects in the RHS. 14594 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14595 // An overload in the RHS can potentially be resolved by the type 14596 // being assigned to. 14597 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14598 if (getLangOpts().CPlusPlus && 14599 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14600 LHSExpr->getType()->isOverloadableType())) 14601 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14602 14603 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14604 } 14605 14606 // Don't resolve overloads if the other type is overloadable. 14607 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14608 LHSExpr->getType()->isOverloadableType()) 14609 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14610 14611 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14612 if (!resolvedRHS.isUsable()) return ExprError(); 14613 RHSExpr = resolvedRHS.get(); 14614 } 14615 14616 if (getLangOpts().CPlusPlus) { 14617 // If either expression is type-dependent, always build an 14618 // overloaded op. 14619 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14620 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14621 14622 // Otherwise, build an overloaded op if either expression has an 14623 // overloadable type. 14624 if (LHSExpr->getType()->isOverloadableType() || 14625 RHSExpr->getType()->isOverloadableType()) 14626 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14627 } 14628 14629 if (getLangOpts().RecoveryAST && 14630 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14631 assert(!getLangOpts().CPlusPlus); 14632 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14633 "Should only occur in error-recovery path."); 14634 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14635 // C [6.15.16] p3: 14636 // An assignment expression has the value of the left operand after the 14637 // assignment, but is not an lvalue. 14638 return CompoundAssignOperator::Create( 14639 Context, LHSExpr, RHSExpr, Opc, 14640 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14641 OpLoc, CurFPFeatureOverrides()); 14642 QualType ResultType; 14643 switch (Opc) { 14644 case BO_Assign: 14645 ResultType = LHSExpr->getType().getUnqualifiedType(); 14646 break; 14647 case BO_LT: 14648 case BO_GT: 14649 case BO_LE: 14650 case BO_GE: 14651 case BO_EQ: 14652 case BO_NE: 14653 case BO_LAnd: 14654 case BO_LOr: 14655 // These operators have a fixed result type regardless of operands. 14656 ResultType = Context.IntTy; 14657 break; 14658 case BO_Comma: 14659 ResultType = RHSExpr->getType(); 14660 break; 14661 default: 14662 ResultType = Context.DependentTy; 14663 break; 14664 } 14665 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14666 VK_PRValue, OK_Ordinary, OpLoc, 14667 CurFPFeatureOverrides()); 14668 } 14669 14670 // Build a built-in binary operation. 14671 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14672 } 14673 14674 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14675 if (T.isNull() || T->isDependentType()) 14676 return false; 14677 14678 if (!T->isPromotableIntegerType()) 14679 return true; 14680 14681 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14682 } 14683 14684 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14685 UnaryOperatorKind Opc, 14686 Expr *InputExpr) { 14687 ExprResult Input = InputExpr; 14688 ExprValueKind VK = VK_PRValue; 14689 ExprObjectKind OK = OK_Ordinary; 14690 QualType resultType; 14691 bool CanOverflow = false; 14692 14693 bool ConvertHalfVec = false; 14694 if (getLangOpts().OpenCL) { 14695 QualType Ty = InputExpr->getType(); 14696 // The only legal unary operation for atomics is '&'. 14697 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14698 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14699 // only with a builtin functions and therefore should be disallowed here. 14700 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14701 || Ty->isBlockPointerType())) { 14702 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14703 << InputExpr->getType() 14704 << Input.get()->getSourceRange()); 14705 } 14706 } 14707 14708 switch (Opc) { 14709 case UO_PreInc: 14710 case UO_PreDec: 14711 case UO_PostInc: 14712 case UO_PostDec: 14713 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14714 OpLoc, 14715 Opc == UO_PreInc || 14716 Opc == UO_PostInc, 14717 Opc == UO_PreInc || 14718 Opc == UO_PreDec); 14719 CanOverflow = isOverflowingIntegerType(Context, resultType); 14720 break; 14721 case UO_AddrOf: 14722 resultType = CheckAddressOfOperand(Input, OpLoc); 14723 CheckAddressOfNoDeref(InputExpr); 14724 RecordModifiableNonNullParam(*this, InputExpr); 14725 break; 14726 case UO_Deref: { 14727 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14728 if (Input.isInvalid()) return ExprError(); 14729 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14730 break; 14731 } 14732 case UO_Plus: 14733 case UO_Minus: 14734 CanOverflow = Opc == UO_Minus && 14735 isOverflowingIntegerType(Context, Input.get()->getType()); 14736 Input = UsualUnaryConversions(Input.get()); 14737 if (Input.isInvalid()) return ExprError(); 14738 // Unary plus and minus require promoting an operand of half vector to a 14739 // float vector and truncating the result back to a half vector. For now, we 14740 // do this only when HalfArgsAndReturns is set (that is, when the target is 14741 // arm or arm64). 14742 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14743 14744 // If the operand is a half vector, promote it to a float vector. 14745 if (ConvertHalfVec) 14746 Input = convertVector(Input.get(), Context.FloatTy, *this); 14747 resultType = Input.get()->getType(); 14748 if (resultType->isDependentType()) 14749 break; 14750 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14751 break; 14752 else if (resultType->isVectorType() && 14753 // The z vector extensions don't allow + or - with bool vectors. 14754 (!Context.getLangOpts().ZVector || 14755 resultType->castAs<VectorType>()->getVectorKind() != 14756 VectorType::AltiVecBool)) 14757 break; 14758 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14759 Opc == UO_Plus && 14760 resultType->isPointerType()) 14761 break; 14762 14763 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14764 << resultType << Input.get()->getSourceRange()); 14765 14766 case UO_Not: // bitwise complement 14767 Input = UsualUnaryConversions(Input.get()); 14768 if (Input.isInvalid()) 14769 return ExprError(); 14770 resultType = Input.get()->getType(); 14771 if (resultType->isDependentType()) 14772 break; 14773 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14774 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14775 // C99 does not support '~' for complex conjugation. 14776 Diag(OpLoc, diag::ext_integer_complement_complex) 14777 << resultType << Input.get()->getSourceRange(); 14778 else if (resultType->hasIntegerRepresentation()) 14779 break; 14780 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14781 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14782 // on vector float types. 14783 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14784 if (!T->isIntegerType()) 14785 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14786 << resultType << Input.get()->getSourceRange()); 14787 } else { 14788 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14789 << resultType << Input.get()->getSourceRange()); 14790 } 14791 break; 14792 14793 case UO_LNot: // logical negation 14794 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14795 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14796 if (Input.isInvalid()) return ExprError(); 14797 resultType = Input.get()->getType(); 14798 14799 // Though we still have to promote half FP to float... 14800 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14801 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14802 resultType = Context.FloatTy; 14803 } 14804 14805 if (resultType->isDependentType()) 14806 break; 14807 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14808 // C99 6.5.3.3p1: ok, fallthrough; 14809 if (Context.getLangOpts().CPlusPlus) { 14810 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14811 // operand contextually converted to bool. 14812 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14813 ScalarTypeToBooleanCastKind(resultType)); 14814 } else if (Context.getLangOpts().OpenCL && 14815 Context.getLangOpts().OpenCLVersion < 120) { 14816 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14817 // operate on scalar float types. 14818 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14819 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14820 << resultType << Input.get()->getSourceRange()); 14821 } 14822 } else if (resultType->isExtVectorType()) { 14823 if (Context.getLangOpts().OpenCL && 14824 Context.getLangOpts().OpenCLVersion < 120 && 14825 !Context.getLangOpts().OpenCLCPlusPlus) { 14826 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14827 // operate on vector float types. 14828 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14829 if (!T->isIntegerType()) 14830 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14831 << resultType << Input.get()->getSourceRange()); 14832 } 14833 // Vector logical not returns the signed variant of the operand type. 14834 resultType = GetSignedVectorType(resultType); 14835 break; 14836 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14837 const VectorType *VTy = resultType->castAs<VectorType>(); 14838 if (VTy->getVectorKind() != VectorType::GenericVector) 14839 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14840 << resultType << Input.get()->getSourceRange()); 14841 14842 // Vector logical not returns the signed variant of the operand type. 14843 resultType = GetSignedVectorType(resultType); 14844 break; 14845 } else { 14846 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14847 << resultType << Input.get()->getSourceRange()); 14848 } 14849 14850 // LNot always has type int. C99 6.5.3.3p5. 14851 // In C++, it's bool. C++ 5.3.1p8 14852 resultType = Context.getLogicalOperationType(); 14853 break; 14854 case UO_Real: 14855 case UO_Imag: 14856 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14857 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14858 // complex l-values to ordinary l-values and all other values to r-values. 14859 if (Input.isInvalid()) return ExprError(); 14860 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14861 if (Input.get()->getValueKind() != VK_PRValue && 14862 Input.get()->getObjectKind() == OK_Ordinary) 14863 VK = Input.get()->getValueKind(); 14864 } else if (!getLangOpts().CPlusPlus) { 14865 // In C, a volatile scalar is read by __imag. In C++, it is not. 14866 Input = DefaultLvalueConversion(Input.get()); 14867 } 14868 break; 14869 case UO_Extension: 14870 resultType = Input.get()->getType(); 14871 VK = Input.get()->getValueKind(); 14872 OK = Input.get()->getObjectKind(); 14873 break; 14874 case UO_Coawait: 14875 // It's unnecessary to represent the pass-through operator co_await in the 14876 // AST; just return the input expression instead. 14877 assert(!Input.get()->getType()->isDependentType() && 14878 "the co_await expression must be non-dependant before " 14879 "building operator co_await"); 14880 return Input; 14881 } 14882 if (resultType.isNull() || Input.isInvalid()) 14883 return ExprError(); 14884 14885 // Check for array bounds violations in the operand of the UnaryOperator, 14886 // except for the '*' and '&' operators that have to be handled specially 14887 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14888 // that are explicitly defined as valid by the standard). 14889 if (Opc != UO_AddrOf && Opc != UO_Deref) 14890 CheckArrayAccess(Input.get()); 14891 14892 auto *UO = 14893 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14894 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14895 14896 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14897 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14898 !isUnevaluatedContext()) 14899 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14900 14901 // Convert the result back to a half vector. 14902 if (ConvertHalfVec) 14903 return convertVector(UO, Context.HalfTy, *this); 14904 return UO; 14905 } 14906 14907 /// Determine whether the given expression is a qualified member 14908 /// access expression, of a form that could be turned into a pointer to member 14909 /// with the address-of operator. 14910 bool Sema::isQualifiedMemberAccess(Expr *E) { 14911 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14912 if (!DRE->getQualifier()) 14913 return false; 14914 14915 ValueDecl *VD = DRE->getDecl(); 14916 if (!VD->isCXXClassMember()) 14917 return false; 14918 14919 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14920 return true; 14921 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14922 return Method->isInstance(); 14923 14924 return false; 14925 } 14926 14927 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14928 if (!ULE->getQualifier()) 14929 return false; 14930 14931 for (NamedDecl *D : ULE->decls()) { 14932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14933 if (Method->isInstance()) 14934 return true; 14935 } else { 14936 // Overload set does not contain methods. 14937 break; 14938 } 14939 } 14940 14941 return false; 14942 } 14943 14944 return false; 14945 } 14946 14947 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14948 UnaryOperatorKind Opc, Expr *Input) { 14949 // First things first: handle placeholders so that the 14950 // overloaded-operator check considers the right type. 14951 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14952 // Increment and decrement of pseudo-object references. 14953 if (pty->getKind() == BuiltinType::PseudoObject && 14954 UnaryOperator::isIncrementDecrementOp(Opc)) 14955 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14956 14957 // extension is always a builtin operator. 14958 if (Opc == UO_Extension) 14959 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14960 14961 // & gets special logic for several kinds of placeholder. 14962 // The builtin code knows what to do. 14963 if (Opc == UO_AddrOf && 14964 (pty->getKind() == BuiltinType::Overload || 14965 pty->getKind() == BuiltinType::UnknownAny || 14966 pty->getKind() == BuiltinType::BoundMember)) 14967 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14968 14969 // Anything else needs to be handled now. 14970 ExprResult Result = CheckPlaceholderExpr(Input); 14971 if (Result.isInvalid()) return ExprError(); 14972 Input = Result.get(); 14973 } 14974 14975 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14976 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14977 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14978 // Find all of the overloaded operators visible from this point. 14979 UnresolvedSet<16> Functions; 14980 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14981 if (S && OverOp != OO_None) 14982 LookupOverloadedOperatorName(OverOp, S, Functions); 14983 14984 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14985 } 14986 14987 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14988 } 14989 14990 // Unary Operators. 'Tok' is the token for the operator. 14991 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14992 tok::TokenKind Op, Expr *Input) { 14993 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14994 } 14995 14996 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14997 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14998 LabelDecl *TheDecl) { 14999 TheDecl->markUsed(Context); 15000 // Create the AST node. The address of a label always has type 'void*'. 15001 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15002 Context.getPointerType(Context.VoidTy)); 15003 } 15004 15005 void Sema::ActOnStartStmtExpr() { 15006 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15007 } 15008 15009 void Sema::ActOnStmtExprError() { 15010 // Note that function is also called by TreeTransform when leaving a 15011 // StmtExpr scope without rebuilding anything. 15012 15013 DiscardCleanupsInEvaluationContext(); 15014 PopExpressionEvaluationContext(); 15015 } 15016 15017 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15018 SourceLocation RPLoc) { 15019 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15020 } 15021 15022 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15023 SourceLocation RPLoc, unsigned TemplateDepth) { 15024 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15025 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15026 15027 if (hasAnyUnrecoverableErrorsInThisFunction()) 15028 DiscardCleanupsInEvaluationContext(); 15029 assert(!Cleanup.exprNeedsCleanups() && 15030 "cleanups within StmtExpr not correctly bound!"); 15031 PopExpressionEvaluationContext(); 15032 15033 // FIXME: there are a variety of strange constraints to enforce here, for 15034 // example, it is not possible to goto into a stmt expression apparently. 15035 // More semantic analysis is needed. 15036 15037 // If there are sub-stmts in the compound stmt, take the type of the last one 15038 // as the type of the stmtexpr. 15039 QualType Ty = Context.VoidTy; 15040 bool StmtExprMayBindToTemp = false; 15041 if (!Compound->body_empty()) { 15042 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15043 if (const auto *LastStmt = 15044 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15045 if (const Expr *Value = LastStmt->getExprStmt()) { 15046 StmtExprMayBindToTemp = true; 15047 Ty = Value->getType(); 15048 } 15049 } 15050 } 15051 15052 // FIXME: Check that expression type is complete/non-abstract; statement 15053 // expressions are not lvalues. 15054 Expr *ResStmtExpr = 15055 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15056 if (StmtExprMayBindToTemp) 15057 return MaybeBindToTemporary(ResStmtExpr); 15058 return ResStmtExpr; 15059 } 15060 15061 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15062 if (ER.isInvalid()) 15063 return ExprError(); 15064 15065 // Do function/array conversion on the last expression, but not 15066 // lvalue-to-rvalue. However, initialize an unqualified type. 15067 ER = DefaultFunctionArrayConversion(ER.get()); 15068 if (ER.isInvalid()) 15069 return ExprError(); 15070 Expr *E = ER.get(); 15071 15072 if (E->isTypeDependent()) 15073 return E; 15074 15075 // In ARC, if the final expression ends in a consume, splice 15076 // the consume out and bind it later. In the alternate case 15077 // (when dealing with a retainable type), the result 15078 // initialization will create a produce. In both cases the 15079 // result will be +1, and we'll need to balance that out with 15080 // a bind. 15081 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15082 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15083 return Cast->getSubExpr(); 15084 15085 // FIXME: Provide a better location for the initialization. 15086 return PerformCopyInitialization( 15087 InitializedEntity::InitializeStmtExprResult( 15088 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15089 SourceLocation(), E); 15090 } 15091 15092 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15093 TypeSourceInfo *TInfo, 15094 ArrayRef<OffsetOfComponent> Components, 15095 SourceLocation RParenLoc) { 15096 QualType ArgTy = TInfo->getType(); 15097 bool Dependent = ArgTy->isDependentType(); 15098 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15099 15100 // We must have at least one component that refers to the type, and the first 15101 // one is known to be a field designator. Verify that the ArgTy represents 15102 // a struct/union/class. 15103 if (!Dependent && !ArgTy->isRecordType()) 15104 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15105 << ArgTy << TypeRange); 15106 15107 // Type must be complete per C99 7.17p3 because a declaring a variable 15108 // with an incomplete type would be ill-formed. 15109 if (!Dependent 15110 && RequireCompleteType(BuiltinLoc, ArgTy, 15111 diag::err_offsetof_incomplete_type, TypeRange)) 15112 return ExprError(); 15113 15114 bool DidWarnAboutNonPOD = false; 15115 QualType CurrentType = ArgTy; 15116 SmallVector<OffsetOfNode, 4> Comps; 15117 SmallVector<Expr*, 4> Exprs; 15118 for (const OffsetOfComponent &OC : Components) { 15119 if (OC.isBrackets) { 15120 // Offset of an array sub-field. TODO: Should we allow vector elements? 15121 if (!CurrentType->isDependentType()) { 15122 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15123 if(!AT) 15124 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15125 << CurrentType); 15126 CurrentType = AT->getElementType(); 15127 } else 15128 CurrentType = Context.DependentTy; 15129 15130 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15131 if (IdxRval.isInvalid()) 15132 return ExprError(); 15133 Expr *Idx = IdxRval.get(); 15134 15135 // The expression must be an integral expression. 15136 // FIXME: An integral constant expression? 15137 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15138 !Idx->getType()->isIntegerType()) 15139 return ExprError( 15140 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15141 << Idx->getSourceRange()); 15142 15143 // Record this array index. 15144 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15145 Exprs.push_back(Idx); 15146 continue; 15147 } 15148 15149 // Offset of a field. 15150 if (CurrentType->isDependentType()) { 15151 // We have the offset of a field, but we can't look into the dependent 15152 // type. Just record the identifier of the field. 15153 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15154 CurrentType = Context.DependentTy; 15155 continue; 15156 } 15157 15158 // We need to have a complete type to look into. 15159 if (RequireCompleteType(OC.LocStart, CurrentType, 15160 diag::err_offsetof_incomplete_type)) 15161 return ExprError(); 15162 15163 // Look for the designated field. 15164 const RecordType *RC = CurrentType->getAs<RecordType>(); 15165 if (!RC) 15166 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15167 << CurrentType); 15168 RecordDecl *RD = RC->getDecl(); 15169 15170 // C++ [lib.support.types]p5: 15171 // The macro offsetof accepts a restricted set of type arguments in this 15172 // International Standard. type shall be a POD structure or a POD union 15173 // (clause 9). 15174 // C++11 [support.types]p4: 15175 // If type is not a standard-layout class (Clause 9), the results are 15176 // undefined. 15177 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15178 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15179 unsigned DiagID = 15180 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15181 : diag::ext_offsetof_non_pod_type; 15182 15183 if (!IsSafe && !DidWarnAboutNonPOD && 15184 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15185 PDiag(DiagID) 15186 << SourceRange(Components[0].LocStart, OC.LocEnd) 15187 << CurrentType)) 15188 DidWarnAboutNonPOD = true; 15189 } 15190 15191 // Look for the field. 15192 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15193 LookupQualifiedName(R, RD); 15194 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15195 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15196 if (!MemberDecl) { 15197 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15198 MemberDecl = IndirectMemberDecl->getAnonField(); 15199 } 15200 15201 if (!MemberDecl) 15202 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15203 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15204 OC.LocEnd)); 15205 15206 // C99 7.17p3: 15207 // (If the specified member is a bit-field, the behavior is undefined.) 15208 // 15209 // We diagnose this as an error. 15210 if (MemberDecl->isBitField()) { 15211 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15212 << MemberDecl->getDeclName() 15213 << SourceRange(BuiltinLoc, RParenLoc); 15214 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15215 return ExprError(); 15216 } 15217 15218 RecordDecl *Parent = MemberDecl->getParent(); 15219 if (IndirectMemberDecl) 15220 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15221 15222 // If the member was found in a base class, introduce OffsetOfNodes for 15223 // the base class indirections. 15224 CXXBasePaths Paths; 15225 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15226 Paths)) { 15227 if (Paths.getDetectedVirtual()) { 15228 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15229 << MemberDecl->getDeclName() 15230 << SourceRange(BuiltinLoc, RParenLoc); 15231 return ExprError(); 15232 } 15233 15234 CXXBasePath &Path = Paths.front(); 15235 for (const CXXBasePathElement &B : Path) 15236 Comps.push_back(OffsetOfNode(B.Base)); 15237 } 15238 15239 if (IndirectMemberDecl) { 15240 for (auto *FI : IndirectMemberDecl->chain()) { 15241 assert(isa<FieldDecl>(FI)); 15242 Comps.push_back(OffsetOfNode(OC.LocStart, 15243 cast<FieldDecl>(FI), OC.LocEnd)); 15244 } 15245 } else 15246 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15247 15248 CurrentType = MemberDecl->getType().getNonReferenceType(); 15249 } 15250 15251 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15252 Comps, Exprs, RParenLoc); 15253 } 15254 15255 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15256 SourceLocation BuiltinLoc, 15257 SourceLocation TypeLoc, 15258 ParsedType ParsedArgTy, 15259 ArrayRef<OffsetOfComponent> Components, 15260 SourceLocation RParenLoc) { 15261 15262 TypeSourceInfo *ArgTInfo; 15263 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15264 if (ArgTy.isNull()) 15265 return ExprError(); 15266 15267 if (!ArgTInfo) 15268 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15269 15270 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15271 } 15272 15273 15274 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15275 Expr *CondExpr, 15276 Expr *LHSExpr, Expr *RHSExpr, 15277 SourceLocation RPLoc) { 15278 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15279 15280 ExprValueKind VK = VK_PRValue; 15281 ExprObjectKind OK = OK_Ordinary; 15282 QualType resType; 15283 bool CondIsTrue = false; 15284 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15285 resType = Context.DependentTy; 15286 } else { 15287 // The conditional expression is required to be a constant expression. 15288 llvm::APSInt condEval(32); 15289 ExprResult CondICE = VerifyIntegerConstantExpression( 15290 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15291 if (CondICE.isInvalid()) 15292 return ExprError(); 15293 CondExpr = CondICE.get(); 15294 CondIsTrue = condEval.getZExtValue(); 15295 15296 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15297 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15298 15299 resType = ActiveExpr->getType(); 15300 VK = ActiveExpr->getValueKind(); 15301 OK = ActiveExpr->getObjectKind(); 15302 } 15303 15304 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15305 resType, VK, OK, RPLoc, CondIsTrue); 15306 } 15307 15308 //===----------------------------------------------------------------------===// 15309 // Clang Extensions. 15310 //===----------------------------------------------------------------------===// 15311 15312 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15313 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15314 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15315 15316 if (LangOpts.CPlusPlus) { 15317 MangleNumberingContext *MCtx; 15318 Decl *ManglingContextDecl; 15319 std::tie(MCtx, ManglingContextDecl) = 15320 getCurrentMangleNumberContext(Block->getDeclContext()); 15321 if (MCtx) { 15322 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15323 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15324 } 15325 } 15326 15327 PushBlockScope(CurScope, Block); 15328 CurContext->addDecl(Block); 15329 if (CurScope) 15330 PushDeclContext(CurScope, Block); 15331 else 15332 CurContext = Block; 15333 15334 getCurBlock()->HasImplicitReturnType = true; 15335 15336 // Enter a new evaluation context to insulate the block from any 15337 // cleanups from the enclosing full-expression. 15338 PushExpressionEvaluationContext( 15339 ExpressionEvaluationContext::PotentiallyEvaluated); 15340 } 15341 15342 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15343 Scope *CurScope) { 15344 assert(ParamInfo.getIdentifier() == nullptr && 15345 "block-id should have no identifier!"); 15346 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15347 BlockScopeInfo *CurBlock = getCurBlock(); 15348 15349 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15350 QualType T = Sig->getType(); 15351 15352 // FIXME: We should allow unexpanded parameter packs here, but that would, 15353 // in turn, make the block expression contain unexpanded parameter packs. 15354 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15355 // Drop the parameters. 15356 FunctionProtoType::ExtProtoInfo EPI; 15357 EPI.HasTrailingReturn = false; 15358 EPI.TypeQuals.addConst(); 15359 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15360 Sig = Context.getTrivialTypeSourceInfo(T); 15361 } 15362 15363 // GetTypeForDeclarator always produces a function type for a block 15364 // literal signature. Furthermore, it is always a FunctionProtoType 15365 // unless the function was written with a typedef. 15366 assert(T->isFunctionType() && 15367 "GetTypeForDeclarator made a non-function block signature"); 15368 15369 // Look for an explicit signature in that function type. 15370 FunctionProtoTypeLoc ExplicitSignature; 15371 15372 if ((ExplicitSignature = Sig->getTypeLoc() 15373 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15374 15375 // Check whether that explicit signature was synthesized by 15376 // GetTypeForDeclarator. If so, don't save that as part of the 15377 // written signature. 15378 if (ExplicitSignature.getLocalRangeBegin() == 15379 ExplicitSignature.getLocalRangeEnd()) { 15380 // This would be much cheaper if we stored TypeLocs instead of 15381 // TypeSourceInfos. 15382 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15383 unsigned Size = Result.getFullDataSize(); 15384 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15385 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15386 15387 ExplicitSignature = FunctionProtoTypeLoc(); 15388 } 15389 } 15390 15391 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15392 CurBlock->FunctionType = T; 15393 15394 const auto *Fn = T->castAs<FunctionType>(); 15395 QualType RetTy = Fn->getReturnType(); 15396 bool isVariadic = 15397 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15398 15399 CurBlock->TheDecl->setIsVariadic(isVariadic); 15400 15401 // Context.DependentTy is used as a placeholder for a missing block 15402 // return type. TODO: what should we do with declarators like: 15403 // ^ * { ... } 15404 // If the answer is "apply template argument deduction".... 15405 if (RetTy != Context.DependentTy) { 15406 CurBlock->ReturnType = RetTy; 15407 CurBlock->TheDecl->setBlockMissingReturnType(false); 15408 CurBlock->HasImplicitReturnType = false; 15409 } 15410 15411 // Push block parameters from the declarator if we had them. 15412 SmallVector<ParmVarDecl*, 8> Params; 15413 if (ExplicitSignature) { 15414 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15415 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15416 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15417 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15418 // Diagnose this as an extension in C17 and earlier. 15419 if (!getLangOpts().C2x) 15420 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15421 } 15422 Params.push_back(Param); 15423 } 15424 15425 // Fake up parameter variables if we have a typedef, like 15426 // ^ fntype { ... } 15427 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15428 for (const auto &I : Fn->param_types()) { 15429 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15430 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15431 Params.push_back(Param); 15432 } 15433 } 15434 15435 // Set the parameters on the block decl. 15436 if (!Params.empty()) { 15437 CurBlock->TheDecl->setParams(Params); 15438 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15439 /*CheckParameterNames=*/false); 15440 } 15441 15442 // Finally we can process decl attributes. 15443 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15444 15445 // Put the parameter variables in scope. 15446 for (auto AI : CurBlock->TheDecl->parameters()) { 15447 AI->setOwningFunction(CurBlock->TheDecl); 15448 15449 // If this has an identifier, add it to the scope stack. 15450 if (AI->getIdentifier()) { 15451 CheckShadow(CurBlock->TheScope, AI); 15452 15453 PushOnScopeChains(AI, CurBlock->TheScope); 15454 } 15455 } 15456 } 15457 15458 /// ActOnBlockError - If there is an error parsing a block, this callback 15459 /// is invoked to pop the information about the block from the action impl. 15460 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15461 // Leave the expression-evaluation context. 15462 DiscardCleanupsInEvaluationContext(); 15463 PopExpressionEvaluationContext(); 15464 15465 // Pop off CurBlock, handle nested blocks. 15466 PopDeclContext(); 15467 PopFunctionScopeInfo(); 15468 } 15469 15470 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15471 /// literal was successfully completed. ^(int x){...} 15472 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15473 Stmt *Body, Scope *CurScope) { 15474 // If blocks are disabled, emit an error. 15475 if (!LangOpts.Blocks) 15476 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15477 15478 // Leave the expression-evaluation context. 15479 if (hasAnyUnrecoverableErrorsInThisFunction()) 15480 DiscardCleanupsInEvaluationContext(); 15481 assert(!Cleanup.exprNeedsCleanups() && 15482 "cleanups within block not correctly bound!"); 15483 PopExpressionEvaluationContext(); 15484 15485 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15486 BlockDecl *BD = BSI->TheDecl; 15487 15488 if (BSI->HasImplicitReturnType) 15489 deduceClosureReturnType(*BSI); 15490 15491 QualType RetTy = Context.VoidTy; 15492 if (!BSI->ReturnType.isNull()) 15493 RetTy = BSI->ReturnType; 15494 15495 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15496 QualType BlockTy; 15497 15498 // If the user wrote a function type in some form, try to use that. 15499 if (!BSI->FunctionType.isNull()) { 15500 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15501 15502 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15503 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15504 15505 // Turn protoless block types into nullary block types. 15506 if (isa<FunctionNoProtoType>(FTy)) { 15507 FunctionProtoType::ExtProtoInfo EPI; 15508 EPI.ExtInfo = Ext; 15509 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15510 15511 // Otherwise, if we don't need to change anything about the function type, 15512 // preserve its sugar structure. 15513 } else if (FTy->getReturnType() == RetTy && 15514 (!NoReturn || FTy->getNoReturnAttr())) { 15515 BlockTy = BSI->FunctionType; 15516 15517 // Otherwise, make the minimal modifications to the function type. 15518 } else { 15519 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15520 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15521 EPI.TypeQuals = Qualifiers(); 15522 EPI.ExtInfo = Ext; 15523 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15524 } 15525 15526 // If we don't have a function type, just build one from nothing. 15527 } else { 15528 FunctionProtoType::ExtProtoInfo EPI; 15529 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15530 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15531 } 15532 15533 DiagnoseUnusedParameters(BD->parameters()); 15534 BlockTy = Context.getBlockPointerType(BlockTy); 15535 15536 // If needed, diagnose invalid gotos and switches in the block. 15537 if (getCurFunction()->NeedsScopeChecking() && 15538 !PP.isCodeCompletionEnabled()) 15539 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15540 15541 BD->setBody(cast<CompoundStmt>(Body)); 15542 15543 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15544 DiagnoseUnguardedAvailabilityViolations(BD); 15545 15546 // Try to apply the named return value optimization. We have to check again 15547 // if we can do this, though, because blocks keep return statements around 15548 // to deduce an implicit return type. 15549 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15550 !BD->isDependentContext()) 15551 computeNRVO(Body, BSI); 15552 15553 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15554 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15555 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15556 NTCUK_Destruct|NTCUK_Copy); 15557 15558 PopDeclContext(); 15559 15560 // Set the captured variables on the block. 15561 SmallVector<BlockDecl::Capture, 4> Captures; 15562 for (Capture &Cap : BSI->Captures) { 15563 if (Cap.isInvalid() || Cap.isThisCapture()) 15564 continue; 15565 15566 VarDecl *Var = Cap.getVariable(); 15567 Expr *CopyExpr = nullptr; 15568 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15569 if (const RecordType *Record = 15570 Cap.getCaptureType()->getAs<RecordType>()) { 15571 // The capture logic needs the destructor, so make sure we mark it. 15572 // Usually this is unnecessary because most local variables have 15573 // their destructors marked at declaration time, but parameters are 15574 // an exception because it's technically only the call site that 15575 // actually requires the destructor. 15576 if (isa<ParmVarDecl>(Var)) 15577 FinalizeVarWithDestructor(Var, Record); 15578 15579 // Enter a separate potentially-evaluated context while building block 15580 // initializers to isolate their cleanups from those of the block 15581 // itself. 15582 // FIXME: Is this appropriate even when the block itself occurs in an 15583 // unevaluated operand? 15584 EnterExpressionEvaluationContext EvalContext( 15585 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15586 15587 SourceLocation Loc = Cap.getLocation(); 15588 15589 ExprResult Result = BuildDeclarationNameExpr( 15590 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15591 15592 // According to the blocks spec, the capture of a variable from 15593 // the stack requires a const copy constructor. This is not true 15594 // of the copy/move done to move a __block variable to the heap. 15595 if (!Result.isInvalid() && 15596 !Result.get()->getType().isConstQualified()) { 15597 Result = ImpCastExprToType(Result.get(), 15598 Result.get()->getType().withConst(), 15599 CK_NoOp, VK_LValue); 15600 } 15601 15602 if (!Result.isInvalid()) { 15603 Result = PerformCopyInitialization( 15604 InitializedEntity::InitializeBlock(Var->getLocation(), 15605 Cap.getCaptureType(), false), 15606 Loc, Result.get()); 15607 } 15608 15609 // Build a full-expression copy expression if initialization 15610 // succeeded and used a non-trivial constructor. Recover from 15611 // errors by pretending that the copy isn't necessary. 15612 if (!Result.isInvalid() && 15613 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15614 ->isTrivial()) { 15615 Result = MaybeCreateExprWithCleanups(Result); 15616 CopyExpr = Result.get(); 15617 } 15618 } 15619 } 15620 15621 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15622 CopyExpr); 15623 Captures.push_back(NewCap); 15624 } 15625 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15626 15627 // Pop the block scope now but keep it alive to the end of this function. 15628 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15629 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15630 15631 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15632 15633 // If the block isn't obviously global, i.e. it captures anything at 15634 // all, then we need to do a few things in the surrounding context: 15635 if (Result->getBlockDecl()->hasCaptures()) { 15636 // First, this expression has a new cleanup object. 15637 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15638 Cleanup.setExprNeedsCleanups(true); 15639 15640 // It also gets a branch-protected scope if any of the captured 15641 // variables needs destruction. 15642 for (const auto &CI : Result->getBlockDecl()->captures()) { 15643 const VarDecl *var = CI.getVariable(); 15644 if (var->getType().isDestructedType() != QualType::DK_none) { 15645 setFunctionHasBranchProtectedScope(); 15646 break; 15647 } 15648 } 15649 } 15650 15651 if (getCurFunction()) 15652 getCurFunction()->addBlock(BD); 15653 15654 return Result; 15655 } 15656 15657 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15658 SourceLocation RPLoc) { 15659 TypeSourceInfo *TInfo; 15660 GetTypeFromParser(Ty, &TInfo); 15661 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15662 } 15663 15664 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15665 Expr *E, TypeSourceInfo *TInfo, 15666 SourceLocation RPLoc) { 15667 Expr *OrigExpr = E; 15668 bool IsMS = false; 15669 15670 // CUDA device code does not support varargs. 15671 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15672 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15673 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15674 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15675 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15676 } 15677 } 15678 15679 // NVPTX does not support va_arg expression. 15680 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15681 Context.getTargetInfo().getTriple().isNVPTX()) 15682 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15683 15684 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15685 // as Microsoft ABI on an actual Microsoft platform, where 15686 // __builtin_ms_va_list and __builtin_va_list are the same.) 15687 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15688 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15689 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15690 if (Context.hasSameType(MSVaListType, E->getType())) { 15691 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15692 return ExprError(); 15693 IsMS = true; 15694 } 15695 } 15696 15697 // Get the va_list type 15698 QualType VaListType = Context.getBuiltinVaListType(); 15699 if (!IsMS) { 15700 if (VaListType->isArrayType()) { 15701 // Deal with implicit array decay; for example, on x86-64, 15702 // va_list is an array, but it's supposed to decay to 15703 // a pointer for va_arg. 15704 VaListType = Context.getArrayDecayedType(VaListType); 15705 // Make sure the input expression also decays appropriately. 15706 ExprResult Result = UsualUnaryConversions(E); 15707 if (Result.isInvalid()) 15708 return ExprError(); 15709 E = Result.get(); 15710 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15711 // If va_list is a record type and we are compiling in C++ mode, 15712 // check the argument using reference binding. 15713 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15714 Context, Context.getLValueReferenceType(VaListType), false); 15715 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15716 if (Init.isInvalid()) 15717 return ExprError(); 15718 E = Init.getAs<Expr>(); 15719 } else { 15720 // Otherwise, the va_list argument must be an l-value because 15721 // it is modified by va_arg. 15722 if (!E->isTypeDependent() && 15723 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15724 return ExprError(); 15725 } 15726 } 15727 15728 if (!IsMS && !E->isTypeDependent() && 15729 !Context.hasSameType(VaListType, E->getType())) 15730 return ExprError( 15731 Diag(E->getBeginLoc(), 15732 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15733 << OrigExpr->getType() << E->getSourceRange()); 15734 15735 if (!TInfo->getType()->isDependentType()) { 15736 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15737 diag::err_second_parameter_to_va_arg_incomplete, 15738 TInfo->getTypeLoc())) 15739 return ExprError(); 15740 15741 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15742 TInfo->getType(), 15743 diag::err_second_parameter_to_va_arg_abstract, 15744 TInfo->getTypeLoc())) 15745 return ExprError(); 15746 15747 if (!TInfo->getType().isPODType(Context)) { 15748 Diag(TInfo->getTypeLoc().getBeginLoc(), 15749 TInfo->getType()->isObjCLifetimeType() 15750 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15751 : diag::warn_second_parameter_to_va_arg_not_pod) 15752 << TInfo->getType() 15753 << TInfo->getTypeLoc().getSourceRange(); 15754 } 15755 15756 // Check for va_arg where arguments of the given type will be promoted 15757 // (i.e. this va_arg is guaranteed to have undefined behavior). 15758 QualType PromoteType; 15759 if (TInfo->getType()->isPromotableIntegerType()) { 15760 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15761 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15762 // and C2x 7.16.1.1p2 says, in part: 15763 // If type is not compatible with the type of the actual next argument 15764 // (as promoted according to the default argument promotions), the 15765 // behavior is undefined, except for the following cases: 15766 // - both types are pointers to qualified or unqualified versions of 15767 // compatible types; 15768 // - one type is a signed integer type, the other type is the 15769 // corresponding unsigned integer type, and the value is 15770 // representable in both types; 15771 // - one type is pointer to qualified or unqualified void and the 15772 // other is a pointer to a qualified or unqualified character type. 15773 // Given that type compatibility is the primary requirement (ignoring 15774 // qualifications), you would think we could call typesAreCompatible() 15775 // directly to test this. However, in C++, that checks for *same type*, 15776 // which causes false positives when passing an enumeration type to 15777 // va_arg. Instead, get the underlying type of the enumeration and pass 15778 // that. 15779 QualType UnderlyingType = TInfo->getType(); 15780 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15781 UnderlyingType = ET->getDecl()->getIntegerType(); 15782 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15783 /*CompareUnqualified*/ true)) 15784 PromoteType = QualType(); 15785 15786 // If the types are still not compatible, we need to test whether the 15787 // promoted type and the underlying type are the same except for 15788 // signedness. Ask the AST for the correctly corresponding type and see 15789 // if that's compatible. 15790 if (!PromoteType.isNull() && 15791 PromoteType->isUnsignedIntegerType() != 15792 UnderlyingType->isUnsignedIntegerType()) { 15793 UnderlyingType = 15794 UnderlyingType->isUnsignedIntegerType() 15795 ? Context.getCorrespondingSignedType(UnderlyingType) 15796 : Context.getCorrespondingUnsignedType(UnderlyingType); 15797 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15798 /*CompareUnqualified*/ true)) 15799 PromoteType = QualType(); 15800 } 15801 } 15802 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15803 PromoteType = Context.DoubleTy; 15804 if (!PromoteType.isNull()) 15805 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15806 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15807 << TInfo->getType() 15808 << PromoteType 15809 << TInfo->getTypeLoc().getSourceRange()); 15810 } 15811 15812 QualType T = TInfo->getType().getNonLValueExprType(Context); 15813 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15814 } 15815 15816 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15817 // The type of __null will be int or long, depending on the size of 15818 // pointers on the target. 15819 QualType Ty; 15820 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15821 if (pw == Context.getTargetInfo().getIntWidth()) 15822 Ty = Context.IntTy; 15823 else if (pw == Context.getTargetInfo().getLongWidth()) 15824 Ty = Context.LongTy; 15825 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15826 Ty = Context.LongLongTy; 15827 else { 15828 llvm_unreachable("I don't know size of pointer!"); 15829 } 15830 15831 return new (Context) GNUNullExpr(Ty, TokenLoc); 15832 } 15833 15834 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15835 SourceLocation BuiltinLoc, 15836 SourceLocation RPLoc) { 15837 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15838 } 15839 15840 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15841 SourceLocation BuiltinLoc, 15842 SourceLocation RPLoc, 15843 DeclContext *ParentContext) { 15844 return new (Context) 15845 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15846 } 15847 15848 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15849 bool Diagnose) { 15850 if (!getLangOpts().ObjC) 15851 return false; 15852 15853 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15854 if (!PT) 15855 return false; 15856 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15857 15858 // Ignore any parens, implicit casts (should only be 15859 // array-to-pointer decays), and not-so-opaque values. The last is 15860 // important for making this trigger for property assignments. 15861 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15862 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15863 if (OV->getSourceExpr()) 15864 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15865 15866 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15867 if (!PT->isObjCIdType() && 15868 !(ID && ID->getIdentifier()->isStr("NSString"))) 15869 return false; 15870 if (!SL->isAscii()) 15871 return false; 15872 15873 if (Diagnose) { 15874 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15875 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15876 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15877 } 15878 return true; 15879 } 15880 15881 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15882 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15883 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15884 !SrcExpr->isNullPointerConstant( 15885 getASTContext(), Expr::NPC_NeverValueDependent)) { 15886 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15887 return false; 15888 if (Diagnose) { 15889 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15890 << /*number*/1 15891 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15892 Expr *NumLit = 15893 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15894 if (NumLit) 15895 Exp = NumLit; 15896 } 15897 return true; 15898 } 15899 15900 return false; 15901 } 15902 15903 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15904 const Expr *SrcExpr) { 15905 if (!DstType->isFunctionPointerType() || 15906 !SrcExpr->getType()->isFunctionType()) 15907 return false; 15908 15909 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15910 if (!DRE) 15911 return false; 15912 15913 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15914 if (!FD) 15915 return false; 15916 15917 return !S.checkAddressOfFunctionIsAvailable(FD, 15918 /*Complain=*/true, 15919 SrcExpr->getBeginLoc()); 15920 } 15921 15922 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15923 SourceLocation Loc, 15924 QualType DstType, QualType SrcType, 15925 Expr *SrcExpr, AssignmentAction Action, 15926 bool *Complained) { 15927 if (Complained) 15928 *Complained = false; 15929 15930 // Decode the result (notice that AST's are still created for extensions). 15931 bool CheckInferredResultType = false; 15932 bool isInvalid = false; 15933 unsigned DiagKind = 0; 15934 ConversionFixItGenerator ConvHints; 15935 bool MayHaveConvFixit = false; 15936 bool MayHaveFunctionDiff = false; 15937 const ObjCInterfaceDecl *IFace = nullptr; 15938 const ObjCProtocolDecl *PDecl = nullptr; 15939 15940 switch (ConvTy) { 15941 case Compatible: 15942 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15943 return false; 15944 15945 case PointerToInt: 15946 if (getLangOpts().CPlusPlus) { 15947 DiagKind = diag::err_typecheck_convert_pointer_int; 15948 isInvalid = true; 15949 } else { 15950 DiagKind = diag::ext_typecheck_convert_pointer_int; 15951 } 15952 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15953 MayHaveConvFixit = true; 15954 break; 15955 case IntToPointer: 15956 if (getLangOpts().CPlusPlus) { 15957 DiagKind = diag::err_typecheck_convert_int_pointer; 15958 isInvalid = true; 15959 } else { 15960 DiagKind = diag::ext_typecheck_convert_int_pointer; 15961 } 15962 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15963 MayHaveConvFixit = true; 15964 break; 15965 case IncompatibleFunctionPointer: 15966 if (getLangOpts().CPlusPlus) { 15967 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15968 isInvalid = true; 15969 } else { 15970 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15971 } 15972 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15973 MayHaveConvFixit = true; 15974 break; 15975 case IncompatiblePointer: 15976 if (Action == AA_Passing_CFAudited) { 15977 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15978 } else if (getLangOpts().CPlusPlus) { 15979 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15980 isInvalid = true; 15981 } else { 15982 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15983 } 15984 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15985 SrcType->isObjCObjectPointerType(); 15986 if (!CheckInferredResultType) { 15987 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15988 } else if (CheckInferredResultType) { 15989 SrcType = SrcType.getUnqualifiedType(); 15990 DstType = DstType.getUnqualifiedType(); 15991 } 15992 MayHaveConvFixit = true; 15993 break; 15994 case IncompatiblePointerSign: 15995 if (getLangOpts().CPlusPlus) { 15996 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15997 isInvalid = true; 15998 } else { 15999 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16000 } 16001 break; 16002 case FunctionVoidPointer: 16003 if (getLangOpts().CPlusPlus) { 16004 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16005 isInvalid = true; 16006 } else { 16007 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16008 } 16009 break; 16010 case IncompatiblePointerDiscardsQualifiers: { 16011 // Perform array-to-pointer decay if necessary. 16012 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16013 16014 isInvalid = true; 16015 16016 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16017 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16018 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16019 DiagKind = diag::err_typecheck_incompatible_address_space; 16020 break; 16021 16022 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16023 DiagKind = diag::err_typecheck_incompatible_ownership; 16024 break; 16025 } 16026 16027 llvm_unreachable("unknown error case for discarding qualifiers!"); 16028 // fallthrough 16029 } 16030 case CompatiblePointerDiscardsQualifiers: 16031 // If the qualifiers lost were because we were applying the 16032 // (deprecated) C++ conversion from a string literal to a char* 16033 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16034 // Ideally, this check would be performed in 16035 // checkPointerTypesForAssignment. However, that would require a 16036 // bit of refactoring (so that the second argument is an 16037 // expression, rather than a type), which should be done as part 16038 // of a larger effort to fix checkPointerTypesForAssignment for 16039 // C++ semantics. 16040 if (getLangOpts().CPlusPlus && 16041 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16042 return false; 16043 if (getLangOpts().CPlusPlus) { 16044 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16045 isInvalid = true; 16046 } else { 16047 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16048 } 16049 16050 break; 16051 case IncompatibleNestedPointerQualifiers: 16052 if (getLangOpts().CPlusPlus) { 16053 isInvalid = true; 16054 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16055 } else { 16056 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16057 } 16058 break; 16059 case IncompatibleNestedPointerAddressSpaceMismatch: 16060 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16061 isInvalid = true; 16062 break; 16063 case IntToBlockPointer: 16064 DiagKind = diag::err_int_to_block_pointer; 16065 isInvalid = true; 16066 break; 16067 case IncompatibleBlockPointer: 16068 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16069 isInvalid = true; 16070 break; 16071 case IncompatibleObjCQualifiedId: { 16072 if (SrcType->isObjCQualifiedIdType()) { 16073 const ObjCObjectPointerType *srcOPT = 16074 SrcType->castAs<ObjCObjectPointerType>(); 16075 for (auto *srcProto : srcOPT->quals()) { 16076 PDecl = srcProto; 16077 break; 16078 } 16079 if (const ObjCInterfaceType *IFaceT = 16080 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16081 IFace = IFaceT->getDecl(); 16082 } 16083 else if (DstType->isObjCQualifiedIdType()) { 16084 const ObjCObjectPointerType *dstOPT = 16085 DstType->castAs<ObjCObjectPointerType>(); 16086 for (auto *dstProto : dstOPT->quals()) { 16087 PDecl = dstProto; 16088 break; 16089 } 16090 if (const ObjCInterfaceType *IFaceT = 16091 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16092 IFace = IFaceT->getDecl(); 16093 } 16094 if (getLangOpts().CPlusPlus) { 16095 DiagKind = diag::err_incompatible_qualified_id; 16096 isInvalid = true; 16097 } else { 16098 DiagKind = diag::warn_incompatible_qualified_id; 16099 } 16100 break; 16101 } 16102 case IncompatibleVectors: 16103 if (getLangOpts().CPlusPlus) { 16104 DiagKind = diag::err_incompatible_vectors; 16105 isInvalid = true; 16106 } else { 16107 DiagKind = diag::warn_incompatible_vectors; 16108 } 16109 break; 16110 case IncompatibleObjCWeakRef: 16111 DiagKind = diag::err_arc_weak_unavailable_assign; 16112 isInvalid = true; 16113 break; 16114 case Incompatible: 16115 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16116 if (Complained) 16117 *Complained = true; 16118 return true; 16119 } 16120 16121 DiagKind = diag::err_typecheck_convert_incompatible; 16122 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16123 MayHaveConvFixit = true; 16124 isInvalid = true; 16125 MayHaveFunctionDiff = true; 16126 break; 16127 } 16128 16129 QualType FirstType, SecondType; 16130 switch (Action) { 16131 case AA_Assigning: 16132 case AA_Initializing: 16133 // The destination type comes first. 16134 FirstType = DstType; 16135 SecondType = SrcType; 16136 break; 16137 16138 case AA_Returning: 16139 case AA_Passing: 16140 case AA_Passing_CFAudited: 16141 case AA_Converting: 16142 case AA_Sending: 16143 case AA_Casting: 16144 // The source type comes first. 16145 FirstType = SrcType; 16146 SecondType = DstType; 16147 break; 16148 } 16149 16150 PartialDiagnostic FDiag = PDiag(DiagKind); 16151 if (Action == AA_Passing_CFAudited) 16152 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16153 else 16154 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16155 16156 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16157 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16158 auto isPlainChar = [](const clang::Type *Type) { 16159 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16160 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16161 }; 16162 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16163 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16164 } 16165 16166 // If we can fix the conversion, suggest the FixIts. 16167 if (!ConvHints.isNull()) { 16168 for (FixItHint &H : ConvHints.Hints) 16169 FDiag << H; 16170 } 16171 16172 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16173 16174 if (MayHaveFunctionDiff) 16175 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16176 16177 Diag(Loc, FDiag); 16178 if ((DiagKind == diag::warn_incompatible_qualified_id || 16179 DiagKind == diag::err_incompatible_qualified_id) && 16180 PDecl && IFace && !IFace->hasDefinition()) 16181 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16182 << IFace << PDecl; 16183 16184 if (SecondType == Context.OverloadTy) 16185 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16186 FirstType, /*TakingAddress=*/true); 16187 16188 if (CheckInferredResultType) 16189 EmitRelatedResultTypeNote(SrcExpr); 16190 16191 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16192 EmitRelatedResultTypeNoteForReturn(DstType); 16193 16194 if (Complained) 16195 *Complained = true; 16196 return isInvalid; 16197 } 16198 16199 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16200 llvm::APSInt *Result, 16201 AllowFoldKind CanFold) { 16202 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16203 public: 16204 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16205 QualType T) override { 16206 return S.Diag(Loc, diag::err_ice_not_integral) 16207 << T << S.LangOpts.CPlusPlus; 16208 } 16209 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16210 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16211 } 16212 } Diagnoser; 16213 16214 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16215 } 16216 16217 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16218 llvm::APSInt *Result, 16219 unsigned DiagID, 16220 AllowFoldKind CanFold) { 16221 class IDDiagnoser : public VerifyICEDiagnoser { 16222 unsigned DiagID; 16223 16224 public: 16225 IDDiagnoser(unsigned DiagID) 16226 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16227 16228 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16229 return S.Diag(Loc, DiagID); 16230 } 16231 } Diagnoser(DiagID); 16232 16233 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16234 } 16235 16236 Sema::SemaDiagnosticBuilder 16237 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16238 QualType T) { 16239 return diagnoseNotICE(S, Loc); 16240 } 16241 16242 Sema::SemaDiagnosticBuilder 16243 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16244 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16245 } 16246 16247 ExprResult 16248 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16249 VerifyICEDiagnoser &Diagnoser, 16250 AllowFoldKind CanFold) { 16251 SourceLocation DiagLoc = E->getBeginLoc(); 16252 16253 if (getLangOpts().CPlusPlus11) { 16254 // C++11 [expr.const]p5: 16255 // If an expression of literal class type is used in a context where an 16256 // integral constant expression is required, then that class type shall 16257 // have a single non-explicit conversion function to an integral or 16258 // unscoped enumeration type 16259 ExprResult Converted; 16260 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16261 VerifyICEDiagnoser &BaseDiagnoser; 16262 public: 16263 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16264 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16265 BaseDiagnoser.Suppress, true), 16266 BaseDiagnoser(BaseDiagnoser) {} 16267 16268 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16269 QualType T) override { 16270 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16271 } 16272 16273 SemaDiagnosticBuilder diagnoseIncomplete( 16274 Sema &S, SourceLocation Loc, QualType T) override { 16275 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16276 } 16277 16278 SemaDiagnosticBuilder diagnoseExplicitConv( 16279 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16280 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16281 } 16282 16283 SemaDiagnosticBuilder noteExplicitConv( 16284 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16285 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16286 << ConvTy->isEnumeralType() << ConvTy; 16287 } 16288 16289 SemaDiagnosticBuilder diagnoseAmbiguous( 16290 Sema &S, SourceLocation Loc, QualType T) override { 16291 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16292 } 16293 16294 SemaDiagnosticBuilder noteAmbiguous( 16295 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16296 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16297 << ConvTy->isEnumeralType() << ConvTy; 16298 } 16299 16300 SemaDiagnosticBuilder diagnoseConversion( 16301 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16302 llvm_unreachable("conversion functions are permitted"); 16303 } 16304 } ConvertDiagnoser(Diagnoser); 16305 16306 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16307 ConvertDiagnoser); 16308 if (Converted.isInvalid()) 16309 return Converted; 16310 E = Converted.get(); 16311 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16312 return ExprError(); 16313 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16314 // An ICE must be of integral or unscoped enumeration type. 16315 if (!Diagnoser.Suppress) 16316 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16317 << E->getSourceRange(); 16318 return ExprError(); 16319 } 16320 16321 ExprResult RValueExpr = DefaultLvalueConversion(E); 16322 if (RValueExpr.isInvalid()) 16323 return ExprError(); 16324 16325 E = RValueExpr.get(); 16326 16327 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16328 // in the non-ICE case. 16329 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16330 if (Result) 16331 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16332 if (!isa<ConstantExpr>(E)) 16333 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16334 : ConstantExpr::Create(Context, E); 16335 return E; 16336 } 16337 16338 Expr::EvalResult EvalResult; 16339 SmallVector<PartialDiagnosticAt, 8> Notes; 16340 EvalResult.Diag = &Notes; 16341 16342 // Try to evaluate the expression, and produce diagnostics explaining why it's 16343 // not a constant expression as a side-effect. 16344 bool Folded = 16345 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16346 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16347 16348 if (!isa<ConstantExpr>(E)) 16349 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16350 16351 // In C++11, we can rely on diagnostics being produced for any expression 16352 // which is not a constant expression. If no diagnostics were produced, then 16353 // this is a constant expression. 16354 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16355 if (Result) 16356 *Result = EvalResult.Val.getInt(); 16357 return E; 16358 } 16359 16360 // If our only note is the usual "invalid subexpression" note, just point 16361 // the caret at its location rather than producing an essentially 16362 // redundant note. 16363 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16364 diag::note_invalid_subexpr_in_const_expr) { 16365 DiagLoc = Notes[0].first; 16366 Notes.clear(); 16367 } 16368 16369 if (!Folded || !CanFold) { 16370 if (!Diagnoser.Suppress) { 16371 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16372 for (const PartialDiagnosticAt &Note : Notes) 16373 Diag(Note.first, Note.second); 16374 } 16375 16376 return ExprError(); 16377 } 16378 16379 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16380 for (const PartialDiagnosticAt &Note : Notes) 16381 Diag(Note.first, Note.second); 16382 16383 if (Result) 16384 *Result = EvalResult.Val.getInt(); 16385 return E; 16386 } 16387 16388 namespace { 16389 // Handle the case where we conclude a expression which we speculatively 16390 // considered to be unevaluated is actually evaluated. 16391 class TransformToPE : public TreeTransform<TransformToPE> { 16392 typedef TreeTransform<TransformToPE> BaseTransform; 16393 16394 public: 16395 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16396 16397 // Make sure we redo semantic analysis 16398 bool AlwaysRebuild() { return true; } 16399 bool ReplacingOriginal() { return true; } 16400 16401 // We need to special-case DeclRefExprs referring to FieldDecls which 16402 // are not part of a member pointer formation; normal TreeTransforming 16403 // doesn't catch this case because of the way we represent them in the AST. 16404 // FIXME: This is a bit ugly; is it really the best way to handle this 16405 // case? 16406 // 16407 // Error on DeclRefExprs referring to FieldDecls. 16408 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16409 if (isa<FieldDecl>(E->getDecl()) && 16410 !SemaRef.isUnevaluatedContext()) 16411 return SemaRef.Diag(E->getLocation(), 16412 diag::err_invalid_non_static_member_use) 16413 << E->getDecl() << E->getSourceRange(); 16414 16415 return BaseTransform::TransformDeclRefExpr(E); 16416 } 16417 16418 // Exception: filter out member pointer formation 16419 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16420 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16421 return E; 16422 16423 return BaseTransform::TransformUnaryOperator(E); 16424 } 16425 16426 // The body of a lambda-expression is in a separate expression evaluation 16427 // context so never needs to be transformed. 16428 // FIXME: Ideally we wouldn't transform the closure type either, and would 16429 // just recreate the capture expressions and lambda expression. 16430 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16431 return SkipLambdaBody(E, Body); 16432 } 16433 }; 16434 } 16435 16436 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16437 assert(isUnevaluatedContext() && 16438 "Should only transform unevaluated expressions"); 16439 ExprEvalContexts.back().Context = 16440 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16441 if (isUnevaluatedContext()) 16442 return E; 16443 return TransformToPE(*this).TransformExpr(E); 16444 } 16445 16446 void 16447 Sema::PushExpressionEvaluationContext( 16448 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16449 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16450 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16451 LambdaContextDecl, ExprContext); 16452 Cleanup.reset(); 16453 if (!MaybeODRUseExprs.empty()) 16454 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16455 } 16456 16457 void 16458 Sema::PushExpressionEvaluationContext( 16459 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16460 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16461 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16462 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16463 } 16464 16465 namespace { 16466 16467 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16468 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16469 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16470 if (E->getOpcode() == UO_Deref) 16471 return CheckPossibleDeref(S, E->getSubExpr()); 16472 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16473 return CheckPossibleDeref(S, E->getBase()); 16474 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16475 return CheckPossibleDeref(S, E->getBase()); 16476 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16477 QualType Inner; 16478 QualType Ty = E->getType(); 16479 if (const auto *Ptr = Ty->getAs<PointerType>()) 16480 Inner = Ptr->getPointeeType(); 16481 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16482 Inner = Arr->getElementType(); 16483 else 16484 return nullptr; 16485 16486 if (Inner->hasAttr(attr::NoDeref)) 16487 return E; 16488 } 16489 return nullptr; 16490 } 16491 16492 } // namespace 16493 16494 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16495 for (const Expr *E : Rec.PossibleDerefs) { 16496 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16497 if (DeclRef) { 16498 const ValueDecl *Decl = DeclRef->getDecl(); 16499 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16500 << Decl->getName() << E->getSourceRange(); 16501 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16502 } else { 16503 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16504 << E->getSourceRange(); 16505 } 16506 } 16507 Rec.PossibleDerefs.clear(); 16508 } 16509 16510 /// Check whether E, which is either a discarded-value expression or an 16511 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16512 /// and if so, remove it from the list of volatile-qualified assignments that 16513 /// we are going to warn are deprecated. 16514 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16515 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16516 return; 16517 16518 // Note: ignoring parens here is not justified by the standard rules, but 16519 // ignoring parentheses seems like a more reasonable approach, and this only 16520 // drives a deprecation warning so doesn't affect conformance. 16521 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16522 if (BO->getOpcode() == BO_Assign) { 16523 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16524 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16525 LHSs.end()); 16526 } 16527 } 16528 } 16529 16530 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16531 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16532 RebuildingImmediateInvocation) 16533 return E; 16534 16535 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16536 /// It's OK if this fails; we'll also remove this in 16537 /// HandleImmediateInvocations, but catching it here allows us to avoid 16538 /// walking the AST looking for it in simple cases. 16539 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16540 if (auto *DeclRef = 16541 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16542 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16543 16544 E = MaybeCreateExprWithCleanups(E); 16545 16546 ConstantExpr *Res = ConstantExpr::Create( 16547 getASTContext(), E.get(), 16548 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16549 getASTContext()), 16550 /*IsImmediateInvocation*/ true); 16551 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16552 return Res; 16553 } 16554 16555 static void EvaluateAndDiagnoseImmediateInvocation( 16556 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16557 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16558 Expr::EvalResult Eval; 16559 Eval.Diag = &Notes; 16560 ConstantExpr *CE = Candidate.getPointer(); 16561 bool Result = CE->EvaluateAsConstantExpr( 16562 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16563 if (!Result || !Notes.empty()) { 16564 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16565 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16566 InnerExpr = FunctionalCast->getSubExpr(); 16567 FunctionDecl *FD = nullptr; 16568 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16569 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16570 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16571 FD = Call->getConstructor(); 16572 else 16573 llvm_unreachable("unhandled decl kind"); 16574 assert(FD->isConsteval()); 16575 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16576 for (auto &Note : Notes) 16577 SemaRef.Diag(Note.first, Note.second); 16578 return; 16579 } 16580 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16581 } 16582 16583 static void RemoveNestedImmediateInvocation( 16584 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16585 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16586 struct ComplexRemove : TreeTransform<ComplexRemove> { 16587 using Base = TreeTransform<ComplexRemove>; 16588 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16589 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16590 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16591 CurrentII; 16592 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16593 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16594 SmallVector<Sema::ImmediateInvocationCandidate, 16595 4>::reverse_iterator Current) 16596 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16597 void RemoveImmediateInvocation(ConstantExpr* E) { 16598 auto It = std::find_if(CurrentII, IISet.rend(), 16599 [E](Sema::ImmediateInvocationCandidate Elem) { 16600 return Elem.getPointer() == E; 16601 }); 16602 assert(It != IISet.rend() && 16603 "ConstantExpr marked IsImmediateInvocation should " 16604 "be present"); 16605 It->setInt(1); // Mark as deleted 16606 } 16607 ExprResult TransformConstantExpr(ConstantExpr *E) { 16608 if (!E->isImmediateInvocation()) 16609 return Base::TransformConstantExpr(E); 16610 RemoveImmediateInvocation(E); 16611 return Base::TransformExpr(E->getSubExpr()); 16612 } 16613 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16614 /// we need to remove its DeclRefExpr from the DRSet. 16615 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16616 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16617 return Base::TransformCXXOperatorCallExpr(E); 16618 } 16619 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16620 /// here. 16621 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16622 if (!Init) 16623 return Init; 16624 /// ConstantExpr are the first layer of implicit node to be removed so if 16625 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16626 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16627 if (CE->isImmediateInvocation()) 16628 RemoveImmediateInvocation(CE); 16629 return Base::TransformInitializer(Init, NotCopyInit); 16630 } 16631 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16632 DRSet.erase(E); 16633 return E; 16634 } 16635 bool AlwaysRebuild() { return false; } 16636 bool ReplacingOriginal() { return true; } 16637 bool AllowSkippingCXXConstructExpr() { 16638 bool Res = AllowSkippingFirstCXXConstructExpr; 16639 AllowSkippingFirstCXXConstructExpr = true; 16640 return Res; 16641 } 16642 bool AllowSkippingFirstCXXConstructExpr = true; 16643 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16644 Rec.ImmediateInvocationCandidates, It); 16645 16646 /// CXXConstructExpr with a single argument are getting skipped by 16647 /// TreeTransform in some situtation because they could be implicit. This 16648 /// can only occur for the top-level CXXConstructExpr because it is used 16649 /// nowhere in the expression being transformed therefore will not be rebuilt. 16650 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16651 /// skipping the first CXXConstructExpr. 16652 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16653 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16654 16655 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16656 assert(Res.isUsable()); 16657 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16658 It->getPointer()->setSubExpr(Res.get()); 16659 } 16660 16661 static void 16662 HandleImmediateInvocations(Sema &SemaRef, 16663 Sema::ExpressionEvaluationContextRecord &Rec) { 16664 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16665 Rec.ReferenceToConsteval.size() == 0) || 16666 SemaRef.RebuildingImmediateInvocation) 16667 return; 16668 16669 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16670 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16671 /// need to remove ReferenceToConsteval in the immediate invocation. 16672 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16673 16674 /// Prevent sema calls during the tree transform from adding pointers that 16675 /// are already in the sets. 16676 llvm::SaveAndRestore<bool> DisableIITracking( 16677 SemaRef.RebuildingImmediateInvocation, true); 16678 16679 /// Prevent diagnostic during tree transfrom as they are duplicates 16680 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16681 16682 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16683 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16684 if (!It->getInt()) 16685 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16686 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16687 Rec.ReferenceToConsteval.size()) { 16688 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16689 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16690 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16691 bool VisitDeclRefExpr(DeclRefExpr *E) { 16692 DRSet.erase(E); 16693 return DRSet.size(); 16694 } 16695 } Visitor(Rec.ReferenceToConsteval); 16696 Visitor.TraverseStmt( 16697 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16698 } 16699 for (auto CE : Rec.ImmediateInvocationCandidates) 16700 if (!CE.getInt()) 16701 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16702 for (auto DR : Rec.ReferenceToConsteval) { 16703 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16704 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16705 << FD; 16706 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16707 } 16708 } 16709 16710 void Sema::PopExpressionEvaluationContext() { 16711 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16712 unsigned NumTypos = Rec.NumTypos; 16713 16714 if (!Rec.Lambdas.empty()) { 16715 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16716 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16717 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16718 unsigned D; 16719 if (Rec.isUnevaluated()) { 16720 // C++11 [expr.prim.lambda]p2: 16721 // A lambda-expression shall not appear in an unevaluated operand 16722 // (Clause 5). 16723 D = diag::err_lambda_unevaluated_operand; 16724 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16725 // C++1y [expr.const]p2: 16726 // A conditional-expression e is a core constant expression unless the 16727 // evaluation of e, following the rules of the abstract machine, would 16728 // evaluate [...] a lambda-expression. 16729 D = diag::err_lambda_in_constant_expression; 16730 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16731 // C++17 [expr.prim.lamda]p2: 16732 // A lambda-expression shall not appear [...] in a template-argument. 16733 D = diag::err_lambda_in_invalid_context; 16734 } else 16735 llvm_unreachable("Couldn't infer lambda error message."); 16736 16737 for (const auto *L : Rec.Lambdas) 16738 Diag(L->getBeginLoc(), D); 16739 } 16740 } 16741 16742 WarnOnPendingNoDerefs(Rec); 16743 HandleImmediateInvocations(*this, Rec); 16744 16745 // Warn on any volatile-qualified simple-assignments that are not discarded- 16746 // value expressions nor unevaluated operands (those cases get removed from 16747 // this list by CheckUnusedVolatileAssignment). 16748 for (auto *BO : Rec.VolatileAssignmentLHSs) 16749 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16750 << BO->getType(); 16751 16752 // When are coming out of an unevaluated context, clear out any 16753 // temporaries that we may have created as part of the evaluation of 16754 // the expression in that context: they aren't relevant because they 16755 // will never be constructed. 16756 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16757 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16758 ExprCleanupObjects.end()); 16759 Cleanup = Rec.ParentCleanup; 16760 CleanupVarDeclMarking(); 16761 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16762 // Otherwise, merge the contexts together. 16763 } else { 16764 Cleanup.mergeFrom(Rec.ParentCleanup); 16765 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16766 Rec.SavedMaybeODRUseExprs.end()); 16767 } 16768 16769 // Pop the current expression evaluation context off the stack. 16770 ExprEvalContexts.pop_back(); 16771 16772 // The global expression evaluation context record is never popped. 16773 ExprEvalContexts.back().NumTypos += NumTypos; 16774 } 16775 16776 void Sema::DiscardCleanupsInEvaluationContext() { 16777 ExprCleanupObjects.erase( 16778 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16779 ExprCleanupObjects.end()); 16780 Cleanup.reset(); 16781 MaybeODRUseExprs.clear(); 16782 } 16783 16784 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16785 ExprResult Result = CheckPlaceholderExpr(E); 16786 if (Result.isInvalid()) 16787 return ExprError(); 16788 E = Result.get(); 16789 if (!E->getType()->isVariablyModifiedType()) 16790 return E; 16791 return TransformToPotentiallyEvaluated(E); 16792 } 16793 16794 /// Are we in a context that is potentially constant evaluated per C++20 16795 /// [expr.const]p12? 16796 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16797 /// C++2a [expr.const]p12: 16798 // An expression or conversion is potentially constant evaluated if it is 16799 switch (SemaRef.ExprEvalContexts.back().Context) { 16800 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16801 // -- a manifestly constant-evaluated expression, 16802 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16803 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16804 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16805 // -- a potentially-evaluated expression, 16806 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16807 // -- an immediate subexpression of a braced-init-list, 16808 16809 // -- [FIXME] an expression of the form & cast-expression that occurs 16810 // within a templated entity 16811 // -- a subexpression of one of the above that is not a subexpression of 16812 // a nested unevaluated operand. 16813 return true; 16814 16815 case Sema::ExpressionEvaluationContext::Unevaluated: 16816 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16817 // Expressions in this context are never evaluated. 16818 return false; 16819 } 16820 llvm_unreachable("Invalid context"); 16821 } 16822 16823 /// Return true if this function has a calling convention that requires mangling 16824 /// in the size of the parameter pack. 16825 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16826 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16827 // we don't need parameter type sizes. 16828 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16829 if (!TT.isOSWindows() || !TT.isX86()) 16830 return false; 16831 16832 // If this is C++ and this isn't an extern "C" function, parameters do not 16833 // need to be complete. In this case, C++ mangling will apply, which doesn't 16834 // use the size of the parameters. 16835 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16836 return false; 16837 16838 // Stdcall, fastcall, and vectorcall need this special treatment. 16839 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16840 switch (CC) { 16841 case CC_X86StdCall: 16842 case CC_X86FastCall: 16843 case CC_X86VectorCall: 16844 return true; 16845 default: 16846 break; 16847 } 16848 return false; 16849 } 16850 16851 /// Require that all of the parameter types of function be complete. Normally, 16852 /// parameter types are only required to be complete when a function is called 16853 /// or defined, but to mangle functions with certain calling conventions, the 16854 /// mangler needs to know the size of the parameter list. In this situation, 16855 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16856 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16857 /// result in a linker error. Clang doesn't implement this behavior, and instead 16858 /// attempts to error at compile time. 16859 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16860 SourceLocation Loc) { 16861 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16862 FunctionDecl *FD; 16863 ParmVarDecl *Param; 16864 16865 public: 16866 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16867 : FD(FD), Param(Param) {} 16868 16869 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16870 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16871 StringRef CCName; 16872 switch (CC) { 16873 case CC_X86StdCall: 16874 CCName = "stdcall"; 16875 break; 16876 case CC_X86FastCall: 16877 CCName = "fastcall"; 16878 break; 16879 case CC_X86VectorCall: 16880 CCName = "vectorcall"; 16881 break; 16882 default: 16883 llvm_unreachable("CC does not need mangling"); 16884 } 16885 16886 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16887 << Param->getDeclName() << FD->getDeclName() << CCName; 16888 } 16889 }; 16890 16891 for (ParmVarDecl *Param : FD->parameters()) { 16892 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16893 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16894 } 16895 } 16896 16897 namespace { 16898 enum class OdrUseContext { 16899 /// Declarations in this context are not odr-used. 16900 None, 16901 /// Declarations in this context are formally odr-used, but this is a 16902 /// dependent context. 16903 Dependent, 16904 /// Declarations in this context are odr-used but not actually used (yet). 16905 FormallyOdrUsed, 16906 /// Declarations in this context are used. 16907 Used 16908 }; 16909 } 16910 16911 /// Are we within a context in which references to resolved functions or to 16912 /// variables result in odr-use? 16913 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16914 OdrUseContext Result; 16915 16916 switch (SemaRef.ExprEvalContexts.back().Context) { 16917 case Sema::ExpressionEvaluationContext::Unevaluated: 16918 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16919 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16920 return OdrUseContext::None; 16921 16922 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16923 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16924 Result = OdrUseContext::Used; 16925 break; 16926 16927 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16928 Result = OdrUseContext::FormallyOdrUsed; 16929 break; 16930 16931 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16932 // A default argument formally results in odr-use, but doesn't actually 16933 // result in a use in any real sense until it itself is used. 16934 Result = OdrUseContext::FormallyOdrUsed; 16935 break; 16936 } 16937 16938 if (SemaRef.CurContext->isDependentContext()) 16939 return OdrUseContext::Dependent; 16940 16941 return Result; 16942 } 16943 16944 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16945 if (!Func->isConstexpr()) 16946 return false; 16947 16948 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16949 return true; 16950 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16951 return CCD && CCD->getInheritedConstructor(); 16952 } 16953 16954 /// Mark a function referenced, and check whether it is odr-used 16955 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16956 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16957 bool MightBeOdrUse) { 16958 assert(Func && "No function?"); 16959 16960 Func->setReferenced(); 16961 16962 // Recursive functions aren't really used until they're used from some other 16963 // context. 16964 bool IsRecursiveCall = CurContext == Func; 16965 16966 // C++11 [basic.def.odr]p3: 16967 // A function whose name appears as a potentially-evaluated expression is 16968 // odr-used if it is the unique lookup result or the selected member of a 16969 // set of overloaded functions [...]. 16970 // 16971 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16972 // can just check that here. 16973 OdrUseContext OdrUse = 16974 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16975 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16976 OdrUse = OdrUseContext::FormallyOdrUsed; 16977 16978 // Trivial default constructors and destructors are never actually used. 16979 // FIXME: What about other special members? 16980 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16981 OdrUse == OdrUseContext::Used) { 16982 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16983 if (Constructor->isDefaultConstructor()) 16984 OdrUse = OdrUseContext::FormallyOdrUsed; 16985 if (isa<CXXDestructorDecl>(Func)) 16986 OdrUse = OdrUseContext::FormallyOdrUsed; 16987 } 16988 16989 // C++20 [expr.const]p12: 16990 // A function [...] is needed for constant evaluation if it is [...] a 16991 // constexpr function that is named by an expression that is potentially 16992 // constant evaluated 16993 bool NeededForConstantEvaluation = 16994 isPotentiallyConstantEvaluatedContext(*this) && 16995 isImplicitlyDefinableConstexprFunction(Func); 16996 16997 // Determine whether we require a function definition to exist, per 16998 // C++11 [temp.inst]p3: 16999 // Unless a function template specialization has been explicitly 17000 // instantiated or explicitly specialized, the function template 17001 // specialization is implicitly instantiated when the specialization is 17002 // referenced in a context that requires a function definition to exist. 17003 // C++20 [temp.inst]p7: 17004 // The existence of a definition of a [...] function is considered to 17005 // affect the semantics of the program if the [...] function is needed for 17006 // constant evaluation by an expression 17007 // C++20 [basic.def.odr]p10: 17008 // Every program shall contain exactly one definition of every non-inline 17009 // function or variable that is odr-used in that program outside of a 17010 // discarded statement 17011 // C++20 [special]p1: 17012 // The implementation will implicitly define [defaulted special members] 17013 // if they are odr-used or needed for constant evaluation. 17014 // 17015 // Note that we skip the implicit instantiation of templates that are only 17016 // used in unused default arguments or by recursive calls to themselves. 17017 // This is formally non-conforming, but seems reasonable in practice. 17018 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17019 NeededForConstantEvaluation); 17020 17021 // C++14 [temp.expl.spec]p6: 17022 // If a template [...] is explicitly specialized then that specialization 17023 // shall be declared before the first use of that specialization that would 17024 // cause an implicit instantiation to take place, in every translation unit 17025 // in which such a use occurs 17026 if (NeedDefinition && 17027 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17028 Func->getMemberSpecializationInfo())) 17029 checkSpecializationVisibility(Loc, Func); 17030 17031 if (getLangOpts().CUDA) 17032 CheckCUDACall(Loc, Func); 17033 17034 if (getLangOpts().SYCLIsDevice) 17035 checkSYCLDeviceFunction(Loc, Func); 17036 17037 // If we need a definition, try to create one. 17038 if (NeedDefinition && !Func->getBody()) { 17039 runWithSufficientStackSpace(Loc, [&] { 17040 if (CXXConstructorDecl *Constructor = 17041 dyn_cast<CXXConstructorDecl>(Func)) { 17042 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17043 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17044 if (Constructor->isDefaultConstructor()) { 17045 if (Constructor->isTrivial() && 17046 !Constructor->hasAttr<DLLExportAttr>()) 17047 return; 17048 DefineImplicitDefaultConstructor(Loc, Constructor); 17049 } else if (Constructor->isCopyConstructor()) { 17050 DefineImplicitCopyConstructor(Loc, Constructor); 17051 } else if (Constructor->isMoveConstructor()) { 17052 DefineImplicitMoveConstructor(Loc, Constructor); 17053 } 17054 } else if (Constructor->getInheritedConstructor()) { 17055 DefineInheritingConstructor(Loc, Constructor); 17056 } 17057 } else if (CXXDestructorDecl *Destructor = 17058 dyn_cast<CXXDestructorDecl>(Func)) { 17059 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17060 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17061 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17062 return; 17063 DefineImplicitDestructor(Loc, Destructor); 17064 } 17065 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17066 MarkVTableUsed(Loc, Destructor->getParent()); 17067 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17068 if (MethodDecl->isOverloadedOperator() && 17069 MethodDecl->getOverloadedOperator() == OO_Equal) { 17070 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17071 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17072 if (MethodDecl->isCopyAssignmentOperator()) 17073 DefineImplicitCopyAssignment(Loc, MethodDecl); 17074 else if (MethodDecl->isMoveAssignmentOperator()) 17075 DefineImplicitMoveAssignment(Loc, MethodDecl); 17076 } 17077 } else if (isa<CXXConversionDecl>(MethodDecl) && 17078 MethodDecl->getParent()->isLambda()) { 17079 CXXConversionDecl *Conversion = 17080 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17081 if (Conversion->isLambdaToBlockPointerConversion()) 17082 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17083 else 17084 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17085 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17086 MarkVTableUsed(Loc, MethodDecl->getParent()); 17087 } 17088 17089 if (Func->isDefaulted() && !Func->isDeleted()) { 17090 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17091 if (DCK != DefaultedComparisonKind::None) 17092 DefineDefaultedComparison(Loc, Func, DCK); 17093 } 17094 17095 // Implicit instantiation of function templates and member functions of 17096 // class templates. 17097 if (Func->isImplicitlyInstantiable()) { 17098 TemplateSpecializationKind TSK = 17099 Func->getTemplateSpecializationKindForInstantiation(); 17100 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17101 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17102 if (FirstInstantiation) { 17103 PointOfInstantiation = Loc; 17104 if (auto *MSI = Func->getMemberSpecializationInfo()) 17105 MSI->setPointOfInstantiation(Loc); 17106 // FIXME: Notify listener. 17107 else 17108 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17109 } else if (TSK != TSK_ImplicitInstantiation) { 17110 // Use the point of use as the point of instantiation, instead of the 17111 // point of explicit instantiation (which we track as the actual point 17112 // of instantiation). This gives better backtraces in diagnostics. 17113 PointOfInstantiation = Loc; 17114 } 17115 17116 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17117 Func->isConstexpr()) { 17118 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17119 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17120 CodeSynthesisContexts.size()) 17121 PendingLocalImplicitInstantiations.push_back( 17122 std::make_pair(Func, PointOfInstantiation)); 17123 else if (Func->isConstexpr()) 17124 // Do not defer instantiations of constexpr functions, to avoid the 17125 // expression evaluator needing to call back into Sema if it sees a 17126 // call to such a function. 17127 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17128 else { 17129 Func->setInstantiationIsPending(true); 17130 PendingInstantiations.push_back( 17131 std::make_pair(Func, PointOfInstantiation)); 17132 // Notify the consumer that a function was implicitly instantiated. 17133 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17134 } 17135 } 17136 } else { 17137 // Walk redefinitions, as some of them may be instantiable. 17138 for (auto i : Func->redecls()) { 17139 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17140 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17141 } 17142 } 17143 }); 17144 } 17145 17146 // C++14 [except.spec]p17: 17147 // An exception-specification is considered to be needed when: 17148 // - the function is odr-used or, if it appears in an unevaluated operand, 17149 // would be odr-used if the expression were potentially-evaluated; 17150 // 17151 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17152 // function is a pure virtual function we're calling, and in that case the 17153 // function was selected by overload resolution and we need to resolve its 17154 // exception specification for a different reason. 17155 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17156 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17157 ResolveExceptionSpec(Loc, FPT); 17158 17159 // If this is the first "real" use, act on that. 17160 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17161 // Keep track of used but undefined functions. 17162 if (!Func->isDefined()) { 17163 if (mightHaveNonExternalLinkage(Func)) 17164 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17165 else if (Func->getMostRecentDecl()->isInlined() && 17166 !LangOpts.GNUInline && 17167 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17168 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17169 else if (isExternalWithNoLinkageType(Func)) 17170 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17171 } 17172 17173 // Some x86 Windows calling conventions mangle the size of the parameter 17174 // pack into the name. Computing the size of the parameters requires the 17175 // parameter types to be complete. Check that now. 17176 if (funcHasParameterSizeMangling(*this, Func)) 17177 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17178 17179 // In the MS C++ ABI, the compiler emits destructor variants where they are 17180 // used. If the destructor is used here but defined elsewhere, mark the 17181 // virtual base destructors referenced. If those virtual base destructors 17182 // are inline, this will ensure they are defined when emitting the complete 17183 // destructor variant. This checking may be redundant if the destructor is 17184 // provided later in this TU. 17185 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17186 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17187 CXXRecordDecl *Parent = Dtor->getParent(); 17188 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17189 CheckCompleteDestructorVariant(Loc, Dtor); 17190 } 17191 } 17192 17193 Func->markUsed(Context); 17194 } 17195 } 17196 17197 /// Directly mark a variable odr-used. Given a choice, prefer to use 17198 /// MarkVariableReferenced since it does additional checks and then 17199 /// calls MarkVarDeclODRUsed. 17200 /// If the variable must be captured: 17201 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17202 /// - else capture it in the DeclContext that maps to the 17203 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17204 static void 17205 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17206 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17207 // Keep track of used but undefined variables. 17208 // FIXME: We shouldn't suppress this warning for static data members. 17209 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17210 (!Var->isExternallyVisible() || Var->isInline() || 17211 SemaRef.isExternalWithNoLinkageType(Var)) && 17212 !(Var->isStaticDataMember() && Var->hasInit())) { 17213 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17214 if (old.isInvalid()) 17215 old = Loc; 17216 } 17217 QualType CaptureType, DeclRefType; 17218 if (SemaRef.LangOpts.OpenMP) 17219 SemaRef.tryCaptureOpenMPLambdas(Var); 17220 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17221 /*EllipsisLoc*/ SourceLocation(), 17222 /*BuildAndDiagnose*/ true, 17223 CaptureType, DeclRefType, 17224 FunctionScopeIndexToStopAt); 17225 17226 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17227 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17228 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17229 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17230 if (VarTarget == Sema::CVT_Host && 17231 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17232 UserTarget == Sema::CFT_Global)) { 17233 // Diagnose ODR-use of host global variables in device functions. 17234 // Reference of device global variables in host functions is allowed 17235 // through shadow variables therefore it is not diagnosed. 17236 if (SemaRef.LangOpts.CUDAIsDevice) { 17237 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17238 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17239 SemaRef.targetDiag(Var->getLocation(), 17240 Var->getType().isConstQualified() 17241 ? diag::note_cuda_const_var_unpromoted 17242 : diag::note_cuda_host_var); 17243 } 17244 } else if (VarTarget == Sema::CVT_Device && 17245 (UserTarget == Sema::CFT_Host || 17246 UserTarget == Sema::CFT_HostDevice) && 17247 !Var->hasExternalStorage()) { 17248 // Record a CUDA/HIP device side variable if it is ODR-used 17249 // by host code. This is done conservatively, when the variable is 17250 // referenced in any of the following contexts: 17251 // - a non-function context 17252 // - a host function 17253 // - a host device function 17254 // This makes the ODR-use of the device side variable by host code to 17255 // be visible in the device compilation for the compiler to be able to 17256 // emit template variables instantiated by host code only and to 17257 // externalize the static device side variable ODR-used by host code. 17258 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17259 } 17260 } 17261 17262 Var->markUsed(SemaRef.Context); 17263 } 17264 17265 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17266 SourceLocation Loc, 17267 unsigned CapturingScopeIndex) { 17268 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17269 } 17270 17271 static void 17272 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17273 ValueDecl *var, DeclContext *DC) { 17274 DeclContext *VarDC = var->getDeclContext(); 17275 17276 // If the parameter still belongs to the translation unit, then 17277 // we're actually just using one parameter in the declaration of 17278 // the next. 17279 if (isa<ParmVarDecl>(var) && 17280 isa<TranslationUnitDecl>(VarDC)) 17281 return; 17282 17283 // For C code, don't diagnose about capture if we're not actually in code 17284 // right now; it's impossible to write a non-constant expression outside of 17285 // function context, so we'll get other (more useful) diagnostics later. 17286 // 17287 // For C++, things get a bit more nasty... it would be nice to suppress this 17288 // diagnostic for certain cases like using a local variable in an array bound 17289 // for a member of a local class, but the correct predicate is not obvious. 17290 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17291 return; 17292 17293 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17294 unsigned ContextKind = 3; // unknown 17295 if (isa<CXXMethodDecl>(VarDC) && 17296 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17297 ContextKind = 2; 17298 } else if (isa<FunctionDecl>(VarDC)) { 17299 ContextKind = 0; 17300 } else if (isa<BlockDecl>(VarDC)) { 17301 ContextKind = 1; 17302 } 17303 17304 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17305 << var << ValueKind << ContextKind << VarDC; 17306 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17307 << var; 17308 17309 // FIXME: Add additional diagnostic info about class etc. which prevents 17310 // capture. 17311 } 17312 17313 17314 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17315 bool &SubCapturesAreNested, 17316 QualType &CaptureType, 17317 QualType &DeclRefType) { 17318 // Check whether we've already captured it. 17319 if (CSI->CaptureMap.count(Var)) { 17320 // If we found a capture, any subcaptures are nested. 17321 SubCapturesAreNested = true; 17322 17323 // Retrieve the capture type for this variable. 17324 CaptureType = CSI->getCapture(Var).getCaptureType(); 17325 17326 // Compute the type of an expression that refers to this variable. 17327 DeclRefType = CaptureType.getNonReferenceType(); 17328 17329 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17330 // are mutable in the sense that user can change their value - they are 17331 // private instances of the captured declarations. 17332 const Capture &Cap = CSI->getCapture(Var); 17333 if (Cap.isCopyCapture() && 17334 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17335 !(isa<CapturedRegionScopeInfo>(CSI) && 17336 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17337 DeclRefType.addConst(); 17338 return true; 17339 } 17340 return false; 17341 } 17342 17343 // Only block literals, captured statements, and lambda expressions can 17344 // capture; other scopes don't work. 17345 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17346 SourceLocation Loc, 17347 const bool Diagnose, Sema &S) { 17348 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17349 return getLambdaAwareParentOfDeclContext(DC); 17350 else if (Var->hasLocalStorage()) { 17351 if (Diagnose) 17352 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17353 } 17354 return nullptr; 17355 } 17356 17357 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17358 // certain types of variables (unnamed, variably modified types etc.) 17359 // so check for eligibility. 17360 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17361 SourceLocation Loc, 17362 const bool Diagnose, Sema &S) { 17363 17364 bool IsBlock = isa<BlockScopeInfo>(CSI); 17365 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17366 17367 // Lambdas are not allowed to capture unnamed variables 17368 // (e.g. anonymous unions). 17369 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17370 // assuming that's the intent. 17371 if (IsLambda && !Var->getDeclName()) { 17372 if (Diagnose) { 17373 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17374 S.Diag(Var->getLocation(), diag::note_declared_at); 17375 } 17376 return false; 17377 } 17378 17379 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17380 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17381 if (Diagnose) { 17382 S.Diag(Loc, diag::err_ref_vm_type); 17383 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17384 } 17385 return false; 17386 } 17387 // Prohibit structs with flexible array members too. 17388 // We cannot capture what is in the tail end of the struct. 17389 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17390 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17391 if (Diagnose) { 17392 if (IsBlock) 17393 S.Diag(Loc, diag::err_ref_flexarray_type); 17394 else 17395 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17396 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17397 } 17398 return false; 17399 } 17400 } 17401 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17402 // Lambdas and captured statements are not allowed to capture __block 17403 // variables; they don't support the expected semantics. 17404 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17405 if (Diagnose) { 17406 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17407 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17408 } 17409 return false; 17410 } 17411 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17412 if (S.getLangOpts().OpenCL && IsBlock && 17413 Var->getType()->isBlockPointerType()) { 17414 if (Diagnose) 17415 S.Diag(Loc, diag::err_opencl_block_ref_block); 17416 return false; 17417 } 17418 17419 return true; 17420 } 17421 17422 // Returns true if the capture by block was successful. 17423 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17424 SourceLocation Loc, 17425 const bool BuildAndDiagnose, 17426 QualType &CaptureType, 17427 QualType &DeclRefType, 17428 const bool Nested, 17429 Sema &S, bool Invalid) { 17430 bool ByRef = false; 17431 17432 // Blocks are not allowed to capture arrays, excepting OpenCL. 17433 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17434 // (decayed to pointers). 17435 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17436 if (BuildAndDiagnose) { 17437 S.Diag(Loc, diag::err_ref_array_type); 17438 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17439 Invalid = true; 17440 } else { 17441 return false; 17442 } 17443 } 17444 17445 // Forbid the block-capture of autoreleasing variables. 17446 if (!Invalid && 17447 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17448 if (BuildAndDiagnose) { 17449 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17450 << /*block*/ 0; 17451 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17452 Invalid = true; 17453 } else { 17454 return false; 17455 } 17456 } 17457 17458 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17459 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17460 QualType PointeeTy = PT->getPointeeType(); 17461 17462 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17463 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17464 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17465 if (BuildAndDiagnose) { 17466 SourceLocation VarLoc = Var->getLocation(); 17467 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17468 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17469 } 17470 } 17471 } 17472 17473 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17474 if (HasBlocksAttr || CaptureType->isReferenceType() || 17475 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17476 // Block capture by reference does not change the capture or 17477 // declaration reference types. 17478 ByRef = true; 17479 } else { 17480 // Block capture by copy introduces 'const'. 17481 CaptureType = CaptureType.getNonReferenceType().withConst(); 17482 DeclRefType = CaptureType; 17483 } 17484 17485 // Actually capture the variable. 17486 if (BuildAndDiagnose) 17487 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17488 CaptureType, Invalid); 17489 17490 return !Invalid; 17491 } 17492 17493 17494 /// Capture the given variable in the captured region. 17495 static bool captureInCapturedRegion( 17496 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17497 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17498 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17499 bool IsTopScope, Sema &S, bool Invalid) { 17500 // By default, capture variables by reference. 17501 bool ByRef = true; 17502 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17503 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17504 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17505 // Using an LValue reference type is consistent with Lambdas (see below). 17506 if (S.isOpenMPCapturedDecl(Var)) { 17507 bool HasConst = DeclRefType.isConstQualified(); 17508 DeclRefType = DeclRefType.getUnqualifiedType(); 17509 // Don't lose diagnostics about assignments to const. 17510 if (HasConst) 17511 DeclRefType.addConst(); 17512 } 17513 // Do not capture firstprivates in tasks. 17514 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17515 OMPC_unknown) 17516 return true; 17517 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17518 RSI->OpenMPCaptureLevel); 17519 } 17520 17521 if (ByRef) 17522 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17523 else 17524 CaptureType = DeclRefType; 17525 17526 // Actually capture the variable. 17527 if (BuildAndDiagnose) 17528 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17529 Loc, SourceLocation(), CaptureType, Invalid); 17530 17531 return !Invalid; 17532 } 17533 17534 /// Capture the given variable in the lambda. 17535 static bool captureInLambda(LambdaScopeInfo *LSI, 17536 VarDecl *Var, 17537 SourceLocation Loc, 17538 const bool BuildAndDiagnose, 17539 QualType &CaptureType, 17540 QualType &DeclRefType, 17541 const bool RefersToCapturedVariable, 17542 const Sema::TryCaptureKind Kind, 17543 SourceLocation EllipsisLoc, 17544 const bool IsTopScope, 17545 Sema &S, bool Invalid) { 17546 // Determine whether we are capturing by reference or by value. 17547 bool ByRef = false; 17548 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17549 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17550 } else { 17551 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17552 } 17553 17554 // Compute the type of the field that will capture this variable. 17555 if (ByRef) { 17556 // C++11 [expr.prim.lambda]p15: 17557 // An entity is captured by reference if it is implicitly or 17558 // explicitly captured but not captured by copy. It is 17559 // unspecified whether additional unnamed non-static data 17560 // members are declared in the closure type for entities 17561 // captured by reference. 17562 // 17563 // FIXME: It is not clear whether we want to build an lvalue reference 17564 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17565 // to do the former, while EDG does the latter. Core issue 1249 will 17566 // clarify, but for now we follow GCC because it's a more permissive and 17567 // easily defensible position. 17568 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17569 } else { 17570 // C++11 [expr.prim.lambda]p14: 17571 // For each entity captured by copy, an unnamed non-static 17572 // data member is declared in the closure type. The 17573 // declaration order of these members is unspecified. The type 17574 // of such a data member is the type of the corresponding 17575 // captured entity if the entity is not a reference to an 17576 // object, or the referenced type otherwise. [Note: If the 17577 // captured entity is a reference to a function, the 17578 // corresponding data member is also a reference to a 17579 // function. - end note ] 17580 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17581 if (!RefType->getPointeeType()->isFunctionType()) 17582 CaptureType = RefType->getPointeeType(); 17583 } 17584 17585 // Forbid the lambda copy-capture of autoreleasing variables. 17586 if (!Invalid && 17587 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17588 if (BuildAndDiagnose) { 17589 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17590 S.Diag(Var->getLocation(), diag::note_previous_decl) 17591 << Var->getDeclName(); 17592 Invalid = true; 17593 } else { 17594 return false; 17595 } 17596 } 17597 17598 // Make sure that by-copy captures are of a complete and non-abstract type. 17599 if (!Invalid && BuildAndDiagnose) { 17600 if (!CaptureType->isDependentType() && 17601 S.RequireCompleteSizedType( 17602 Loc, CaptureType, 17603 diag::err_capture_of_incomplete_or_sizeless_type, 17604 Var->getDeclName())) 17605 Invalid = true; 17606 else if (S.RequireNonAbstractType(Loc, CaptureType, 17607 diag::err_capture_of_abstract_type)) 17608 Invalid = true; 17609 } 17610 } 17611 17612 // Compute the type of a reference to this captured variable. 17613 if (ByRef) 17614 DeclRefType = CaptureType.getNonReferenceType(); 17615 else { 17616 // C++ [expr.prim.lambda]p5: 17617 // The closure type for a lambda-expression has a public inline 17618 // function call operator [...]. This function call operator is 17619 // declared const (9.3.1) if and only if the lambda-expression's 17620 // parameter-declaration-clause is not followed by mutable. 17621 DeclRefType = CaptureType.getNonReferenceType(); 17622 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17623 DeclRefType.addConst(); 17624 } 17625 17626 // Add the capture. 17627 if (BuildAndDiagnose) 17628 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17629 Loc, EllipsisLoc, CaptureType, Invalid); 17630 17631 return !Invalid; 17632 } 17633 17634 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17635 // Offer a Copy fix even if the type is dependent. 17636 if (Var->getType()->isDependentType()) 17637 return true; 17638 QualType T = Var->getType().getNonReferenceType(); 17639 if (T.isTriviallyCopyableType(Context)) 17640 return true; 17641 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17642 17643 if (!(RD = RD->getDefinition())) 17644 return false; 17645 if (RD->hasSimpleCopyConstructor()) 17646 return true; 17647 if (RD->hasUserDeclaredCopyConstructor()) 17648 for (CXXConstructorDecl *Ctor : RD->ctors()) 17649 if (Ctor->isCopyConstructor()) 17650 return !Ctor->isDeleted(); 17651 } 17652 return false; 17653 } 17654 17655 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17656 /// default capture. Fixes may be omitted if they aren't allowed by the 17657 /// standard, for example we can't emit a default copy capture fix-it if we 17658 /// already explicitly copy capture capture another variable. 17659 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17660 VarDecl *Var) { 17661 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17662 // Don't offer Capture by copy of default capture by copy fixes if Var is 17663 // known not to be copy constructible. 17664 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17665 17666 SmallString<32> FixBuffer; 17667 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17668 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17669 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17670 if (ShouldOfferCopyFix) { 17671 // Offer fixes to insert an explicit capture for the variable. 17672 // [] -> [VarName] 17673 // [OtherCapture] -> [OtherCapture, VarName] 17674 FixBuffer.assign({Separator, Var->getName()}); 17675 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17676 << Var << /*value*/ 0 17677 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17678 } 17679 // As above but capture by reference. 17680 FixBuffer.assign({Separator, "&", Var->getName()}); 17681 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17682 << Var << /*reference*/ 1 17683 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17684 } 17685 17686 // Only try to offer default capture if there are no captures excluding this 17687 // and init captures. 17688 // [this]: OK. 17689 // [X = Y]: OK. 17690 // [&A, &B]: Don't offer. 17691 // [A, B]: Don't offer. 17692 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17693 return !C.isThisCapture() && !C.isInitCapture(); 17694 })) 17695 return; 17696 17697 // The default capture specifiers, '=' or '&', must appear first in the 17698 // capture body. 17699 SourceLocation DefaultInsertLoc = 17700 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17701 17702 if (ShouldOfferCopyFix) { 17703 bool CanDefaultCopyCapture = true; 17704 // [=, *this] OK since c++17 17705 // [=, this] OK since c++20 17706 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17707 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17708 ? LSI->getCXXThisCapture().isCopyCapture() 17709 : false; 17710 // We can't use default capture by copy if any captures already specified 17711 // capture by copy. 17712 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17713 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17714 })) { 17715 FixBuffer.assign({"=", Separator}); 17716 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17717 << /*value*/ 0 17718 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17719 } 17720 } 17721 17722 // We can't use default capture by reference if any captures already specified 17723 // capture by reference. 17724 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17725 return !C.isInitCapture() && C.isReferenceCapture() && 17726 !C.isThisCapture(); 17727 })) { 17728 FixBuffer.assign({"&", Separator}); 17729 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17730 << /*reference*/ 1 17731 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17732 } 17733 } 17734 17735 bool Sema::tryCaptureVariable( 17736 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17737 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17738 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17739 // An init-capture is notionally from the context surrounding its 17740 // declaration, but its parent DC is the lambda class. 17741 DeclContext *VarDC = Var->getDeclContext(); 17742 if (Var->isInitCapture()) 17743 VarDC = VarDC->getParent(); 17744 17745 DeclContext *DC = CurContext; 17746 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17747 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17748 // We need to sync up the Declaration Context with the 17749 // FunctionScopeIndexToStopAt 17750 if (FunctionScopeIndexToStopAt) { 17751 unsigned FSIndex = FunctionScopes.size() - 1; 17752 while (FSIndex != MaxFunctionScopesIndex) { 17753 DC = getLambdaAwareParentOfDeclContext(DC); 17754 --FSIndex; 17755 } 17756 } 17757 17758 17759 // If the variable is declared in the current context, there is no need to 17760 // capture it. 17761 if (VarDC == DC) return true; 17762 17763 // Capture global variables if it is required to use private copy of this 17764 // variable. 17765 bool IsGlobal = !Var->hasLocalStorage(); 17766 if (IsGlobal && 17767 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17768 MaxFunctionScopesIndex))) 17769 return true; 17770 Var = Var->getCanonicalDecl(); 17771 17772 // Walk up the stack to determine whether we can capture the variable, 17773 // performing the "simple" checks that don't depend on type. We stop when 17774 // we've either hit the declared scope of the variable or find an existing 17775 // capture of that variable. We start from the innermost capturing-entity 17776 // (the DC) and ensure that all intervening capturing-entities 17777 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17778 // declcontext can either capture the variable or have already captured 17779 // the variable. 17780 CaptureType = Var->getType(); 17781 DeclRefType = CaptureType.getNonReferenceType(); 17782 bool Nested = false; 17783 bool Explicit = (Kind != TryCapture_Implicit); 17784 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17785 do { 17786 // Only block literals, captured statements, and lambda expressions can 17787 // capture; other scopes don't work. 17788 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17789 ExprLoc, 17790 BuildAndDiagnose, 17791 *this); 17792 // We need to check for the parent *first* because, if we *have* 17793 // private-captured a global variable, we need to recursively capture it in 17794 // intermediate blocks, lambdas, etc. 17795 if (!ParentDC) { 17796 if (IsGlobal) { 17797 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17798 break; 17799 } 17800 return true; 17801 } 17802 17803 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17804 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17805 17806 17807 // Check whether we've already captured it. 17808 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17809 DeclRefType)) { 17810 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17811 break; 17812 } 17813 // If we are instantiating a generic lambda call operator body, 17814 // we do not want to capture new variables. What was captured 17815 // during either a lambdas transformation or initial parsing 17816 // should be used. 17817 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17818 if (BuildAndDiagnose) { 17819 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17820 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17821 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17822 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17823 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17824 buildLambdaCaptureFixit(*this, LSI, Var); 17825 } else 17826 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17827 } 17828 return true; 17829 } 17830 17831 // Try to capture variable-length arrays types. 17832 if (Var->getType()->isVariablyModifiedType()) { 17833 // We're going to walk down into the type and look for VLA 17834 // expressions. 17835 QualType QTy = Var->getType(); 17836 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17837 QTy = PVD->getOriginalType(); 17838 captureVariablyModifiedType(Context, QTy, CSI); 17839 } 17840 17841 if (getLangOpts().OpenMP) { 17842 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17843 // OpenMP private variables should not be captured in outer scope, so 17844 // just break here. Similarly, global variables that are captured in a 17845 // target region should not be captured outside the scope of the region. 17846 if (RSI->CapRegionKind == CR_OpenMP) { 17847 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17848 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17849 // If the variable is private (i.e. not captured) and has variably 17850 // modified type, we still need to capture the type for correct 17851 // codegen in all regions, associated with the construct. Currently, 17852 // it is captured in the innermost captured region only. 17853 if (IsOpenMPPrivateDecl != OMPC_unknown && 17854 Var->getType()->isVariablyModifiedType()) { 17855 QualType QTy = Var->getType(); 17856 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17857 QTy = PVD->getOriginalType(); 17858 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17859 I < E; ++I) { 17860 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17861 FunctionScopes[FunctionScopesIndex - I]); 17862 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17863 "Wrong number of captured regions associated with the " 17864 "OpenMP construct."); 17865 captureVariablyModifiedType(Context, QTy, OuterRSI); 17866 } 17867 } 17868 bool IsTargetCap = 17869 IsOpenMPPrivateDecl != OMPC_private && 17870 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17871 RSI->OpenMPCaptureLevel); 17872 // Do not capture global if it is not privatized in outer regions. 17873 bool IsGlobalCap = 17874 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17875 RSI->OpenMPCaptureLevel); 17876 17877 // When we detect target captures we are looking from inside the 17878 // target region, therefore we need to propagate the capture from the 17879 // enclosing region. Therefore, the capture is not initially nested. 17880 if (IsTargetCap) 17881 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17882 17883 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17884 (IsGlobal && !IsGlobalCap)) { 17885 Nested = !IsTargetCap; 17886 bool HasConst = DeclRefType.isConstQualified(); 17887 DeclRefType = DeclRefType.getUnqualifiedType(); 17888 // Don't lose diagnostics about assignments to const. 17889 if (HasConst) 17890 DeclRefType.addConst(); 17891 CaptureType = Context.getLValueReferenceType(DeclRefType); 17892 break; 17893 } 17894 } 17895 } 17896 } 17897 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17898 // No capture-default, and this is not an explicit capture 17899 // so cannot capture this variable. 17900 if (BuildAndDiagnose) { 17901 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17902 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17903 auto *LSI = cast<LambdaScopeInfo>(CSI); 17904 if (LSI->Lambda) { 17905 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17906 buildLambdaCaptureFixit(*this, LSI, Var); 17907 } 17908 // FIXME: If we error out because an outer lambda can not implicitly 17909 // capture a variable that an inner lambda explicitly captures, we 17910 // should have the inner lambda do the explicit capture - because 17911 // it makes for cleaner diagnostics later. This would purely be done 17912 // so that the diagnostic does not misleadingly claim that a variable 17913 // can not be captured by a lambda implicitly even though it is captured 17914 // explicitly. Suggestion: 17915 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17916 // at the function head 17917 // - cache the StartingDeclContext - this must be a lambda 17918 // - captureInLambda in the innermost lambda the variable. 17919 } 17920 return true; 17921 } 17922 17923 FunctionScopesIndex--; 17924 DC = ParentDC; 17925 Explicit = false; 17926 } while (!VarDC->Equals(DC)); 17927 17928 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17929 // computing the type of the capture at each step, checking type-specific 17930 // requirements, and adding captures if requested. 17931 // If the variable had already been captured previously, we start capturing 17932 // at the lambda nested within that one. 17933 bool Invalid = false; 17934 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17935 ++I) { 17936 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17937 17938 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17939 // certain types of variables (unnamed, variably modified types etc.) 17940 // so check for eligibility. 17941 if (!Invalid) 17942 Invalid = 17943 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17944 17945 // After encountering an error, if we're actually supposed to capture, keep 17946 // capturing in nested contexts to suppress any follow-on diagnostics. 17947 if (Invalid && !BuildAndDiagnose) 17948 return true; 17949 17950 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17951 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17952 DeclRefType, Nested, *this, Invalid); 17953 Nested = true; 17954 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17955 Invalid = !captureInCapturedRegion( 17956 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17957 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17958 Nested = true; 17959 } else { 17960 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17961 Invalid = 17962 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17963 DeclRefType, Nested, Kind, EllipsisLoc, 17964 /*IsTopScope*/ I == N - 1, *this, Invalid); 17965 Nested = true; 17966 } 17967 17968 if (Invalid && !BuildAndDiagnose) 17969 return true; 17970 } 17971 return Invalid; 17972 } 17973 17974 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17975 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17976 QualType CaptureType; 17977 QualType DeclRefType; 17978 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17979 /*BuildAndDiagnose=*/true, CaptureType, 17980 DeclRefType, nullptr); 17981 } 17982 17983 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17984 QualType CaptureType; 17985 QualType DeclRefType; 17986 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17987 /*BuildAndDiagnose=*/false, CaptureType, 17988 DeclRefType, nullptr); 17989 } 17990 17991 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17992 QualType CaptureType; 17993 QualType DeclRefType; 17994 17995 // Determine whether we can capture this variable. 17996 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17997 /*BuildAndDiagnose=*/false, CaptureType, 17998 DeclRefType, nullptr)) 17999 return QualType(); 18000 18001 return DeclRefType; 18002 } 18003 18004 namespace { 18005 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18006 // The produced TemplateArgumentListInfo* points to data stored within this 18007 // object, so should only be used in contexts where the pointer will not be 18008 // used after the CopiedTemplateArgs object is destroyed. 18009 class CopiedTemplateArgs { 18010 bool HasArgs; 18011 TemplateArgumentListInfo TemplateArgStorage; 18012 public: 18013 template<typename RefExpr> 18014 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18015 if (HasArgs) 18016 E->copyTemplateArgumentsInto(TemplateArgStorage); 18017 } 18018 operator TemplateArgumentListInfo*() 18019 #ifdef __has_cpp_attribute 18020 #if __has_cpp_attribute(clang::lifetimebound) 18021 [[clang::lifetimebound]] 18022 #endif 18023 #endif 18024 { 18025 return HasArgs ? &TemplateArgStorage : nullptr; 18026 } 18027 }; 18028 } 18029 18030 /// Walk the set of potential results of an expression and mark them all as 18031 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18032 /// 18033 /// \return A new expression if we found any potential results, ExprEmpty() if 18034 /// not, and ExprError() if we diagnosed an error. 18035 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18036 NonOdrUseReason NOUR) { 18037 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18038 // an object that satisfies the requirements for appearing in a 18039 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18040 // is immediately applied." This function handles the lvalue-to-rvalue 18041 // conversion part. 18042 // 18043 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18044 // transform it into the relevant kind of non-odr-use node and rebuild the 18045 // tree of nodes leading to it. 18046 // 18047 // This is a mini-TreeTransform that only transforms a restricted subset of 18048 // nodes (and only certain operands of them). 18049 18050 // Rebuild a subexpression. 18051 auto Rebuild = [&](Expr *Sub) { 18052 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18053 }; 18054 18055 // Check whether a potential result satisfies the requirements of NOUR. 18056 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18057 // Any entity other than a VarDecl is always odr-used whenever it's named 18058 // in a potentially-evaluated expression. 18059 auto *VD = dyn_cast<VarDecl>(D); 18060 if (!VD) 18061 return true; 18062 18063 // C++2a [basic.def.odr]p4: 18064 // A variable x whose name appears as a potentially-evalauted expression 18065 // e is odr-used by e unless 18066 // -- x is a reference that is usable in constant expressions, or 18067 // -- x is a variable of non-reference type that is usable in constant 18068 // expressions and has no mutable subobjects, and e is an element of 18069 // the set of potential results of an expression of 18070 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18071 // conversion is applied, or 18072 // -- x is a variable of non-reference type, and e is an element of the 18073 // set of potential results of a discarded-value expression to which 18074 // the lvalue-to-rvalue conversion is not applied 18075 // 18076 // We check the first bullet and the "potentially-evaluated" condition in 18077 // BuildDeclRefExpr. We check the type requirements in the second bullet 18078 // in CheckLValueToRValueConversionOperand below. 18079 switch (NOUR) { 18080 case NOUR_None: 18081 case NOUR_Unevaluated: 18082 llvm_unreachable("unexpected non-odr-use-reason"); 18083 18084 case NOUR_Constant: 18085 // Constant references were handled when they were built. 18086 if (VD->getType()->isReferenceType()) 18087 return true; 18088 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18089 if (RD->hasMutableFields()) 18090 return true; 18091 if (!VD->isUsableInConstantExpressions(S.Context)) 18092 return true; 18093 break; 18094 18095 case NOUR_Discarded: 18096 if (VD->getType()->isReferenceType()) 18097 return true; 18098 break; 18099 } 18100 return false; 18101 }; 18102 18103 // Mark that this expression does not constitute an odr-use. 18104 auto MarkNotOdrUsed = [&] { 18105 S.MaybeODRUseExprs.remove(E); 18106 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18107 LSI->markVariableExprAsNonODRUsed(E); 18108 }; 18109 18110 // C++2a [basic.def.odr]p2: 18111 // The set of potential results of an expression e is defined as follows: 18112 switch (E->getStmtClass()) { 18113 // -- If e is an id-expression, ... 18114 case Expr::DeclRefExprClass: { 18115 auto *DRE = cast<DeclRefExpr>(E); 18116 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18117 break; 18118 18119 // Rebuild as a non-odr-use DeclRefExpr. 18120 MarkNotOdrUsed(); 18121 return DeclRefExpr::Create( 18122 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18123 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18124 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18125 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18126 } 18127 18128 case Expr::FunctionParmPackExprClass: { 18129 auto *FPPE = cast<FunctionParmPackExpr>(E); 18130 // If any of the declarations in the pack is odr-used, then the expression 18131 // as a whole constitutes an odr-use. 18132 for (VarDecl *D : *FPPE) 18133 if (IsPotentialResultOdrUsed(D)) 18134 return ExprEmpty(); 18135 18136 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18137 // nothing cares about whether we marked this as an odr-use, but it might 18138 // be useful for non-compiler tools. 18139 MarkNotOdrUsed(); 18140 break; 18141 } 18142 18143 // -- If e is a subscripting operation with an array operand... 18144 case Expr::ArraySubscriptExprClass: { 18145 auto *ASE = cast<ArraySubscriptExpr>(E); 18146 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18147 if (!OldBase->getType()->isArrayType()) 18148 break; 18149 ExprResult Base = Rebuild(OldBase); 18150 if (!Base.isUsable()) 18151 return Base; 18152 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18153 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18154 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18155 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18156 ASE->getRBracketLoc()); 18157 } 18158 18159 case Expr::MemberExprClass: { 18160 auto *ME = cast<MemberExpr>(E); 18161 // -- If e is a class member access expression [...] naming a non-static 18162 // data member... 18163 if (isa<FieldDecl>(ME->getMemberDecl())) { 18164 ExprResult Base = Rebuild(ME->getBase()); 18165 if (!Base.isUsable()) 18166 return Base; 18167 return MemberExpr::Create( 18168 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18169 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18170 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18171 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18172 ME->getObjectKind(), ME->isNonOdrUse()); 18173 } 18174 18175 if (ME->getMemberDecl()->isCXXInstanceMember()) 18176 break; 18177 18178 // -- If e is a class member access expression naming a static data member, 18179 // ... 18180 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18181 break; 18182 18183 // Rebuild as a non-odr-use MemberExpr. 18184 MarkNotOdrUsed(); 18185 return MemberExpr::Create( 18186 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18187 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18188 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18189 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18190 return ExprEmpty(); 18191 } 18192 18193 case Expr::BinaryOperatorClass: { 18194 auto *BO = cast<BinaryOperator>(E); 18195 Expr *LHS = BO->getLHS(); 18196 Expr *RHS = BO->getRHS(); 18197 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18198 if (BO->getOpcode() == BO_PtrMemD) { 18199 ExprResult Sub = Rebuild(LHS); 18200 if (!Sub.isUsable()) 18201 return Sub; 18202 LHS = Sub.get(); 18203 // -- If e is a comma expression, ... 18204 } else if (BO->getOpcode() == BO_Comma) { 18205 ExprResult Sub = Rebuild(RHS); 18206 if (!Sub.isUsable()) 18207 return Sub; 18208 RHS = Sub.get(); 18209 } else { 18210 break; 18211 } 18212 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18213 LHS, RHS); 18214 } 18215 18216 // -- If e has the form (e1)... 18217 case Expr::ParenExprClass: { 18218 auto *PE = cast<ParenExpr>(E); 18219 ExprResult Sub = Rebuild(PE->getSubExpr()); 18220 if (!Sub.isUsable()) 18221 return Sub; 18222 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18223 } 18224 18225 // -- If e is a glvalue conditional expression, ... 18226 // We don't apply this to a binary conditional operator. FIXME: Should we? 18227 case Expr::ConditionalOperatorClass: { 18228 auto *CO = cast<ConditionalOperator>(E); 18229 ExprResult LHS = Rebuild(CO->getLHS()); 18230 if (LHS.isInvalid()) 18231 return ExprError(); 18232 ExprResult RHS = Rebuild(CO->getRHS()); 18233 if (RHS.isInvalid()) 18234 return ExprError(); 18235 if (!LHS.isUsable() && !RHS.isUsable()) 18236 return ExprEmpty(); 18237 if (!LHS.isUsable()) 18238 LHS = CO->getLHS(); 18239 if (!RHS.isUsable()) 18240 RHS = CO->getRHS(); 18241 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18242 CO->getCond(), LHS.get(), RHS.get()); 18243 } 18244 18245 // [Clang extension] 18246 // -- If e has the form __extension__ e1... 18247 case Expr::UnaryOperatorClass: { 18248 auto *UO = cast<UnaryOperator>(E); 18249 if (UO->getOpcode() != UO_Extension) 18250 break; 18251 ExprResult Sub = Rebuild(UO->getSubExpr()); 18252 if (!Sub.isUsable()) 18253 return Sub; 18254 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18255 Sub.get()); 18256 } 18257 18258 // [Clang extension] 18259 // -- If e has the form _Generic(...), the set of potential results is the 18260 // union of the sets of potential results of the associated expressions. 18261 case Expr::GenericSelectionExprClass: { 18262 auto *GSE = cast<GenericSelectionExpr>(E); 18263 18264 SmallVector<Expr *, 4> AssocExprs; 18265 bool AnyChanged = false; 18266 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18267 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18268 if (AssocExpr.isInvalid()) 18269 return ExprError(); 18270 if (AssocExpr.isUsable()) { 18271 AssocExprs.push_back(AssocExpr.get()); 18272 AnyChanged = true; 18273 } else { 18274 AssocExprs.push_back(OrigAssocExpr); 18275 } 18276 } 18277 18278 return AnyChanged ? S.CreateGenericSelectionExpr( 18279 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18280 GSE->getRParenLoc(), GSE->getControllingExpr(), 18281 GSE->getAssocTypeSourceInfos(), AssocExprs) 18282 : ExprEmpty(); 18283 } 18284 18285 // [Clang extension] 18286 // -- If e has the form __builtin_choose_expr(...), the set of potential 18287 // results is the union of the sets of potential results of the 18288 // second and third subexpressions. 18289 case Expr::ChooseExprClass: { 18290 auto *CE = cast<ChooseExpr>(E); 18291 18292 ExprResult LHS = Rebuild(CE->getLHS()); 18293 if (LHS.isInvalid()) 18294 return ExprError(); 18295 18296 ExprResult RHS = Rebuild(CE->getLHS()); 18297 if (RHS.isInvalid()) 18298 return ExprError(); 18299 18300 if (!LHS.get() && !RHS.get()) 18301 return ExprEmpty(); 18302 if (!LHS.isUsable()) 18303 LHS = CE->getLHS(); 18304 if (!RHS.isUsable()) 18305 RHS = CE->getRHS(); 18306 18307 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18308 RHS.get(), CE->getRParenLoc()); 18309 } 18310 18311 // Step through non-syntactic nodes. 18312 case Expr::ConstantExprClass: { 18313 auto *CE = cast<ConstantExpr>(E); 18314 ExprResult Sub = Rebuild(CE->getSubExpr()); 18315 if (!Sub.isUsable()) 18316 return Sub; 18317 return ConstantExpr::Create(S.Context, Sub.get()); 18318 } 18319 18320 // We could mostly rely on the recursive rebuilding to rebuild implicit 18321 // casts, but not at the top level, so rebuild them here. 18322 case Expr::ImplicitCastExprClass: { 18323 auto *ICE = cast<ImplicitCastExpr>(E); 18324 // Only step through the narrow set of cast kinds we expect to encounter. 18325 // Anything else suggests we've left the region in which potential results 18326 // can be found. 18327 switch (ICE->getCastKind()) { 18328 case CK_NoOp: 18329 case CK_DerivedToBase: 18330 case CK_UncheckedDerivedToBase: { 18331 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18332 if (!Sub.isUsable()) 18333 return Sub; 18334 CXXCastPath Path(ICE->path()); 18335 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18336 ICE->getValueKind(), &Path); 18337 } 18338 18339 default: 18340 break; 18341 } 18342 break; 18343 } 18344 18345 default: 18346 break; 18347 } 18348 18349 // Can't traverse through this node. Nothing to do. 18350 return ExprEmpty(); 18351 } 18352 18353 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18354 // Check whether the operand is or contains an object of non-trivial C union 18355 // type. 18356 if (E->getType().isVolatileQualified() && 18357 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18358 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18359 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18360 Sema::NTCUC_LValueToRValueVolatile, 18361 NTCUK_Destruct|NTCUK_Copy); 18362 18363 // C++2a [basic.def.odr]p4: 18364 // [...] an expression of non-volatile-qualified non-class type to which 18365 // the lvalue-to-rvalue conversion is applied [...] 18366 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18367 return E; 18368 18369 ExprResult Result = 18370 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18371 if (Result.isInvalid()) 18372 return ExprError(); 18373 return Result.get() ? Result : E; 18374 } 18375 18376 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18377 Res = CorrectDelayedTyposInExpr(Res); 18378 18379 if (!Res.isUsable()) 18380 return Res; 18381 18382 // If a constant-expression is a reference to a variable where we delay 18383 // deciding whether it is an odr-use, just assume we will apply the 18384 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18385 // (a non-type template argument), we have special handling anyway. 18386 return CheckLValueToRValueConversionOperand(Res.get()); 18387 } 18388 18389 void Sema::CleanupVarDeclMarking() { 18390 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18391 // call. 18392 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18393 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18394 18395 for (Expr *E : LocalMaybeODRUseExprs) { 18396 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18397 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18398 DRE->getLocation(), *this); 18399 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18400 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18401 *this); 18402 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18403 for (VarDecl *VD : *FP) 18404 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18405 } else { 18406 llvm_unreachable("Unexpected expression"); 18407 } 18408 } 18409 18410 assert(MaybeODRUseExprs.empty() && 18411 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18412 } 18413 18414 static void DoMarkVarDeclReferenced( 18415 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18416 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18417 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18418 isa<FunctionParmPackExpr>(E)) && 18419 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18420 Var->setReferenced(); 18421 18422 if (Var->isInvalidDecl()) 18423 return; 18424 18425 auto *MSI = Var->getMemberSpecializationInfo(); 18426 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18427 : Var->getTemplateSpecializationKind(); 18428 18429 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18430 bool UsableInConstantExpr = 18431 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18432 18433 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18434 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18435 } 18436 18437 // C++20 [expr.const]p12: 18438 // A variable [...] is needed for constant evaluation if it is [...] a 18439 // variable whose name appears as a potentially constant evaluated 18440 // expression that is either a contexpr variable or is of non-volatile 18441 // const-qualified integral type or of reference type 18442 bool NeededForConstantEvaluation = 18443 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18444 18445 bool NeedDefinition = 18446 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18447 18448 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18449 "Can't instantiate a partial template specialization."); 18450 18451 // If this might be a member specialization of a static data member, check 18452 // the specialization is visible. We already did the checks for variable 18453 // template specializations when we created them. 18454 if (NeedDefinition && TSK != TSK_Undeclared && 18455 !isa<VarTemplateSpecializationDecl>(Var)) 18456 SemaRef.checkSpecializationVisibility(Loc, Var); 18457 18458 // Perform implicit instantiation of static data members, static data member 18459 // templates of class templates, and variable template specializations. Delay 18460 // instantiations of variable templates, except for those that could be used 18461 // in a constant expression. 18462 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18463 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18464 // instantiation declaration if a variable is usable in a constant 18465 // expression (among other cases). 18466 bool TryInstantiating = 18467 TSK == TSK_ImplicitInstantiation || 18468 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18469 18470 if (TryInstantiating) { 18471 SourceLocation PointOfInstantiation = 18472 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18473 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18474 if (FirstInstantiation) { 18475 PointOfInstantiation = Loc; 18476 if (MSI) 18477 MSI->setPointOfInstantiation(PointOfInstantiation); 18478 // FIXME: Notify listener. 18479 else 18480 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18481 } 18482 18483 if (UsableInConstantExpr) { 18484 // Do not defer instantiations of variables that could be used in a 18485 // constant expression. 18486 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18487 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18488 }); 18489 18490 // Re-set the member to trigger a recomputation of the dependence bits 18491 // for the expression. 18492 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18493 DRE->setDecl(DRE->getDecl()); 18494 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18495 ME->setMemberDecl(ME->getMemberDecl()); 18496 } else if (FirstInstantiation || 18497 isa<VarTemplateSpecializationDecl>(Var)) { 18498 // FIXME: For a specialization of a variable template, we don't 18499 // distinguish between "declaration and type implicitly instantiated" 18500 // and "implicit instantiation of definition requested", so we have 18501 // no direct way to avoid enqueueing the pending instantiation 18502 // multiple times. 18503 SemaRef.PendingInstantiations 18504 .push_back(std::make_pair(Var, PointOfInstantiation)); 18505 } 18506 } 18507 } 18508 18509 // C++2a [basic.def.odr]p4: 18510 // A variable x whose name appears as a potentially-evaluated expression e 18511 // is odr-used by e unless 18512 // -- x is a reference that is usable in constant expressions 18513 // -- x is a variable of non-reference type that is usable in constant 18514 // expressions and has no mutable subobjects [FIXME], and e is an 18515 // element of the set of potential results of an expression of 18516 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18517 // conversion is applied 18518 // -- x is a variable of non-reference type, and e is an element of the set 18519 // of potential results of a discarded-value expression to which the 18520 // lvalue-to-rvalue conversion is not applied [FIXME] 18521 // 18522 // We check the first part of the second bullet here, and 18523 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18524 // FIXME: To get the third bullet right, we need to delay this even for 18525 // variables that are not usable in constant expressions. 18526 18527 // If we already know this isn't an odr-use, there's nothing more to do. 18528 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18529 if (DRE->isNonOdrUse()) 18530 return; 18531 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18532 if (ME->isNonOdrUse()) 18533 return; 18534 18535 switch (OdrUse) { 18536 case OdrUseContext::None: 18537 assert((!E || isa<FunctionParmPackExpr>(E)) && 18538 "missing non-odr-use marking for unevaluated decl ref"); 18539 break; 18540 18541 case OdrUseContext::FormallyOdrUsed: 18542 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18543 // behavior. 18544 break; 18545 18546 case OdrUseContext::Used: 18547 // If we might later find that this expression isn't actually an odr-use, 18548 // delay the marking. 18549 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18550 SemaRef.MaybeODRUseExprs.insert(E); 18551 else 18552 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18553 break; 18554 18555 case OdrUseContext::Dependent: 18556 // If this is a dependent context, we don't need to mark variables as 18557 // odr-used, but we may still need to track them for lambda capture. 18558 // FIXME: Do we also need to do this inside dependent typeid expressions 18559 // (which are modeled as unevaluated at this point)? 18560 const bool RefersToEnclosingScope = 18561 (SemaRef.CurContext != Var->getDeclContext() && 18562 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18563 if (RefersToEnclosingScope) { 18564 LambdaScopeInfo *const LSI = 18565 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18566 if (LSI && (!LSI->CallOperator || 18567 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18568 // If a variable could potentially be odr-used, defer marking it so 18569 // until we finish analyzing the full expression for any 18570 // lvalue-to-rvalue 18571 // or discarded value conversions that would obviate odr-use. 18572 // Add it to the list of potential captures that will be analyzed 18573 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18574 // unless the variable is a reference that was initialized by a constant 18575 // expression (this will never need to be captured or odr-used). 18576 // 18577 // FIXME: We can simplify this a lot after implementing P0588R1. 18578 assert(E && "Capture variable should be used in an expression."); 18579 if (!Var->getType()->isReferenceType() || 18580 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18581 LSI->addPotentialCapture(E->IgnoreParens()); 18582 } 18583 } 18584 break; 18585 } 18586 } 18587 18588 /// Mark a variable referenced, and check whether it is odr-used 18589 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18590 /// used directly for normal expressions referring to VarDecl. 18591 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18592 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18593 } 18594 18595 static void 18596 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18597 bool MightBeOdrUse, 18598 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18599 if (SemaRef.isInOpenMPDeclareTargetContext()) 18600 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18601 18602 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18603 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18604 return; 18605 } 18606 18607 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18608 18609 // If this is a call to a method via a cast, also mark the method in the 18610 // derived class used in case codegen can devirtualize the call. 18611 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18612 if (!ME) 18613 return; 18614 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18615 if (!MD) 18616 return; 18617 // Only attempt to devirtualize if this is truly a virtual call. 18618 bool IsVirtualCall = MD->isVirtual() && 18619 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18620 if (!IsVirtualCall) 18621 return; 18622 18623 // If it's possible to devirtualize the call, mark the called function 18624 // referenced. 18625 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18626 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18627 if (DM) 18628 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18629 } 18630 18631 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18632 /// 18633 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18634 /// handled with care if the DeclRefExpr is not newly-created. 18635 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18636 // TODO: update this with DR# once a defect report is filed. 18637 // C++11 defect. The address of a pure member should not be an ODR use, even 18638 // if it's a qualified reference. 18639 bool OdrUse = true; 18640 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18641 if (Method->isVirtual() && 18642 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18643 OdrUse = false; 18644 18645 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18646 if (!isConstantEvaluated() && FD->isConsteval() && 18647 !RebuildingImmediateInvocation) 18648 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18649 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18650 RefsMinusAssignments); 18651 } 18652 18653 /// Perform reference-marking and odr-use handling for a MemberExpr. 18654 void Sema::MarkMemberReferenced(MemberExpr *E) { 18655 // C++11 [basic.def.odr]p2: 18656 // A non-overloaded function whose name appears as a potentially-evaluated 18657 // expression or a member of a set of candidate functions, if selected by 18658 // overload resolution when referred to from a potentially-evaluated 18659 // expression, is odr-used, unless it is a pure virtual function and its 18660 // name is not explicitly qualified. 18661 bool MightBeOdrUse = true; 18662 if (E->performsVirtualDispatch(getLangOpts())) { 18663 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18664 if (Method->isPure()) 18665 MightBeOdrUse = false; 18666 } 18667 SourceLocation Loc = 18668 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18669 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18670 RefsMinusAssignments); 18671 } 18672 18673 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18674 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18675 for (VarDecl *VD : *E) 18676 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18677 RefsMinusAssignments); 18678 } 18679 18680 /// Perform marking for a reference to an arbitrary declaration. It 18681 /// marks the declaration referenced, and performs odr-use checking for 18682 /// functions and variables. This method should not be used when building a 18683 /// normal expression which refers to a variable. 18684 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18685 bool MightBeOdrUse) { 18686 if (MightBeOdrUse) { 18687 if (auto *VD = dyn_cast<VarDecl>(D)) { 18688 MarkVariableReferenced(Loc, VD); 18689 return; 18690 } 18691 } 18692 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18693 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18694 return; 18695 } 18696 D->setReferenced(); 18697 } 18698 18699 namespace { 18700 // Mark all of the declarations used by a type as referenced. 18701 // FIXME: Not fully implemented yet! We need to have a better understanding 18702 // of when we're entering a context we should not recurse into. 18703 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18704 // TreeTransforms rebuilding the type in a new context. Rather than 18705 // duplicating the TreeTransform logic, we should consider reusing it here. 18706 // Currently that causes problems when rebuilding LambdaExprs. 18707 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18708 Sema &S; 18709 SourceLocation Loc; 18710 18711 public: 18712 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18713 18714 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18715 18716 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18717 }; 18718 } 18719 18720 bool MarkReferencedDecls::TraverseTemplateArgument( 18721 const TemplateArgument &Arg) { 18722 { 18723 // A non-type template argument is a constant-evaluated context. 18724 EnterExpressionEvaluationContext Evaluated( 18725 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18726 if (Arg.getKind() == TemplateArgument::Declaration) { 18727 if (Decl *D = Arg.getAsDecl()) 18728 S.MarkAnyDeclReferenced(Loc, D, true); 18729 } else if (Arg.getKind() == TemplateArgument::Expression) { 18730 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18731 } 18732 } 18733 18734 return Inherited::TraverseTemplateArgument(Arg); 18735 } 18736 18737 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18738 MarkReferencedDecls Marker(*this, Loc); 18739 Marker.TraverseType(T); 18740 } 18741 18742 namespace { 18743 /// Helper class that marks all of the declarations referenced by 18744 /// potentially-evaluated subexpressions as "referenced". 18745 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18746 public: 18747 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18748 bool SkipLocalVariables; 18749 18750 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18751 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18752 18753 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18754 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18755 } 18756 18757 void VisitDeclRefExpr(DeclRefExpr *E) { 18758 // If we were asked not to visit local variables, don't. 18759 if (SkipLocalVariables) { 18760 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18761 if (VD->hasLocalStorage()) 18762 return; 18763 } 18764 18765 // FIXME: This can trigger the instantiation of the initializer of a 18766 // variable, which can cause the expression to become value-dependent 18767 // or error-dependent. Do we need to propagate the new dependence bits? 18768 S.MarkDeclRefReferenced(E); 18769 } 18770 18771 void VisitMemberExpr(MemberExpr *E) { 18772 S.MarkMemberReferenced(E); 18773 Visit(E->getBase()); 18774 } 18775 }; 18776 } // namespace 18777 18778 /// Mark any declarations that appear within this expression or any 18779 /// potentially-evaluated subexpressions as "referenced". 18780 /// 18781 /// \param SkipLocalVariables If true, don't mark local variables as 18782 /// 'referenced'. 18783 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18784 bool SkipLocalVariables) { 18785 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18786 } 18787 18788 /// Emit a diagnostic that describes an effect on the run-time behavior 18789 /// of the program being compiled. 18790 /// 18791 /// This routine emits the given diagnostic when the code currently being 18792 /// type-checked is "potentially evaluated", meaning that there is a 18793 /// possibility that the code will actually be executable. Code in sizeof() 18794 /// expressions, code used only during overload resolution, etc., are not 18795 /// potentially evaluated. This routine will suppress such diagnostics or, 18796 /// in the absolutely nutty case of potentially potentially evaluated 18797 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18798 /// later. 18799 /// 18800 /// This routine should be used for all diagnostics that describe the run-time 18801 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18802 /// Failure to do so will likely result in spurious diagnostics or failures 18803 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18804 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18805 const PartialDiagnostic &PD) { 18806 switch (ExprEvalContexts.back().Context) { 18807 case ExpressionEvaluationContext::Unevaluated: 18808 case ExpressionEvaluationContext::UnevaluatedList: 18809 case ExpressionEvaluationContext::UnevaluatedAbstract: 18810 case ExpressionEvaluationContext::DiscardedStatement: 18811 // The argument will never be evaluated, so don't complain. 18812 break; 18813 18814 case ExpressionEvaluationContext::ConstantEvaluated: 18815 // Relevant diagnostics should be produced by constant evaluation. 18816 break; 18817 18818 case ExpressionEvaluationContext::PotentiallyEvaluated: 18819 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18820 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18821 FunctionScopes.back()->PossiblyUnreachableDiags. 18822 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18823 return true; 18824 } 18825 18826 // The initializer of a constexpr variable or of the first declaration of a 18827 // static data member is not syntactically a constant evaluated constant, 18828 // but nonetheless is always required to be a constant expression, so we 18829 // can skip diagnosing. 18830 // FIXME: Using the mangling context here is a hack. 18831 if (auto *VD = dyn_cast_or_null<VarDecl>( 18832 ExprEvalContexts.back().ManglingContextDecl)) { 18833 if (VD->isConstexpr() || 18834 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18835 break; 18836 // FIXME: For any other kind of variable, we should build a CFG for its 18837 // initializer and check whether the context in question is reachable. 18838 } 18839 18840 Diag(Loc, PD); 18841 return true; 18842 } 18843 18844 return false; 18845 } 18846 18847 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18848 const PartialDiagnostic &PD) { 18849 return DiagRuntimeBehavior( 18850 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18851 } 18852 18853 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18854 CallExpr *CE, FunctionDecl *FD) { 18855 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18856 return false; 18857 18858 // If we're inside a decltype's expression, don't check for a valid return 18859 // type or construct temporaries until we know whether this is the last call. 18860 if (ExprEvalContexts.back().ExprContext == 18861 ExpressionEvaluationContextRecord::EK_Decltype) { 18862 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18863 return false; 18864 } 18865 18866 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18867 FunctionDecl *FD; 18868 CallExpr *CE; 18869 18870 public: 18871 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18872 : FD(FD), CE(CE) { } 18873 18874 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18875 if (!FD) { 18876 S.Diag(Loc, diag::err_call_incomplete_return) 18877 << T << CE->getSourceRange(); 18878 return; 18879 } 18880 18881 S.Diag(Loc, diag::err_call_function_incomplete_return) 18882 << CE->getSourceRange() << FD << T; 18883 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18884 << FD->getDeclName(); 18885 } 18886 } Diagnoser(FD, CE); 18887 18888 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18889 return true; 18890 18891 return false; 18892 } 18893 18894 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18895 // will prevent this condition from triggering, which is what we want. 18896 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18897 SourceLocation Loc; 18898 18899 unsigned diagnostic = diag::warn_condition_is_assignment; 18900 bool IsOrAssign = false; 18901 18902 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18903 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18904 return; 18905 18906 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18907 18908 // Greylist some idioms by putting them into a warning subcategory. 18909 if (ObjCMessageExpr *ME 18910 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18911 Selector Sel = ME->getSelector(); 18912 18913 // self = [<foo> init...] 18914 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18915 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18916 18917 // <foo> = [<bar> nextObject] 18918 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18919 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18920 } 18921 18922 Loc = Op->getOperatorLoc(); 18923 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18924 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18925 return; 18926 18927 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18928 Loc = Op->getOperatorLoc(); 18929 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18930 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18931 else { 18932 // Not an assignment. 18933 return; 18934 } 18935 18936 Diag(Loc, diagnostic) << E->getSourceRange(); 18937 18938 SourceLocation Open = E->getBeginLoc(); 18939 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18940 Diag(Loc, diag::note_condition_assign_silence) 18941 << FixItHint::CreateInsertion(Open, "(") 18942 << FixItHint::CreateInsertion(Close, ")"); 18943 18944 if (IsOrAssign) 18945 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18946 << FixItHint::CreateReplacement(Loc, "!="); 18947 else 18948 Diag(Loc, diag::note_condition_assign_to_comparison) 18949 << FixItHint::CreateReplacement(Loc, "=="); 18950 } 18951 18952 /// Redundant parentheses over an equality comparison can indicate 18953 /// that the user intended an assignment used as condition. 18954 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18955 // Don't warn if the parens came from a macro. 18956 SourceLocation parenLoc = ParenE->getBeginLoc(); 18957 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18958 return; 18959 // Don't warn for dependent expressions. 18960 if (ParenE->isTypeDependent()) 18961 return; 18962 18963 Expr *E = ParenE->IgnoreParens(); 18964 18965 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18966 if (opE->getOpcode() == BO_EQ && 18967 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18968 == Expr::MLV_Valid) { 18969 SourceLocation Loc = opE->getOperatorLoc(); 18970 18971 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18972 SourceRange ParenERange = ParenE->getSourceRange(); 18973 Diag(Loc, diag::note_equality_comparison_silence) 18974 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18975 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18976 Diag(Loc, diag::note_equality_comparison_to_assign) 18977 << FixItHint::CreateReplacement(Loc, "="); 18978 } 18979 } 18980 18981 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18982 bool IsConstexpr) { 18983 DiagnoseAssignmentAsCondition(E); 18984 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18985 DiagnoseEqualityWithExtraParens(parenE); 18986 18987 ExprResult result = CheckPlaceholderExpr(E); 18988 if (result.isInvalid()) return ExprError(); 18989 E = result.get(); 18990 18991 if (!E->isTypeDependent()) { 18992 if (getLangOpts().CPlusPlus) 18993 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18994 18995 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18996 if (ERes.isInvalid()) 18997 return ExprError(); 18998 E = ERes.get(); 18999 19000 QualType T = E->getType(); 19001 if (!T->isScalarType()) { // C99 6.8.4.1p1 19002 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19003 << T << E->getSourceRange(); 19004 return ExprError(); 19005 } 19006 CheckBoolLikeConversion(E, Loc); 19007 } 19008 19009 return E; 19010 } 19011 19012 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19013 Expr *SubExpr, ConditionKind CK) { 19014 // Empty conditions are valid in for-statements. 19015 if (!SubExpr) 19016 return ConditionResult(); 19017 19018 ExprResult Cond; 19019 switch (CK) { 19020 case ConditionKind::Boolean: 19021 Cond = CheckBooleanCondition(Loc, SubExpr); 19022 break; 19023 19024 case ConditionKind::ConstexprIf: 19025 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19026 break; 19027 19028 case ConditionKind::Switch: 19029 Cond = CheckSwitchCondition(Loc, SubExpr); 19030 break; 19031 } 19032 if (Cond.isInvalid()) { 19033 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19034 {SubExpr}); 19035 if (!Cond.get()) 19036 return ConditionError(); 19037 } 19038 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19039 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19040 if (!FullExpr.get()) 19041 return ConditionError(); 19042 19043 return ConditionResult(*this, nullptr, FullExpr, 19044 CK == ConditionKind::ConstexprIf); 19045 } 19046 19047 namespace { 19048 /// A visitor for rebuilding a call to an __unknown_any expression 19049 /// to have an appropriate type. 19050 struct RebuildUnknownAnyFunction 19051 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19052 19053 Sema &S; 19054 19055 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19056 19057 ExprResult VisitStmt(Stmt *S) { 19058 llvm_unreachable("unexpected statement!"); 19059 } 19060 19061 ExprResult VisitExpr(Expr *E) { 19062 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19063 << E->getSourceRange(); 19064 return ExprError(); 19065 } 19066 19067 /// Rebuild an expression which simply semantically wraps another 19068 /// expression which it shares the type and value kind of. 19069 template <class T> ExprResult rebuildSugarExpr(T *E) { 19070 ExprResult SubResult = Visit(E->getSubExpr()); 19071 if (SubResult.isInvalid()) return ExprError(); 19072 19073 Expr *SubExpr = SubResult.get(); 19074 E->setSubExpr(SubExpr); 19075 E->setType(SubExpr->getType()); 19076 E->setValueKind(SubExpr->getValueKind()); 19077 assert(E->getObjectKind() == OK_Ordinary); 19078 return E; 19079 } 19080 19081 ExprResult VisitParenExpr(ParenExpr *E) { 19082 return rebuildSugarExpr(E); 19083 } 19084 19085 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19086 return rebuildSugarExpr(E); 19087 } 19088 19089 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19090 ExprResult SubResult = Visit(E->getSubExpr()); 19091 if (SubResult.isInvalid()) return ExprError(); 19092 19093 Expr *SubExpr = SubResult.get(); 19094 E->setSubExpr(SubExpr); 19095 E->setType(S.Context.getPointerType(SubExpr->getType())); 19096 assert(E->getValueKind() == VK_PRValue); 19097 assert(E->getObjectKind() == OK_Ordinary); 19098 return E; 19099 } 19100 19101 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19102 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19103 19104 E->setType(VD->getType()); 19105 19106 assert(E->getValueKind() == VK_PRValue); 19107 if (S.getLangOpts().CPlusPlus && 19108 !(isa<CXXMethodDecl>(VD) && 19109 cast<CXXMethodDecl>(VD)->isInstance())) 19110 E->setValueKind(VK_LValue); 19111 19112 return E; 19113 } 19114 19115 ExprResult VisitMemberExpr(MemberExpr *E) { 19116 return resolveDecl(E, E->getMemberDecl()); 19117 } 19118 19119 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19120 return resolveDecl(E, E->getDecl()); 19121 } 19122 }; 19123 } 19124 19125 /// Given a function expression of unknown-any type, try to rebuild it 19126 /// to have a function type. 19127 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19128 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19129 if (Result.isInvalid()) return ExprError(); 19130 return S.DefaultFunctionArrayConversion(Result.get()); 19131 } 19132 19133 namespace { 19134 /// A visitor for rebuilding an expression of type __unknown_anytype 19135 /// into one which resolves the type directly on the referring 19136 /// expression. Strict preservation of the original source 19137 /// structure is not a goal. 19138 struct RebuildUnknownAnyExpr 19139 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19140 19141 Sema &S; 19142 19143 /// The current destination type. 19144 QualType DestType; 19145 19146 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19147 : S(S), DestType(CastType) {} 19148 19149 ExprResult VisitStmt(Stmt *S) { 19150 llvm_unreachable("unexpected statement!"); 19151 } 19152 19153 ExprResult VisitExpr(Expr *E) { 19154 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19155 << E->getSourceRange(); 19156 return ExprError(); 19157 } 19158 19159 ExprResult VisitCallExpr(CallExpr *E); 19160 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19161 19162 /// Rebuild an expression which simply semantically wraps another 19163 /// expression which it shares the type and value kind of. 19164 template <class T> ExprResult rebuildSugarExpr(T *E) { 19165 ExprResult SubResult = Visit(E->getSubExpr()); 19166 if (SubResult.isInvalid()) return ExprError(); 19167 Expr *SubExpr = SubResult.get(); 19168 E->setSubExpr(SubExpr); 19169 E->setType(SubExpr->getType()); 19170 E->setValueKind(SubExpr->getValueKind()); 19171 assert(E->getObjectKind() == OK_Ordinary); 19172 return E; 19173 } 19174 19175 ExprResult VisitParenExpr(ParenExpr *E) { 19176 return rebuildSugarExpr(E); 19177 } 19178 19179 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19180 return rebuildSugarExpr(E); 19181 } 19182 19183 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19184 const PointerType *Ptr = DestType->getAs<PointerType>(); 19185 if (!Ptr) { 19186 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19187 << E->getSourceRange(); 19188 return ExprError(); 19189 } 19190 19191 if (isa<CallExpr>(E->getSubExpr())) { 19192 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19193 << E->getSourceRange(); 19194 return ExprError(); 19195 } 19196 19197 assert(E->getValueKind() == VK_PRValue); 19198 assert(E->getObjectKind() == OK_Ordinary); 19199 E->setType(DestType); 19200 19201 // Build the sub-expression as if it were an object of the pointee type. 19202 DestType = Ptr->getPointeeType(); 19203 ExprResult SubResult = Visit(E->getSubExpr()); 19204 if (SubResult.isInvalid()) return ExprError(); 19205 E->setSubExpr(SubResult.get()); 19206 return E; 19207 } 19208 19209 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19210 19211 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19212 19213 ExprResult VisitMemberExpr(MemberExpr *E) { 19214 return resolveDecl(E, E->getMemberDecl()); 19215 } 19216 19217 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19218 return resolveDecl(E, E->getDecl()); 19219 } 19220 }; 19221 } 19222 19223 /// Rebuilds a call expression which yielded __unknown_anytype. 19224 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19225 Expr *CalleeExpr = E->getCallee(); 19226 19227 enum FnKind { 19228 FK_MemberFunction, 19229 FK_FunctionPointer, 19230 FK_BlockPointer 19231 }; 19232 19233 FnKind Kind; 19234 QualType CalleeType = CalleeExpr->getType(); 19235 if (CalleeType == S.Context.BoundMemberTy) { 19236 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19237 Kind = FK_MemberFunction; 19238 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19239 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19240 CalleeType = Ptr->getPointeeType(); 19241 Kind = FK_FunctionPointer; 19242 } else { 19243 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19244 Kind = FK_BlockPointer; 19245 } 19246 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19247 19248 // Verify that this is a legal result type of a function. 19249 if (DestType->isArrayType() || DestType->isFunctionType()) { 19250 unsigned diagID = diag::err_func_returning_array_function; 19251 if (Kind == FK_BlockPointer) 19252 diagID = diag::err_block_returning_array_function; 19253 19254 S.Diag(E->getExprLoc(), diagID) 19255 << DestType->isFunctionType() << DestType; 19256 return ExprError(); 19257 } 19258 19259 // Otherwise, go ahead and set DestType as the call's result. 19260 E->setType(DestType.getNonLValueExprType(S.Context)); 19261 E->setValueKind(Expr::getValueKindForType(DestType)); 19262 assert(E->getObjectKind() == OK_Ordinary); 19263 19264 // Rebuild the function type, replacing the result type with DestType. 19265 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19266 if (Proto) { 19267 // __unknown_anytype(...) is a special case used by the debugger when 19268 // it has no idea what a function's signature is. 19269 // 19270 // We want to build this call essentially under the K&R 19271 // unprototyped rules, but making a FunctionNoProtoType in C++ 19272 // would foul up all sorts of assumptions. However, we cannot 19273 // simply pass all arguments as variadic arguments, nor can we 19274 // portably just call the function under a non-variadic type; see 19275 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19276 // However, it turns out that in practice it is generally safe to 19277 // call a function declared as "A foo(B,C,D);" under the prototype 19278 // "A foo(B,C,D,...);". The only known exception is with the 19279 // Windows ABI, where any variadic function is implicitly cdecl 19280 // regardless of its normal CC. Therefore we change the parameter 19281 // types to match the types of the arguments. 19282 // 19283 // This is a hack, but it is far superior to moving the 19284 // corresponding target-specific code from IR-gen to Sema/AST. 19285 19286 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19287 SmallVector<QualType, 8> ArgTypes; 19288 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19289 ArgTypes.reserve(E->getNumArgs()); 19290 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19291 Expr *Arg = E->getArg(i); 19292 QualType ArgType = Arg->getType(); 19293 if (E->isLValue()) { 19294 ArgType = S.Context.getLValueReferenceType(ArgType); 19295 } else if (E->isXValue()) { 19296 ArgType = S.Context.getRValueReferenceType(ArgType); 19297 } 19298 ArgTypes.push_back(ArgType); 19299 } 19300 ParamTypes = ArgTypes; 19301 } 19302 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19303 Proto->getExtProtoInfo()); 19304 } else { 19305 DestType = S.Context.getFunctionNoProtoType(DestType, 19306 FnType->getExtInfo()); 19307 } 19308 19309 // Rebuild the appropriate pointer-to-function type. 19310 switch (Kind) { 19311 case FK_MemberFunction: 19312 // Nothing to do. 19313 break; 19314 19315 case FK_FunctionPointer: 19316 DestType = S.Context.getPointerType(DestType); 19317 break; 19318 19319 case FK_BlockPointer: 19320 DestType = S.Context.getBlockPointerType(DestType); 19321 break; 19322 } 19323 19324 // Finally, we can recurse. 19325 ExprResult CalleeResult = Visit(CalleeExpr); 19326 if (!CalleeResult.isUsable()) return ExprError(); 19327 E->setCallee(CalleeResult.get()); 19328 19329 // Bind a temporary if necessary. 19330 return S.MaybeBindToTemporary(E); 19331 } 19332 19333 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19334 // Verify that this is a legal result type of a call. 19335 if (DestType->isArrayType() || DestType->isFunctionType()) { 19336 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19337 << DestType->isFunctionType() << DestType; 19338 return ExprError(); 19339 } 19340 19341 // Rewrite the method result type if available. 19342 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19343 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19344 Method->setReturnType(DestType); 19345 } 19346 19347 // Change the type of the message. 19348 E->setType(DestType.getNonReferenceType()); 19349 E->setValueKind(Expr::getValueKindForType(DestType)); 19350 19351 return S.MaybeBindToTemporary(E); 19352 } 19353 19354 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19355 // The only case we should ever see here is a function-to-pointer decay. 19356 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19357 assert(E->getValueKind() == VK_PRValue); 19358 assert(E->getObjectKind() == OK_Ordinary); 19359 19360 E->setType(DestType); 19361 19362 // Rebuild the sub-expression as the pointee (function) type. 19363 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19364 19365 ExprResult Result = Visit(E->getSubExpr()); 19366 if (!Result.isUsable()) return ExprError(); 19367 19368 E->setSubExpr(Result.get()); 19369 return E; 19370 } else if (E->getCastKind() == CK_LValueToRValue) { 19371 assert(E->getValueKind() == VK_PRValue); 19372 assert(E->getObjectKind() == OK_Ordinary); 19373 19374 assert(isa<BlockPointerType>(E->getType())); 19375 19376 E->setType(DestType); 19377 19378 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19379 DestType = S.Context.getLValueReferenceType(DestType); 19380 19381 ExprResult Result = Visit(E->getSubExpr()); 19382 if (!Result.isUsable()) return ExprError(); 19383 19384 E->setSubExpr(Result.get()); 19385 return E; 19386 } else { 19387 llvm_unreachable("Unhandled cast type!"); 19388 } 19389 } 19390 19391 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19392 ExprValueKind ValueKind = VK_LValue; 19393 QualType Type = DestType; 19394 19395 // We know how to make this work for certain kinds of decls: 19396 19397 // - functions 19398 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19399 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19400 DestType = Ptr->getPointeeType(); 19401 ExprResult Result = resolveDecl(E, VD); 19402 if (Result.isInvalid()) return ExprError(); 19403 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19404 VK_PRValue); 19405 } 19406 19407 if (!Type->isFunctionType()) { 19408 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19409 << VD << E->getSourceRange(); 19410 return ExprError(); 19411 } 19412 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19413 // We must match the FunctionDecl's type to the hack introduced in 19414 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19415 // type. See the lengthy commentary in that routine. 19416 QualType FDT = FD->getType(); 19417 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19418 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19419 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19420 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19421 SourceLocation Loc = FD->getLocation(); 19422 FunctionDecl *NewFD = FunctionDecl::Create( 19423 S.Context, FD->getDeclContext(), Loc, Loc, 19424 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19425 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19426 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19427 19428 if (FD->getQualifier()) 19429 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19430 19431 SmallVector<ParmVarDecl*, 16> Params; 19432 for (const auto &AI : FT->param_types()) { 19433 ParmVarDecl *Param = 19434 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19435 Param->setScopeInfo(0, Params.size()); 19436 Params.push_back(Param); 19437 } 19438 NewFD->setParams(Params); 19439 DRE->setDecl(NewFD); 19440 VD = DRE->getDecl(); 19441 } 19442 } 19443 19444 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19445 if (MD->isInstance()) { 19446 ValueKind = VK_PRValue; 19447 Type = S.Context.BoundMemberTy; 19448 } 19449 19450 // Function references aren't l-values in C. 19451 if (!S.getLangOpts().CPlusPlus) 19452 ValueKind = VK_PRValue; 19453 19454 // - variables 19455 } else if (isa<VarDecl>(VD)) { 19456 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19457 Type = RefTy->getPointeeType(); 19458 } else if (Type->isFunctionType()) { 19459 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19460 << VD << E->getSourceRange(); 19461 return ExprError(); 19462 } 19463 19464 // - nothing else 19465 } else { 19466 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19467 << VD << E->getSourceRange(); 19468 return ExprError(); 19469 } 19470 19471 // Modifying the declaration like this is friendly to IR-gen but 19472 // also really dangerous. 19473 VD->setType(DestType); 19474 E->setType(Type); 19475 E->setValueKind(ValueKind); 19476 return E; 19477 } 19478 19479 /// Check a cast of an unknown-any type. We intentionally only 19480 /// trigger this for C-style casts. 19481 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19482 Expr *CastExpr, CastKind &CastKind, 19483 ExprValueKind &VK, CXXCastPath &Path) { 19484 // The type we're casting to must be either void or complete. 19485 if (!CastType->isVoidType() && 19486 RequireCompleteType(TypeRange.getBegin(), CastType, 19487 diag::err_typecheck_cast_to_incomplete)) 19488 return ExprError(); 19489 19490 // Rewrite the casted expression from scratch. 19491 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19492 if (!result.isUsable()) return ExprError(); 19493 19494 CastExpr = result.get(); 19495 VK = CastExpr->getValueKind(); 19496 CastKind = CK_NoOp; 19497 19498 return CastExpr; 19499 } 19500 19501 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19502 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19503 } 19504 19505 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19506 Expr *arg, QualType ¶mType) { 19507 // If the syntactic form of the argument is not an explicit cast of 19508 // any sort, just do default argument promotion. 19509 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19510 if (!castArg) { 19511 ExprResult result = DefaultArgumentPromotion(arg); 19512 if (result.isInvalid()) return ExprError(); 19513 paramType = result.get()->getType(); 19514 return result; 19515 } 19516 19517 // Otherwise, use the type that was written in the explicit cast. 19518 assert(!arg->hasPlaceholderType()); 19519 paramType = castArg->getTypeAsWritten(); 19520 19521 // Copy-initialize a parameter of that type. 19522 InitializedEntity entity = 19523 InitializedEntity::InitializeParameter(Context, paramType, 19524 /*consumed*/ false); 19525 return PerformCopyInitialization(entity, callLoc, arg); 19526 } 19527 19528 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19529 Expr *orig = E; 19530 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19531 while (true) { 19532 E = E->IgnoreParenImpCasts(); 19533 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19534 E = call->getCallee(); 19535 diagID = diag::err_uncasted_call_of_unknown_any; 19536 } else { 19537 break; 19538 } 19539 } 19540 19541 SourceLocation loc; 19542 NamedDecl *d; 19543 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19544 loc = ref->getLocation(); 19545 d = ref->getDecl(); 19546 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19547 loc = mem->getMemberLoc(); 19548 d = mem->getMemberDecl(); 19549 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19550 diagID = diag::err_uncasted_call_of_unknown_any; 19551 loc = msg->getSelectorStartLoc(); 19552 d = msg->getMethodDecl(); 19553 if (!d) { 19554 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19555 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19556 << orig->getSourceRange(); 19557 return ExprError(); 19558 } 19559 } else { 19560 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19561 << E->getSourceRange(); 19562 return ExprError(); 19563 } 19564 19565 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19566 19567 // Never recoverable. 19568 return ExprError(); 19569 } 19570 19571 /// Check for operands with placeholder types and complain if found. 19572 /// Returns ExprError() if there was an error and no recovery was possible. 19573 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19574 if (!Context.isDependenceAllowed()) { 19575 // C cannot handle TypoExpr nodes on either side of a binop because it 19576 // doesn't handle dependent types properly, so make sure any TypoExprs have 19577 // been dealt with before checking the operands. 19578 ExprResult Result = CorrectDelayedTyposInExpr(E); 19579 if (!Result.isUsable()) return ExprError(); 19580 E = Result.get(); 19581 } 19582 19583 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19584 if (!placeholderType) return E; 19585 19586 switch (placeholderType->getKind()) { 19587 19588 // Overloaded expressions. 19589 case BuiltinType::Overload: { 19590 // Try to resolve a single function template specialization. 19591 // This is obligatory. 19592 ExprResult Result = E; 19593 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19594 return Result; 19595 19596 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19597 // leaves Result unchanged on failure. 19598 Result = E; 19599 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19600 return Result; 19601 19602 // If that failed, try to recover with a call. 19603 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19604 /*complain*/ true); 19605 return Result; 19606 } 19607 19608 // Bound member functions. 19609 case BuiltinType::BoundMember: { 19610 ExprResult result = E; 19611 const Expr *BME = E->IgnoreParens(); 19612 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19613 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19614 if (isa<CXXPseudoDestructorExpr>(BME)) { 19615 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19616 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19617 if (ME->getMemberNameInfo().getName().getNameKind() == 19618 DeclarationName::CXXDestructorName) 19619 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19620 } 19621 tryToRecoverWithCall(result, PD, 19622 /*complain*/ true); 19623 return result; 19624 } 19625 19626 // ARC unbridged casts. 19627 case BuiltinType::ARCUnbridgedCast: { 19628 Expr *realCast = stripARCUnbridgedCast(E); 19629 diagnoseARCUnbridgedCast(realCast); 19630 return realCast; 19631 } 19632 19633 // Expressions of unknown type. 19634 case BuiltinType::UnknownAny: 19635 return diagnoseUnknownAnyExpr(*this, E); 19636 19637 // Pseudo-objects. 19638 case BuiltinType::PseudoObject: 19639 return checkPseudoObjectRValue(E); 19640 19641 case BuiltinType::BuiltinFn: { 19642 // Accept __noop without parens by implicitly converting it to a call expr. 19643 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19644 if (DRE) { 19645 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19646 if (FD->getBuiltinID() == Builtin::BI__noop) { 19647 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19648 CK_BuiltinFnToFnPtr) 19649 .get(); 19650 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19651 VK_PRValue, SourceLocation(), 19652 FPOptionsOverride()); 19653 } 19654 } 19655 19656 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19657 return ExprError(); 19658 } 19659 19660 case BuiltinType::IncompleteMatrixIdx: 19661 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19662 ->getRowIdx() 19663 ->getBeginLoc(), 19664 diag::err_matrix_incomplete_index); 19665 return ExprError(); 19666 19667 // Expressions of unknown type. 19668 case BuiltinType::OMPArraySection: 19669 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19670 return ExprError(); 19671 19672 // Expressions of unknown type. 19673 case BuiltinType::OMPArrayShaping: 19674 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19675 19676 case BuiltinType::OMPIterator: 19677 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19678 19679 // Everything else should be impossible. 19680 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19681 case BuiltinType::Id: 19682 #include "clang/Basic/OpenCLImageTypes.def" 19683 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19684 case BuiltinType::Id: 19685 #include "clang/Basic/OpenCLExtensionTypes.def" 19686 #define SVE_TYPE(Name, Id, SingletonId) \ 19687 case BuiltinType::Id: 19688 #include "clang/Basic/AArch64SVEACLETypes.def" 19689 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19690 case BuiltinType::Id: 19691 #include "clang/Basic/PPCTypes.def" 19692 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19693 #include "clang/Basic/RISCVVTypes.def" 19694 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19695 #define PLACEHOLDER_TYPE(Id, SingletonId) 19696 #include "clang/AST/BuiltinTypes.def" 19697 break; 19698 } 19699 19700 llvm_unreachable("invalid placeholder type!"); 19701 } 19702 19703 bool Sema::CheckCaseExpression(Expr *E) { 19704 if (E->isTypeDependent()) 19705 return true; 19706 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19707 return E->getType()->isIntegralOrEnumerationType(); 19708 return false; 19709 } 19710 19711 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19712 ExprResult 19713 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19714 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19715 "Unknown Objective-C Boolean value!"); 19716 QualType BoolT = Context.ObjCBuiltinBoolTy; 19717 if (!Context.getBOOLDecl()) { 19718 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19719 Sema::LookupOrdinaryName); 19720 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19721 NamedDecl *ND = Result.getFoundDecl(); 19722 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19723 Context.setBOOLDecl(TD); 19724 } 19725 } 19726 if (Context.getBOOLDecl()) 19727 BoolT = Context.getBOOLType(); 19728 return new (Context) 19729 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19730 } 19731 19732 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19733 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19734 SourceLocation RParen) { 19735 19736 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19737 19738 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19739 return Spec.getPlatform() == Platform; 19740 }); 19741 19742 VersionTuple Version; 19743 if (Spec != AvailSpecs.end()) 19744 Version = Spec->getVersion(); 19745 19746 // The use of `@available` in the enclosing context should be analyzed to 19747 // warn when it's used inappropriately (i.e. not if(@available)). 19748 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19749 Context->HasPotentialAvailabilityViolations = true; 19750 19751 return new (Context) 19752 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19753 } 19754 19755 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19756 ArrayRef<Expr *> SubExprs, QualType T) { 19757 if (!Context.getLangOpts().RecoveryAST) 19758 return ExprError(); 19759 19760 if (isSFINAEContext()) 19761 return ExprError(); 19762 19763 if (T.isNull() || T->isUndeducedType() || 19764 !Context.getLangOpts().RecoveryASTType) 19765 // We don't know the concrete type, fallback to dependent type. 19766 T = Context.DependentTy; 19767 19768 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19769 } 19770