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 QualType ExprTy = E->getType(); 4058 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4059 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4060 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4061 return new (Context) ParenExpr(L, R, E); 4062 } 4063 4064 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4065 SourceLocation Loc, 4066 SourceRange ArgRange) { 4067 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4068 // scalar or vector data type argument..." 4069 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4070 // type (C99 6.2.5p18) or void. 4071 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4072 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4073 << T << ArgRange; 4074 return true; 4075 } 4076 4077 assert((T->isVoidType() || !T->isIncompleteType()) && 4078 "Scalar types should always be complete"); 4079 return false; 4080 } 4081 4082 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4083 SourceLocation Loc, 4084 SourceRange ArgRange, 4085 UnaryExprOrTypeTrait TraitKind) { 4086 // Invalid types must be hard errors for SFINAE in C++. 4087 if (S.LangOpts.CPlusPlus) 4088 return true; 4089 4090 // C99 6.5.3.4p1: 4091 if (T->isFunctionType() && 4092 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4093 TraitKind == UETT_PreferredAlignOf)) { 4094 // sizeof(function)/alignof(function) is allowed as an extension. 4095 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4096 << getTraitSpelling(TraitKind) << ArgRange; 4097 return false; 4098 } 4099 4100 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4101 // this is an error (OpenCL v1.1 s6.3.k) 4102 if (T->isVoidType()) { 4103 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4104 : diag::ext_sizeof_alignof_void_type; 4105 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4106 return false; 4107 } 4108 4109 return true; 4110 } 4111 4112 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4113 SourceLocation Loc, 4114 SourceRange ArgRange, 4115 UnaryExprOrTypeTrait TraitKind) { 4116 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4117 // runtime doesn't allow it. 4118 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4119 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4120 << T << (TraitKind == UETT_SizeOf) 4121 << ArgRange; 4122 return true; 4123 } 4124 4125 return false; 4126 } 4127 4128 /// Check whether E is a pointer from a decayed array type (the decayed 4129 /// pointer type is equal to T) and emit a warning if it is. 4130 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4131 Expr *E) { 4132 // Don't warn if the operation changed the type. 4133 if (T != E->getType()) 4134 return; 4135 4136 // Now look for array decays. 4137 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4138 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4139 return; 4140 4141 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4142 << ICE->getType() 4143 << ICE->getSubExpr()->getType(); 4144 } 4145 4146 /// Check the constraints on expression operands to unary type expression 4147 /// and type traits. 4148 /// 4149 /// Completes any types necessary and validates the constraints on the operand 4150 /// expression. The logic mostly mirrors the type-based overload, but may modify 4151 /// the expression as it completes the type for that expression through template 4152 /// instantiation, etc. 4153 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4154 UnaryExprOrTypeTrait ExprKind) { 4155 QualType ExprTy = E->getType(); 4156 assert(!ExprTy->isReferenceType()); 4157 4158 bool IsUnevaluatedOperand = 4159 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4160 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4161 if (IsUnevaluatedOperand) { 4162 ExprResult Result = CheckUnevaluatedOperand(E); 4163 if (Result.isInvalid()) 4164 return true; 4165 E = Result.get(); 4166 } 4167 4168 // The operand for sizeof and alignof is in an unevaluated expression context, 4169 // so side effects could result in unintended consequences. 4170 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4171 // used to build SFINAE gadgets. 4172 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4173 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4174 !E->isInstantiationDependent() && 4175 E->HasSideEffects(Context, false)) 4176 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4177 4178 if (ExprKind == UETT_VecStep) 4179 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4180 E->getSourceRange()); 4181 4182 // Explicitly list some types as extensions. 4183 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4184 E->getSourceRange(), ExprKind)) 4185 return false; 4186 4187 // 'alignof' applied to an expression only requires the base element type of 4188 // the expression to be complete. 'sizeof' requires the expression's type to 4189 // be complete (and will attempt to complete it if it's an array of unknown 4190 // bound). 4191 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4192 if (RequireCompleteSizedType( 4193 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4194 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4195 getTraitSpelling(ExprKind), E->getSourceRange())) 4196 return true; 4197 } else { 4198 if (RequireCompleteSizedExprType( 4199 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4200 getTraitSpelling(ExprKind), E->getSourceRange())) 4201 return true; 4202 } 4203 4204 // Completing the expression's type may have changed it. 4205 ExprTy = E->getType(); 4206 assert(!ExprTy->isReferenceType()); 4207 4208 if (ExprTy->isFunctionType()) { 4209 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4210 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4211 return true; 4212 } 4213 4214 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4215 E->getSourceRange(), ExprKind)) 4216 return true; 4217 4218 if (ExprKind == UETT_SizeOf) { 4219 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4220 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4221 QualType OType = PVD->getOriginalType(); 4222 QualType Type = PVD->getType(); 4223 if (Type->isPointerType() && OType->isArrayType()) { 4224 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4225 << Type << OType; 4226 Diag(PVD->getLocation(), diag::note_declared_at); 4227 } 4228 } 4229 } 4230 4231 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4232 // decays into a pointer and returns an unintended result. This is most 4233 // likely a typo for "sizeof(array) op x". 4234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4235 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4236 BO->getLHS()); 4237 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4238 BO->getRHS()); 4239 } 4240 } 4241 4242 return false; 4243 } 4244 4245 /// Check the constraints on operands to unary expression and type 4246 /// traits. 4247 /// 4248 /// This will complete any types necessary, and validate the various constraints 4249 /// on those operands. 4250 /// 4251 /// The UsualUnaryConversions() function is *not* called by this routine. 4252 /// C99 6.3.2.1p[2-4] all state: 4253 /// Except when it is the operand of the sizeof operator ... 4254 /// 4255 /// C++ [expr.sizeof]p4 4256 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4257 /// standard conversions are not applied to the operand of sizeof. 4258 /// 4259 /// This policy is followed for all of the unary trait expressions. 4260 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4261 SourceLocation OpLoc, 4262 SourceRange ExprRange, 4263 UnaryExprOrTypeTrait ExprKind) { 4264 if (ExprType->isDependentType()) 4265 return false; 4266 4267 // C++ [expr.sizeof]p2: 4268 // When applied to a reference or a reference type, the result 4269 // is the size of the referenced type. 4270 // C++11 [expr.alignof]p3: 4271 // When alignof is applied to a reference type, the result 4272 // shall be the alignment of the referenced type. 4273 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4274 ExprType = Ref->getPointeeType(); 4275 4276 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4277 // When alignof or _Alignof is applied to an array type, the result 4278 // is the alignment of the element type. 4279 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4280 ExprKind == UETT_OpenMPRequiredSimdAlign) 4281 ExprType = Context.getBaseElementType(ExprType); 4282 4283 if (ExprKind == UETT_VecStep) 4284 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4285 4286 // Explicitly list some types as extensions. 4287 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4288 ExprKind)) 4289 return false; 4290 4291 if (RequireCompleteSizedType( 4292 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4293 getTraitSpelling(ExprKind), ExprRange)) 4294 return true; 4295 4296 if (ExprType->isFunctionType()) { 4297 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4298 << getTraitSpelling(ExprKind) << ExprRange; 4299 return true; 4300 } 4301 4302 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4303 ExprKind)) 4304 return true; 4305 4306 return false; 4307 } 4308 4309 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4310 // Cannot know anything else if the expression is dependent. 4311 if (E->isTypeDependent()) 4312 return false; 4313 4314 if (E->getObjectKind() == OK_BitField) { 4315 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4316 << 1 << E->getSourceRange(); 4317 return true; 4318 } 4319 4320 ValueDecl *D = nullptr; 4321 Expr *Inner = E->IgnoreParens(); 4322 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4323 D = DRE->getDecl(); 4324 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4325 D = ME->getMemberDecl(); 4326 } 4327 4328 // If it's a field, require the containing struct to have a 4329 // complete definition so that we can compute the layout. 4330 // 4331 // This can happen in C++11 onwards, either by naming the member 4332 // in a way that is not transformed into a member access expression 4333 // (in an unevaluated operand, for instance), or by naming the member 4334 // in a trailing-return-type. 4335 // 4336 // For the record, since __alignof__ on expressions is a GCC 4337 // extension, GCC seems to permit this but always gives the 4338 // nonsensical answer 0. 4339 // 4340 // We don't really need the layout here --- we could instead just 4341 // directly check for all the appropriate alignment-lowing 4342 // attributes --- but that would require duplicating a lot of 4343 // logic that just isn't worth duplicating for such a marginal 4344 // use-case. 4345 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4346 // Fast path this check, since we at least know the record has a 4347 // definition if we can find a member of it. 4348 if (!FD->getParent()->isCompleteDefinition()) { 4349 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4350 << E->getSourceRange(); 4351 return true; 4352 } 4353 4354 // Otherwise, if it's a field, and the field doesn't have 4355 // reference type, then it must have a complete type (or be a 4356 // flexible array member, which we explicitly want to 4357 // white-list anyway), which makes the following checks trivial. 4358 if (!FD->getType()->isReferenceType()) 4359 return false; 4360 } 4361 4362 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4363 } 4364 4365 bool Sema::CheckVecStepExpr(Expr *E) { 4366 E = E->IgnoreParens(); 4367 4368 // Cannot know anything else if the expression is dependent. 4369 if (E->isTypeDependent()) 4370 return false; 4371 4372 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4373 } 4374 4375 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4376 CapturingScopeInfo *CSI) { 4377 assert(T->isVariablyModifiedType()); 4378 assert(CSI != nullptr); 4379 4380 // We're going to walk down into the type and look for VLA expressions. 4381 do { 4382 const Type *Ty = T.getTypePtr(); 4383 switch (Ty->getTypeClass()) { 4384 #define TYPE(Class, Base) 4385 #define ABSTRACT_TYPE(Class, Base) 4386 #define NON_CANONICAL_TYPE(Class, Base) 4387 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4388 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4389 #include "clang/AST/TypeNodes.inc" 4390 T = QualType(); 4391 break; 4392 // These types are never variably-modified. 4393 case Type::Builtin: 4394 case Type::Complex: 4395 case Type::Vector: 4396 case Type::ExtVector: 4397 case Type::ConstantMatrix: 4398 case Type::Record: 4399 case Type::Enum: 4400 case Type::Elaborated: 4401 case Type::TemplateSpecialization: 4402 case Type::ObjCObject: 4403 case Type::ObjCInterface: 4404 case Type::ObjCObjectPointer: 4405 case Type::ObjCTypeParam: 4406 case Type::Pipe: 4407 case Type::ExtInt: 4408 llvm_unreachable("type class is never variably-modified!"); 4409 case Type::Adjusted: 4410 T = cast<AdjustedType>(Ty)->getOriginalType(); 4411 break; 4412 case Type::Decayed: 4413 T = cast<DecayedType>(Ty)->getPointeeType(); 4414 break; 4415 case Type::Pointer: 4416 T = cast<PointerType>(Ty)->getPointeeType(); 4417 break; 4418 case Type::BlockPointer: 4419 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4420 break; 4421 case Type::LValueReference: 4422 case Type::RValueReference: 4423 T = cast<ReferenceType>(Ty)->getPointeeType(); 4424 break; 4425 case Type::MemberPointer: 4426 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4427 break; 4428 case Type::ConstantArray: 4429 case Type::IncompleteArray: 4430 // Losing element qualification here is fine. 4431 T = cast<ArrayType>(Ty)->getElementType(); 4432 break; 4433 case Type::VariableArray: { 4434 // Losing element qualification here is fine. 4435 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4436 4437 // Unknown size indication requires no size computation. 4438 // Otherwise, evaluate and record it. 4439 auto Size = VAT->getSizeExpr(); 4440 if (Size && !CSI->isVLATypeCaptured(VAT) && 4441 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4442 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4443 4444 T = VAT->getElementType(); 4445 break; 4446 } 4447 case Type::FunctionProto: 4448 case Type::FunctionNoProto: 4449 T = cast<FunctionType>(Ty)->getReturnType(); 4450 break; 4451 case Type::Paren: 4452 case Type::TypeOf: 4453 case Type::UnaryTransform: 4454 case Type::Attributed: 4455 case Type::SubstTemplateTypeParm: 4456 case Type::MacroQualified: 4457 // Keep walking after single level desugaring. 4458 T = T.getSingleStepDesugaredType(Context); 4459 break; 4460 case Type::Typedef: 4461 T = cast<TypedefType>(Ty)->desugar(); 4462 break; 4463 case Type::Decltype: 4464 T = cast<DecltypeType>(Ty)->desugar(); 4465 break; 4466 case Type::Auto: 4467 case Type::DeducedTemplateSpecialization: 4468 T = cast<DeducedType>(Ty)->getDeducedType(); 4469 break; 4470 case Type::TypeOfExpr: 4471 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4472 break; 4473 case Type::Atomic: 4474 T = cast<AtomicType>(Ty)->getValueType(); 4475 break; 4476 } 4477 } while (!T.isNull() && T->isVariablyModifiedType()); 4478 } 4479 4480 /// Build a sizeof or alignof expression given a type operand. 4481 ExprResult 4482 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4483 SourceLocation OpLoc, 4484 UnaryExprOrTypeTrait ExprKind, 4485 SourceRange R) { 4486 if (!TInfo) 4487 return ExprError(); 4488 4489 QualType T = TInfo->getType(); 4490 4491 if (!T->isDependentType() && 4492 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4493 return ExprError(); 4494 4495 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4496 if (auto *TT = T->getAs<TypedefType>()) { 4497 for (auto I = FunctionScopes.rbegin(), 4498 E = std::prev(FunctionScopes.rend()); 4499 I != E; ++I) { 4500 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4501 if (CSI == nullptr) 4502 break; 4503 DeclContext *DC = nullptr; 4504 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4505 DC = LSI->CallOperator; 4506 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4507 DC = CRSI->TheCapturedDecl; 4508 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4509 DC = BSI->TheDecl; 4510 if (DC) { 4511 if (DC->containsDecl(TT->getDecl())) 4512 break; 4513 captureVariablyModifiedType(Context, T, CSI); 4514 } 4515 } 4516 } 4517 } 4518 4519 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4520 return new (Context) UnaryExprOrTypeTraitExpr( 4521 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4522 } 4523 4524 /// Build a sizeof or alignof expression given an expression 4525 /// operand. 4526 ExprResult 4527 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4528 UnaryExprOrTypeTrait ExprKind) { 4529 ExprResult PE = CheckPlaceholderExpr(E); 4530 if (PE.isInvalid()) 4531 return ExprError(); 4532 4533 E = PE.get(); 4534 4535 // Verify that the operand is valid. 4536 bool isInvalid = false; 4537 if (E->isTypeDependent()) { 4538 // Delay type-checking for type-dependent expressions. 4539 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4540 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4541 } else if (ExprKind == UETT_VecStep) { 4542 isInvalid = CheckVecStepExpr(E); 4543 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4544 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4545 isInvalid = true; 4546 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4547 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4548 isInvalid = true; 4549 } else { 4550 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4551 } 4552 4553 if (isInvalid) 4554 return ExprError(); 4555 4556 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4557 PE = TransformToPotentiallyEvaluated(E); 4558 if (PE.isInvalid()) return ExprError(); 4559 E = PE.get(); 4560 } 4561 4562 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4563 return new (Context) UnaryExprOrTypeTraitExpr( 4564 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4565 } 4566 4567 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4568 /// expr and the same for @c alignof and @c __alignof 4569 /// Note that the ArgRange is invalid if isType is false. 4570 ExprResult 4571 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4572 UnaryExprOrTypeTrait ExprKind, bool IsType, 4573 void *TyOrEx, SourceRange ArgRange) { 4574 // If error parsing type, ignore. 4575 if (!TyOrEx) return ExprError(); 4576 4577 if (IsType) { 4578 TypeSourceInfo *TInfo; 4579 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4580 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4581 } 4582 4583 Expr *ArgEx = (Expr *)TyOrEx; 4584 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4585 return Result; 4586 } 4587 4588 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4589 bool IsReal) { 4590 if (V.get()->isTypeDependent()) 4591 return S.Context.DependentTy; 4592 4593 // _Real and _Imag are only l-values for normal l-values. 4594 if (V.get()->getObjectKind() != OK_Ordinary) { 4595 V = S.DefaultLvalueConversion(V.get()); 4596 if (V.isInvalid()) 4597 return QualType(); 4598 } 4599 4600 // These operators return the element type of a complex type. 4601 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4602 return CT->getElementType(); 4603 4604 // Otherwise they pass through real integer and floating point types here. 4605 if (V.get()->getType()->isArithmeticType()) 4606 return V.get()->getType(); 4607 4608 // Test for placeholders. 4609 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4610 if (PR.isInvalid()) return QualType(); 4611 if (PR.get() != V.get()) { 4612 V = PR; 4613 return CheckRealImagOperand(S, V, Loc, IsReal); 4614 } 4615 4616 // Reject anything else. 4617 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4618 << (IsReal ? "__real" : "__imag"); 4619 return QualType(); 4620 } 4621 4622 4623 4624 ExprResult 4625 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4626 tok::TokenKind Kind, Expr *Input) { 4627 UnaryOperatorKind Opc; 4628 switch (Kind) { 4629 default: llvm_unreachable("Unknown unary op!"); 4630 case tok::plusplus: Opc = UO_PostInc; break; 4631 case tok::minusminus: Opc = UO_PostDec; break; 4632 } 4633 4634 // Since this might is a postfix expression, get rid of ParenListExprs. 4635 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4636 if (Result.isInvalid()) return ExprError(); 4637 Input = Result.get(); 4638 4639 return BuildUnaryOp(S, OpLoc, Opc, Input); 4640 } 4641 4642 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4643 /// 4644 /// \return true on error 4645 static bool checkArithmeticOnObjCPointer(Sema &S, 4646 SourceLocation opLoc, 4647 Expr *op) { 4648 assert(op->getType()->isObjCObjectPointerType()); 4649 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4650 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4651 return false; 4652 4653 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4654 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4655 << op->getSourceRange(); 4656 return true; 4657 } 4658 4659 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4660 auto *BaseNoParens = Base->IgnoreParens(); 4661 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4662 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4663 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4664 } 4665 4666 ExprResult 4667 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4668 Expr *idx, SourceLocation rbLoc) { 4669 if (base && !base->getType().isNull() && 4670 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4671 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4672 SourceLocation(), /*Length*/ nullptr, 4673 /*Stride=*/nullptr, rbLoc); 4674 4675 // Since this might be a postfix expression, get rid of ParenListExprs. 4676 if (isa<ParenListExpr>(base)) { 4677 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4678 if (result.isInvalid()) return ExprError(); 4679 base = result.get(); 4680 } 4681 4682 // Check if base and idx form a MatrixSubscriptExpr. 4683 // 4684 // Helper to check for comma expressions, which are not allowed as indices for 4685 // matrix subscript expressions. 4686 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4687 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4688 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4689 << SourceRange(base->getBeginLoc(), rbLoc); 4690 return true; 4691 } 4692 return false; 4693 }; 4694 // The matrix subscript operator ([][])is considered a single operator. 4695 // Separating the index expressions by parenthesis is not allowed. 4696 if (base->getType()->isSpecificPlaceholderType( 4697 BuiltinType::IncompleteMatrixIdx) && 4698 !isa<MatrixSubscriptExpr>(base)) { 4699 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4700 << SourceRange(base->getBeginLoc(), rbLoc); 4701 return ExprError(); 4702 } 4703 // If the base is a MatrixSubscriptExpr, try to create a new 4704 // MatrixSubscriptExpr. 4705 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4706 if (matSubscriptE) { 4707 if (CheckAndReportCommaError(idx)) 4708 return ExprError(); 4709 4710 assert(matSubscriptE->isIncomplete() && 4711 "base has to be an incomplete matrix subscript"); 4712 return CreateBuiltinMatrixSubscriptExpr( 4713 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4714 } 4715 4716 // Handle any non-overload placeholder types in the base and index 4717 // expressions. We can't handle overloads here because the other 4718 // operand might be an overloadable type, in which case the overload 4719 // resolution for the operator overload should get the first crack 4720 // at the overload. 4721 bool IsMSPropertySubscript = false; 4722 if (base->getType()->isNonOverloadPlaceholderType()) { 4723 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4724 if (!IsMSPropertySubscript) { 4725 ExprResult result = CheckPlaceholderExpr(base); 4726 if (result.isInvalid()) 4727 return ExprError(); 4728 base = result.get(); 4729 } 4730 } 4731 4732 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4733 if (base->getType()->isMatrixType()) { 4734 if (CheckAndReportCommaError(idx)) 4735 return ExprError(); 4736 4737 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4738 } 4739 4740 // A comma-expression as the index is deprecated in C++2a onwards. 4741 if (getLangOpts().CPlusPlus20 && 4742 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4743 (isa<CXXOperatorCallExpr>(idx) && 4744 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4745 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4746 << SourceRange(base->getBeginLoc(), rbLoc); 4747 } 4748 4749 if (idx->getType()->isNonOverloadPlaceholderType()) { 4750 ExprResult result = CheckPlaceholderExpr(idx); 4751 if (result.isInvalid()) return ExprError(); 4752 idx = result.get(); 4753 } 4754 4755 // Build an unanalyzed expression if either operand is type-dependent. 4756 if (getLangOpts().CPlusPlus && 4757 (base->isTypeDependent() || idx->isTypeDependent())) { 4758 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4759 VK_LValue, OK_Ordinary, rbLoc); 4760 } 4761 4762 // MSDN, property (C++) 4763 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4764 // This attribute can also be used in the declaration of an empty array in a 4765 // class or structure definition. For example: 4766 // __declspec(property(get=GetX, put=PutX)) int x[]; 4767 // The above statement indicates that x[] can be used with one or more array 4768 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4769 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4770 if (IsMSPropertySubscript) { 4771 // Build MS property subscript expression if base is MS property reference 4772 // or MS property subscript. 4773 return new (Context) MSPropertySubscriptExpr( 4774 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4775 } 4776 4777 // Use C++ overloaded-operator rules if either operand has record 4778 // type. The spec says to do this if either type is *overloadable*, 4779 // but enum types can't declare subscript operators or conversion 4780 // operators, so there's nothing interesting for overload resolution 4781 // to do if there aren't any record types involved. 4782 // 4783 // ObjC pointers have their own subscripting logic that is not tied 4784 // to overload resolution and so should not take this path. 4785 if (getLangOpts().CPlusPlus && 4786 (base->getType()->isRecordType() || 4787 (!base->getType()->isObjCObjectPointerType() && 4788 idx->getType()->isRecordType()))) { 4789 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4790 } 4791 4792 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4793 4794 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4795 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4796 4797 return Res; 4798 } 4799 4800 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4801 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4802 InitializationKind Kind = 4803 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4804 InitializationSequence InitSeq(*this, Entity, Kind, E); 4805 return InitSeq.Perform(*this, Entity, Kind, E); 4806 } 4807 4808 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4809 Expr *ColumnIdx, 4810 SourceLocation RBLoc) { 4811 ExprResult BaseR = CheckPlaceholderExpr(Base); 4812 if (BaseR.isInvalid()) 4813 return BaseR; 4814 Base = BaseR.get(); 4815 4816 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4817 if (RowR.isInvalid()) 4818 return RowR; 4819 RowIdx = RowR.get(); 4820 4821 if (!ColumnIdx) 4822 return new (Context) MatrixSubscriptExpr( 4823 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4824 4825 // Build an unanalyzed expression if any of the operands is type-dependent. 4826 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4827 ColumnIdx->isTypeDependent()) 4828 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4829 Context.DependentTy, RBLoc); 4830 4831 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4832 if (ColumnR.isInvalid()) 4833 return ColumnR; 4834 ColumnIdx = ColumnR.get(); 4835 4836 // Check that IndexExpr is an integer expression. If it is a constant 4837 // expression, check that it is less than Dim (= the number of elements in the 4838 // corresponding dimension). 4839 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4840 bool IsColumnIdx) -> Expr * { 4841 if (!IndexExpr->getType()->isIntegerType() && 4842 !IndexExpr->isTypeDependent()) { 4843 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4844 << IsColumnIdx; 4845 return nullptr; 4846 } 4847 4848 if (Optional<llvm::APSInt> Idx = 4849 IndexExpr->getIntegerConstantExpr(Context)) { 4850 if ((*Idx < 0 || *Idx >= Dim)) { 4851 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4852 << IsColumnIdx << Dim; 4853 return nullptr; 4854 } 4855 } 4856 4857 ExprResult ConvExpr = 4858 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4859 assert(!ConvExpr.isInvalid() && 4860 "should be able to convert any integer type to size type"); 4861 return ConvExpr.get(); 4862 }; 4863 4864 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4865 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4866 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4867 if (!RowIdx || !ColumnIdx) 4868 return ExprError(); 4869 4870 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4871 MTy->getElementType(), RBLoc); 4872 } 4873 4874 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4875 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4876 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4877 4878 // For expressions like `&(*s).b`, the base is recorded and what should be 4879 // checked. 4880 const MemberExpr *Member = nullptr; 4881 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4882 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4883 4884 LastRecord.PossibleDerefs.erase(StrippedExpr); 4885 } 4886 4887 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4888 if (isUnevaluatedContext()) 4889 return; 4890 4891 QualType ResultTy = E->getType(); 4892 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4893 4894 // Bail if the element is an array since it is not memory access. 4895 if (isa<ArrayType>(ResultTy)) 4896 return; 4897 4898 if (ResultTy->hasAttr(attr::NoDeref)) { 4899 LastRecord.PossibleDerefs.insert(E); 4900 return; 4901 } 4902 4903 // Check if the base type is a pointer to a member access of a struct 4904 // marked with noderef. 4905 const Expr *Base = E->getBase(); 4906 QualType BaseTy = Base->getType(); 4907 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4908 // Not a pointer access 4909 return; 4910 4911 const MemberExpr *Member = nullptr; 4912 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4913 Member->isArrow()) 4914 Base = Member->getBase(); 4915 4916 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4917 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4918 LastRecord.PossibleDerefs.insert(E); 4919 } 4920 } 4921 4922 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4923 Expr *LowerBound, 4924 SourceLocation ColonLocFirst, 4925 SourceLocation ColonLocSecond, 4926 Expr *Length, Expr *Stride, 4927 SourceLocation RBLoc) { 4928 if (Base->getType()->isPlaceholderType() && 4929 !Base->getType()->isSpecificPlaceholderType( 4930 BuiltinType::OMPArraySection)) { 4931 ExprResult Result = CheckPlaceholderExpr(Base); 4932 if (Result.isInvalid()) 4933 return ExprError(); 4934 Base = Result.get(); 4935 } 4936 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4937 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4938 if (Result.isInvalid()) 4939 return ExprError(); 4940 Result = DefaultLvalueConversion(Result.get()); 4941 if (Result.isInvalid()) 4942 return ExprError(); 4943 LowerBound = Result.get(); 4944 } 4945 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4946 ExprResult Result = CheckPlaceholderExpr(Length); 4947 if (Result.isInvalid()) 4948 return ExprError(); 4949 Result = DefaultLvalueConversion(Result.get()); 4950 if (Result.isInvalid()) 4951 return ExprError(); 4952 Length = Result.get(); 4953 } 4954 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4955 ExprResult Result = CheckPlaceholderExpr(Stride); 4956 if (Result.isInvalid()) 4957 return ExprError(); 4958 Result = DefaultLvalueConversion(Result.get()); 4959 if (Result.isInvalid()) 4960 return ExprError(); 4961 Stride = Result.get(); 4962 } 4963 4964 // Build an unanalyzed expression if either operand is type-dependent. 4965 if (Base->isTypeDependent() || 4966 (LowerBound && 4967 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4968 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4969 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4970 return new (Context) OMPArraySectionExpr( 4971 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4972 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4973 } 4974 4975 // Perform default conversions. 4976 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4977 QualType ResultTy; 4978 if (OriginalTy->isAnyPointerType()) { 4979 ResultTy = OriginalTy->getPointeeType(); 4980 } else if (OriginalTy->isArrayType()) { 4981 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4982 } else { 4983 return ExprError( 4984 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4985 << Base->getSourceRange()); 4986 } 4987 // C99 6.5.2.1p1 4988 if (LowerBound) { 4989 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4990 LowerBound); 4991 if (Res.isInvalid()) 4992 return ExprError(Diag(LowerBound->getExprLoc(), 4993 diag::err_omp_typecheck_section_not_integer) 4994 << 0 << LowerBound->getSourceRange()); 4995 LowerBound = Res.get(); 4996 4997 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4998 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4999 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5000 << 0 << LowerBound->getSourceRange(); 5001 } 5002 if (Length) { 5003 auto Res = 5004 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5005 if (Res.isInvalid()) 5006 return ExprError(Diag(Length->getExprLoc(), 5007 diag::err_omp_typecheck_section_not_integer) 5008 << 1 << Length->getSourceRange()); 5009 Length = Res.get(); 5010 5011 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5012 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5013 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5014 << 1 << Length->getSourceRange(); 5015 } 5016 if (Stride) { 5017 ExprResult Res = 5018 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5019 if (Res.isInvalid()) 5020 return ExprError(Diag(Stride->getExprLoc(), 5021 diag::err_omp_typecheck_section_not_integer) 5022 << 1 << Stride->getSourceRange()); 5023 Stride = Res.get(); 5024 5025 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5026 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5027 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5028 << 1 << Stride->getSourceRange(); 5029 } 5030 5031 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5032 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5033 // type. Note that functions are not objects, and that (in C99 parlance) 5034 // incomplete types are not object types. 5035 if (ResultTy->isFunctionType()) { 5036 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5037 << ResultTy << Base->getSourceRange(); 5038 return ExprError(); 5039 } 5040 5041 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5042 diag::err_omp_section_incomplete_type, Base)) 5043 return ExprError(); 5044 5045 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5046 Expr::EvalResult Result; 5047 if (LowerBound->EvaluateAsInt(Result, Context)) { 5048 // OpenMP 5.0, [2.1.5 Array Sections] 5049 // The array section must be a subset of the original array. 5050 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5051 if (LowerBoundValue.isNegative()) { 5052 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5053 << LowerBound->getSourceRange(); 5054 return ExprError(); 5055 } 5056 } 5057 } 5058 5059 if (Length) { 5060 Expr::EvalResult Result; 5061 if (Length->EvaluateAsInt(Result, Context)) { 5062 // OpenMP 5.0, [2.1.5 Array Sections] 5063 // The length must evaluate to non-negative integers. 5064 llvm::APSInt LengthValue = Result.Val.getInt(); 5065 if (LengthValue.isNegative()) { 5066 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5067 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5068 << Length->getSourceRange(); 5069 return ExprError(); 5070 } 5071 } 5072 } else if (ColonLocFirst.isValid() && 5073 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5074 !OriginalTy->isVariableArrayType()))) { 5075 // OpenMP 5.0, [2.1.5 Array Sections] 5076 // When the size of the array dimension is not known, the length must be 5077 // specified explicitly. 5078 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5079 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5080 return ExprError(); 5081 } 5082 5083 if (Stride) { 5084 Expr::EvalResult Result; 5085 if (Stride->EvaluateAsInt(Result, Context)) { 5086 // OpenMP 5.0, [2.1.5 Array Sections] 5087 // The stride must evaluate to a positive integer. 5088 llvm::APSInt StrideValue = Result.Val.getInt(); 5089 if (!StrideValue.isStrictlyPositive()) { 5090 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5091 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5092 << Stride->getSourceRange(); 5093 return ExprError(); 5094 } 5095 } 5096 } 5097 5098 if (!Base->getType()->isSpecificPlaceholderType( 5099 BuiltinType::OMPArraySection)) { 5100 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5101 if (Result.isInvalid()) 5102 return ExprError(); 5103 Base = Result.get(); 5104 } 5105 return new (Context) OMPArraySectionExpr( 5106 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5107 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5108 } 5109 5110 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5111 SourceLocation RParenLoc, 5112 ArrayRef<Expr *> Dims, 5113 ArrayRef<SourceRange> Brackets) { 5114 if (Base->getType()->isPlaceholderType()) { 5115 ExprResult Result = CheckPlaceholderExpr(Base); 5116 if (Result.isInvalid()) 5117 return ExprError(); 5118 Result = DefaultLvalueConversion(Result.get()); 5119 if (Result.isInvalid()) 5120 return ExprError(); 5121 Base = Result.get(); 5122 } 5123 QualType BaseTy = Base->getType(); 5124 // Delay analysis of the types/expressions if instantiation/specialization is 5125 // required. 5126 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5127 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5128 LParenLoc, RParenLoc, Dims, Brackets); 5129 if (!BaseTy->isPointerType() || 5130 (!Base->isTypeDependent() && 5131 BaseTy->getPointeeType()->isIncompleteType())) 5132 return ExprError(Diag(Base->getExprLoc(), 5133 diag::err_omp_non_pointer_type_array_shaping_base) 5134 << Base->getSourceRange()); 5135 5136 SmallVector<Expr *, 4> NewDims; 5137 bool ErrorFound = false; 5138 for (Expr *Dim : Dims) { 5139 if (Dim->getType()->isPlaceholderType()) { 5140 ExprResult Result = CheckPlaceholderExpr(Dim); 5141 if (Result.isInvalid()) { 5142 ErrorFound = true; 5143 continue; 5144 } 5145 Result = DefaultLvalueConversion(Result.get()); 5146 if (Result.isInvalid()) { 5147 ErrorFound = true; 5148 continue; 5149 } 5150 Dim = Result.get(); 5151 } 5152 if (!Dim->isTypeDependent()) { 5153 ExprResult Result = 5154 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5155 if (Result.isInvalid()) { 5156 ErrorFound = true; 5157 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5158 << Dim->getSourceRange(); 5159 continue; 5160 } 5161 Dim = Result.get(); 5162 Expr::EvalResult EvResult; 5163 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5164 // OpenMP 5.0, [2.1.4 Array Shaping] 5165 // Each si is an integral type expression that must evaluate to a 5166 // positive integer. 5167 llvm::APSInt Value = EvResult.Val.getInt(); 5168 if (!Value.isStrictlyPositive()) { 5169 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5170 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5171 << Dim->getSourceRange(); 5172 ErrorFound = true; 5173 continue; 5174 } 5175 } 5176 } 5177 NewDims.push_back(Dim); 5178 } 5179 if (ErrorFound) 5180 return ExprError(); 5181 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5182 LParenLoc, RParenLoc, NewDims, Brackets); 5183 } 5184 5185 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5186 SourceLocation LLoc, SourceLocation RLoc, 5187 ArrayRef<OMPIteratorData> Data) { 5188 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5189 bool IsCorrect = true; 5190 for (const OMPIteratorData &D : Data) { 5191 TypeSourceInfo *TInfo = nullptr; 5192 SourceLocation StartLoc; 5193 QualType DeclTy; 5194 if (!D.Type.getAsOpaquePtr()) { 5195 // OpenMP 5.0, 2.1.6 Iterators 5196 // In an iterator-specifier, if the iterator-type is not specified then 5197 // the type of that iterator is of int type. 5198 DeclTy = Context.IntTy; 5199 StartLoc = D.DeclIdentLoc; 5200 } else { 5201 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5202 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5203 } 5204 5205 bool IsDeclTyDependent = DeclTy->isDependentType() || 5206 DeclTy->containsUnexpandedParameterPack() || 5207 DeclTy->isInstantiationDependentType(); 5208 if (!IsDeclTyDependent) { 5209 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5210 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5211 // The iterator-type must be an integral or pointer type. 5212 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5213 << DeclTy; 5214 IsCorrect = false; 5215 continue; 5216 } 5217 if (DeclTy.isConstant(Context)) { 5218 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5219 // The iterator-type must not be const qualified. 5220 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5221 << DeclTy; 5222 IsCorrect = false; 5223 continue; 5224 } 5225 } 5226 5227 // Iterator declaration. 5228 assert(D.DeclIdent && "Identifier expected."); 5229 // Always try to create iterator declarator to avoid extra error messages 5230 // about unknown declarations use. 5231 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5232 D.DeclIdent, DeclTy, TInfo, SC_None); 5233 VD->setImplicit(); 5234 if (S) { 5235 // Check for conflicting previous declaration. 5236 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5237 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5238 ForVisibleRedeclaration); 5239 Previous.suppressDiagnostics(); 5240 LookupName(Previous, S); 5241 5242 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5243 /*AllowInlineNamespace=*/false); 5244 if (!Previous.empty()) { 5245 NamedDecl *Old = Previous.getRepresentativeDecl(); 5246 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5247 Diag(Old->getLocation(), diag::note_previous_definition); 5248 } else { 5249 PushOnScopeChains(VD, S); 5250 } 5251 } else { 5252 CurContext->addDecl(VD); 5253 } 5254 Expr *Begin = D.Range.Begin; 5255 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5256 ExprResult BeginRes = 5257 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5258 Begin = BeginRes.get(); 5259 } 5260 Expr *End = D.Range.End; 5261 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5262 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5263 End = EndRes.get(); 5264 } 5265 Expr *Step = D.Range.Step; 5266 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5267 if (!Step->getType()->isIntegralType(Context)) { 5268 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5269 << Step << Step->getSourceRange(); 5270 IsCorrect = false; 5271 continue; 5272 } 5273 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5274 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5275 // If the step expression of a range-specification equals zero, the 5276 // behavior is unspecified. 5277 if (Result && Result->isNullValue()) { 5278 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5279 << Step << Step->getSourceRange(); 5280 IsCorrect = false; 5281 continue; 5282 } 5283 } 5284 if (!Begin || !End || !IsCorrect) { 5285 IsCorrect = false; 5286 continue; 5287 } 5288 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5289 IDElem.IteratorDecl = VD; 5290 IDElem.AssignmentLoc = D.AssignLoc; 5291 IDElem.Range.Begin = Begin; 5292 IDElem.Range.End = End; 5293 IDElem.Range.Step = Step; 5294 IDElem.ColonLoc = D.ColonLoc; 5295 IDElem.SecondColonLoc = D.SecColonLoc; 5296 } 5297 if (!IsCorrect) { 5298 // Invalidate all created iterator declarations if error is found. 5299 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5300 if (Decl *ID = D.IteratorDecl) 5301 ID->setInvalidDecl(); 5302 } 5303 return ExprError(); 5304 } 5305 SmallVector<OMPIteratorHelperData, 4> Helpers; 5306 if (!CurContext->isDependentContext()) { 5307 // Build number of ityeration for each iteration range. 5308 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5309 // ((Begini-Stepi-1-Endi) / -Stepi); 5310 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5311 // (Endi - Begini) 5312 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5313 D.Range.Begin); 5314 if(!Res.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 ExprResult St, St1; 5319 if (D.Range.Step) { 5320 St = D.Range.Step; 5321 // (Endi - Begini) + Stepi 5322 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5323 if (!Res.isUsable()) { 5324 IsCorrect = false; 5325 continue; 5326 } 5327 // (Endi - Begini) + Stepi - 1 5328 Res = 5329 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5330 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5331 if (!Res.isUsable()) { 5332 IsCorrect = false; 5333 continue; 5334 } 5335 // ((Endi - Begini) + Stepi - 1) / Stepi 5336 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5337 if (!Res.isUsable()) { 5338 IsCorrect = false; 5339 continue; 5340 } 5341 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5342 // (Begini - Endi) 5343 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5344 D.Range.Begin, D.Range.End); 5345 if (!Res1.isUsable()) { 5346 IsCorrect = false; 5347 continue; 5348 } 5349 // (Begini - Endi) - Stepi 5350 Res1 = 5351 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5352 if (!Res1.isUsable()) { 5353 IsCorrect = false; 5354 continue; 5355 } 5356 // (Begini - Endi) - Stepi - 1 5357 Res1 = 5358 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5359 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5360 if (!Res1.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5365 Res1 = 5366 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5367 if (!Res1.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 // Stepi > 0. 5372 ExprResult CmpRes = 5373 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5374 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5375 if (!CmpRes.isUsable()) { 5376 IsCorrect = false; 5377 continue; 5378 } 5379 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5380 Res.get(), Res1.get()); 5381 if (!Res.isUsable()) { 5382 IsCorrect = false; 5383 continue; 5384 } 5385 } 5386 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5387 if (!Res.isUsable()) { 5388 IsCorrect = false; 5389 continue; 5390 } 5391 5392 // Build counter update. 5393 // Build counter. 5394 auto *CounterVD = 5395 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5396 D.IteratorDecl->getBeginLoc(), nullptr, 5397 Res.get()->getType(), nullptr, SC_None); 5398 CounterVD->setImplicit(); 5399 ExprResult RefRes = 5400 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5401 D.IteratorDecl->getBeginLoc()); 5402 // Build counter update. 5403 // I = Begini + counter * Stepi; 5404 ExprResult UpdateRes; 5405 if (D.Range.Step) { 5406 UpdateRes = CreateBuiltinBinOp( 5407 D.AssignmentLoc, BO_Mul, 5408 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5409 } else { 5410 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5411 } 5412 if (!UpdateRes.isUsable()) { 5413 IsCorrect = false; 5414 continue; 5415 } 5416 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5417 UpdateRes.get()); 5418 if (!UpdateRes.isUsable()) { 5419 IsCorrect = false; 5420 continue; 5421 } 5422 ExprResult VDRes = 5423 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5424 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5425 D.IteratorDecl->getBeginLoc()); 5426 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5427 UpdateRes.get()); 5428 if (!UpdateRes.isUsable()) { 5429 IsCorrect = false; 5430 continue; 5431 } 5432 UpdateRes = 5433 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5434 if (!UpdateRes.isUsable()) { 5435 IsCorrect = false; 5436 continue; 5437 } 5438 ExprResult CounterUpdateRes = 5439 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5440 if (!CounterUpdateRes.isUsable()) { 5441 IsCorrect = false; 5442 continue; 5443 } 5444 CounterUpdateRes = 5445 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5446 if (!CounterUpdateRes.isUsable()) { 5447 IsCorrect = false; 5448 continue; 5449 } 5450 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5451 HD.CounterVD = CounterVD; 5452 HD.Upper = Res.get(); 5453 HD.Update = UpdateRes.get(); 5454 HD.CounterUpdate = CounterUpdateRes.get(); 5455 } 5456 } else { 5457 Helpers.assign(ID.size(), {}); 5458 } 5459 if (!IsCorrect) { 5460 // Invalidate all created iterator declarations if error is found. 5461 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5462 if (Decl *ID = D.IteratorDecl) 5463 ID->setInvalidDecl(); 5464 } 5465 return ExprError(); 5466 } 5467 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5468 LLoc, RLoc, ID, Helpers); 5469 } 5470 5471 ExprResult 5472 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5473 Expr *Idx, SourceLocation RLoc) { 5474 Expr *LHSExp = Base; 5475 Expr *RHSExp = Idx; 5476 5477 ExprValueKind VK = VK_LValue; 5478 ExprObjectKind OK = OK_Ordinary; 5479 5480 // Per C++ core issue 1213, the result is an xvalue if either operand is 5481 // a non-lvalue array, and an lvalue otherwise. 5482 if (getLangOpts().CPlusPlus11) { 5483 for (auto *Op : {LHSExp, RHSExp}) { 5484 Op = Op->IgnoreImplicit(); 5485 if (Op->getType()->isArrayType() && !Op->isLValue()) 5486 VK = VK_XValue; 5487 } 5488 } 5489 5490 // Perform default conversions. 5491 if (!LHSExp->getType()->getAs<VectorType>()) { 5492 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5493 if (Result.isInvalid()) 5494 return ExprError(); 5495 LHSExp = Result.get(); 5496 } 5497 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5498 if (Result.isInvalid()) 5499 return ExprError(); 5500 RHSExp = Result.get(); 5501 5502 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5503 5504 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5505 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5506 // in the subscript position. As a result, we need to derive the array base 5507 // and index from the expression types. 5508 Expr *BaseExpr, *IndexExpr; 5509 QualType ResultType; 5510 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5511 BaseExpr = LHSExp; 5512 IndexExpr = RHSExp; 5513 ResultType = Context.DependentTy; 5514 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5515 BaseExpr = LHSExp; 5516 IndexExpr = RHSExp; 5517 ResultType = PTy->getPointeeType(); 5518 } else if (const ObjCObjectPointerType *PTy = 5519 LHSTy->getAs<ObjCObjectPointerType>()) { 5520 BaseExpr = LHSExp; 5521 IndexExpr = RHSExp; 5522 5523 // Use custom logic if this should be the pseudo-object subscript 5524 // expression. 5525 if (!LangOpts.isSubscriptPointerArithmetic()) 5526 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5527 nullptr); 5528 5529 ResultType = PTy->getPointeeType(); 5530 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5531 // Handle the uncommon case of "123[Ptr]". 5532 BaseExpr = RHSExp; 5533 IndexExpr = LHSExp; 5534 ResultType = PTy->getPointeeType(); 5535 } else if (const ObjCObjectPointerType *PTy = 5536 RHSTy->getAs<ObjCObjectPointerType>()) { 5537 // Handle the uncommon case of "123[Ptr]". 5538 BaseExpr = RHSExp; 5539 IndexExpr = LHSExp; 5540 ResultType = PTy->getPointeeType(); 5541 if (!LangOpts.isSubscriptPointerArithmetic()) { 5542 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5543 << ResultType << BaseExpr->getSourceRange(); 5544 return ExprError(); 5545 } 5546 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5547 BaseExpr = LHSExp; // vectors: V[123] 5548 IndexExpr = RHSExp; 5549 // We apply C++ DR1213 to vector subscripting too. 5550 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_PRValue) { 5551 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5552 if (Materialized.isInvalid()) 5553 return ExprError(); 5554 LHSExp = Materialized.get(); 5555 } 5556 VK = LHSExp->getValueKind(); 5557 if (VK != VK_PRValue) 5558 OK = OK_VectorComponent; 5559 5560 ResultType = VTy->getElementType(); 5561 QualType BaseType = BaseExpr->getType(); 5562 Qualifiers BaseQuals = BaseType.getQualifiers(); 5563 Qualifiers MemberQuals = ResultType.getQualifiers(); 5564 Qualifiers Combined = BaseQuals + MemberQuals; 5565 if (Combined != MemberQuals) 5566 ResultType = Context.getQualifiedType(ResultType, Combined); 5567 } else if (LHSTy->isArrayType()) { 5568 // If we see an array that wasn't promoted by 5569 // DefaultFunctionArrayLvalueConversion, it must be an array that 5570 // wasn't promoted because of the C90 rule that doesn't 5571 // allow promoting non-lvalue arrays. Warn, then 5572 // force the promotion here. 5573 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5574 << LHSExp->getSourceRange(); 5575 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5576 CK_ArrayToPointerDecay).get(); 5577 LHSTy = LHSExp->getType(); 5578 5579 BaseExpr = LHSExp; 5580 IndexExpr = RHSExp; 5581 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5582 } else if (RHSTy->isArrayType()) { 5583 // Same as previous, except for 123[f().a] case 5584 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5585 << RHSExp->getSourceRange(); 5586 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5587 CK_ArrayToPointerDecay).get(); 5588 RHSTy = RHSExp->getType(); 5589 5590 BaseExpr = RHSExp; 5591 IndexExpr = LHSExp; 5592 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5593 } else { 5594 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5595 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5596 } 5597 // C99 6.5.2.1p1 5598 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5599 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5600 << IndexExpr->getSourceRange()); 5601 5602 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5603 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5604 && !IndexExpr->isTypeDependent()) 5605 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5606 5607 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5608 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5609 // type. Note that Functions are not objects, and that (in C99 parlance) 5610 // incomplete types are not object types. 5611 if (ResultType->isFunctionType()) { 5612 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5613 << ResultType << BaseExpr->getSourceRange(); 5614 return ExprError(); 5615 } 5616 5617 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5618 // GNU extension: subscripting on pointer to void 5619 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5620 << BaseExpr->getSourceRange(); 5621 5622 // C forbids expressions of unqualified void type from being l-values. 5623 // See IsCForbiddenLValueType. 5624 if (!ResultType.hasQualifiers()) 5625 VK = VK_PRValue; 5626 } else if (!ResultType->isDependentType() && 5627 RequireCompleteSizedType( 5628 LLoc, ResultType, 5629 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5630 return ExprError(); 5631 5632 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5633 !ResultType.isCForbiddenLValueType()); 5634 5635 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5636 FunctionScopes.size() > 1) { 5637 if (auto *TT = 5638 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5639 for (auto I = FunctionScopes.rbegin(), 5640 E = std::prev(FunctionScopes.rend()); 5641 I != E; ++I) { 5642 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5643 if (CSI == nullptr) 5644 break; 5645 DeclContext *DC = nullptr; 5646 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5647 DC = LSI->CallOperator; 5648 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5649 DC = CRSI->TheCapturedDecl; 5650 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5651 DC = BSI->TheDecl; 5652 if (DC) { 5653 if (DC->containsDecl(TT->getDecl())) 5654 break; 5655 captureVariablyModifiedType( 5656 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5657 } 5658 } 5659 } 5660 } 5661 5662 return new (Context) 5663 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5664 } 5665 5666 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5667 ParmVarDecl *Param) { 5668 if (Param->hasUnparsedDefaultArg()) { 5669 // If we've already cleared out the location for the default argument, 5670 // that means we're parsing it right now. 5671 if (!UnparsedDefaultArgLocs.count(Param)) { 5672 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5673 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5674 Param->setInvalidDecl(); 5675 return true; 5676 } 5677 5678 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5679 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5680 Diag(UnparsedDefaultArgLocs[Param], 5681 diag::note_default_argument_declared_here); 5682 return true; 5683 } 5684 5685 if (Param->hasUninstantiatedDefaultArg() && 5686 InstantiateDefaultArgument(CallLoc, FD, Param)) 5687 return true; 5688 5689 assert(Param->hasInit() && "default argument but no initializer?"); 5690 5691 // If the default expression creates temporaries, we need to 5692 // push them to the current stack of expression temporaries so they'll 5693 // be properly destroyed. 5694 // FIXME: We should really be rebuilding the default argument with new 5695 // bound temporaries; see the comment in PR5810. 5696 // We don't need to do that with block decls, though, because 5697 // blocks in default argument expression can never capture anything. 5698 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5699 // Set the "needs cleanups" bit regardless of whether there are 5700 // any explicit objects. 5701 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5702 5703 // Append all the objects to the cleanup list. Right now, this 5704 // should always be a no-op, because blocks in default argument 5705 // expressions should never be able to capture anything. 5706 assert(!Init->getNumObjects() && 5707 "default argument expression has capturing blocks?"); 5708 } 5709 5710 // We already type-checked the argument, so we know it works. 5711 // Just mark all of the declarations in this potentially-evaluated expression 5712 // as being "referenced". 5713 EnterExpressionEvaluationContext EvalContext( 5714 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5715 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5716 /*SkipLocalVariables=*/true); 5717 return false; 5718 } 5719 5720 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5721 FunctionDecl *FD, ParmVarDecl *Param) { 5722 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5723 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5724 return ExprError(); 5725 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5726 } 5727 5728 Sema::VariadicCallType 5729 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5730 Expr *Fn) { 5731 if (Proto && Proto->isVariadic()) { 5732 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5733 return VariadicConstructor; 5734 else if (Fn && Fn->getType()->isBlockPointerType()) 5735 return VariadicBlock; 5736 else if (FDecl) { 5737 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5738 if (Method->isInstance()) 5739 return VariadicMethod; 5740 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5741 return VariadicMethod; 5742 return VariadicFunction; 5743 } 5744 return VariadicDoesNotApply; 5745 } 5746 5747 namespace { 5748 class FunctionCallCCC final : public FunctionCallFilterCCC { 5749 public: 5750 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5751 unsigned NumArgs, MemberExpr *ME) 5752 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5753 FunctionName(FuncName) {} 5754 5755 bool ValidateCandidate(const TypoCorrection &candidate) override { 5756 if (!candidate.getCorrectionSpecifier() || 5757 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5758 return false; 5759 } 5760 5761 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5762 } 5763 5764 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5765 return std::make_unique<FunctionCallCCC>(*this); 5766 } 5767 5768 private: 5769 const IdentifierInfo *const FunctionName; 5770 }; 5771 } 5772 5773 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5774 FunctionDecl *FDecl, 5775 ArrayRef<Expr *> Args) { 5776 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5777 DeclarationName FuncName = FDecl->getDeclName(); 5778 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5779 5780 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5781 if (TypoCorrection Corrected = S.CorrectTypo( 5782 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5783 S.getScopeForContext(S.CurContext), nullptr, CCC, 5784 Sema::CTK_ErrorRecovery)) { 5785 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5786 if (Corrected.isOverloaded()) { 5787 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5788 OverloadCandidateSet::iterator Best; 5789 for (NamedDecl *CD : Corrected) { 5790 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5791 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5792 OCS); 5793 } 5794 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5795 case OR_Success: 5796 ND = Best->FoundDecl; 5797 Corrected.setCorrectionDecl(ND); 5798 break; 5799 default: 5800 break; 5801 } 5802 } 5803 ND = ND->getUnderlyingDecl(); 5804 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5805 return Corrected; 5806 } 5807 } 5808 return TypoCorrection(); 5809 } 5810 5811 /// ConvertArgumentsForCall - Converts the arguments specified in 5812 /// Args/NumArgs to the parameter types of the function FDecl with 5813 /// function prototype Proto. Call is the call expression itself, and 5814 /// Fn is the function expression. For a C++ member function, this 5815 /// routine does not attempt to convert the object argument. Returns 5816 /// true if the call is ill-formed. 5817 bool 5818 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5819 FunctionDecl *FDecl, 5820 const FunctionProtoType *Proto, 5821 ArrayRef<Expr *> Args, 5822 SourceLocation RParenLoc, 5823 bool IsExecConfig) { 5824 // Bail out early if calling a builtin with custom typechecking. 5825 if (FDecl) 5826 if (unsigned ID = FDecl->getBuiltinID()) 5827 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5828 return false; 5829 5830 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5831 // assignment, to the types of the corresponding parameter, ... 5832 unsigned NumParams = Proto->getNumParams(); 5833 bool Invalid = false; 5834 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5835 unsigned FnKind = Fn->getType()->isBlockPointerType() 5836 ? 1 /* block */ 5837 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5838 : 0 /* function */); 5839 5840 // If too few arguments are available (and we don't have default 5841 // arguments for the remaining parameters), don't make the call. 5842 if (Args.size() < NumParams) { 5843 if (Args.size() < MinArgs) { 5844 TypoCorrection TC; 5845 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5846 unsigned diag_id = 5847 MinArgs == NumParams && !Proto->isVariadic() 5848 ? diag::err_typecheck_call_too_few_args_suggest 5849 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5850 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5851 << static_cast<unsigned>(Args.size()) 5852 << TC.getCorrectionRange()); 5853 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5854 Diag(RParenLoc, 5855 MinArgs == NumParams && !Proto->isVariadic() 5856 ? diag::err_typecheck_call_too_few_args_one 5857 : diag::err_typecheck_call_too_few_args_at_least_one) 5858 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5859 else 5860 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5861 ? diag::err_typecheck_call_too_few_args 5862 : diag::err_typecheck_call_too_few_args_at_least) 5863 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5864 << Fn->getSourceRange(); 5865 5866 // Emit the location of the prototype. 5867 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5868 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5869 5870 return true; 5871 } 5872 // We reserve space for the default arguments when we create 5873 // the call expression, before calling ConvertArgumentsForCall. 5874 assert((Call->getNumArgs() == NumParams) && 5875 "We should have reserved space for the default arguments before!"); 5876 } 5877 5878 // If too many are passed and not variadic, error on the extras and drop 5879 // them. 5880 if (Args.size() > NumParams) { 5881 if (!Proto->isVariadic()) { 5882 TypoCorrection TC; 5883 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5884 unsigned diag_id = 5885 MinArgs == NumParams && !Proto->isVariadic() 5886 ? diag::err_typecheck_call_too_many_args_suggest 5887 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5888 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5889 << static_cast<unsigned>(Args.size()) 5890 << TC.getCorrectionRange()); 5891 } else if (NumParams == 1 && FDecl && 5892 FDecl->getParamDecl(0)->getDeclName()) 5893 Diag(Args[NumParams]->getBeginLoc(), 5894 MinArgs == NumParams 5895 ? diag::err_typecheck_call_too_many_args_one 5896 : diag::err_typecheck_call_too_many_args_at_most_one) 5897 << FnKind << FDecl->getParamDecl(0) 5898 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5899 << SourceRange(Args[NumParams]->getBeginLoc(), 5900 Args.back()->getEndLoc()); 5901 else 5902 Diag(Args[NumParams]->getBeginLoc(), 5903 MinArgs == NumParams 5904 ? diag::err_typecheck_call_too_many_args 5905 : diag::err_typecheck_call_too_many_args_at_most) 5906 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5907 << Fn->getSourceRange() 5908 << SourceRange(Args[NumParams]->getBeginLoc(), 5909 Args.back()->getEndLoc()); 5910 5911 // Emit the location of the prototype. 5912 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5913 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5914 5915 // This deletes the extra arguments. 5916 Call->shrinkNumArgs(NumParams); 5917 return true; 5918 } 5919 } 5920 SmallVector<Expr *, 8> AllArgs; 5921 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5922 5923 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5924 AllArgs, CallType); 5925 if (Invalid) 5926 return true; 5927 unsigned TotalNumArgs = AllArgs.size(); 5928 for (unsigned i = 0; i < TotalNumArgs; ++i) 5929 Call->setArg(i, AllArgs[i]); 5930 5931 Call->computeDependence(); 5932 return false; 5933 } 5934 5935 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5936 const FunctionProtoType *Proto, 5937 unsigned FirstParam, ArrayRef<Expr *> Args, 5938 SmallVectorImpl<Expr *> &AllArgs, 5939 VariadicCallType CallType, bool AllowExplicit, 5940 bool IsListInitialization) { 5941 unsigned NumParams = Proto->getNumParams(); 5942 bool Invalid = false; 5943 size_t ArgIx = 0; 5944 // Continue to check argument types (even if we have too few/many args). 5945 for (unsigned i = FirstParam; i < NumParams; i++) { 5946 QualType ProtoArgType = Proto->getParamType(i); 5947 5948 Expr *Arg; 5949 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5950 if (ArgIx < Args.size()) { 5951 Arg = Args[ArgIx++]; 5952 5953 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5954 diag::err_call_incomplete_argument, Arg)) 5955 return true; 5956 5957 // Strip the unbridged-cast placeholder expression off, if applicable. 5958 bool CFAudited = false; 5959 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5960 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5961 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5962 Arg = stripARCUnbridgedCast(Arg); 5963 else if (getLangOpts().ObjCAutoRefCount && 5964 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5965 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5966 CFAudited = true; 5967 5968 if (Proto->getExtParameterInfo(i).isNoEscape() && 5969 ProtoArgType->isBlockPointerType()) 5970 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5971 BE->getBlockDecl()->setDoesNotEscape(); 5972 5973 InitializedEntity Entity = 5974 Param ? InitializedEntity::InitializeParameter(Context, Param, 5975 ProtoArgType) 5976 : InitializedEntity::InitializeParameter( 5977 Context, ProtoArgType, Proto->isParamConsumed(i)); 5978 5979 // Remember that parameter belongs to a CF audited API. 5980 if (CFAudited) 5981 Entity.setParameterCFAudited(); 5982 5983 ExprResult ArgE = PerformCopyInitialization( 5984 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5985 if (ArgE.isInvalid()) 5986 return true; 5987 5988 Arg = ArgE.getAs<Expr>(); 5989 } else { 5990 assert(Param && "can't use default arguments without a known callee"); 5991 5992 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5993 if (ArgExpr.isInvalid()) 5994 return true; 5995 5996 Arg = ArgExpr.getAs<Expr>(); 5997 } 5998 5999 // Check for array bounds violations for each argument to the call. This 6000 // check only triggers warnings when the argument isn't a more complex Expr 6001 // with its own checking, such as a BinaryOperator. 6002 CheckArrayAccess(Arg); 6003 6004 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6005 CheckStaticArrayArgument(CallLoc, Param, Arg); 6006 6007 AllArgs.push_back(Arg); 6008 } 6009 6010 // If this is a variadic call, handle args passed through "...". 6011 if (CallType != VariadicDoesNotApply) { 6012 // Assume that extern "C" functions with variadic arguments that 6013 // return __unknown_anytype aren't *really* variadic. 6014 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6015 FDecl->isExternC()) { 6016 for (Expr *A : Args.slice(ArgIx)) { 6017 QualType paramType; // ignored 6018 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6019 Invalid |= arg.isInvalid(); 6020 AllArgs.push_back(arg.get()); 6021 } 6022 6023 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6024 } else { 6025 for (Expr *A : Args.slice(ArgIx)) { 6026 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6027 Invalid |= Arg.isInvalid(); 6028 AllArgs.push_back(Arg.get()); 6029 } 6030 } 6031 6032 // Check for array bounds violations. 6033 for (Expr *A : Args.slice(ArgIx)) 6034 CheckArrayAccess(A); 6035 } 6036 return Invalid; 6037 } 6038 6039 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6040 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6041 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6042 TL = DTL.getOriginalLoc(); 6043 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6044 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6045 << ATL.getLocalSourceRange(); 6046 } 6047 6048 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6049 /// array parameter, check that it is non-null, and that if it is formed by 6050 /// array-to-pointer decay, the underlying array is sufficiently large. 6051 /// 6052 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6053 /// array type derivation, then for each call to the function, the value of the 6054 /// corresponding actual argument shall provide access to the first element of 6055 /// an array with at least as many elements as specified by the size expression. 6056 void 6057 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6058 ParmVarDecl *Param, 6059 const Expr *ArgExpr) { 6060 // Static array parameters are not supported in C++. 6061 if (!Param || getLangOpts().CPlusPlus) 6062 return; 6063 6064 QualType OrigTy = Param->getOriginalType(); 6065 6066 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6067 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6068 return; 6069 6070 if (ArgExpr->isNullPointerConstant(Context, 6071 Expr::NPC_NeverValueDependent)) { 6072 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6073 DiagnoseCalleeStaticArrayParam(*this, Param); 6074 return; 6075 } 6076 6077 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6078 if (!CAT) 6079 return; 6080 6081 const ConstantArrayType *ArgCAT = 6082 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6083 if (!ArgCAT) 6084 return; 6085 6086 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6087 ArgCAT->getElementType())) { 6088 if (ArgCAT->getSize().ult(CAT->getSize())) { 6089 Diag(CallLoc, diag::warn_static_array_too_small) 6090 << ArgExpr->getSourceRange() 6091 << (unsigned)ArgCAT->getSize().getZExtValue() 6092 << (unsigned)CAT->getSize().getZExtValue() << 0; 6093 DiagnoseCalleeStaticArrayParam(*this, Param); 6094 } 6095 return; 6096 } 6097 6098 Optional<CharUnits> ArgSize = 6099 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6100 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6101 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6102 Diag(CallLoc, diag::warn_static_array_too_small) 6103 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6104 << (unsigned)ParmSize->getQuantity() << 1; 6105 DiagnoseCalleeStaticArrayParam(*this, Param); 6106 } 6107 } 6108 6109 /// Given a function expression of unknown-any type, try to rebuild it 6110 /// to have a function type. 6111 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6112 6113 /// Is the given type a placeholder that we need to lower out 6114 /// immediately during argument processing? 6115 static bool isPlaceholderToRemoveAsArg(QualType type) { 6116 // Placeholders are never sugared. 6117 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6118 if (!placeholder) return false; 6119 6120 switch (placeholder->getKind()) { 6121 // Ignore all the non-placeholder types. 6122 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6123 case BuiltinType::Id: 6124 #include "clang/Basic/OpenCLImageTypes.def" 6125 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6126 case BuiltinType::Id: 6127 #include "clang/Basic/OpenCLExtensionTypes.def" 6128 // In practice we'll never use this, since all SVE types are sugared 6129 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6130 #define SVE_TYPE(Name, Id, SingletonId) \ 6131 case BuiltinType::Id: 6132 #include "clang/Basic/AArch64SVEACLETypes.def" 6133 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6134 case BuiltinType::Id: 6135 #include "clang/Basic/PPCTypes.def" 6136 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6137 #include "clang/Basic/RISCVVTypes.def" 6138 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6139 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6140 #include "clang/AST/BuiltinTypes.def" 6141 return false; 6142 6143 // We cannot lower out overload sets; they might validly be resolved 6144 // by the call machinery. 6145 case BuiltinType::Overload: 6146 return false; 6147 6148 // Unbridged casts in ARC can be handled in some call positions and 6149 // should be left in place. 6150 case BuiltinType::ARCUnbridgedCast: 6151 return false; 6152 6153 // Pseudo-objects should be converted as soon as possible. 6154 case BuiltinType::PseudoObject: 6155 return true; 6156 6157 // The debugger mode could theoretically but currently does not try 6158 // to resolve unknown-typed arguments based on known parameter types. 6159 case BuiltinType::UnknownAny: 6160 return true; 6161 6162 // These are always invalid as call arguments and should be reported. 6163 case BuiltinType::BoundMember: 6164 case BuiltinType::BuiltinFn: 6165 case BuiltinType::IncompleteMatrixIdx: 6166 case BuiltinType::OMPArraySection: 6167 case BuiltinType::OMPArrayShaping: 6168 case BuiltinType::OMPIterator: 6169 return true; 6170 6171 } 6172 llvm_unreachable("bad builtin type kind"); 6173 } 6174 6175 /// Check an argument list for placeholders that we won't try to 6176 /// handle later. 6177 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6178 // Apply this processing to all the arguments at once instead of 6179 // dying at the first failure. 6180 bool hasInvalid = false; 6181 for (size_t i = 0, e = args.size(); i != e; i++) { 6182 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6183 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6184 if (result.isInvalid()) hasInvalid = true; 6185 else args[i] = result.get(); 6186 } 6187 } 6188 return hasInvalid; 6189 } 6190 6191 /// If a builtin function has a pointer argument with no explicit address 6192 /// space, then it should be able to accept a pointer to any address 6193 /// space as input. In order to do this, we need to replace the 6194 /// standard builtin declaration with one that uses the same address space 6195 /// as the call. 6196 /// 6197 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6198 /// it does not contain any pointer arguments without 6199 /// an address space qualifer. Otherwise the rewritten 6200 /// FunctionDecl is returned. 6201 /// TODO: Handle pointer return types. 6202 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6203 FunctionDecl *FDecl, 6204 MultiExprArg ArgExprs) { 6205 6206 QualType DeclType = FDecl->getType(); 6207 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6208 6209 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6210 ArgExprs.size() < FT->getNumParams()) 6211 return nullptr; 6212 6213 bool NeedsNewDecl = false; 6214 unsigned i = 0; 6215 SmallVector<QualType, 8> OverloadParams; 6216 6217 for (QualType ParamType : FT->param_types()) { 6218 6219 // Convert array arguments to pointer to simplify type lookup. 6220 ExprResult ArgRes = 6221 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6222 if (ArgRes.isInvalid()) 6223 return nullptr; 6224 Expr *Arg = ArgRes.get(); 6225 QualType ArgType = Arg->getType(); 6226 if (!ParamType->isPointerType() || 6227 ParamType.hasAddressSpace() || 6228 !ArgType->isPointerType() || 6229 !ArgType->getPointeeType().hasAddressSpace()) { 6230 OverloadParams.push_back(ParamType); 6231 continue; 6232 } 6233 6234 QualType PointeeType = ParamType->getPointeeType(); 6235 if (PointeeType.hasAddressSpace()) 6236 continue; 6237 6238 NeedsNewDecl = true; 6239 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6240 6241 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6242 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6243 } 6244 6245 if (!NeedsNewDecl) 6246 return nullptr; 6247 6248 FunctionProtoType::ExtProtoInfo EPI; 6249 EPI.Variadic = FT->isVariadic(); 6250 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6251 OverloadParams, EPI); 6252 DeclContext *Parent = FDecl->getParent(); 6253 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6254 FDecl->getLocation(), 6255 FDecl->getLocation(), 6256 FDecl->getIdentifier(), 6257 OverloadTy, 6258 /*TInfo=*/nullptr, 6259 SC_Extern, false, 6260 /*hasPrototype=*/true); 6261 SmallVector<ParmVarDecl*, 16> Params; 6262 FT = cast<FunctionProtoType>(OverloadTy); 6263 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6264 QualType ParamType = FT->getParamType(i); 6265 ParmVarDecl *Parm = 6266 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6267 SourceLocation(), nullptr, ParamType, 6268 /*TInfo=*/nullptr, SC_None, nullptr); 6269 Parm->setScopeInfo(0, i); 6270 Params.push_back(Parm); 6271 } 6272 OverloadDecl->setParams(Params); 6273 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6274 return OverloadDecl; 6275 } 6276 6277 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6278 FunctionDecl *Callee, 6279 MultiExprArg ArgExprs) { 6280 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6281 // similar attributes) really don't like it when functions are called with an 6282 // invalid number of args. 6283 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6284 /*PartialOverloading=*/false) && 6285 !Callee->isVariadic()) 6286 return; 6287 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6288 return; 6289 6290 if (const EnableIfAttr *Attr = 6291 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6292 S.Diag(Fn->getBeginLoc(), 6293 isa<CXXMethodDecl>(Callee) 6294 ? diag::err_ovl_no_viable_member_function_in_call 6295 : diag::err_ovl_no_viable_function_in_call) 6296 << Callee << Callee->getSourceRange(); 6297 S.Diag(Callee->getLocation(), 6298 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6299 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6300 return; 6301 } 6302 } 6303 6304 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6305 const UnresolvedMemberExpr *const UME, Sema &S) { 6306 6307 const auto GetFunctionLevelDCIfCXXClass = 6308 [](Sema &S) -> const CXXRecordDecl * { 6309 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6310 if (!DC || !DC->getParent()) 6311 return nullptr; 6312 6313 // If the call to some member function was made from within a member 6314 // function body 'M' return return 'M's parent. 6315 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6316 return MD->getParent()->getCanonicalDecl(); 6317 // else the call was made from within a default member initializer of a 6318 // class, so return the class. 6319 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6320 return RD->getCanonicalDecl(); 6321 return nullptr; 6322 }; 6323 // If our DeclContext is neither a member function nor a class (in the 6324 // case of a lambda in a default member initializer), we can't have an 6325 // enclosing 'this'. 6326 6327 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6328 if (!CurParentClass) 6329 return false; 6330 6331 // The naming class for implicit member functions call is the class in which 6332 // name lookup starts. 6333 const CXXRecordDecl *const NamingClass = 6334 UME->getNamingClass()->getCanonicalDecl(); 6335 assert(NamingClass && "Must have naming class even for implicit access"); 6336 6337 // If the unresolved member functions were found in a 'naming class' that is 6338 // related (either the same or derived from) to the class that contains the 6339 // member function that itself contained the implicit member access. 6340 6341 return CurParentClass == NamingClass || 6342 CurParentClass->isDerivedFrom(NamingClass); 6343 } 6344 6345 static void 6346 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6347 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6348 6349 if (!UME) 6350 return; 6351 6352 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6353 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6354 // already been captured, or if this is an implicit member function call (if 6355 // it isn't, an attempt to capture 'this' should already have been made). 6356 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6357 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6358 return; 6359 6360 // Check if the naming class in which the unresolved members were found is 6361 // related (same as or is a base of) to the enclosing class. 6362 6363 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6364 return; 6365 6366 6367 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6368 // If the enclosing function is not dependent, then this lambda is 6369 // capture ready, so if we can capture this, do so. 6370 if (!EnclosingFunctionCtx->isDependentContext()) { 6371 // If the current lambda and all enclosing lambdas can capture 'this' - 6372 // then go ahead and capture 'this' (since our unresolved overload set 6373 // contains at least one non-static member function). 6374 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6375 S.CheckCXXThisCapture(CallLoc); 6376 } else if (S.CurContext->isDependentContext()) { 6377 // ... since this is an implicit member reference, that might potentially 6378 // involve a 'this' capture, mark 'this' for potential capture in 6379 // enclosing lambdas. 6380 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6381 CurLSI->addPotentialThisCapture(CallLoc); 6382 } 6383 } 6384 6385 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6386 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6387 Expr *ExecConfig) { 6388 ExprResult Call = 6389 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6390 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6391 if (Call.isInvalid()) 6392 return Call; 6393 6394 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6395 // language modes. 6396 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6397 if (ULE->hasExplicitTemplateArgs() && 6398 ULE->decls_begin() == ULE->decls_end()) { 6399 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6400 ? diag::warn_cxx17_compat_adl_only_template_id 6401 : diag::ext_adl_only_template_id) 6402 << ULE->getName(); 6403 } 6404 } 6405 6406 if (LangOpts.OpenMP) 6407 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6408 ExecConfig); 6409 6410 return Call; 6411 } 6412 6413 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6414 /// This provides the location of the left/right parens and a list of comma 6415 /// locations. 6416 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6417 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6418 Expr *ExecConfig, bool IsExecConfig, 6419 bool AllowRecovery) { 6420 // Since this might be a postfix expression, get rid of ParenListExprs. 6421 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6422 if (Result.isInvalid()) return ExprError(); 6423 Fn = Result.get(); 6424 6425 if (checkArgsForPlaceholders(*this, ArgExprs)) 6426 return ExprError(); 6427 6428 if (getLangOpts().CPlusPlus) { 6429 // If this is a pseudo-destructor expression, build the call immediately. 6430 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6431 if (!ArgExprs.empty()) { 6432 // Pseudo-destructor calls should not have any arguments. 6433 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6434 << FixItHint::CreateRemoval( 6435 SourceRange(ArgExprs.front()->getBeginLoc(), 6436 ArgExprs.back()->getEndLoc())); 6437 } 6438 6439 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6440 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6441 } 6442 if (Fn->getType() == Context.PseudoObjectTy) { 6443 ExprResult result = CheckPlaceholderExpr(Fn); 6444 if (result.isInvalid()) return ExprError(); 6445 Fn = result.get(); 6446 } 6447 6448 // Determine whether this is a dependent call inside a C++ template, 6449 // in which case we won't do any semantic analysis now. 6450 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6451 if (ExecConfig) { 6452 return CUDAKernelCallExpr::Create(Context, Fn, 6453 cast<CallExpr>(ExecConfig), ArgExprs, 6454 Context.DependentTy, VK_PRValue, 6455 RParenLoc, CurFPFeatureOverrides()); 6456 } else { 6457 6458 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6459 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6460 Fn->getBeginLoc()); 6461 6462 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6463 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6464 } 6465 } 6466 6467 // Determine whether this is a call to an object (C++ [over.call.object]). 6468 if (Fn->getType()->isRecordType()) 6469 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6470 RParenLoc); 6471 6472 if (Fn->getType() == Context.UnknownAnyTy) { 6473 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6474 if (result.isInvalid()) return ExprError(); 6475 Fn = result.get(); 6476 } 6477 6478 if (Fn->getType() == Context.BoundMemberTy) { 6479 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6480 RParenLoc, AllowRecovery); 6481 } 6482 } 6483 6484 // Check for overloaded calls. This can happen even in C due to extensions. 6485 if (Fn->getType() == Context.OverloadTy) { 6486 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6487 6488 // We aren't supposed to apply this logic if there's an '&' involved. 6489 if (!find.HasFormOfMemberPointer) { 6490 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6491 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6492 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6493 OverloadExpr *ovl = find.Expression; 6494 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6495 return BuildOverloadedCallExpr( 6496 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6497 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6498 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6499 RParenLoc, AllowRecovery); 6500 } 6501 } 6502 6503 // If we're directly calling a function, get the appropriate declaration. 6504 if (Fn->getType() == Context.UnknownAnyTy) { 6505 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6506 if (result.isInvalid()) return ExprError(); 6507 Fn = result.get(); 6508 } 6509 6510 Expr *NakedFn = Fn->IgnoreParens(); 6511 6512 bool CallingNDeclIndirectly = false; 6513 NamedDecl *NDecl = nullptr; 6514 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6515 if (UnOp->getOpcode() == UO_AddrOf) { 6516 CallingNDeclIndirectly = true; 6517 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6518 } 6519 } 6520 6521 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6522 NDecl = DRE->getDecl(); 6523 6524 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6525 if (FDecl && FDecl->getBuiltinID()) { 6526 // Rewrite the function decl for this builtin by replacing parameters 6527 // with no explicit address space with the address space of the arguments 6528 // in ArgExprs. 6529 if ((FDecl = 6530 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6531 NDecl = FDecl; 6532 Fn = DeclRefExpr::Create( 6533 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6534 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6535 nullptr, DRE->isNonOdrUse()); 6536 } 6537 } 6538 } else if (isa<MemberExpr>(NakedFn)) 6539 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6540 6541 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6542 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6543 FD, /*Complain=*/true, Fn->getBeginLoc())) 6544 return ExprError(); 6545 6546 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6547 } 6548 6549 if (Context.isDependenceAllowed() && 6550 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6551 assert(!getLangOpts().CPlusPlus); 6552 assert((Fn->containsErrors() || 6553 llvm::any_of(ArgExprs, 6554 [](clang::Expr *E) { return E->containsErrors(); })) && 6555 "should only occur in error-recovery path."); 6556 QualType ReturnType = 6557 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6558 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6559 : Context.DependentTy; 6560 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6561 Expr::getValueKindForType(ReturnType), RParenLoc, 6562 CurFPFeatureOverrides()); 6563 } 6564 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6565 ExecConfig, IsExecConfig); 6566 } 6567 6568 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6569 // with the specified CallArgs 6570 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6571 MultiExprArg CallArgs) { 6572 StringRef Name = Context.BuiltinInfo.getName(Id); 6573 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6574 Sema::LookupOrdinaryName); 6575 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6576 6577 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6578 assert(BuiltInDecl && "failed to find builtin declaration"); 6579 6580 ExprResult DeclRef = 6581 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6582 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6583 6584 ExprResult Call = 6585 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6586 6587 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6588 return Call.get(); 6589 } 6590 6591 /// Parse a __builtin_astype expression. 6592 /// 6593 /// __builtin_astype( value, dst type ) 6594 /// 6595 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6596 SourceLocation BuiltinLoc, 6597 SourceLocation RParenLoc) { 6598 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6599 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6600 } 6601 6602 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6603 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6604 SourceLocation BuiltinLoc, 6605 SourceLocation RParenLoc) { 6606 ExprValueKind VK = VK_PRValue; 6607 ExprObjectKind OK = OK_Ordinary; 6608 QualType SrcTy = E->getType(); 6609 if (!SrcTy->isDependentType() && 6610 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6611 return ExprError( 6612 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6613 << DestTy << SrcTy << E->getSourceRange()); 6614 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6615 } 6616 6617 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6618 /// provided arguments. 6619 /// 6620 /// __builtin_convertvector( value, dst type ) 6621 /// 6622 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6623 SourceLocation BuiltinLoc, 6624 SourceLocation RParenLoc) { 6625 TypeSourceInfo *TInfo; 6626 GetTypeFromParser(ParsedDestTy, &TInfo); 6627 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6628 } 6629 6630 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6631 /// i.e. an expression not of \p OverloadTy. The expression should 6632 /// unary-convert to an expression of function-pointer or 6633 /// block-pointer type. 6634 /// 6635 /// \param NDecl the declaration being called, if available 6636 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6637 SourceLocation LParenLoc, 6638 ArrayRef<Expr *> Args, 6639 SourceLocation RParenLoc, Expr *Config, 6640 bool IsExecConfig, ADLCallKind UsesADL) { 6641 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6642 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6643 6644 // Functions with 'interrupt' attribute cannot be called directly. 6645 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6646 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6647 return ExprError(); 6648 } 6649 6650 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6651 // so there's some risk when calling out to non-interrupt handler functions 6652 // that the callee might not preserve them. This is easy to diagnose here, 6653 // but can be very challenging to debug. 6654 // Likewise, X86 interrupt handlers may only call routines with attribute 6655 // no_caller_saved_registers since there is no efficient way to 6656 // save and restore the non-GPR state. 6657 if (auto *Caller = getCurFunctionDecl()) { 6658 if (Caller->hasAttr<ARMInterruptAttr>()) { 6659 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6660 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6661 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6662 if (FDecl) 6663 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6664 } 6665 } 6666 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6667 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6668 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6669 if (FDecl) 6670 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6671 } 6672 } 6673 6674 // Promote the function operand. 6675 // We special-case function promotion here because we only allow promoting 6676 // builtin functions to function pointers in the callee of a call. 6677 ExprResult Result; 6678 QualType ResultTy; 6679 if (BuiltinID && 6680 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6681 // Extract the return type from the (builtin) function pointer type. 6682 // FIXME Several builtins still have setType in 6683 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6684 // Builtins.def to ensure they are correct before removing setType calls. 6685 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6686 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6687 ResultTy = FDecl->getCallResultType(); 6688 } else { 6689 Result = CallExprUnaryConversions(Fn); 6690 ResultTy = Context.BoolTy; 6691 } 6692 if (Result.isInvalid()) 6693 return ExprError(); 6694 Fn = Result.get(); 6695 6696 // Check for a valid function type, but only if it is not a builtin which 6697 // requires custom type checking. These will be handled by 6698 // CheckBuiltinFunctionCall below just after creation of the call expression. 6699 const FunctionType *FuncT = nullptr; 6700 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6701 retry: 6702 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6703 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6704 // have type pointer to function". 6705 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6706 if (!FuncT) 6707 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6708 << Fn->getType() << Fn->getSourceRange()); 6709 } else if (const BlockPointerType *BPT = 6710 Fn->getType()->getAs<BlockPointerType>()) { 6711 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6712 } else { 6713 // Handle calls to expressions of unknown-any type. 6714 if (Fn->getType() == Context.UnknownAnyTy) { 6715 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6716 if (rewrite.isInvalid()) 6717 return ExprError(); 6718 Fn = rewrite.get(); 6719 goto retry; 6720 } 6721 6722 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6723 << Fn->getType() << Fn->getSourceRange()); 6724 } 6725 } 6726 6727 // Get the number of parameters in the function prototype, if any. 6728 // We will allocate space for max(Args.size(), NumParams) arguments 6729 // in the call expression. 6730 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6731 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6732 6733 CallExpr *TheCall; 6734 if (Config) { 6735 assert(UsesADL == ADLCallKind::NotADL && 6736 "CUDAKernelCallExpr should not use ADL"); 6737 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6738 Args, ResultTy, VK_PRValue, RParenLoc, 6739 CurFPFeatureOverrides(), NumParams); 6740 } else { 6741 TheCall = 6742 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6743 CurFPFeatureOverrides(), NumParams, UsesADL); 6744 } 6745 6746 if (!Context.isDependenceAllowed()) { 6747 // Forget about the nulled arguments since typo correction 6748 // do not handle them well. 6749 TheCall->shrinkNumArgs(Args.size()); 6750 // C cannot always handle TypoExpr nodes in builtin calls and direct 6751 // function calls as their argument checking don't necessarily handle 6752 // dependent types properly, so make sure any TypoExprs have been 6753 // dealt with. 6754 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6755 if (!Result.isUsable()) return ExprError(); 6756 CallExpr *TheOldCall = TheCall; 6757 TheCall = dyn_cast<CallExpr>(Result.get()); 6758 bool CorrectedTypos = TheCall != TheOldCall; 6759 if (!TheCall) return Result; 6760 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6761 6762 // A new call expression node was created if some typos were corrected. 6763 // However it may not have been constructed with enough storage. In this 6764 // case, rebuild the node with enough storage. The waste of space is 6765 // immaterial since this only happens when some typos were corrected. 6766 if (CorrectedTypos && Args.size() < NumParams) { 6767 if (Config) 6768 TheCall = CUDAKernelCallExpr::Create( 6769 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6770 RParenLoc, CurFPFeatureOverrides(), NumParams); 6771 else 6772 TheCall = 6773 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6774 CurFPFeatureOverrides(), NumParams, UsesADL); 6775 } 6776 // We can now handle the nulled arguments for the default arguments. 6777 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6778 } 6779 6780 // Bail out early if calling a builtin with custom type checking. 6781 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6782 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6783 6784 if (getLangOpts().CUDA) { 6785 if (Config) { 6786 // CUDA: Kernel calls must be to global functions 6787 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6788 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6789 << FDecl << Fn->getSourceRange()); 6790 6791 // CUDA: Kernel function must have 'void' return type 6792 if (!FuncT->getReturnType()->isVoidType() && 6793 !FuncT->getReturnType()->getAs<AutoType>() && 6794 !FuncT->getReturnType()->isInstantiationDependentType()) 6795 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6796 << Fn->getType() << Fn->getSourceRange()); 6797 } else { 6798 // CUDA: Calls to global functions must be configured 6799 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6800 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6801 << FDecl << Fn->getSourceRange()); 6802 } 6803 } 6804 6805 // Check for a valid return type 6806 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6807 FDecl)) 6808 return ExprError(); 6809 6810 // We know the result type of the call, set it. 6811 TheCall->setType(FuncT->getCallResultType(Context)); 6812 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6813 6814 if (Proto) { 6815 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6816 IsExecConfig)) 6817 return ExprError(); 6818 } else { 6819 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6820 6821 if (FDecl) { 6822 // Check if we have too few/too many template arguments, based 6823 // on our knowledge of the function definition. 6824 const FunctionDecl *Def = nullptr; 6825 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6826 Proto = Def->getType()->getAs<FunctionProtoType>(); 6827 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6828 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6829 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6830 } 6831 6832 // If the function we're calling isn't a function prototype, but we have 6833 // a function prototype from a prior declaratiom, use that prototype. 6834 if (!FDecl->hasPrototype()) 6835 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6836 } 6837 6838 // Promote the arguments (C99 6.5.2.2p6). 6839 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6840 Expr *Arg = Args[i]; 6841 6842 if (Proto && i < Proto->getNumParams()) { 6843 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6844 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6845 ExprResult ArgE = 6846 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6847 if (ArgE.isInvalid()) 6848 return true; 6849 6850 Arg = ArgE.getAs<Expr>(); 6851 6852 } else { 6853 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6854 6855 if (ArgE.isInvalid()) 6856 return true; 6857 6858 Arg = ArgE.getAs<Expr>(); 6859 } 6860 6861 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6862 diag::err_call_incomplete_argument, Arg)) 6863 return ExprError(); 6864 6865 TheCall->setArg(i, Arg); 6866 } 6867 TheCall->computeDependence(); 6868 } 6869 6870 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6871 if (!Method->isStatic()) 6872 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6873 << Fn->getSourceRange()); 6874 6875 // Check for sentinels 6876 if (NDecl) 6877 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6878 6879 // Warn for unions passing across security boundary (CMSE). 6880 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6881 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6882 if (const auto *RT = 6883 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6884 if (RT->getDecl()->isOrContainsUnion()) 6885 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6886 << 0 << i; 6887 } 6888 } 6889 } 6890 6891 // Do special checking on direct calls to functions. 6892 if (FDecl) { 6893 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6894 return ExprError(); 6895 6896 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6897 6898 if (BuiltinID) 6899 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6900 } else if (NDecl) { 6901 if (CheckPointerCall(NDecl, TheCall, Proto)) 6902 return ExprError(); 6903 } else { 6904 if (CheckOtherCall(TheCall, Proto)) 6905 return ExprError(); 6906 } 6907 6908 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6909 } 6910 6911 ExprResult 6912 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6913 SourceLocation RParenLoc, Expr *InitExpr) { 6914 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6915 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6916 6917 TypeSourceInfo *TInfo; 6918 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6919 if (!TInfo) 6920 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6921 6922 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6923 } 6924 6925 ExprResult 6926 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6927 SourceLocation RParenLoc, Expr *LiteralExpr) { 6928 QualType literalType = TInfo->getType(); 6929 6930 if (literalType->isArrayType()) { 6931 if (RequireCompleteSizedType( 6932 LParenLoc, Context.getBaseElementType(literalType), 6933 diag::err_array_incomplete_or_sizeless_type, 6934 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6935 return ExprError(); 6936 if (literalType->isVariableArrayType()) { 6937 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6938 diag::err_variable_object_no_init)) { 6939 return ExprError(); 6940 } 6941 } 6942 } else if (!literalType->isDependentType() && 6943 RequireCompleteType(LParenLoc, literalType, 6944 diag::err_typecheck_decl_incomplete_type, 6945 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6946 return ExprError(); 6947 6948 InitializedEntity Entity 6949 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6950 InitializationKind Kind 6951 = InitializationKind::CreateCStyleCast(LParenLoc, 6952 SourceRange(LParenLoc, RParenLoc), 6953 /*InitList=*/true); 6954 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6955 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6956 &literalType); 6957 if (Result.isInvalid()) 6958 return ExprError(); 6959 LiteralExpr = Result.get(); 6960 6961 bool isFileScope = !CurContext->isFunctionOrMethod(); 6962 6963 // In C, compound literals are l-values for some reason. 6964 // For GCC compatibility, in C++, file-scope array compound literals with 6965 // constant initializers are also l-values, and compound literals are 6966 // otherwise prvalues. 6967 // 6968 // (GCC also treats C++ list-initialized file-scope array prvalues with 6969 // constant initializers as l-values, but that's non-conforming, so we don't 6970 // follow it there.) 6971 // 6972 // FIXME: It would be better to handle the lvalue cases as materializing and 6973 // lifetime-extending a temporary object, but our materialized temporaries 6974 // representation only supports lifetime extension from a variable, not "out 6975 // of thin air". 6976 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6977 // is bound to the result of applying array-to-pointer decay to the compound 6978 // literal. 6979 // FIXME: GCC supports compound literals of reference type, which should 6980 // obviously have a value kind derived from the kind of reference involved. 6981 ExprValueKind VK = 6982 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6983 ? VK_PRValue 6984 : VK_LValue; 6985 6986 if (isFileScope) 6987 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6988 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6989 Expr *Init = ILE->getInit(i); 6990 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6991 } 6992 6993 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6994 VK, LiteralExpr, isFileScope); 6995 if (isFileScope) { 6996 if (!LiteralExpr->isTypeDependent() && 6997 !LiteralExpr->isValueDependent() && 6998 !literalType->isDependentType()) // C99 6.5.2.5p3 6999 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7000 return ExprError(); 7001 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7002 literalType.getAddressSpace() != LangAS::Default) { 7003 // Embedded-C extensions to C99 6.5.2.5: 7004 // "If the compound literal occurs inside the body of a function, the 7005 // type name shall not be qualified by an address-space qualifier." 7006 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7007 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7008 return ExprError(); 7009 } 7010 7011 if (!isFileScope && !getLangOpts().CPlusPlus) { 7012 // Compound literals that have automatic storage duration are destroyed at 7013 // the end of the scope in C; in C++, they're just temporaries. 7014 7015 // Emit diagnostics if it is or contains a C union type that is non-trivial 7016 // to destruct. 7017 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7018 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7019 NTCUC_CompoundLiteral, NTCUK_Destruct); 7020 7021 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7022 if (literalType.isDestructedType()) { 7023 Cleanup.setExprNeedsCleanups(true); 7024 ExprCleanupObjects.push_back(E); 7025 getCurFunction()->setHasBranchProtectedScope(); 7026 } 7027 } 7028 7029 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7030 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7031 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7032 E->getInitializer()->getExprLoc()); 7033 7034 return MaybeBindToTemporary(E); 7035 } 7036 7037 ExprResult 7038 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7039 SourceLocation RBraceLoc) { 7040 // Only produce each kind of designated initialization diagnostic once. 7041 SourceLocation FirstDesignator; 7042 bool DiagnosedArrayDesignator = false; 7043 bool DiagnosedNestedDesignator = false; 7044 bool DiagnosedMixedDesignator = false; 7045 7046 // Check that any designated initializers are syntactically valid in the 7047 // current language mode. 7048 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7049 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7050 if (FirstDesignator.isInvalid()) 7051 FirstDesignator = DIE->getBeginLoc(); 7052 7053 if (!getLangOpts().CPlusPlus) 7054 break; 7055 7056 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7057 DiagnosedNestedDesignator = true; 7058 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7059 << DIE->getDesignatorsSourceRange(); 7060 } 7061 7062 for (auto &Desig : DIE->designators()) { 7063 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7064 DiagnosedArrayDesignator = true; 7065 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7066 << Desig.getSourceRange(); 7067 } 7068 } 7069 7070 if (!DiagnosedMixedDesignator && 7071 !isa<DesignatedInitExpr>(InitArgList[0])) { 7072 DiagnosedMixedDesignator = true; 7073 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7074 << DIE->getSourceRange(); 7075 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7076 << InitArgList[0]->getSourceRange(); 7077 } 7078 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7079 isa<DesignatedInitExpr>(InitArgList[0])) { 7080 DiagnosedMixedDesignator = true; 7081 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7082 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7083 << DIE->getSourceRange(); 7084 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7085 << InitArgList[I]->getSourceRange(); 7086 } 7087 } 7088 7089 if (FirstDesignator.isValid()) { 7090 // Only diagnose designated initiaization as a C++20 extension if we didn't 7091 // already diagnose use of (non-C++20) C99 designator syntax. 7092 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7093 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7094 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7095 ? diag::warn_cxx17_compat_designated_init 7096 : diag::ext_cxx_designated_init); 7097 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7098 Diag(FirstDesignator, diag::ext_designated_init); 7099 } 7100 } 7101 7102 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7103 } 7104 7105 ExprResult 7106 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7107 SourceLocation RBraceLoc) { 7108 // Semantic analysis for initializers is done by ActOnDeclarator() and 7109 // CheckInitializer() - it requires knowledge of the object being initialized. 7110 7111 // Immediately handle non-overload placeholders. Overloads can be 7112 // resolved contextually, but everything else here can't. 7113 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7114 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7115 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7116 7117 // Ignore failures; dropping the entire initializer list because 7118 // of one failure would be terrible for indexing/etc. 7119 if (result.isInvalid()) continue; 7120 7121 InitArgList[I] = result.get(); 7122 } 7123 } 7124 7125 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7126 RBraceLoc); 7127 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7128 return E; 7129 } 7130 7131 /// Do an explicit extend of the given block pointer if we're in ARC. 7132 void Sema::maybeExtendBlockObject(ExprResult &E) { 7133 assert(E.get()->getType()->isBlockPointerType()); 7134 assert(E.get()->isPRValue()); 7135 7136 // Only do this in an r-value context. 7137 if (!getLangOpts().ObjCAutoRefCount) return; 7138 7139 E = ImplicitCastExpr::Create( 7140 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7141 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7142 Cleanup.setExprNeedsCleanups(true); 7143 } 7144 7145 /// Prepare a conversion of the given expression to an ObjC object 7146 /// pointer type. 7147 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7148 QualType type = E.get()->getType(); 7149 if (type->isObjCObjectPointerType()) { 7150 return CK_BitCast; 7151 } else if (type->isBlockPointerType()) { 7152 maybeExtendBlockObject(E); 7153 return CK_BlockPointerToObjCPointerCast; 7154 } else { 7155 assert(type->isPointerType()); 7156 return CK_CPointerToObjCPointerCast; 7157 } 7158 } 7159 7160 /// Prepares for a scalar cast, performing all the necessary stages 7161 /// except the final cast and returning the kind required. 7162 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7163 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7164 // Also, callers should have filtered out the invalid cases with 7165 // pointers. Everything else should be possible. 7166 7167 QualType SrcTy = Src.get()->getType(); 7168 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7169 return CK_NoOp; 7170 7171 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7172 case Type::STK_MemberPointer: 7173 llvm_unreachable("member pointer type in C"); 7174 7175 case Type::STK_CPointer: 7176 case Type::STK_BlockPointer: 7177 case Type::STK_ObjCObjectPointer: 7178 switch (DestTy->getScalarTypeKind()) { 7179 case Type::STK_CPointer: { 7180 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7181 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7182 if (SrcAS != DestAS) 7183 return CK_AddressSpaceConversion; 7184 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7185 return CK_NoOp; 7186 return CK_BitCast; 7187 } 7188 case Type::STK_BlockPointer: 7189 return (SrcKind == Type::STK_BlockPointer 7190 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7191 case Type::STK_ObjCObjectPointer: 7192 if (SrcKind == Type::STK_ObjCObjectPointer) 7193 return CK_BitCast; 7194 if (SrcKind == Type::STK_CPointer) 7195 return CK_CPointerToObjCPointerCast; 7196 maybeExtendBlockObject(Src); 7197 return CK_BlockPointerToObjCPointerCast; 7198 case Type::STK_Bool: 7199 return CK_PointerToBoolean; 7200 case Type::STK_Integral: 7201 return CK_PointerToIntegral; 7202 case Type::STK_Floating: 7203 case Type::STK_FloatingComplex: 7204 case Type::STK_IntegralComplex: 7205 case Type::STK_MemberPointer: 7206 case Type::STK_FixedPoint: 7207 llvm_unreachable("illegal cast from pointer"); 7208 } 7209 llvm_unreachable("Should have returned before this"); 7210 7211 case Type::STK_FixedPoint: 7212 switch (DestTy->getScalarTypeKind()) { 7213 case Type::STK_FixedPoint: 7214 return CK_FixedPointCast; 7215 case Type::STK_Bool: 7216 return CK_FixedPointToBoolean; 7217 case Type::STK_Integral: 7218 return CK_FixedPointToIntegral; 7219 case Type::STK_Floating: 7220 return CK_FixedPointToFloating; 7221 case Type::STK_IntegralComplex: 7222 case Type::STK_FloatingComplex: 7223 Diag(Src.get()->getExprLoc(), 7224 diag::err_unimplemented_conversion_with_fixed_point_type) 7225 << DestTy; 7226 return CK_IntegralCast; 7227 case Type::STK_CPointer: 7228 case Type::STK_ObjCObjectPointer: 7229 case Type::STK_BlockPointer: 7230 case Type::STK_MemberPointer: 7231 llvm_unreachable("illegal cast to pointer type"); 7232 } 7233 llvm_unreachable("Should have returned before this"); 7234 7235 case Type::STK_Bool: // casting from bool is like casting from an integer 7236 case Type::STK_Integral: 7237 switch (DestTy->getScalarTypeKind()) { 7238 case Type::STK_CPointer: 7239 case Type::STK_ObjCObjectPointer: 7240 case Type::STK_BlockPointer: 7241 if (Src.get()->isNullPointerConstant(Context, 7242 Expr::NPC_ValueDependentIsNull)) 7243 return CK_NullToPointer; 7244 return CK_IntegralToPointer; 7245 case Type::STK_Bool: 7246 return CK_IntegralToBoolean; 7247 case Type::STK_Integral: 7248 return CK_IntegralCast; 7249 case Type::STK_Floating: 7250 return CK_IntegralToFloating; 7251 case Type::STK_IntegralComplex: 7252 Src = ImpCastExprToType(Src.get(), 7253 DestTy->castAs<ComplexType>()->getElementType(), 7254 CK_IntegralCast); 7255 return CK_IntegralRealToComplex; 7256 case Type::STK_FloatingComplex: 7257 Src = ImpCastExprToType(Src.get(), 7258 DestTy->castAs<ComplexType>()->getElementType(), 7259 CK_IntegralToFloating); 7260 return CK_FloatingRealToComplex; 7261 case Type::STK_MemberPointer: 7262 llvm_unreachable("member pointer type in C"); 7263 case Type::STK_FixedPoint: 7264 return CK_IntegralToFixedPoint; 7265 } 7266 llvm_unreachable("Should have returned before this"); 7267 7268 case Type::STK_Floating: 7269 switch (DestTy->getScalarTypeKind()) { 7270 case Type::STK_Floating: 7271 return CK_FloatingCast; 7272 case Type::STK_Bool: 7273 return CK_FloatingToBoolean; 7274 case Type::STK_Integral: 7275 return CK_FloatingToIntegral; 7276 case Type::STK_FloatingComplex: 7277 Src = ImpCastExprToType(Src.get(), 7278 DestTy->castAs<ComplexType>()->getElementType(), 7279 CK_FloatingCast); 7280 return CK_FloatingRealToComplex; 7281 case Type::STK_IntegralComplex: 7282 Src = ImpCastExprToType(Src.get(), 7283 DestTy->castAs<ComplexType>()->getElementType(), 7284 CK_FloatingToIntegral); 7285 return CK_IntegralRealToComplex; 7286 case Type::STK_CPointer: 7287 case Type::STK_ObjCObjectPointer: 7288 case Type::STK_BlockPointer: 7289 llvm_unreachable("valid float->pointer cast?"); 7290 case Type::STK_MemberPointer: 7291 llvm_unreachable("member pointer type in C"); 7292 case Type::STK_FixedPoint: 7293 return CK_FloatingToFixedPoint; 7294 } 7295 llvm_unreachable("Should have returned before this"); 7296 7297 case Type::STK_FloatingComplex: 7298 switch (DestTy->getScalarTypeKind()) { 7299 case Type::STK_FloatingComplex: 7300 return CK_FloatingComplexCast; 7301 case Type::STK_IntegralComplex: 7302 return CK_FloatingComplexToIntegralComplex; 7303 case Type::STK_Floating: { 7304 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7305 if (Context.hasSameType(ET, DestTy)) 7306 return CK_FloatingComplexToReal; 7307 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7308 return CK_FloatingCast; 7309 } 7310 case Type::STK_Bool: 7311 return CK_FloatingComplexToBoolean; 7312 case Type::STK_Integral: 7313 Src = ImpCastExprToType(Src.get(), 7314 SrcTy->castAs<ComplexType>()->getElementType(), 7315 CK_FloatingComplexToReal); 7316 return CK_FloatingToIntegral; 7317 case Type::STK_CPointer: 7318 case Type::STK_ObjCObjectPointer: 7319 case Type::STK_BlockPointer: 7320 llvm_unreachable("valid complex float->pointer cast?"); 7321 case Type::STK_MemberPointer: 7322 llvm_unreachable("member pointer type in C"); 7323 case Type::STK_FixedPoint: 7324 Diag(Src.get()->getExprLoc(), 7325 diag::err_unimplemented_conversion_with_fixed_point_type) 7326 << SrcTy; 7327 return CK_IntegralCast; 7328 } 7329 llvm_unreachable("Should have returned before this"); 7330 7331 case Type::STK_IntegralComplex: 7332 switch (DestTy->getScalarTypeKind()) { 7333 case Type::STK_FloatingComplex: 7334 return CK_IntegralComplexToFloatingComplex; 7335 case Type::STK_IntegralComplex: 7336 return CK_IntegralComplexCast; 7337 case Type::STK_Integral: { 7338 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7339 if (Context.hasSameType(ET, DestTy)) 7340 return CK_IntegralComplexToReal; 7341 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7342 return CK_IntegralCast; 7343 } 7344 case Type::STK_Bool: 7345 return CK_IntegralComplexToBoolean; 7346 case Type::STK_Floating: 7347 Src = ImpCastExprToType(Src.get(), 7348 SrcTy->castAs<ComplexType>()->getElementType(), 7349 CK_IntegralComplexToReal); 7350 return CK_IntegralToFloating; 7351 case Type::STK_CPointer: 7352 case Type::STK_ObjCObjectPointer: 7353 case Type::STK_BlockPointer: 7354 llvm_unreachable("valid complex int->pointer cast?"); 7355 case Type::STK_MemberPointer: 7356 llvm_unreachable("member pointer type in C"); 7357 case Type::STK_FixedPoint: 7358 Diag(Src.get()->getExprLoc(), 7359 diag::err_unimplemented_conversion_with_fixed_point_type) 7360 << SrcTy; 7361 return CK_IntegralCast; 7362 } 7363 llvm_unreachable("Should have returned before this"); 7364 } 7365 7366 llvm_unreachable("Unhandled scalar cast"); 7367 } 7368 7369 static bool breakDownVectorType(QualType type, uint64_t &len, 7370 QualType &eltType) { 7371 // Vectors are simple. 7372 if (const VectorType *vecType = type->getAs<VectorType>()) { 7373 len = vecType->getNumElements(); 7374 eltType = vecType->getElementType(); 7375 assert(eltType->isScalarType()); 7376 return true; 7377 } 7378 7379 // We allow lax conversion to and from non-vector types, but only if 7380 // they're real types (i.e. non-complex, non-pointer scalar types). 7381 if (!type->isRealType()) return false; 7382 7383 len = 1; 7384 eltType = type; 7385 return true; 7386 } 7387 7388 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7389 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7390 /// allowed? 7391 /// 7392 /// This will also return false if the two given types do not make sense from 7393 /// the perspective of SVE bitcasts. 7394 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7395 assert(srcTy->isVectorType() || destTy->isVectorType()); 7396 7397 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7398 if (!FirstType->isSizelessBuiltinType()) 7399 return false; 7400 7401 const auto *VecTy = SecondType->getAs<VectorType>(); 7402 return VecTy && 7403 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7404 }; 7405 7406 return ValidScalableConversion(srcTy, destTy) || 7407 ValidScalableConversion(destTy, srcTy); 7408 } 7409 7410 /// Are the two types matrix types and do they have the same dimensions i.e. 7411 /// do they have the same number of rows and the same number of columns? 7412 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7413 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7414 return false; 7415 7416 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7417 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7418 7419 return matSrcType->getNumRows() == matDestType->getNumRows() && 7420 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7421 } 7422 7423 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7424 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7425 7426 uint64_t SrcLen, DestLen; 7427 QualType SrcEltTy, DestEltTy; 7428 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7429 return false; 7430 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7431 return false; 7432 7433 // ASTContext::getTypeSize will return the size rounded up to a 7434 // power of 2, so instead of using that, we need to use the raw 7435 // element size multiplied by the element count. 7436 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7437 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7438 7439 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7440 } 7441 7442 /// Are the two types lax-compatible vector types? That is, given 7443 /// that one of them is a vector, do they have equal storage sizes, 7444 /// where the storage size is the number of elements times the element 7445 /// size? 7446 /// 7447 /// This will also return false if either of the types is neither a 7448 /// vector nor a real type. 7449 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7450 assert(destTy->isVectorType() || srcTy->isVectorType()); 7451 7452 // Disallow lax conversions between scalars and ExtVectors (these 7453 // conversions are allowed for other vector types because common headers 7454 // depend on them). Most scalar OP ExtVector cases are handled by the 7455 // splat path anyway, which does what we want (convert, not bitcast). 7456 // What this rules out for ExtVectors is crazy things like char4*float. 7457 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7458 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7459 7460 return areVectorTypesSameSize(srcTy, destTy); 7461 } 7462 7463 /// Is this a legal conversion between two types, one of which is 7464 /// known to be a vector type? 7465 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7466 assert(destTy->isVectorType() || srcTy->isVectorType()); 7467 7468 switch (Context.getLangOpts().getLaxVectorConversions()) { 7469 case LangOptions::LaxVectorConversionKind::None: 7470 return false; 7471 7472 case LangOptions::LaxVectorConversionKind::Integer: 7473 if (!srcTy->isIntegralOrEnumerationType()) { 7474 auto *Vec = srcTy->getAs<VectorType>(); 7475 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7476 return false; 7477 } 7478 if (!destTy->isIntegralOrEnumerationType()) { 7479 auto *Vec = destTy->getAs<VectorType>(); 7480 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7481 return false; 7482 } 7483 // OK, integer (vector) -> integer (vector) bitcast. 7484 break; 7485 7486 case LangOptions::LaxVectorConversionKind::All: 7487 break; 7488 } 7489 7490 return areLaxCompatibleVectorTypes(srcTy, destTy); 7491 } 7492 7493 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7494 CastKind &Kind) { 7495 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7496 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7497 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7498 << DestTy << SrcTy << R; 7499 } 7500 } else if (SrcTy->isMatrixType()) { 7501 return Diag(R.getBegin(), 7502 diag::err_invalid_conversion_between_matrix_and_type) 7503 << SrcTy << DestTy << R; 7504 } else if (DestTy->isMatrixType()) { 7505 return Diag(R.getBegin(), 7506 diag::err_invalid_conversion_between_matrix_and_type) 7507 << DestTy << SrcTy << R; 7508 } 7509 7510 Kind = CK_MatrixCast; 7511 return false; 7512 } 7513 7514 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7515 CastKind &Kind) { 7516 assert(VectorTy->isVectorType() && "Not a vector type!"); 7517 7518 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7519 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7520 return Diag(R.getBegin(), 7521 Ty->isVectorType() ? 7522 diag::err_invalid_conversion_between_vectors : 7523 diag::err_invalid_conversion_between_vector_and_integer) 7524 << VectorTy << Ty << R; 7525 } else 7526 return Diag(R.getBegin(), 7527 diag::err_invalid_conversion_between_vector_and_scalar) 7528 << VectorTy << Ty << R; 7529 7530 Kind = CK_BitCast; 7531 return false; 7532 } 7533 7534 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7535 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7536 7537 if (DestElemTy == SplattedExpr->getType()) 7538 return SplattedExpr; 7539 7540 assert(DestElemTy->isFloatingType() || 7541 DestElemTy->isIntegralOrEnumerationType()); 7542 7543 CastKind CK; 7544 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7545 // OpenCL requires that we convert `true` boolean expressions to -1, but 7546 // only when splatting vectors. 7547 if (DestElemTy->isFloatingType()) { 7548 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7549 // in two steps: boolean to signed integral, then to floating. 7550 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7551 CK_BooleanToSignedIntegral); 7552 SplattedExpr = CastExprRes.get(); 7553 CK = CK_IntegralToFloating; 7554 } else { 7555 CK = CK_BooleanToSignedIntegral; 7556 } 7557 } else { 7558 ExprResult CastExprRes = SplattedExpr; 7559 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7560 if (CastExprRes.isInvalid()) 7561 return ExprError(); 7562 SplattedExpr = CastExprRes.get(); 7563 } 7564 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7565 } 7566 7567 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7568 Expr *CastExpr, CastKind &Kind) { 7569 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7570 7571 QualType SrcTy = CastExpr->getType(); 7572 7573 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7574 // an ExtVectorType. 7575 // In OpenCL, casts between vectors of different types are not allowed. 7576 // (See OpenCL 6.2). 7577 if (SrcTy->isVectorType()) { 7578 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7579 (getLangOpts().OpenCL && 7580 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7581 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7582 << DestTy << SrcTy << R; 7583 return ExprError(); 7584 } 7585 Kind = CK_BitCast; 7586 return CastExpr; 7587 } 7588 7589 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7590 // conversion will take place first from scalar to elt type, and then 7591 // splat from elt type to vector. 7592 if (SrcTy->isPointerType()) 7593 return Diag(R.getBegin(), 7594 diag::err_invalid_conversion_between_vector_and_scalar) 7595 << DestTy << SrcTy << R; 7596 7597 Kind = CK_VectorSplat; 7598 return prepareVectorSplat(DestTy, CastExpr); 7599 } 7600 7601 ExprResult 7602 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7603 Declarator &D, ParsedType &Ty, 7604 SourceLocation RParenLoc, Expr *CastExpr) { 7605 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7606 "ActOnCastExpr(): missing type or expr"); 7607 7608 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7609 if (D.isInvalidType()) 7610 return ExprError(); 7611 7612 if (getLangOpts().CPlusPlus) { 7613 // Check that there are no default arguments (C++ only). 7614 CheckExtraCXXDefaultArguments(D); 7615 } else { 7616 // Make sure any TypoExprs have been dealt with. 7617 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7618 if (!Res.isUsable()) 7619 return ExprError(); 7620 CastExpr = Res.get(); 7621 } 7622 7623 checkUnusedDeclAttributes(D); 7624 7625 QualType castType = castTInfo->getType(); 7626 Ty = CreateParsedType(castType, castTInfo); 7627 7628 bool isVectorLiteral = false; 7629 7630 // Check for an altivec or OpenCL literal, 7631 // i.e. all the elements are integer constants. 7632 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7633 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7634 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7635 && castType->isVectorType() && (PE || PLE)) { 7636 if (PLE && PLE->getNumExprs() == 0) { 7637 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7638 return ExprError(); 7639 } 7640 if (PE || PLE->getNumExprs() == 1) { 7641 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7642 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7643 isVectorLiteral = true; 7644 } 7645 else 7646 isVectorLiteral = true; 7647 } 7648 7649 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7650 // then handle it as such. 7651 if (isVectorLiteral) 7652 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7653 7654 // If the Expr being casted is a ParenListExpr, handle it specially. 7655 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7656 // sequence of BinOp comma operators. 7657 if (isa<ParenListExpr>(CastExpr)) { 7658 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7659 if (Result.isInvalid()) return ExprError(); 7660 CastExpr = Result.get(); 7661 } 7662 7663 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7664 !getSourceManager().isInSystemMacro(LParenLoc)) 7665 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7666 7667 CheckTollFreeBridgeCast(castType, CastExpr); 7668 7669 CheckObjCBridgeRelatedCast(castType, CastExpr); 7670 7671 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7672 7673 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7674 } 7675 7676 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7677 SourceLocation RParenLoc, Expr *E, 7678 TypeSourceInfo *TInfo) { 7679 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7680 "Expected paren or paren list expression"); 7681 7682 Expr **exprs; 7683 unsigned numExprs; 7684 Expr *subExpr; 7685 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7686 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7687 LiteralLParenLoc = PE->getLParenLoc(); 7688 LiteralRParenLoc = PE->getRParenLoc(); 7689 exprs = PE->getExprs(); 7690 numExprs = PE->getNumExprs(); 7691 } else { // isa<ParenExpr> by assertion at function entrance 7692 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7693 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7694 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7695 exprs = &subExpr; 7696 numExprs = 1; 7697 } 7698 7699 QualType Ty = TInfo->getType(); 7700 assert(Ty->isVectorType() && "Expected vector type"); 7701 7702 SmallVector<Expr *, 8> initExprs; 7703 const VectorType *VTy = Ty->castAs<VectorType>(); 7704 unsigned numElems = VTy->getNumElements(); 7705 7706 // '(...)' form of vector initialization in AltiVec: the number of 7707 // initializers must be one or must match the size of the vector. 7708 // If a single value is specified in the initializer then it will be 7709 // replicated to all the components of the vector 7710 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7711 // The number of initializers must be one or must match the size of the 7712 // vector. If a single value is specified in the initializer then it will 7713 // be replicated to all the components of the vector 7714 if (numExprs == 1) { 7715 QualType ElemTy = VTy->getElementType(); 7716 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7717 if (Literal.isInvalid()) 7718 return ExprError(); 7719 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7720 PrepareScalarCast(Literal, ElemTy)); 7721 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7722 } 7723 else if (numExprs < numElems) { 7724 Diag(E->getExprLoc(), 7725 diag::err_incorrect_number_of_vector_initializers); 7726 return ExprError(); 7727 } 7728 else 7729 initExprs.append(exprs, exprs + numExprs); 7730 } 7731 else { 7732 // For OpenCL, when the number of initializers is a single value, 7733 // it will be replicated to all components of the vector. 7734 if (getLangOpts().OpenCL && 7735 VTy->getVectorKind() == VectorType::GenericVector && 7736 numExprs == 1) { 7737 QualType ElemTy = VTy->getElementType(); 7738 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7739 if (Literal.isInvalid()) 7740 return ExprError(); 7741 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7742 PrepareScalarCast(Literal, ElemTy)); 7743 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7744 } 7745 7746 initExprs.append(exprs, exprs + numExprs); 7747 } 7748 // FIXME: This means that pretty-printing the final AST will produce curly 7749 // braces instead of the original commas. 7750 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7751 initExprs, LiteralRParenLoc); 7752 initE->setType(Ty); 7753 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7754 } 7755 7756 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7757 /// the ParenListExpr into a sequence of comma binary operators. 7758 ExprResult 7759 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7760 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7761 if (!E) 7762 return OrigExpr; 7763 7764 ExprResult Result(E->getExpr(0)); 7765 7766 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7767 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7768 E->getExpr(i)); 7769 7770 if (Result.isInvalid()) return ExprError(); 7771 7772 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7773 } 7774 7775 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7776 SourceLocation R, 7777 MultiExprArg Val) { 7778 return ParenListExpr::Create(Context, L, Val, R); 7779 } 7780 7781 /// Emit a specialized diagnostic when one expression is a null pointer 7782 /// constant and the other is not a pointer. Returns true if a diagnostic is 7783 /// emitted. 7784 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7785 SourceLocation QuestionLoc) { 7786 Expr *NullExpr = LHSExpr; 7787 Expr *NonPointerExpr = RHSExpr; 7788 Expr::NullPointerConstantKind NullKind = 7789 NullExpr->isNullPointerConstant(Context, 7790 Expr::NPC_ValueDependentIsNotNull); 7791 7792 if (NullKind == Expr::NPCK_NotNull) { 7793 NullExpr = RHSExpr; 7794 NonPointerExpr = LHSExpr; 7795 NullKind = 7796 NullExpr->isNullPointerConstant(Context, 7797 Expr::NPC_ValueDependentIsNotNull); 7798 } 7799 7800 if (NullKind == Expr::NPCK_NotNull) 7801 return false; 7802 7803 if (NullKind == Expr::NPCK_ZeroExpression) 7804 return false; 7805 7806 if (NullKind == Expr::NPCK_ZeroLiteral) { 7807 // In this case, check to make sure that we got here from a "NULL" 7808 // string in the source code. 7809 NullExpr = NullExpr->IgnoreParenImpCasts(); 7810 SourceLocation loc = NullExpr->getExprLoc(); 7811 if (!findMacroSpelling(loc, "NULL")) 7812 return false; 7813 } 7814 7815 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7816 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7817 << NonPointerExpr->getType() << DiagType 7818 << NonPointerExpr->getSourceRange(); 7819 return true; 7820 } 7821 7822 /// Return false if the condition expression is valid, true otherwise. 7823 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7824 QualType CondTy = Cond->getType(); 7825 7826 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7827 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7828 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7829 << CondTy << Cond->getSourceRange(); 7830 return true; 7831 } 7832 7833 // C99 6.5.15p2 7834 if (CondTy->isScalarType()) return false; 7835 7836 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7837 << CondTy << Cond->getSourceRange(); 7838 return true; 7839 } 7840 7841 /// Handle when one or both operands are void type. 7842 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7843 ExprResult &RHS) { 7844 Expr *LHSExpr = LHS.get(); 7845 Expr *RHSExpr = RHS.get(); 7846 7847 if (!LHSExpr->getType()->isVoidType()) 7848 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7849 << RHSExpr->getSourceRange(); 7850 if (!RHSExpr->getType()->isVoidType()) 7851 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7852 << LHSExpr->getSourceRange(); 7853 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7854 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7855 return S.Context.VoidTy; 7856 } 7857 7858 /// Return false if the NullExpr can be promoted to PointerTy, 7859 /// true otherwise. 7860 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7861 QualType PointerTy) { 7862 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7863 !NullExpr.get()->isNullPointerConstant(S.Context, 7864 Expr::NPC_ValueDependentIsNull)) 7865 return true; 7866 7867 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7868 return false; 7869 } 7870 7871 /// Checks compatibility between two pointers and return the resulting 7872 /// type. 7873 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7874 ExprResult &RHS, 7875 SourceLocation Loc) { 7876 QualType LHSTy = LHS.get()->getType(); 7877 QualType RHSTy = RHS.get()->getType(); 7878 7879 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7880 // Two identical pointers types are always compatible. 7881 return LHSTy; 7882 } 7883 7884 QualType lhptee, rhptee; 7885 7886 // Get the pointee types. 7887 bool IsBlockPointer = false; 7888 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7889 lhptee = LHSBTy->getPointeeType(); 7890 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7891 IsBlockPointer = true; 7892 } else { 7893 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7894 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7895 } 7896 7897 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7898 // differently qualified versions of compatible types, the result type is 7899 // a pointer to an appropriately qualified version of the composite 7900 // type. 7901 7902 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7903 // clause doesn't make sense for our extensions. E.g. address space 2 should 7904 // be incompatible with address space 3: they may live on different devices or 7905 // anything. 7906 Qualifiers lhQual = lhptee.getQualifiers(); 7907 Qualifiers rhQual = rhptee.getQualifiers(); 7908 7909 LangAS ResultAddrSpace = LangAS::Default; 7910 LangAS LAddrSpace = lhQual.getAddressSpace(); 7911 LangAS RAddrSpace = rhQual.getAddressSpace(); 7912 7913 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7914 // spaces is disallowed. 7915 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7916 ResultAddrSpace = LAddrSpace; 7917 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7918 ResultAddrSpace = RAddrSpace; 7919 else { 7920 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7921 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7922 << RHS.get()->getSourceRange(); 7923 return QualType(); 7924 } 7925 7926 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7927 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7928 lhQual.removeCVRQualifiers(); 7929 rhQual.removeCVRQualifiers(); 7930 7931 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7932 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7933 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7934 // qual types are compatible iff 7935 // * corresponded types are compatible 7936 // * CVR qualifiers are equal 7937 // * address spaces are equal 7938 // Thus for conditional operator we merge CVR and address space unqualified 7939 // pointees and if there is a composite type we return a pointer to it with 7940 // merged qualifiers. 7941 LHSCastKind = 7942 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7943 RHSCastKind = 7944 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7945 lhQual.removeAddressSpace(); 7946 rhQual.removeAddressSpace(); 7947 7948 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7949 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7950 7951 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7952 7953 if (CompositeTy.isNull()) { 7954 // In this situation, we assume void* type. No especially good 7955 // reason, but this is what gcc does, and we do have to pick 7956 // to get a consistent AST. 7957 QualType incompatTy; 7958 incompatTy = S.Context.getPointerType( 7959 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7960 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7961 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7962 7963 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7964 // for casts between types with incompatible address space qualifiers. 7965 // For the following code the compiler produces casts between global and 7966 // local address spaces of the corresponded innermost pointees: 7967 // local int *global *a; 7968 // global int *global *b; 7969 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7970 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7971 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7972 << RHS.get()->getSourceRange(); 7973 7974 return incompatTy; 7975 } 7976 7977 // The pointer types are compatible. 7978 // In case of OpenCL ResultTy should have the address space qualifier 7979 // which is a superset of address spaces of both the 2nd and the 3rd 7980 // operands of the conditional operator. 7981 QualType ResultTy = [&, ResultAddrSpace]() { 7982 if (S.getLangOpts().OpenCL) { 7983 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7984 CompositeQuals.setAddressSpace(ResultAddrSpace); 7985 return S.Context 7986 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7987 .withCVRQualifiers(MergedCVRQual); 7988 } 7989 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7990 }(); 7991 if (IsBlockPointer) 7992 ResultTy = S.Context.getBlockPointerType(ResultTy); 7993 else 7994 ResultTy = S.Context.getPointerType(ResultTy); 7995 7996 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7997 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7998 return ResultTy; 7999 } 8000 8001 /// Return the resulting type when the operands are both block pointers. 8002 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8003 ExprResult &LHS, 8004 ExprResult &RHS, 8005 SourceLocation Loc) { 8006 QualType LHSTy = LHS.get()->getType(); 8007 QualType RHSTy = RHS.get()->getType(); 8008 8009 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8010 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8011 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8012 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8013 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8014 return destType; 8015 } 8016 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8017 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8018 << RHS.get()->getSourceRange(); 8019 return QualType(); 8020 } 8021 8022 // We have 2 block pointer types. 8023 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8024 } 8025 8026 /// Return the resulting type when the operands are both pointers. 8027 static QualType 8028 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8029 ExprResult &RHS, 8030 SourceLocation Loc) { 8031 // get the pointer types 8032 QualType LHSTy = LHS.get()->getType(); 8033 QualType RHSTy = RHS.get()->getType(); 8034 8035 // get the "pointed to" types 8036 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8037 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8038 8039 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8040 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8041 // Figure out necessary qualifiers (C99 6.5.15p6) 8042 QualType destPointee 8043 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8044 QualType destType = S.Context.getPointerType(destPointee); 8045 // Add qualifiers if necessary. 8046 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8047 // Promote to void*. 8048 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8049 return destType; 8050 } 8051 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8052 QualType destPointee 8053 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8054 QualType destType = S.Context.getPointerType(destPointee); 8055 // Add qualifiers if necessary. 8056 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8057 // Promote to void*. 8058 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8059 return destType; 8060 } 8061 8062 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8063 } 8064 8065 /// Return false if the first expression is not an integer and the second 8066 /// expression is not a pointer, true otherwise. 8067 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8068 Expr* PointerExpr, SourceLocation Loc, 8069 bool IsIntFirstExpr) { 8070 if (!PointerExpr->getType()->isPointerType() || 8071 !Int.get()->getType()->isIntegerType()) 8072 return false; 8073 8074 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8075 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8076 8077 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8078 << Expr1->getType() << Expr2->getType() 8079 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8080 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8081 CK_IntegralToPointer); 8082 return true; 8083 } 8084 8085 /// Simple conversion between integer and floating point types. 8086 /// 8087 /// Used when handling the OpenCL conditional operator where the 8088 /// condition is a vector while the other operands are scalar. 8089 /// 8090 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8091 /// types are either integer or floating type. Between the two 8092 /// operands, the type with the higher rank is defined as the "result 8093 /// type". The other operand needs to be promoted to the same type. No 8094 /// other type promotion is allowed. We cannot use 8095 /// UsualArithmeticConversions() for this purpose, since it always 8096 /// promotes promotable types. 8097 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8098 ExprResult &RHS, 8099 SourceLocation QuestionLoc) { 8100 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8101 if (LHS.isInvalid()) 8102 return QualType(); 8103 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8104 if (RHS.isInvalid()) 8105 return QualType(); 8106 8107 // For conversion purposes, we ignore any qualifiers. 8108 // For example, "const float" and "float" are equivalent. 8109 QualType LHSType = 8110 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8111 QualType RHSType = 8112 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8113 8114 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8115 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8116 << LHSType << LHS.get()->getSourceRange(); 8117 return QualType(); 8118 } 8119 8120 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8121 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8122 << RHSType << RHS.get()->getSourceRange(); 8123 return QualType(); 8124 } 8125 8126 // If both types are identical, no conversion is needed. 8127 if (LHSType == RHSType) 8128 return LHSType; 8129 8130 // Now handle "real" floating types (i.e. float, double, long double). 8131 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8132 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8133 /*IsCompAssign = */ false); 8134 8135 // Finally, we have two differing integer types. 8136 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8137 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8138 } 8139 8140 /// Convert scalar operands to a vector that matches the 8141 /// condition in length. 8142 /// 8143 /// Used when handling the OpenCL conditional operator where the 8144 /// condition is a vector while the other operands are scalar. 8145 /// 8146 /// We first compute the "result type" for the scalar operands 8147 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8148 /// into a vector of that type where the length matches the condition 8149 /// vector type. s6.11.6 requires that the element types of the result 8150 /// and the condition must have the same number of bits. 8151 static QualType 8152 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8153 QualType CondTy, SourceLocation QuestionLoc) { 8154 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8155 if (ResTy.isNull()) return QualType(); 8156 8157 const VectorType *CV = CondTy->getAs<VectorType>(); 8158 assert(CV); 8159 8160 // Determine the vector result type 8161 unsigned NumElements = CV->getNumElements(); 8162 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8163 8164 // Ensure that all types have the same number of bits 8165 if (S.Context.getTypeSize(CV->getElementType()) 8166 != S.Context.getTypeSize(ResTy)) { 8167 // Since VectorTy is created internally, it does not pretty print 8168 // with an OpenCL name. Instead, we just print a description. 8169 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8170 SmallString<64> Str; 8171 llvm::raw_svector_ostream OS(Str); 8172 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8173 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8174 << CondTy << OS.str(); 8175 return QualType(); 8176 } 8177 8178 // Convert operands to the vector result type 8179 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8180 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8181 8182 return VectorTy; 8183 } 8184 8185 /// Return false if this is a valid OpenCL condition vector 8186 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8187 SourceLocation QuestionLoc) { 8188 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8189 // integral type. 8190 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8191 assert(CondTy); 8192 QualType EleTy = CondTy->getElementType(); 8193 if (EleTy->isIntegerType()) return false; 8194 8195 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8196 << Cond->getType() << Cond->getSourceRange(); 8197 return true; 8198 } 8199 8200 /// Return false if the vector condition type and the vector 8201 /// result type are compatible. 8202 /// 8203 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8204 /// number of elements, and their element types have the same number 8205 /// of bits. 8206 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8207 SourceLocation QuestionLoc) { 8208 const VectorType *CV = CondTy->getAs<VectorType>(); 8209 const VectorType *RV = VecResTy->getAs<VectorType>(); 8210 assert(CV && RV); 8211 8212 if (CV->getNumElements() != RV->getNumElements()) { 8213 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8214 << CondTy << VecResTy; 8215 return true; 8216 } 8217 8218 QualType CVE = CV->getElementType(); 8219 QualType RVE = RV->getElementType(); 8220 8221 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8222 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8223 << CondTy << VecResTy; 8224 return true; 8225 } 8226 8227 return false; 8228 } 8229 8230 /// Return the resulting type for the conditional operator in 8231 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8232 /// s6.3.i) when the condition is a vector type. 8233 static QualType 8234 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8235 ExprResult &LHS, ExprResult &RHS, 8236 SourceLocation QuestionLoc) { 8237 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8238 if (Cond.isInvalid()) 8239 return QualType(); 8240 QualType CondTy = Cond.get()->getType(); 8241 8242 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8243 return QualType(); 8244 8245 // If either operand is a vector then find the vector type of the 8246 // result as specified in OpenCL v1.1 s6.3.i. 8247 if (LHS.get()->getType()->isVectorType() || 8248 RHS.get()->getType()->isVectorType()) { 8249 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8250 /*isCompAssign*/false, 8251 /*AllowBothBool*/true, 8252 /*AllowBoolConversions*/false); 8253 if (VecResTy.isNull()) return QualType(); 8254 // The result type must match the condition type as specified in 8255 // OpenCL v1.1 s6.11.6. 8256 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8257 return QualType(); 8258 return VecResTy; 8259 } 8260 8261 // Both operands are scalar. 8262 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8263 } 8264 8265 /// Return true if the Expr is block type 8266 static bool checkBlockType(Sema &S, const Expr *E) { 8267 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8268 QualType Ty = CE->getCallee()->getType(); 8269 if (Ty->isBlockPointerType()) { 8270 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8271 return true; 8272 } 8273 } 8274 return false; 8275 } 8276 8277 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8278 /// In that case, LHS = cond. 8279 /// C99 6.5.15 8280 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8281 ExprResult &RHS, ExprValueKind &VK, 8282 ExprObjectKind &OK, 8283 SourceLocation QuestionLoc) { 8284 8285 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8286 if (!LHSResult.isUsable()) return QualType(); 8287 LHS = LHSResult; 8288 8289 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8290 if (!RHSResult.isUsable()) return QualType(); 8291 RHS = RHSResult; 8292 8293 // C++ is sufficiently different to merit its own checker. 8294 if (getLangOpts().CPlusPlus) 8295 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8296 8297 VK = VK_PRValue; 8298 OK = OK_Ordinary; 8299 8300 if (Context.isDependenceAllowed() && 8301 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8302 RHS.get()->isTypeDependent())) { 8303 assert(!getLangOpts().CPlusPlus); 8304 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8305 RHS.get()->containsErrors()) && 8306 "should only occur in error-recovery path."); 8307 return Context.DependentTy; 8308 } 8309 8310 // The OpenCL operator with a vector condition is sufficiently 8311 // different to merit its own checker. 8312 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8313 Cond.get()->getType()->isExtVectorType()) 8314 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8315 8316 // First, check the condition. 8317 Cond = UsualUnaryConversions(Cond.get()); 8318 if (Cond.isInvalid()) 8319 return QualType(); 8320 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8321 return QualType(); 8322 8323 // Now check the two expressions. 8324 if (LHS.get()->getType()->isVectorType() || 8325 RHS.get()->getType()->isVectorType()) 8326 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8327 /*AllowBothBool*/true, 8328 /*AllowBoolConversions*/false); 8329 8330 QualType ResTy = 8331 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8332 if (LHS.isInvalid() || RHS.isInvalid()) 8333 return QualType(); 8334 8335 QualType LHSTy = LHS.get()->getType(); 8336 QualType RHSTy = RHS.get()->getType(); 8337 8338 // Diagnose attempts to convert between __float128 and long double where 8339 // such conversions currently can't be handled. 8340 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8341 Diag(QuestionLoc, 8342 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8344 return QualType(); 8345 } 8346 8347 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8348 // selection operator (?:). 8349 if (getLangOpts().OpenCL && 8350 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8351 return QualType(); 8352 } 8353 8354 // If both operands have arithmetic type, do the usual arithmetic conversions 8355 // to find a common type: C99 6.5.15p3,5. 8356 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8357 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8358 // different sizes, or between ExtInts and other types. 8359 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8360 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8361 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8362 << RHS.get()->getSourceRange(); 8363 return QualType(); 8364 } 8365 8366 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8367 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8368 8369 return ResTy; 8370 } 8371 8372 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8373 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8374 return LHSTy; 8375 } 8376 8377 // If both operands are the same structure or union type, the result is that 8378 // type. 8379 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8380 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8381 if (LHSRT->getDecl() == RHSRT->getDecl()) 8382 // "If both the operands have structure or union type, the result has 8383 // that type." This implies that CV qualifiers are dropped. 8384 return LHSTy.getUnqualifiedType(); 8385 // FIXME: Type of conditional expression must be complete in C mode. 8386 } 8387 8388 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8389 // The following || allows only one side to be void (a GCC-ism). 8390 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8391 return checkConditionalVoidType(*this, LHS, RHS); 8392 } 8393 8394 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8395 // the type of the other operand." 8396 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8397 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8398 8399 // All objective-c pointer type analysis is done here. 8400 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8401 QuestionLoc); 8402 if (LHS.isInvalid() || RHS.isInvalid()) 8403 return QualType(); 8404 if (!compositeType.isNull()) 8405 return compositeType; 8406 8407 8408 // Handle block pointer types. 8409 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8410 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8411 QuestionLoc); 8412 8413 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8414 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8415 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8416 QuestionLoc); 8417 8418 // GCC compatibility: soften pointer/integer mismatch. Note that 8419 // null pointers have been filtered out by this point. 8420 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8421 /*IsIntFirstExpr=*/true)) 8422 return RHSTy; 8423 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8424 /*IsIntFirstExpr=*/false)) 8425 return LHSTy; 8426 8427 // Allow ?: operations in which both operands have the same 8428 // built-in sizeless type. 8429 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8430 return LHSTy; 8431 8432 // Emit a better diagnostic if one of the expressions is a null pointer 8433 // constant and the other is not a pointer type. In this case, the user most 8434 // likely forgot to take the address of the other expression. 8435 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8436 return QualType(); 8437 8438 // Otherwise, the operands are not compatible. 8439 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8440 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8441 << RHS.get()->getSourceRange(); 8442 return QualType(); 8443 } 8444 8445 /// FindCompositeObjCPointerType - Helper method to find composite type of 8446 /// two objective-c pointer types of the two input expressions. 8447 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8448 SourceLocation QuestionLoc) { 8449 QualType LHSTy = LHS.get()->getType(); 8450 QualType RHSTy = RHS.get()->getType(); 8451 8452 // Handle things like Class and struct objc_class*. Here we case the result 8453 // to the pseudo-builtin, because that will be implicitly cast back to the 8454 // redefinition type if an attempt is made to access its fields. 8455 if (LHSTy->isObjCClassType() && 8456 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8457 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8458 return LHSTy; 8459 } 8460 if (RHSTy->isObjCClassType() && 8461 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8462 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8463 return RHSTy; 8464 } 8465 // And the same for struct objc_object* / id 8466 if (LHSTy->isObjCIdType() && 8467 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8468 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8469 return LHSTy; 8470 } 8471 if (RHSTy->isObjCIdType() && 8472 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8473 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8474 return RHSTy; 8475 } 8476 // And the same for struct objc_selector* / SEL 8477 if (Context.isObjCSelType(LHSTy) && 8478 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8479 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8480 return LHSTy; 8481 } 8482 if (Context.isObjCSelType(RHSTy) && 8483 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8484 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8485 return RHSTy; 8486 } 8487 // Check constraints for Objective-C object pointers types. 8488 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8489 8490 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8491 // Two identical object pointer types are always compatible. 8492 return LHSTy; 8493 } 8494 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8495 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8496 QualType compositeType = LHSTy; 8497 8498 // If both operands are interfaces and either operand can be 8499 // assigned to the other, use that type as the composite 8500 // type. This allows 8501 // xxx ? (A*) a : (B*) b 8502 // where B is a subclass of A. 8503 // 8504 // Additionally, as for assignment, if either type is 'id' 8505 // allow silent coercion. Finally, if the types are 8506 // incompatible then make sure to use 'id' as the composite 8507 // type so the result is acceptable for sending messages to. 8508 8509 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8510 // It could return the composite type. 8511 if (!(compositeType = 8512 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8513 // Nothing more to do. 8514 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8515 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8516 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8517 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8518 } else if ((LHSOPT->isObjCQualifiedIdType() || 8519 RHSOPT->isObjCQualifiedIdType()) && 8520 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8521 true)) { 8522 // Need to handle "id<xx>" explicitly. 8523 // GCC allows qualified id and any Objective-C type to devolve to 8524 // id. Currently localizing to here until clear this should be 8525 // part of ObjCQualifiedIdTypesAreCompatible. 8526 compositeType = Context.getObjCIdType(); 8527 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8528 compositeType = Context.getObjCIdType(); 8529 } else { 8530 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8531 << LHSTy << RHSTy 8532 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8533 QualType incompatTy = Context.getObjCIdType(); 8534 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8535 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8536 return incompatTy; 8537 } 8538 // The object pointer types are compatible. 8539 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8540 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8541 return compositeType; 8542 } 8543 // Check Objective-C object pointer types and 'void *' 8544 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8545 if (getLangOpts().ObjCAutoRefCount) { 8546 // ARC forbids the implicit conversion of object pointers to 'void *', 8547 // so these types are not compatible. 8548 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8550 LHS = RHS = true; 8551 return QualType(); 8552 } 8553 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8554 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8555 QualType destPointee 8556 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8557 QualType destType = Context.getPointerType(destPointee); 8558 // Add qualifiers if necessary. 8559 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8560 // Promote to void*. 8561 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8562 return destType; 8563 } 8564 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8565 if (getLangOpts().ObjCAutoRefCount) { 8566 // ARC forbids the implicit conversion of object pointers to 'void *', 8567 // so these types are not compatible. 8568 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8569 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8570 LHS = RHS = true; 8571 return QualType(); 8572 } 8573 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8574 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8575 QualType destPointee 8576 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8577 QualType destType = Context.getPointerType(destPointee); 8578 // Add qualifiers if necessary. 8579 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8580 // Promote to void*. 8581 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8582 return destType; 8583 } 8584 return QualType(); 8585 } 8586 8587 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8588 /// ParenRange in parentheses. 8589 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8590 const PartialDiagnostic &Note, 8591 SourceRange ParenRange) { 8592 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8593 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8594 EndLoc.isValid()) { 8595 Self.Diag(Loc, Note) 8596 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8597 << FixItHint::CreateInsertion(EndLoc, ")"); 8598 } else { 8599 // We can't display the parentheses, so just show the bare note. 8600 Self.Diag(Loc, Note) << ParenRange; 8601 } 8602 } 8603 8604 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8605 return BinaryOperator::isAdditiveOp(Opc) || 8606 BinaryOperator::isMultiplicativeOp(Opc) || 8607 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8608 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8609 // not any of the logical operators. Bitwise-xor is commonly used as a 8610 // logical-xor because there is no logical-xor operator. The logical 8611 // operators, including uses of xor, have a high false positive rate for 8612 // precedence warnings. 8613 } 8614 8615 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8616 /// expression, either using a built-in or overloaded operator, 8617 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8618 /// expression. 8619 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8620 Expr **RHSExprs) { 8621 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8622 E = E->IgnoreImpCasts(); 8623 E = E->IgnoreConversionOperatorSingleStep(); 8624 E = E->IgnoreImpCasts(); 8625 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8626 E = MTE->getSubExpr(); 8627 E = E->IgnoreImpCasts(); 8628 } 8629 8630 // Built-in binary operator. 8631 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8632 if (IsArithmeticOp(OP->getOpcode())) { 8633 *Opcode = OP->getOpcode(); 8634 *RHSExprs = OP->getRHS(); 8635 return true; 8636 } 8637 } 8638 8639 // Overloaded operator. 8640 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8641 if (Call->getNumArgs() != 2) 8642 return false; 8643 8644 // Make sure this is really a binary operator that is safe to pass into 8645 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8646 OverloadedOperatorKind OO = Call->getOperator(); 8647 if (OO < OO_Plus || OO > OO_Arrow || 8648 OO == OO_PlusPlus || OO == OO_MinusMinus) 8649 return false; 8650 8651 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8652 if (IsArithmeticOp(OpKind)) { 8653 *Opcode = OpKind; 8654 *RHSExprs = Call->getArg(1); 8655 return true; 8656 } 8657 } 8658 8659 return false; 8660 } 8661 8662 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8663 /// or is a logical expression such as (x==y) which has int type, but is 8664 /// commonly interpreted as boolean. 8665 static bool ExprLooksBoolean(Expr *E) { 8666 E = E->IgnoreParenImpCasts(); 8667 8668 if (E->getType()->isBooleanType()) 8669 return true; 8670 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8671 return OP->isComparisonOp() || OP->isLogicalOp(); 8672 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8673 return OP->getOpcode() == UO_LNot; 8674 if (E->getType()->isPointerType()) 8675 return true; 8676 // FIXME: What about overloaded operator calls returning "unspecified boolean 8677 // type"s (commonly pointer-to-members)? 8678 8679 return false; 8680 } 8681 8682 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8683 /// and binary operator are mixed in a way that suggests the programmer assumed 8684 /// the conditional operator has higher precedence, for example: 8685 /// "int x = a + someBinaryCondition ? 1 : 2". 8686 static void DiagnoseConditionalPrecedence(Sema &Self, 8687 SourceLocation OpLoc, 8688 Expr *Condition, 8689 Expr *LHSExpr, 8690 Expr *RHSExpr) { 8691 BinaryOperatorKind CondOpcode; 8692 Expr *CondRHS; 8693 8694 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8695 return; 8696 if (!ExprLooksBoolean(CondRHS)) 8697 return; 8698 8699 // The condition is an arithmetic binary expression, with a right- 8700 // hand side that looks boolean, so warn. 8701 8702 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8703 ? diag::warn_precedence_bitwise_conditional 8704 : diag::warn_precedence_conditional; 8705 8706 Self.Diag(OpLoc, DiagID) 8707 << Condition->getSourceRange() 8708 << BinaryOperator::getOpcodeStr(CondOpcode); 8709 8710 SuggestParentheses( 8711 Self, OpLoc, 8712 Self.PDiag(diag::note_precedence_silence) 8713 << BinaryOperator::getOpcodeStr(CondOpcode), 8714 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8715 8716 SuggestParentheses(Self, OpLoc, 8717 Self.PDiag(diag::note_precedence_conditional_first), 8718 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8719 } 8720 8721 /// Compute the nullability of a conditional expression. 8722 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8723 QualType LHSTy, QualType RHSTy, 8724 ASTContext &Ctx) { 8725 if (!ResTy->isAnyPointerType()) 8726 return ResTy; 8727 8728 auto GetNullability = [&Ctx](QualType Ty) { 8729 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8730 if (Kind) { 8731 // For our purposes, treat _Nullable_result as _Nullable. 8732 if (*Kind == NullabilityKind::NullableResult) 8733 return NullabilityKind::Nullable; 8734 return *Kind; 8735 } 8736 return NullabilityKind::Unspecified; 8737 }; 8738 8739 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8740 NullabilityKind MergedKind; 8741 8742 // Compute nullability of a binary conditional expression. 8743 if (IsBin) { 8744 if (LHSKind == NullabilityKind::NonNull) 8745 MergedKind = NullabilityKind::NonNull; 8746 else 8747 MergedKind = RHSKind; 8748 // Compute nullability of a normal conditional expression. 8749 } else { 8750 if (LHSKind == NullabilityKind::Nullable || 8751 RHSKind == NullabilityKind::Nullable) 8752 MergedKind = NullabilityKind::Nullable; 8753 else if (LHSKind == NullabilityKind::NonNull) 8754 MergedKind = RHSKind; 8755 else if (RHSKind == NullabilityKind::NonNull) 8756 MergedKind = LHSKind; 8757 else 8758 MergedKind = NullabilityKind::Unspecified; 8759 } 8760 8761 // Return if ResTy already has the correct nullability. 8762 if (GetNullability(ResTy) == MergedKind) 8763 return ResTy; 8764 8765 // Strip all nullability from ResTy. 8766 while (ResTy->getNullability(Ctx)) 8767 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8768 8769 // Create a new AttributedType with the new nullability kind. 8770 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8771 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8772 } 8773 8774 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8775 /// in the case of a the GNU conditional expr extension. 8776 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8777 SourceLocation ColonLoc, 8778 Expr *CondExpr, Expr *LHSExpr, 8779 Expr *RHSExpr) { 8780 if (!Context.isDependenceAllowed()) { 8781 // C cannot handle TypoExpr nodes in the condition because it 8782 // doesn't handle dependent types properly, so make sure any TypoExprs have 8783 // been dealt with before checking the operands. 8784 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8785 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8786 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8787 8788 if (!CondResult.isUsable()) 8789 return ExprError(); 8790 8791 if (LHSExpr) { 8792 if (!LHSResult.isUsable()) 8793 return ExprError(); 8794 } 8795 8796 if (!RHSResult.isUsable()) 8797 return ExprError(); 8798 8799 CondExpr = CondResult.get(); 8800 LHSExpr = LHSResult.get(); 8801 RHSExpr = RHSResult.get(); 8802 } 8803 8804 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8805 // was the condition. 8806 OpaqueValueExpr *opaqueValue = nullptr; 8807 Expr *commonExpr = nullptr; 8808 if (!LHSExpr) { 8809 commonExpr = CondExpr; 8810 // Lower out placeholder types first. This is important so that we don't 8811 // try to capture a placeholder. This happens in few cases in C++; such 8812 // as Objective-C++'s dictionary subscripting syntax. 8813 if (commonExpr->hasPlaceholderType()) { 8814 ExprResult result = CheckPlaceholderExpr(commonExpr); 8815 if (!result.isUsable()) return ExprError(); 8816 commonExpr = result.get(); 8817 } 8818 // We usually want to apply unary conversions *before* saving, except 8819 // in the special case of a C++ l-value conditional. 8820 if (!(getLangOpts().CPlusPlus 8821 && !commonExpr->isTypeDependent() 8822 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8823 && commonExpr->isGLValue() 8824 && commonExpr->isOrdinaryOrBitFieldObject() 8825 && RHSExpr->isOrdinaryOrBitFieldObject() 8826 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8827 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8828 if (commonRes.isInvalid()) 8829 return ExprError(); 8830 commonExpr = commonRes.get(); 8831 } 8832 8833 // If the common expression is a class or array prvalue, materialize it 8834 // so that we can safely refer to it multiple times. 8835 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8836 commonExpr->getType()->isArrayType())) { 8837 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8838 if (MatExpr.isInvalid()) 8839 return ExprError(); 8840 commonExpr = MatExpr.get(); 8841 } 8842 8843 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8844 commonExpr->getType(), 8845 commonExpr->getValueKind(), 8846 commonExpr->getObjectKind(), 8847 commonExpr); 8848 LHSExpr = CondExpr = opaqueValue; 8849 } 8850 8851 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8852 ExprValueKind VK = VK_PRValue; 8853 ExprObjectKind OK = OK_Ordinary; 8854 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8855 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8856 VK, OK, QuestionLoc); 8857 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8858 RHS.isInvalid()) 8859 return ExprError(); 8860 8861 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8862 RHS.get()); 8863 8864 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8865 8866 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8867 Context); 8868 8869 if (!commonExpr) 8870 return new (Context) 8871 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8872 RHS.get(), result, VK, OK); 8873 8874 return new (Context) BinaryConditionalOperator( 8875 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8876 ColonLoc, result, VK, OK); 8877 } 8878 8879 // Check if we have a conversion between incompatible cmse function pointer 8880 // types, that is, a conversion between a function pointer with the 8881 // cmse_nonsecure_call attribute and one without. 8882 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8883 QualType ToType) { 8884 if (const auto *ToFn = 8885 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8886 if (const auto *FromFn = 8887 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8888 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8889 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8890 8891 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8892 } 8893 } 8894 return false; 8895 } 8896 8897 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8898 // being closely modeled after the C99 spec:-). The odd characteristic of this 8899 // routine is it effectively iqnores the qualifiers on the top level pointee. 8900 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8901 // FIXME: add a couple examples in this comment. 8902 static Sema::AssignConvertType 8903 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8904 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8905 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8906 8907 // get the "pointed to" type (ignoring qualifiers at the top level) 8908 const Type *lhptee, *rhptee; 8909 Qualifiers lhq, rhq; 8910 std::tie(lhptee, lhq) = 8911 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8912 std::tie(rhptee, rhq) = 8913 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8914 8915 Sema::AssignConvertType ConvTy = Sema::Compatible; 8916 8917 // C99 6.5.16.1p1: This following citation is common to constraints 8918 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8919 // qualifiers of the type *pointed to* by the right; 8920 8921 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8922 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8923 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8924 // Ignore lifetime for further calculation. 8925 lhq.removeObjCLifetime(); 8926 rhq.removeObjCLifetime(); 8927 } 8928 8929 if (!lhq.compatiblyIncludes(rhq)) { 8930 // Treat address-space mismatches as fatal. 8931 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8932 return Sema::IncompatiblePointerDiscardsQualifiers; 8933 8934 // It's okay to add or remove GC or lifetime qualifiers when converting to 8935 // and from void*. 8936 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8937 .compatiblyIncludes( 8938 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8939 && (lhptee->isVoidType() || rhptee->isVoidType())) 8940 ; // keep old 8941 8942 // Treat lifetime mismatches as fatal. 8943 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8944 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8945 8946 // For GCC/MS compatibility, other qualifier mismatches are treated 8947 // as still compatible in C. 8948 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8949 } 8950 8951 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8952 // incomplete type and the other is a pointer to a qualified or unqualified 8953 // version of void... 8954 if (lhptee->isVoidType()) { 8955 if (rhptee->isIncompleteOrObjectType()) 8956 return ConvTy; 8957 8958 // As an extension, we allow cast to/from void* to function pointer. 8959 assert(rhptee->isFunctionType()); 8960 return Sema::FunctionVoidPointer; 8961 } 8962 8963 if (rhptee->isVoidType()) { 8964 if (lhptee->isIncompleteOrObjectType()) 8965 return ConvTy; 8966 8967 // As an extension, we allow cast to/from void* to function pointer. 8968 assert(lhptee->isFunctionType()); 8969 return Sema::FunctionVoidPointer; 8970 } 8971 8972 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8973 // unqualified versions of compatible types, ... 8974 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8975 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8976 // Check if the pointee types are compatible ignoring the sign. 8977 // We explicitly check for char so that we catch "char" vs 8978 // "unsigned char" on systems where "char" is unsigned. 8979 if (lhptee->isCharType()) 8980 ltrans = S.Context.UnsignedCharTy; 8981 else if (lhptee->hasSignedIntegerRepresentation()) 8982 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8983 8984 if (rhptee->isCharType()) 8985 rtrans = S.Context.UnsignedCharTy; 8986 else if (rhptee->hasSignedIntegerRepresentation()) 8987 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8988 8989 if (ltrans == rtrans) { 8990 // Types are compatible ignoring the sign. Qualifier incompatibility 8991 // takes priority over sign incompatibility because the sign 8992 // warning can be disabled. 8993 if (ConvTy != Sema::Compatible) 8994 return ConvTy; 8995 8996 return Sema::IncompatiblePointerSign; 8997 } 8998 8999 // If we are a multi-level pointer, it's possible that our issue is simply 9000 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9001 // the eventual target type is the same and the pointers have the same 9002 // level of indirection, this must be the issue. 9003 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9004 do { 9005 std::tie(lhptee, lhq) = 9006 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9007 std::tie(rhptee, rhq) = 9008 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9009 9010 // Inconsistent address spaces at this point is invalid, even if the 9011 // address spaces would be compatible. 9012 // FIXME: This doesn't catch address space mismatches for pointers of 9013 // different nesting levels, like: 9014 // __local int *** a; 9015 // int ** b = a; 9016 // It's not clear how to actually determine when such pointers are 9017 // invalidly incompatible. 9018 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9019 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9020 9021 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9022 9023 if (lhptee == rhptee) 9024 return Sema::IncompatibleNestedPointerQualifiers; 9025 } 9026 9027 // General pointer incompatibility takes priority over qualifiers. 9028 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9029 return Sema::IncompatibleFunctionPointer; 9030 return Sema::IncompatiblePointer; 9031 } 9032 if (!S.getLangOpts().CPlusPlus && 9033 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9034 return Sema::IncompatibleFunctionPointer; 9035 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9036 return Sema::IncompatibleFunctionPointer; 9037 return ConvTy; 9038 } 9039 9040 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9041 /// block pointer types are compatible or whether a block and normal pointer 9042 /// are compatible. It is more restrict than comparing two function pointer 9043 // types. 9044 static Sema::AssignConvertType 9045 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9046 QualType RHSType) { 9047 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9048 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9049 9050 QualType lhptee, rhptee; 9051 9052 // get the "pointed to" type (ignoring qualifiers at the top level) 9053 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9054 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9055 9056 // In C++, the types have to match exactly. 9057 if (S.getLangOpts().CPlusPlus) 9058 return Sema::IncompatibleBlockPointer; 9059 9060 Sema::AssignConvertType ConvTy = Sema::Compatible; 9061 9062 // For blocks we enforce that qualifiers are identical. 9063 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9064 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9065 if (S.getLangOpts().OpenCL) { 9066 LQuals.removeAddressSpace(); 9067 RQuals.removeAddressSpace(); 9068 } 9069 if (LQuals != RQuals) 9070 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9071 9072 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9073 // assignment. 9074 // The current behavior is similar to C++ lambdas. A block might be 9075 // assigned to a variable iff its return type and parameters are compatible 9076 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9077 // an assignment. Presumably it should behave in way that a function pointer 9078 // assignment does in C, so for each parameter and return type: 9079 // * CVR and address space of LHS should be a superset of CVR and address 9080 // space of RHS. 9081 // * unqualified types should be compatible. 9082 if (S.getLangOpts().OpenCL) { 9083 if (!S.Context.typesAreBlockPointerCompatible( 9084 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9085 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9086 return Sema::IncompatibleBlockPointer; 9087 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9088 return Sema::IncompatibleBlockPointer; 9089 9090 return ConvTy; 9091 } 9092 9093 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9094 /// for assignment compatibility. 9095 static Sema::AssignConvertType 9096 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9097 QualType RHSType) { 9098 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9099 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9100 9101 if (LHSType->isObjCBuiltinType()) { 9102 // Class is not compatible with ObjC object pointers. 9103 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9104 !RHSType->isObjCQualifiedClassType()) 9105 return Sema::IncompatiblePointer; 9106 return Sema::Compatible; 9107 } 9108 if (RHSType->isObjCBuiltinType()) { 9109 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9110 !LHSType->isObjCQualifiedClassType()) 9111 return Sema::IncompatiblePointer; 9112 return Sema::Compatible; 9113 } 9114 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9115 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9116 9117 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9118 // make an exception for id<P> 9119 !LHSType->isObjCQualifiedIdType()) 9120 return Sema::CompatiblePointerDiscardsQualifiers; 9121 9122 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9123 return Sema::Compatible; 9124 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9125 return Sema::IncompatibleObjCQualifiedId; 9126 return Sema::IncompatiblePointer; 9127 } 9128 9129 Sema::AssignConvertType 9130 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9131 QualType LHSType, QualType RHSType) { 9132 // Fake up an opaque expression. We don't actually care about what 9133 // cast operations are required, so if CheckAssignmentConstraints 9134 // adds casts to this they'll be wasted, but fortunately that doesn't 9135 // usually happen on valid code. 9136 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9137 ExprResult RHSPtr = &RHSExpr; 9138 CastKind K; 9139 9140 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9141 } 9142 9143 /// This helper function returns true if QT is a vector type that has element 9144 /// type ElementType. 9145 static bool isVector(QualType QT, QualType ElementType) { 9146 if (const VectorType *VT = QT->getAs<VectorType>()) 9147 return VT->getElementType().getCanonicalType() == ElementType; 9148 return false; 9149 } 9150 9151 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9152 /// has code to accommodate several GCC extensions when type checking 9153 /// pointers. Here are some objectionable examples that GCC considers warnings: 9154 /// 9155 /// int a, *pint; 9156 /// short *pshort; 9157 /// struct foo *pfoo; 9158 /// 9159 /// pint = pshort; // warning: assignment from incompatible pointer type 9160 /// a = pint; // warning: assignment makes integer from pointer without a cast 9161 /// pint = a; // warning: assignment makes pointer from integer without a cast 9162 /// pint = pfoo; // warning: assignment from incompatible pointer type 9163 /// 9164 /// As a result, the code for dealing with pointers is more complex than the 9165 /// C99 spec dictates. 9166 /// 9167 /// Sets 'Kind' for any result kind except Incompatible. 9168 Sema::AssignConvertType 9169 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9170 CastKind &Kind, bool ConvertRHS) { 9171 QualType RHSType = RHS.get()->getType(); 9172 QualType OrigLHSType = LHSType; 9173 9174 // Get canonical types. We're not formatting these types, just comparing 9175 // them. 9176 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9177 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9178 9179 // Common case: no conversion required. 9180 if (LHSType == RHSType) { 9181 Kind = CK_NoOp; 9182 return Compatible; 9183 } 9184 9185 // If we have an atomic type, try a non-atomic assignment, then just add an 9186 // atomic qualification step. 9187 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9188 Sema::AssignConvertType result = 9189 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9190 if (result != Compatible) 9191 return result; 9192 if (Kind != CK_NoOp && ConvertRHS) 9193 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9194 Kind = CK_NonAtomicToAtomic; 9195 return Compatible; 9196 } 9197 9198 // If the left-hand side is a reference type, then we are in a 9199 // (rare!) case where we've allowed the use of references in C, 9200 // e.g., as a parameter type in a built-in function. In this case, 9201 // just make sure that the type referenced is compatible with the 9202 // right-hand side type. The caller is responsible for adjusting 9203 // LHSType so that the resulting expression does not have reference 9204 // type. 9205 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9206 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9207 Kind = CK_LValueBitCast; 9208 return Compatible; 9209 } 9210 return Incompatible; 9211 } 9212 9213 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9214 // to the same ExtVector type. 9215 if (LHSType->isExtVectorType()) { 9216 if (RHSType->isExtVectorType()) 9217 return Incompatible; 9218 if (RHSType->isArithmeticType()) { 9219 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9220 if (ConvertRHS) 9221 RHS = prepareVectorSplat(LHSType, RHS.get()); 9222 Kind = CK_VectorSplat; 9223 return Compatible; 9224 } 9225 } 9226 9227 // Conversions to or from vector type. 9228 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9229 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9230 // Allow assignments of an AltiVec vector type to an equivalent GCC 9231 // vector type and vice versa 9232 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9233 Kind = CK_BitCast; 9234 return Compatible; 9235 } 9236 9237 // If we are allowing lax vector conversions, and LHS and RHS are both 9238 // vectors, the total size only needs to be the same. This is a bitcast; 9239 // no bits are changed but the result type is different. 9240 if (isLaxVectorConversion(RHSType, LHSType)) { 9241 Kind = CK_BitCast; 9242 return IncompatibleVectors; 9243 } 9244 } 9245 9246 // When the RHS comes from another lax conversion (e.g. binops between 9247 // scalars and vectors) the result is canonicalized as a vector. When the 9248 // LHS is also a vector, the lax is allowed by the condition above. Handle 9249 // the case where LHS is a scalar. 9250 if (LHSType->isScalarType()) { 9251 const VectorType *VecType = RHSType->getAs<VectorType>(); 9252 if (VecType && VecType->getNumElements() == 1 && 9253 isLaxVectorConversion(RHSType, LHSType)) { 9254 ExprResult *VecExpr = &RHS; 9255 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9256 Kind = CK_BitCast; 9257 return Compatible; 9258 } 9259 } 9260 9261 // Allow assignments between fixed-length and sizeless SVE vectors. 9262 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9263 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9264 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9265 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9266 Kind = CK_BitCast; 9267 return Compatible; 9268 } 9269 9270 return Incompatible; 9271 } 9272 9273 // Diagnose attempts to convert between __float128 and long double where 9274 // such conversions currently can't be handled. 9275 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9276 return Incompatible; 9277 9278 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9279 // discards the imaginary part. 9280 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9281 !LHSType->getAs<ComplexType>()) 9282 return Incompatible; 9283 9284 // Arithmetic conversions. 9285 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9286 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9287 if (ConvertRHS) 9288 Kind = PrepareScalarCast(RHS, LHSType); 9289 return Compatible; 9290 } 9291 9292 // Conversions to normal pointers. 9293 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9294 // U* -> T* 9295 if (isa<PointerType>(RHSType)) { 9296 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9297 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9298 if (AddrSpaceL != AddrSpaceR) 9299 Kind = CK_AddressSpaceConversion; 9300 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9301 Kind = CK_NoOp; 9302 else 9303 Kind = CK_BitCast; 9304 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9305 } 9306 9307 // int -> T* 9308 if (RHSType->isIntegerType()) { 9309 Kind = CK_IntegralToPointer; // FIXME: null? 9310 return IntToPointer; 9311 } 9312 9313 // C pointers are not compatible with ObjC object pointers, 9314 // with two exceptions: 9315 if (isa<ObjCObjectPointerType>(RHSType)) { 9316 // - conversions to void* 9317 if (LHSPointer->getPointeeType()->isVoidType()) { 9318 Kind = CK_BitCast; 9319 return Compatible; 9320 } 9321 9322 // - conversions from 'Class' to the redefinition type 9323 if (RHSType->isObjCClassType() && 9324 Context.hasSameType(LHSType, 9325 Context.getObjCClassRedefinitionType())) { 9326 Kind = CK_BitCast; 9327 return Compatible; 9328 } 9329 9330 Kind = CK_BitCast; 9331 return IncompatiblePointer; 9332 } 9333 9334 // U^ -> void* 9335 if (RHSType->getAs<BlockPointerType>()) { 9336 if (LHSPointer->getPointeeType()->isVoidType()) { 9337 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9338 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9339 ->getPointeeType() 9340 .getAddressSpace(); 9341 Kind = 9342 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9343 return Compatible; 9344 } 9345 } 9346 9347 return Incompatible; 9348 } 9349 9350 // Conversions to block pointers. 9351 if (isa<BlockPointerType>(LHSType)) { 9352 // U^ -> T^ 9353 if (RHSType->isBlockPointerType()) { 9354 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9355 ->getPointeeType() 9356 .getAddressSpace(); 9357 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9358 ->getPointeeType() 9359 .getAddressSpace(); 9360 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9361 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9362 } 9363 9364 // int or null -> T^ 9365 if (RHSType->isIntegerType()) { 9366 Kind = CK_IntegralToPointer; // FIXME: null 9367 return IntToBlockPointer; 9368 } 9369 9370 // id -> T^ 9371 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9372 Kind = CK_AnyPointerToBlockPointerCast; 9373 return Compatible; 9374 } 9375 9376 // void* -> T^ 9377 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9378 if (RHSPT->getPointeeType()->isVoidType()) { 9379 Kind = CK_AnyPointerToBlockPointerCast; 9380 return Compatible; 9381 } 9382 9383 return Incompatible; 9384 } 9385 9386 // Conversions to Objective-C pointers. 9387 if (isa<ObjCObjectPointerType>(LHSType)) { 9388 // A* -> B* 9389 if (RHSType->isObjCObjectPointerType()) { 9390 Kind = CK_BitCast; 9391 Sema::AssignConvertType result = 9392 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9393 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9394 result == Compatible && 9395 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9396 result = IncompatibleObjCWeakRef; 9397 return result; 9398 } 9399 9400 // int or null -> A* 9401 if (RHSType->isIntegerType()) { 9402 Kind = CK_IntegralToPointer; // FIXME: null 9403 return IntToPointer; 9404 } 9405 9406 // In general, C pointers are not compatible with ObjC object pointers, 9407 // with two exceptions: 9408 if (isa<PointerType>(RHSType)) { 9409 Kind = CK_CPointerToObjCPointerCast; 9410 9411 // - conversions from 'void*' 9412 if (RHSType->isVoidPointerType()) { 9413 return Compatible; 9414 } 9415 9416 // - conversions to 'Class' from its redefinition type 9417 if (LHSType->isObjCClassType() && 9418 Context.hasSameType(RHSType, 9419 Context.getObjCClassRedefinitionType())) { 9420 return Compatible; 9421 } 9422 9423 return IncompatiblePointer; 9424 } 9425 9426 // Only under strict condition T^ is compatible with an Objective-C pointer. 9427 if (RHSType->isBlockPointerType() && 9428 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9429 if (ConvertRHS) 9430 maybeExtendBlockObject(RHS); 9431 Kind = CK_BlockPointerToObjCPointerCast; 9432 return Compatible; 9433 } 9434 9435 return Incompatible; 9436 } 9437 9438 // Conversions from pointers that are not covered by the above. 9439 if (isa<PointerType>(RHSType)) { 9440 // T* -> _Bool 9441 if (LHSType == Context.BoolTy) { 9442 Kind = CK_PointerToBoolean; 9443 return Compatible; 9444 } 9445 9446 // T* -> int 9447 if (LHSType->isIntegerType()) { 9448 Kind = CK_PointerToIntegral; 9449 return PointerToInt; 9450 } 9451 9452 return Incompatible; 9453 } 9454 9455 // Conversions from Objective-C pointers that are not covered by the above. 9456 if (isa<ObjCObjectPointerType>(RHSType)) { 9457 // T* -> _Bool 9458 if (LHSType == Context.BoolTy) { 9459 Kind = CK_PointerToBoolean; 9460 return Compatible; 9461 } 9462 9463 // T* -> int 9464 if (LHSType->isIntegerType()) { 9465 Kind = CK_PointerToIntegral; 9466 return PointerToInt; 9467 } 9468 9469 return Incompatible; 9470 } 9471 9472 // struct A -> struct B 9473 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9474 if (Context.typesAreCompatible(LHSType, RHSType)) { 9475 Kind = CK_NoOp; 9476 return Compatible; 9477 } 9478 } 9479 9480 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9481 Kind = CK_IntToOCLSampler; 9482 return Compatible; 9483 } 9484 9485 return Incompatible; 9486 } 9487 9488 /// Constructs a transparent union from an expression that is 9489 /// used to initialize the transparent union. 9490 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9491 ExprResult &EResult, QualType UnionType, 9492 FieldDecl *Field) { 9493 // Build an initializer list that designates the appropriate member 9494 // of the transparent union. 9495 Expr *E = EResult.get(); 9496 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9497 E, SourceLocation()); 9498 Initializer->setType(UnionType); 9499 Initializer->setInitializedFieldInUnion(Field); 9500 9501 // Build a compound literal constructing a value of the transparent 9502 // union type from this initializer list. 9503 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9504 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9505 VK_PRValue, Initializer, false); 9506 } 9507 9508 Sema::AssignConvertType 9509 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9510 ExprResult &RHS) { 9511 QualType RHSType = RHS.get()->getType(); 9512 9513 // If the ArgType is a Union type, we want to handle a potential 9514 // transparent_union GCC extension. 9515 const RecordType *UT = ArgType->getAsUnionType(); 9516 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9517 return Incompatible; 9518 9519 // The field to initialize within the transparent union. 9520 RecordDecl *UD = UT->getDecl(); 9521 FieldDecl *InitField = nullptr; 9522 // It's compatible if the expression matches any of the fields. 9523 for (auto *it : UD->fields()) { 9524 if (it->getType()->isPointerType()) { 9525 // If the transparent union contains a pointer type, we allow: 9526 // 1) void pointer 9527 // 2) null pointer constant 9528 if (RHSType->isPointerType()) 9529 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9530 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9531 InitField = it; 9532 break; 9533 } 9534 9535 if (RHS.get()->isNullPointerConstant(Context, 9536 Expr::NPC_ValueDependentIsNull)) { 9537 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9538 CK_NullToPointer); 9539 InitField = it; 9540 break; 9541 } 9542 } 9543 9544 CastKind Kind; 9545 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9546 == Compatible) { 9547 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9548 InitField = it; 9549 break; 9550 } 9551 } 9552 9553 if (!InitField) 9554 return Incompatible; 9555 9556 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9557 return Compatible; 9558 } 9559 9560 Sema::AssignConvertType 9561 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9562 bool Diagnose, 9563 bool DiagnoseCFAudited, 9564 bool ConvertRHS) { 9565 // We need to be able to tell the caller whether we diagnosed a problem, if 9566 // they ask us to issue diagnostics. 9567 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9568 9569 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9570 // we can't avoid *all* modifications at the moment, so we need some somewhere 9571 // to put the updated value. 9572 ExprResult LocalRHS = CallerRHS; 9573 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9574 9575 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9576 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9577 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9578 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9579 Diag(RHS.get()->getExprLoc(), 9580 diag::warn_noderef_to_dereferenceable_pointer) 9581 << RHS.get()->getSourceRange(); 9582 } 9583 } 9584 } 9585 9586 if (getLangOpts().CPlusPlus) { 9587 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9588 // C++ 5.17p3: If the left operand is not of class type, the 9589 // expression is implicitly converted (C++ 4) to the 9590 // cv-unqualified type of the left operand. 9591 QualType RHSType = RHS.get()->getType(); 9592 if (Diagnose) { 9593 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9594 AA_Assigning); 9595 } else { 9596 ImplicitConversionSequence ICS = 9597 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9598 /*SuppressUserConversions=*/false, 9599 AllowedExplicit::None, 9600 /*InOverloadResolution=*/false, 9601 /*CStyle=*/false, 9602 /*AllowObjCWritebackConversion=*/false); 9603 if (ICS.isFailure()) 9604 return Incompatible; 9605 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9606 ICS, AA_Assigning); 9607 } 9608 if (RHS.isInvalid()) 9609 return Incompatible; 9610 Sema::AssignConvertType result = Compatible; 9611 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9612 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9613 result = IncompatibleObjCWeakRef; 9614 return result; 9615 } 9616 9617 // FIXME: Currently, we fall through and treat C++ classes like C 9618 // structures. 9619 // FIXME: We also fall through for atomics; not sure what should 9620 // happen there, though. 9621 } else if (RHS.get()->getType() == Context.OverloadTy) { 9622 // As a set of extensions to C, we support overloading on functions. These 9623 // functions need to be resolved here. 9624 DeclAccessPair DAP; 9625 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9626 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9627 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9628 else 9629 return Incompatible; 9630 } 9631 9632 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9633 // a null pointer constant. 9634 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9635 LHSType->isBlockPointerType()) && 9636 RHS.get()->isNullPointerConstant(Context, 9637 Expr::NPC_ValueDependentIsNull)) { 9638 if (Diagnose || ConvertRHS) { 9639 CastKind Kind; 9640 CXXCastPath Path; 9641 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9642 /*IgnoreBaseAccess=*/false, Diagnose); 9643 if (ConvertRHS) 9644 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9645 } 9646 return Compatible; 9647 } 9648 9649 // OpenCL queue_t type assignment. 9650 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9651 Context, Expr::NPC_ValueDependentIsNull)) { 9652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9653 return Compatible; 9654 } 9655 9656 // This check seems unnatural, however it is necessary to ensure the proper 9657 // conversion of functions/arrays. If the conversion were done for all 9658 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9659 // expressions that suppress this implicit conversion (&, sizeof). 9660 // 9661 // Suppress this for references: C++ 8.5.3p5. 9662 if (!LHSType->isReferenceType()) { 9663 // FIXME: We potentially allocate here even if ConvertRHS is false. 9664 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9665 if (RHS.isInvalid()) 9666 return Incompatible; 9667 } 9668 CastKind Kind; 9669 Sema::AssignConvertType result = 9670 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9671 9672 // C99 6.5.16.1p2: The value of the right operand is converted to the 9673 // type of the assignment expression. 9674 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9675 // so that we can use references in built-in functions even in C. 9676 // The getNonReferenceType() call makes sure that the resulting expression 9677 // does not have reference type. 9678 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9679 QualType Ty = LHSType.getNonLValueExprType(Context); 9680 Expr *E = RHS.get(); 9681 9682 // Check for various Objective-C errors. If we are not reporting 9683 // diagnostics and just checking for errors, e.g., during overload 9684 // resolution, return Incompatible to indicate the failure. 9685 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9686 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9687 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9688 if (!Diagnose) 9689 return Incompatible; 9690 } 9691 if (getLangOpts().ObjC && 9692 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9693 E->getType(), E, Diagnose) || 9694 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9695 if (!Diagnose) 9696 return Incompatible; 9697 // Replace the expression with a corrected version and continue so we 9698 // can find further errors. 9699 RHS = E; 9700 return Compatible; 9701 } 9702 9703 if (ConvertRHS) 9704 RHS = ImpCastExprToType(E, Ty, Kind); 9705 } 9706 9707 return result; 9708 } 9709 9710 namespace { 9711 /// The original operand to an operator, prior to the application of the usual 9712 /// arithmetic conversions and converting the arguments of a builtin operator 9713 /// candidate. 9714 struct OriginalOperand { 9715 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9716 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9717 Op = MTE->getSubExpr(); 9718 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9719 Op = BTE->getSubExpr(); 9720 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9721 Orig = ICE->getSubExprAsWritten(); 9722 Conversion = ICE->getConversionFunction(); 9723 } 9724 } 9725 9726 QualType getType() const { return Orig->getType(); } 9727 9728 Expr *Orig; 9729 NamedDecl *Conversion; 9730 }; 9731 } 9732 9733 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9734 ExprResult &RHS) { 9735 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9736 9737 Diag(Loc, diag::err_typecheck_invalid_operands) 9738 << OrigLHS.getType() << OrigRHS.getType() 9739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9740 9741 // If a user-defined conversion was applied to either of the operands prior 9742 // to applying the built-in operator rules, tell the user about it. 9743 if (OrigLHS.Conversion) { 9744 Diag(OrigLHS.Conversion->getLocation(), 9745 diag::note_typecheck_invalid_operands_converted) 9746 << 0 << LHS.get()->getType(); 9747 } 9748 if (OrigRHS.Conversion) { 9749 Diag(OrigRHS.Conversion->getLocation(), 9750 diag::note_typecheck_invalid_operands_converted) 9751 << 1 << RHS.get()->getType(); 9752 } 9753 9754 return QualType(); 9755 } 9756 9757 // Diagnose cases where a scalar was implicitly converted to a vector and 9758 // diagnose the underlying types. Otherwise, diagnose the error 9759 // as invalid vector logical operands for non-C++ cases. 9760 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9761 ExprResult &RHS) { 9762 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9763 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9764 9765 bool LHSNatVec = LHSType->isVectorType(); 9766 bool RHSNatVec = RHSType->isVectorType(); 9767 9768 if (!(LHSNatVec && RHSNatVec)) { 9769 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9770 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9771 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9772 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9773 << Vector->getSourceRange(); 9774 return QualType(); 9775 } 9776 9777 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9778 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9779 << RHS.get()->getSourceRange(); 9780 9781 return QualType(); 9782 } 9783 9784 /// Try to convert a value of non-vector type to a vector type by converting 9785 /// the type to the element type of the vector and then performing a splat. 9786 /// If the language is OpenCL, we only use conversions that promote scalar 9787 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9788 /// for float->int. 9789 /// 9790 /// OpenCL V2.0 6.2.6.p2: 9791 /// An error shall occur if any scalar operand type has greater rank 9792 /// than the type of the vector element. 9793 /// 9794 /// \param scalar - if non-null, actually perform the conversions 9795 /// \return true if the operation fails (but without diagnosing the failure) 9796 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9797 QualType scalarTy, 9798 QualType vectorEltTy, 9799 QualType vectorTy, 9800 unsigned &DiagID) { 9801 // The conversion to apply to the scalar before splatting it, 9802 // if necessary. 9803 CastKind scalarCast = CK_NoOp; 9804 9805 if (vectorEltTy->isIntegralType(S.Context)) { 9806 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9807 (scalarTy->isIntegerType() && 9808 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9809 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9810 return true; 9811 } 9812 if (!scalarTy->isIntegralType(S.Context)) 9813 return true; 9814 scalarCast = CK_IntegralCast; 9815 } else if (vectorEltTy->isRealFloatingType()) { 9816 if (scalarTy->isRealFloatingType()) { 9817 if (S.getLangOpts().OpenCL && 9818 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9819 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9820 return true; 9821 } 9822 scalarCast = CK_FloatingCast; 9823 } 9824 else if (scalarTy->isIntegralType(S.Context)) 9825 scalarCast = CK_IntegralToFloating; 9826 else 9827 return true; 9828 } else { 9829 return true; 9830 } 9831 9832 // Adjust scalar if desired. 9833 if (scalar) { 9834 if (scalarCast != CK_NoOp) 9835 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9836 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9837 } 9838 return false; 9839 } 9840 9841 /// Convert vector E to a vector with the same number of elements but different 9842 /// element type. 9843 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9844 const auto *VecTy = E->getType()->getAs<VectorType>(); 9845 assert(VecTy && "Expression E must be a vector"); 9846 QualType NewVecTy = S.Context.getVectorType(ElementType, 9847 VecTy->getNumElements(), 9848 VecTy->getVectorKind()); 9849 9850 // Look through the implicit cast. Return the subexpression if its type is 9851 // NewVecTy. 9852 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9853 if (ICE->getSubExpr()->getType() == NewVecTy) 9854 return ICE->getSubExpr(); 9855 9856 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9857 return S.ImpCastExprToType(E, NewVecTy, Cast); 9858 } 9859 9860 /// Test if a (constant) integer Int can be casted to another integer type 9861 /// IntTy without losing precision. 9862 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9863 QualType OtherIntTy) { 9864 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9865 9866 // Reject cases where the value of the Int is unknown as that would 9867 // possibly cause truncation, but accept cases where the scalar can be 9868 // demoted without loss of precision. 9869 Expr::EvalResult EVResult; 9870 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9871 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9872 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9873 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9874 9875 if (CstInt) { 9876 // If the scalar is constant and is of a higher order and has more active 9877 // bits that the vector element type, reject it. 9878 llvm::APSInt Result = EVResult.Val.getInt(); 9879 unsigned NumBits = IntSigned 9880 ? (Result.isNegative() ? Result.getMinSignedBits() 9881 : Result.getActiveBits()) 9882 : Result.getActiveBits(); 9883 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9884 return true; 9885 9886 // If the signedness of the scalar type and the vector element type 9887 // differs and the number of bits is greater than that of the vector 9888 // element reject it. 9889 return (IntSigned != OtherIntSigned && 9890 NumBits > S.Context.getIntWidth(OtherIntTy)); 9891 } 9892 9893 // Reject cases where the value of the scalar is not constant and it's 9894 // order is greater than that of the vector element type. 9895 return (Order < 0); 9896 } 9897 9898 /// Test if a (constant) integer Int can be casted to floating point type 9899 /// FloatTy without losing precision. 9900 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9901 QualType FloatTy) { 9902 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9903 9904 // Determine if the integer constant can be expressed as a floating point 9905 // number of the appropriate type. 9906 Expr::EvalResult EVResult; 9907 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9908 9909 uint64_t Bits = 0; 9910 if (CstInt) { 9911 // Reject constants that would be truncated if they were converted to 9912 // the floating point type. Test by simple to/from conversion. 9913 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9914 // could be avoided if there was a convertFromAPInt method 9915 // which could signal back if implicit truncation occurred. 9916 llvm::APSInt Result = EVResult.Val.getInt(); 9917 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9918 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9919 llvm::APFloat::rmTowardZero); 9920 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9921 !IntTy->hasSignedIntegerRepresentation()); 9922 bool Ignored = false; 9923 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9924 &Ignored); 9925 if (Result != ConvertBack) 9926 return true; 9927 } else { 9928 // Reject types that cannot be fully encoded into the mantissa of 9929 // the float. 9930 Bits = S.Context.getTypeSize(IntTy); 9931 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9932 S.Context.getFloatTypeSemantics(FloatTy)); 9933 if (Bits > FloatPrec) 9934 return true; 9935 } 9936 9937 return false; 9938 } 9939 9940 /// Attempt to convert and splat Scalar into a vector whose types matches 9941 /// Vector following GCC conversion rules. The rule is that implicit 9942 /// conversion can occur when Scalar can be casted to match Vector's element 9943 /// type without causing truncation of Scalar. 9944 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9945 ExprResult *Vector) { 9946 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9947 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9948 const VectorType *VT = VectorTy->getAs<VectorType>(); 9949 9950 assert(!isa<ExtVectorType>(VT) && 9951 "ExtVectorTypes should not be handled here!"); 9952 9953 QualType VectorEltTy = VT->getElementType(); 9954 9955 // Reject cases where the vector element type or the scalar element type are 9956 // not integral or floating point types. 9957 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9958 return true; 9959 9960 // The conversion to apply to the scalar before splatting it, 9961 // if necessary. 9962 CastKind ScalarCast = CK_NoOp; 9963 9964 // Accept cases where the vector elements are integers and the scalar is 9965 // an integer. 9966 // FIXME: Notionally if the scalar was a floating point value with a precise 9967 // integral representation, we could cast it to an appropriate integer 9968 // type and then perform the rest of the checks here. GCC will perform 9969 // this conversion in some cases as determined by the input language. 9970 // We should accept it on a language independent basis. 9971 if (VectorEltTy->isIntegralType(S.Context) && 9972 ScalarTy->isIntegralType(S.Context) && 9973 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9974 9975 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9976 return true; 9977 9978 ScalarCast = CK_IntegralCast; 9979 } else if (VectorEltTy->isIntegralType(S.Context) && 9980 ScalarTy->isRealFloatingType()) { 9981 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9982 ScalarCast = CK_FloatingToIntegral; 9983 else 9984 return true; 9985 } else if (VectorEltTy->isRealFloatingType()) { 9986 if (ScalarTy->isRealFloatingType()) { 9987 9988 // Reject cases where the scalar type is not a constant and has a higher 9989 // Order than the vector element type. 9990 llvm::APFloat Result(0.0); 9991 9992 // Determine whether this is a constant scalar. In the event that the 9993 // value is dependent (and thus cannot be evaluated by the constant 9994 // evaluator), skip the evaluation. This will then diagnose once the 9995 // expression is instantiated. 9996 bool CstScalar = Scalar->get()->isValueDependent() || 9997 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9998 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9999 if (!CstScalar && Order < 0) 10000 return true; 10001 10002 // If the scalar cannot be safely casted to the vector element type, 10003 // reject it. 10004 if (CstScalar) { 10005 bool Truncated = false; 10006 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10007 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10008 if (Truncated) 10009 return true; 10010 } 10011 10012 ScalarCast = CK_FloatingCast; 10013 } else if (ScalarTy->isIntegralType(S.Context)) { 10014 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10015 return true; 10016 10017 ScalarCast = CK_IntegralToFloating; 10018 } else 10019 return true; 10020 } else if (ScalarTy->isEnumeralType()) 10021 return true; 10022 10023 // Adjust scalar if desired. 10024 if (Scalar) { 10025 if (ScalarCast != CK_NoOp) 10026 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10027 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10028 } 10029 return false; 10030 } 10031 10032 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10033 SourceLocation Loc, bool IsCompAssign, 10034 bool AllowBothBool, 10035 bool AllowBoolConversions) { 10036 if (!IsCompAssign) { 10037 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10038 if (LHS.isInvalid()) 10039 return QualType(); 10040 } 10041 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10042 if (RHS.isInvalid()) 10043 return QualType(); 10044 10045 // For conversion purposes, we ignore any qualifiers. 10046 // For example, "const float" and "float" are equivalent. 10047 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10048 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10049 10050 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10051 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10052 assert(LHSVecType || RHSVecType); 10053 10054 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10055 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10056 return InvalidOperands(Loc, LHS, RHS); 10057 10058 // AltiVec-style "vector bool op vector bool" combinations are allowed 10059 // for some operators but not others. 10060 if (!AllowBothBool && 10061 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10062 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10063 return InvalidOperands(Loc, LHS, RHS); 10064 10065 // If the vector types are identical, return. 10066 if (Context.hasSameType(LHSType, RHSType)) 10067 return LHSType; 10068 10069 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10070 if (LHSVecType && RHSVecType && 10071 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10072 if (isa<ExtVectorType>(LHSVecType)) { 10073 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10074 return LHSType; 10075 } 10076 10077 if (!IsCompAssign) 10078 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10079 return RHSType; 10080 } 10081 10082 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10083 // can be mixed, with the result being the non-bool type. The non-bool 10084 // operand must have integer element type. 10085 if (AllowBoolConversions && LHSVecType && RHSVecType && 10086 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10087 (Context.getTypeSize(LHSVecType->getElementType()) == 10088 Context.getTypeSize(RHSVecType->getElementType()))) { 10089 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10090 LHSVecType->getElementType()->isIntegerType() && 10091 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10092 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10093 return LHSType; 10094 } 10095 if (!IsCompAssign && 10096 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10097 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10098 RHSVecType->getElementType()->isIntegerType()) { 10099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10100 return RHSType; 10101 } 10102 } 10103 10104 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10105 // since the ambiguity can affect the ABI. 10106 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10107 const VectorType *VecType = SecondType->getAs<VectorType>(); 10108 return FirstType->isSizelessBuiltinType() && VecType && 10109 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10110 VecType->getVectorKind() == 10111 VectorType::SveFixedLengthPredicateVector); 10112 }; 10113 10114 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10115 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10116 return QualType(); 10117 } 10118 10119 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10120 // since the ambiguity can affect the ABI. 10121 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10122 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10123 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10124 10125 if (FirstVecType && SecondVecType) 10126 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10127 (SecondVecType->getVectorKind() == 10128 VectorType::SveFixedLengthDataVector || 10129 SecondVecType->getVectorKind() == 10130 VectorType::SveFixedLengthPredicateVector); 10131 10132 return FirstType->isSizelessBuiltinType() && SecondVecType && 10133 SecondVecType->getVectorKind() == VectorType::GenericVector; 10134 }; 10135 10136 if (IsSveGnuConversion(LHSType, RHSType) || 10137 IsSveGnuConversion(RHSType, LHSType)) { 10138 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10139 return QualType(); 10140 } 10141 10142 // If there's a vector type and a scalar, try to convert the scalar to 10143 // the vector element type and splat. 10144 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10145 if (!RHSVecType) { 10146 if (isa<ExtVectorType>(LHSVecType)) { 10147 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10148 LHSVecType->getElementType(), LHSType, 10149 DiagID)) 10150 return LHSType; 10151 } else { 10152 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10153 return LHSType; 10154 } 10155 } 10156 if (!LHSVecType) { 10157 if (isa<ExtVectorType>(RHSVecType)) { 10158 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10159 LHSType, RHSVecType->getElementType(), 10160 RHSType, DiagID)) 10161 return RHSType; 10162 } else { 10163 if (LHS.get()->getValueKind() == VK_LValue || 10164 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10165 return RHSType; 10166 } 10167 } 10168 10169 // FIXME: The code below also handles conversion between vectors and 10170 // non-scalars, we should break this down into fine grained specific checks 10171 // and emit proper diagnostics. 10172 QualType VecType = LHSVecType ? LHSType : RHSType; 10173 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10174 QualType OtherType = LHSVecType ? RHSType : LHSType; 10175 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10176 if (isLaxVectorConversion(OtherType, VecType)) { 10177 // If we're allowing lax vector conversions, only the total (data) size 10178 // needs to be the same. For non compound assignment, if one of the types is 10179 // scalar, the result is always the vector type. 10180 if (!IsCompAssign) { 10181 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10182 return VecType; 10183 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10184 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10185 // type. Note that this is already done by non-compound assignments in 10186 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10187 // <1 x T> -> T. The result is also a vector type. 10188 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10189 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10190 ExprResult *RHSExpr = &RHS; 10191 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10192 return VecType; 10193 } 10194 } 10195 10196 // Okay, the expression is invalid. 10197 10198 // If there's a non-vector, non-real operand, diagnose that. 10199 if ((!RHSVecType && !RHSType->isRealType()) || 10200 (!LHSVecType && !LHSType->isRealType())) { 10201 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10202 << LHSType << RHSType 10203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10204 return QualType(); 10205 } 10206 10207 // OpenCL V1.1 6.2.6.p1: 10208 // If the operands are of more than one vector type, then an error shall 10209 // occur. Implicit conversions between vector types are not permitted, per 10210 // section 6.2.1. 10211 if (getLangOpts().OpenCL && 10212 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10213 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10214 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10215 << RHSType; 10216 return QualType(); 10217 } 10218 10219 10220 // If there is a vector type that is not a ExtVector and a scalar, we reach 10221 // this point if scalar could not be converted to the vector's element type 10222 // without truncation. 10223 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10224 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10225 QualType Scalar = LHSVecType ? RHSType : LHSType; 10226 QualType Vector = LHSVecType ? LHSType : RHSType; 10227 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10228 Diag(Loc, 10229 diag::err_typecheck_vector_not_convertable_implict_truncation) 10230 << ScalarOrVector << Scalar << Vector; 10231 10232 return QualType(); 10233 } 10234 10235 // Otherwise, use the generic diagnostic. 10236 Diag(Loc, DiagID) 10237 << LHSType << RHSType 10238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10239 return QualType(); 10240 } 10241 10242 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10243 // expression. These are mainly cases where the null pointer is used as an 10244 // integer instead of a pointer. 10245 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10246 SourceLocation Loc, bool IsCompare) { 10247 // The canonical way to check for a GNU null is with isNullPointerConstant, 10248 // but we use a bit of a hack here for speed; this is a relatively 10249 // hot path, and isNullPointerConstant is slow. 10250 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10251 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10252 10253 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10254 10255 // Avoid analyzing cases where the result will either be invalid (and 10256 // diagnosed as such) or entirely valid and not something to warn about. 10257 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10258 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10259 return; 10260 10261 // Comparison operations would not make sense with a null pointer no matter 10262 // what the other expression is. 10263 if (!IsCompare) { 10264 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10265 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10266 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10267 return; 10268 } 10269 10270 // The rest of the operations only make sense with a null pointer 10271 // if the other expression is a pointer. 10272 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10273 NonNullType->canDecayToPointerType()) 10274 return; 10275 10276 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10277 << LHSNull /* LHS is NULL */ << NonNullType 10278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10279 } 10280 10281 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10282 SourceLocation Loc) { 10283 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10284 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10285 if (!LUE || !RUE) 10286 return; 10287 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10288 RUE->getKind() != UETT_SizeOf) 10289 return; 10290 10291 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10292 QualType LHSTy = LHSArg->getType(); 10293 QualType RHSTy; 10294 10295 if (RUE->isArgumentType()) 10296 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10297 else 10298 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10299 10300 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10301 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10302 return; 10303 10304 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10305 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10306 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10307 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10308 << LHSArgDecl; 10309 } 10310 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10311 QualType ArrayElemTy = ArrayTy->getElementType(); 10312 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10313 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10314 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10315 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10316 return; 10317 S.Diag(Loc, diag::warn_division_sizeof_array) 10318 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10319 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10320 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10321 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10322 << LHSArgDecl; 10323 } 10324 10325 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10326 } 10327 } 10328 10329 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10330 ExprResult &RHS, 10331 SourceLocation Loc, bool IsDiv) { 10332 // Check for division/remainder by zero. 10333 Expr::EvalResult RHSValue; 10334 if (!RHS.get()->isValueDependent() && 10335 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10336 RHSValue.Val.getInt() == 0) 10337 S.DiagRuntimeBehavior(Loc, RHS.get(), 10338 S.PDiag(diag::warn_remainder_division_by_zero) 10339 << IsDiv << RHS.get()->getSourceRange()); 10340 } 10341 10342 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10343 SourceLocation Loc, 10344 bool IsCompAssign, bool IsDiv) { 10345 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10346 10347 QualType LHSTy = LHS.get()->getType(); 10348 QualType RHSTy = RHS.get()->getType(); 10349 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10350 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10351 /*AllowBothBool*/getLangOpts().AltiVec, 10352 /*AllowBoolConversions*/false); 10353 if (!IsDiv && 10354 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10355 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10356 // For division, only matrix-by-scalar is supported. Other combinations with 10357 // matrix types are invalid. 10358 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10359 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 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 10367 if (compType.isNull() || !compType->isArithmeticType()) 10368 return InvalidOperands(Loc, LHS, RHS); 10369 if (IsDiv) { 10370 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10371 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10372 } 10373 return compType; 10374 } 10375 10376 QualType Sema::CheckRemainderOperands( 10377 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10378 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10379 10380 if (LHS.get()->getType()->isVectorType() || 10381 RHS.get()->getType()->isVectorType()) { 10382 if (LHS.get()->getType()->hasIntegerRepresentation() && 10383 RHS.get()->getType()->hasIntegerRepresentation()) 10384 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10385 /*AllowBothBool*/getLangOpts().AltiVec, 10386 /*AllowBoolConversions*/false); 10387 return InvalidOperands(Loc, LHS, RHS); 10388 } 10389 10390 QualType compType = UsualArithmeticConversions( 10391 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10392 if (LHS.isInvalid() || RHS.isInvalid()) 10393 return QualType(); 10394 10395 if (compType.isNull() || !compType->isIntegerType()) 10396 return InvalidOperands(Loc, LHS, RHS); 10397 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10398 return compType; 10399 } 10400 10401 /// Diagnose invalid arithmetic on two void pointers. 10402 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10403 Expr *LHSExpr, Expr *RHSExpr) { 10404 S.Diag(Loc, S.getLangOpts().CPlusPlus 10405 ? diag::err_typecheck_pointer_arith_void_type 10406 : diag::ext_gnu_void_ptr) 10407 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10408 << RHSExpr->getSourceRange(); 10409 } 10410 10411 /// Diagnose invalid arithmetic on a void pointer. 10412 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10413 Expr *Pointer) { 10414 S.Diag(Loc, S.getLangOpts().CPlusPlus 10415 ? diag::err_typecheck_pointer_arith_void_type 10416 : diag::ext_gnu_void_ptr) 10417 << 0 /* one pointer */ << Pointer->getSourceRange(); 10418 } 10419 10420 /// Diagnose invalid arithmetic on a null pointer. 10421 /// 10422 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10423 /// idiom, which we recognize as a GNU extension. 10424 /// 10425 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10426 Expr *Pointer, bool IsGNUIdiom) { 10427 if (IsGNUIdiom) 10428 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10429 << Pointer->getSourceRange(); 10430 else 10431 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10432 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10433 } 10434 10435 /// Diagnose invalid arithmetic on two function pointers. 10436 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10437 Expr *LHS, Expr *RHS) { 10438 assert(LHS->getType()->isAnyPointerType()); 10439 assert(RHS->getType()->isAnyPointerType()); 10440 S.Diag(Loc, S.getLangOpts().CPlusPlus 10441 ? diag::err_typecheck_pointer_arith_function_type 10442 : diag::ext_gnu_ptr_func_arith) 10443 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10444 // We only show the second type if it differs from the first. 10445 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10446 RHS->getType()) 10447 << RHS->getType()->getPointeeType() 10448 << LHS->getSourceRange() << RHS->getSourceRange(); 10449 } 10450 10451 /// Diagnose invalid arithmetic on a function pointer. 10452 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10453 Expr *Pointer) { 10454 assert(Pointer->getType()->isAnyPointerType()); 10455 S.Diag(Loc, S.getLangOpts().CPlusPlus 10456 ? diag::err_typecheck_pointer_arith_function_type 10457 : diag::ext_gnu_ptr_func_arith) 10458 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10459 << 0 /* one pointer, so only one type */ 10460 << Pointer->getSourceRange(); 10461 } 10462 10463 /// Emit error if Operand is incomplete pointer type 10464 /// 10465 /// \returns True if pointer has incomplete type 10466 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10467 Expr *Operand) { 10468 QualType ResType = Operand->getType(); 10469 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10470 ResType = ResAtomicType->getValueType(); 10471 10472 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10473 QualType PointeeTy = ResType->getPointeeType(); 10474 return S.RequireCompleteSizedType( 10475 Loc, PointeeTy, 10476 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10477 Operand->getSourceRange()); 10478 } 10479 10480 /// Check the validity of an arithmetic pointer operand. 10481 /// 10482 /// If the operand has pointer type, this code will check for pointer types 10483 /// which are invalid in arithmetic operations. These will be diagnosed 10484 /// appropriately, including whether or not the use is supported as an 10485 /// extension. 10486 /// 10487 /// \returns True when the operand is valid to use (even if as an extension). 10488 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10489 Expr *Operand) { 10490 QualType ResType = Operand->getType(); 10491 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10492 ResType = ResAtomicType->getValueType(); 10493 10494 if (!ResType->isAnyPointerType()) return true; 10495 10496 QualType PointeeTy = ResType->getPointeeType(); 10497 if (PointeeTy->isVoidType()) { 10498 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10499 return !S.getLangOpts().CPlusPlus; 10500 } 10501 if (PointeeTy->isFunctionType()) { 10502 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10503 return !S.getLangOpts().CPlusPlus; 10504 } 10505 10506 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10507 10508 return true; 10509 } 10510 10511 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10512 /// operands. 10513 /// 10514 /// This routine will diagnose any invalid arithmetic on pointer operands much 10515 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10516 /// for emitting a single diagnostic even for operations where both LHS and RHS 10517 /// are (potentially problematic) pointers. 10518 /// 10519 /// \returns True when the operand is valid to use (even if as an extension). 10520 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10521 Expr *LHSExpr, Expr *RHSExpr) { 10522 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10523 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10524 if (!isLHSPointer && !isRHSPointer) return true; 10525 10526 QualType LHSPointeeTy, RHSPointeeTy; 10527 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10528 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10529 10530 // if both are pointers check if operation is valid wrt address spaces 10531 if (isLHSPointer && isRHSPointer) { 10532 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10533 S.Diag(Loc, 10534 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10535 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10536 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10537 return false; 10538 } 10539 } 10540 10541 // Check for arithmetic on pointers to incomplete types. 10542 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10543 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10544 if (isLHSVoidPtr || isRHSVoidPtr) { 10545 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10546 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10547 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10548 10549 return !S.getLangOpts().CPlusPlus; 10550 } 10551 10552 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10553 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10554 if (isLHSFuncPtr || isRHSFuncPtr) { 10555 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10556 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10557 RHSExpr); 10558 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10559 10560 return !S.getLangOpts().CPlusPlus; 10561 } 10562 10563 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10564 return false; 10565 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10566 return false; 10567 10568 return true; 10569 } 10570 10571 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10572 /// literal. 10573 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10574 Expr *LHSExpr, Expr *RHSExpr) { 10575 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10576 Expr* IndexExpr = RHSExpr; 10577 if (!StrExpr) { 10578 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10579 IndexExpr = LHSExpr; 10580 } 10581 10582 bool IsStringPlusInt = StrExpr && 10583 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10584 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10585 return; 10586 10587 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10588 Self.Diag(OpLoc, diag::warn_string_plus_int) 10589 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10590 10591 // Only print a fixit for "str" + int, not for int + "str". 10592 if (IndexExpr == RHSExpr) { 10593 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10594 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10595 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10596 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10597 << FixItHint::CreateInsertion(EndLoc, "]"); 10598 } else 10599 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10600 } 10601 10602 /// Emit a warning when adding a char literal to a string. 10603 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10604 Expr *LHSExpr, Expr *RHSExpr) { 10605 const Expr *StringRefExpr = LHSExpr; 10606 const CharacterLiteral *CharExpr = 10607 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10608 10609 if (!CharExpr) { 10610 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10611 StringRefExpr = RHSExpr; 10612 } 10613 10614 if (!CharExpr || !StringRefExpr) 10615 return; 10616 10617 const QualType StringType = StringRefExpr->getType(); 10618 10619 // Return if not a PointerType. 10620 if (!StringType->isAnyPointerType()) 10621 return; 10622 10623 // Return if not a CharacterType. 10624 if (!StringType->getPointeeType()->isAnyCharacterType()) 10625 return; 10626 10627 ASTContext &Ctx = Self.getASTContext(); 10628 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10629 10630 const QualType CharType = CharExpr->getType(); 10631 if (!CharType->isAnyCharacterType() && 10632 CharType->isIntegerType() && 10633 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10634 Self.Diag(OpLoc, diag::warn_string_plus_char) 10635 << DiagRange << Ctx.CharTy; 10636 } else { 10637 Self.Diag(OpLoc, diag::warn_string_plus_char) 10638 << DiagRange << CharExpr->getType(); 10639 } 10640 10641 // Only print a fixit for str + char, not for char + str. 10642 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10643 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10644 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10645 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10646 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10647 << FixItHint::CreateInsertion(EndLoc, "]"); 10648 } else { 10649 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10650 } 10651 } 10652 10653 /// Emit error when two pointers are incompatible. 10654 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10655 Expr *LHSExpr, Expr *RHSExpr) { 10656 assert(LHSExpr->getType()->isAnyPointerType()); 10657 assert(RHSExpr->getType()->isAnyPointerType()); 10658 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10659 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10660 << RHSExpr->getSourceRange(); 10661 } 10662 10663 // C99 6.5.6 10664 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10665 SourceLocation Loc, BinaryOperatorKind Opc, 10666 QualType* CompLHSTy) { 10667 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10668 10669 if (LHS.get()->getType()->isVectorType() || 10670 RHS.get()->getType()->isVectorType()) { 10671 QualType compType = CheckVectorOperands( 10672 LHS, RHS, Loc, CompLHSTy, 10673 /*AllowBothBool*/getLangOpts().AltiVec, 10674 /*AllowBoolConversions*/getLangOpts().ZVector); 10675 if (CompLHSTy) *CompLHSTy = compType; 10676 return compType; 10677 } 10678 10679 if (LHS.get()->getType()->isConstantMatrixType() || 10680 RHS.get()->getType()->isConstantMatrixType()) { 10681 QualType compType = 10682 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10683 if (CompLHSTy) 10684 *CompLHSTy = compType; 10685 return compType; 10686 } 10687 10688 QualType compType = UsualArithmeticConversions( 10689 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10690 if (LHS.isInvalid() || RHS.isInvalid()) 10691 return QualType(); 10692 10693 // Diagnose "string literal" '+' int and string '+' "char literal". 10694 if (Opc == BO_Add) { 10695 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10696 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10697 } 10698 10699 // handle the common case first (both operands are arithmetic). 10700 if (!compType.isNull() && compType->isArithmeticType()) { 10701 if (CompLHSTy) *CompLHSTy = compType; 10702 return compType; 10703 } 10704 10705 // Type-checking. Ultimately the pointer's going to be in PExp; 10706 // note that we bias towards the LHS being the pointer. 10707 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10708 10709 bool isObjCPointer; 10710 if (PExp->getType()->isPointerType()) { 10711 isObjCPointer = false; 10712 } else if (PExp->getType()->isObjCObjectPointerType()) { 10713 isObjCPointer = true; 10714 } else { 10715 std::swap(PExp, IExp); 10716 if (PExp->getType()->isPointerType()) { 10717 isObjCPointer = false; 10718 } else if (PExp->getType()->isObjCObjectPointerType()) { 10719 isObjCPointer = true; 10720 } else { 10721 return InvalidOperands(Loc, LHS, RHS); 10722 } 10723 } 10724 assert(PExp->getType()->isAnyPointerType()); 10725 10726 if (!IExp->getType()->isIntegerType()) 10727 return InvalidOperands(Loc, LHS, RHS); 10728 10729 // Adding to a null pointer results in undefined behavior. 10730 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10731 Context, Expr::NPC_ValueDependentIsNotNull)) { 10732 // In C++ adding zero to a null pointer is defined. 10733 Expr::EvalResult KnownVal; 10734 if (!getLangOpts().CPlusPlus || 10735 (!IExp->isValueDependent() && 10736 (!IExp->EvaluateAsInt(KnownVal, Context) || 10737 KnownVal.Val.getInt() != 0))) { 10738 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10739 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10740 Context, BO_Add, PExp, IExp); 10741 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10742 } 10743 } 10744 10745 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10746 return QualType(); 10747 10748 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10749 return QualType(); 10750 10751 // Check array bounds for pointer arithemtic 10752 CheckArrayAccess(PExp, IExp); 10753 10754 if (CompLHSTy) { 10755 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10756 if (LHSTy.isNull()) { 10757 LHSTy = LHS.get()->getType(); 10758 if (LHSTy->isPromotableIntegerType()) 10759 LHSTy = Context.getPromotedIntegerType(LHSTy); 10760 } 10761 *CompLHSTy = LHSTy; 10762 } 10763 10764 return PExp->getType(); 10765 } 10766 10767 // C99 6.5.6 10768 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10769 SourceLocation Loc, 10770 QualType* CompLHSTy) { 10771 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10772 10773 if (LHS.get()->getType()->isVectorType() || 10774 RHS.get()->getType()->isVectorType()) { 10775 QualType compType = CheckVectorOperands( 10776 LHS, RHS, Loc, CompLHSTy, 10777 /*AllowBothBool*/getLangOpts().AltiVec, 10778 /*AllowBoolConversions*/getLangOpts().ZVector); 10779 if (CompLHSTy) *CompLHSTy = compType; 10780 return compType; 10781 } 10782 10783 if (LHS.get()->getType()->isConstantMatrixType() || 10784 RHS.get()->getType()->isConstantMatrixType()) { 10785 QualType compType = 10786 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10787 if (CompLHSTy) 10788 *CompLHSTy = compType; 10789 return compType; 10790 } 10791 10792 QualType compType = UsualArithmeticConversions( 10793 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10794 if (LHS.isInvalid() || RHS.isInvalid()) 10795 return QualType(); 10796 10797 // Enforce type constraints: C99 6.5.6p3. 10798 10799 // Handle the common case first (both operands are arithmetic). 10800 if (!compType.isNull() && compType->isArithmeticType()) { 10801 if (CompLHSTy) *CompLHSTy = compType; 10802 return compType; 10803 } 10804 10805 // Either ptr - int or ptr - ptr. 10806 if (LHS.get()->getType()->isAnyPointerType()) { 10807 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10808 10809 // Diagnose bad cases where we step over interface counts. 10810 if (LHS.get()->getType()->isObjCObjectPointerType() && 10811 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10812 return QualType(); 10813 10814 // The result type of a pointer-int computation is the pointer type. 10815 if (RHS.get()->getType()->isIntegerType()) { 10816 // Subtracting from a null pointer should produce a warning. 10817 // The last argument to the diagnose call says this doesn't match the 10818 // GNU int-to-pointer idiom. 10819 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10820 Expr::NPC_ValueDependentIsNotNull)) { 10821 // In C++ adding zero to a null pointer is defined. 10822 Expr::EvalResult KnownVal; 10823 if (!getLangOpts().CPlusPlus || 10824 (!RHS.get()->isValueDependent() && 10825 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10826 KnownVal.Val.getInt() != 0))) { 10827 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10828 } 10829 } 10830 10831 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10832 return QualType(); 10833 10834 // Check array bounds for pointer arithemtic 10835 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10836 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10837 10838 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10839 return LHS.get()->getType(); 10840 } 10841 10842 // Handle pointer-pointer subtractions. 10843 if (const PointerType *RHSPTy 10844 = RHS.get()->getType()->getAs<PointerType>()) { 10845 QualType rpointee = RHSPTy->getPointeeType(); 10846 10847 if (getLangOpts().CPlusPlus) { 10848 // Pointee types must be the same: C++ [expr.add] 10849 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10850 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10851 } 10852 } else { 10853 // Pointee types must be compatible C99 6.5.6p3 10854 if (!Context.typesAreCompatible( 10855 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10856 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10857 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10858 return QualType(); 10859 } 10860 } 10861 10862 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10863 LHS.get(), RHS.get())) 10864 return QualType(); 10865 10866 // FIXME: Add warnings for nullptr - ptr. 10867 10868 // The pointee type may have zero size. As an extension, a structure or 10869 // union may have zero size or an array may have zero length. In this 10870 // case subtraction does not make sense. 10871 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10872 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10873 if (ElementSize.isZero()) { 10874 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10875 << rpointee.getUnqualifiedType() 10876 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10877 } 10878 } 10879 10880 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10881 return Context.getPointerDiffType(); 10882 } 10883 } 10884 10885 return InvalidOperands(Loc, LHS, RHS); 10886 } 10887 10888 static bool isScopedEnumerationType(QualType T) { 10889 if (const EnumType *ET = T->getAs<EnumType>()) 10890 return ET->getDecl()->isScoped(); 10891 return false; 10892 } 10893 10894 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10895 SourceLocation Loc, BinaryOperatorKind Opc, 10896 QualType LHSType) { 10897 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10898 // so skip remaining warnings as we don't want to modify values within Sema. 10899 if (S.getLangOpts().OpenCL) 10900 return; 10901 10902 // Check right/shifter operand 10903 Expr::EvalResult RHSResult; 10904 if (RHS.get()->isValueDependent() || 10905 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10906 return; 10907 llvm::APSInt Right = RHSResult.Val.getInt(); 10908 10909 if (Right.isNegative()) { 10910 S.DiagRuntimeBehavior(Loc, RHS.get(), 10911 S.PDiag(diag::warn_shift_negative) 10912 << RHS.get()->getSourceRange()); 10913 return; 10914 } 10915 10916 QualType LHSExprType = LHS.get()->getType(); 10917 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10918 if (LHSExprType->isExtIntType()) 10919 LeftSize = S.Context.getIntWidth(LHSExprType); 10920 else if (LHSExprType->isFixedPointType()) { 10921 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10922 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10923 } 10924 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10925 if (Right.uge(LeftBits)) { 10926 S.DiagRuntimeBehavior(Loc, RHS.get(), 10927 S.PDiag(diag::warn_shift_gt_typewidth) 10928 << RHS.get()->getSourceRange()); 10929 return; 10930 } 10931 10932 // FIXME: We probably need to handle fixed point types specially here. 10933 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10934 return; 10935 10936 // When left shifting an ICE which is signed, we can check for overflow which 10937 // according to C++ standards prior to C++2a has undefined behavior 10938 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10939 // more than the maximum value representable in the result type, so never 10940 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10941 // expression is still probably a bug.) 10942 Expr::EvalResult LHSResult; 10943 if (LHS.get()->isValueDependent() || 10944 LHSType->hasUnsignedIntegerRepresentation() || 10945 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10946 return; 10947 llvm::APSInt Left = LHSResult.Val.getInt(); 10948 10949 // If LHS does not have a signed type and non-negative value 10950 // then, the behavior is undefined before C++2a. Warn about it. 10951 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10952 !S.getLangOpts().CPlusPlus20) { 10953 S.DiagRuntimeBehavior(Loc, LHS.get(), 10954 S.PDiag(diag::warn_shift_lhs_negative) 10955 << LHS.get()->getSourceRange()); 10956 return; 10957 } 10958 10959 llvm::APInt ResultBits = 10960 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10961 if (LeftBits.uge(ResultBits)) 10962 return; 10963 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10964 Result = Result.shl(Right); 10965 10966 // Print the bit representation of the signed integer as an unsigned 10967 // hexadecimal number. 10968 SmallString<40> HexResult; 10969 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10970 10971 // If we are only missing a sign bit, this is less likely to result in actual 10972 // bugs -- if the result is cast back to an unsigned type, it will have the 10973 // expected value. Thus we place this behind a different warning that can be 10974 // turned off separately if needed. 10975 if (LeftBits == ResultBits - 1) { 10976 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10977 << HexResult << LHSType 10978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10979 return; 10980 } 10981 10982 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10983 << HexResult.str() << Result.getMinSignedBits() << LHSType 10984 << Left.getBitWidth() << LHS.get()->getSourceRange() 10985 << RHS.get()->getSourceRange(); 10986 } 10987 10988 /// Return the resulting type when a vector is shifted 10989 /// by a scalar or vector shift amount. 10990 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10991 SourceLocation Loc, bool IsCompAssign) { 10992 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10993 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10994 !LHS.get()->getType()->isVectorType()) { 10995 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10996 << RHS.get()->getType() << LHS.get()->getType() 10997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10998 return QualType(); 10999 } 11000 11001 if (!IsCompAssign) { 11002 LHS = S.UsualUnaryConversions(LHS.get()); 11003 if (LHS.isInvalid()) return QualType(); 11004 } 11005 11006 RHS = S.UsualUnaryConversions(RHS.get()); 11007 if (RHS.isInvalid()) return QualType(); 11008 11009 QualType LHSType = LHS.get()->getType(); 11010 // Note that LHS might be a scalar because the routine calls not only in 11011 // OpenCL case. 11012 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11013 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11014 11015 // Note that RHS might not be a vector. 11016 QualType RHSType = RHS.get()->getType(); 11017 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11018 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11019 11020 // The operands need to be integers. 11021 if (!LHSEleType->isIntegerType()) { 11022 S.Diag(Loc, diag::err_typecheck_expect_int) 11023 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11024 return QualType(); 11025 } 11026 11027 if (!RHSEleType->isIntegerType()) { 11028 S.Diag(Loc, diag::err_typecheck_expect_int) 11029 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11030 return QualType(); 11031 } 11032 11033 if (!LHSVecTy) { 11034 assert(RHSVecTy); 11035 if (IsCompAssign) 11036 return RHSType; 11037 if (LHSEleType != RHSEleType) { 11038 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11039 LHSEleType = RHSEleType; 11040 } 11041 QualType VecTy = 11042 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11043 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11044 LHSType = VecTy; 11045 } else if (RHSVecTy) { 11046 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11047 // are applied component-wise. So if RHS is a vector, then ensure 11048 // that the number of elements is the same as LHS... 11049 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11050 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11051 << LHS.get()->getType() << RHS.get()->getType() 11052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11053 return QualType(); 11054 } 11055 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11056 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11057 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11058 if (LHSBT != RHSBT && 11059 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11060 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11061 << LHS.get()->getType() << RHS.get()->getType() 11062 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11063 } 11064 } 11065 } else { 11066 // ...else expand RHS to match the number of elements in LHS. 11067 QualType VecTy = 11068 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11069 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11070 } 11071 11072 return LHSType; 11073 } 11074 11075 // C99 6.5.7 11076 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11077 SourceLocation Loc, BinaryOperatorKind Opc, 11078 bool IsCompAssign) { 11079 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11080 11081 // Vector shifts promote their scalar inputs to vector type. 11082 if (LHS.get()->getType()->isVectorType() || 11083 RHS.get()->getType()->isVectorType()) { 11084 if (LangOpts.ZVector) { 11085 // The shift operators for the z vector extensions work basically 11086 // like general shifts, except that neither the LHS nor the RHS is 11087 // allowed to be a "vector bool". 11088 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11089 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11090 return InvalidOperands(Loc, LHS, RHS); 11091 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11092 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11093 return InvalidOperands(Loc, LHS, RHS); 11094 } 11095 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11096 } 11097 11098 // Shifts don't perform usual arithmetic conversions, they just do integer 11099 // promotions on each operand. C99 6.5.7p3 11100 11101 // For the LHS, do usual unary conversions, but then reset them away 11102 // if this is a compound assignment. 11103 ExprResult OldLHS = LHS; 11104 LHS = UsualUnaryConversions(LHS.get()); 11105 if (LHS.isInvalid()) 11106 return QualType(); 11107 QualType LHSType = LHS.get()->getType(); 11108 if (IsCompAssign) LHS = OldLHS; 11109 11110 // The RHS is simpler. 11111 RHS = UsualUnaryConversions(RHS.get()); 11112 if (RHS.isInvalid()) 11113 return QualType(); 11114 QualType RHSType = RHS.get()->getType(); 11115 11116 // C99 6.5.7p2: Each of the operands shall have integer type. 11117 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11118 if ((!LHSType->isFixedPointOrIntegerType() && 11119 !LHSType->hasIntegerRepresentation()) || 11120 !RHSType->hasIntegerRepresentation()) 11121 return InvalidOperands(Loc, LHS, RHS); 11122 11123 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11124 // hasIntegerRepresentation() above instead of this. 11125 if (isScopedEnumerationType(LHSType) || 11126 isScopedEnumerationType(RHSType)) { 11127 return InvalidOperands(Loc, LHS, RHS); 11128 } 11129 // Sanity-check shift operands 11130 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11131 11132 // "The type of the result is that of the promoted left operand." 11133 return LHSType; 11134 } 11135 11136 /// Diagnose bad pointer comparisons. 11137 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11138 ExprResult &LHS, ExprResult &RHS, 11139 bool IsError) { 11140 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11141 : diag::ext_typecheck_comparison_of_distinct_pointers) 11142 << LHS.get()->getType() << RHS.get()->getType() 11143 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11144 } 11145 11146 /// Returns false if the pointers are converted to a composite type, 11147 /// true otherwise. 11148 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11149 ExprResult &LHS, ExprResult &RHS) { 11150 // C++ [expr.rel]p2: 11151 // [...] Pointer conversions (4.10) and qualification 11152 // conversions (4.4) are performed on pointer operands (or on 11153 // a pointer operand and a null pointer constant) to bring 11154 // them to their composite pointer type. [...] 11155 // 11156 // C++ [expr.eq]p1 uses the same notion for (in)equality 11157 // comparisons of pointers. 11158 11159 QualType LHSType = LHS.get()->getType(); 11160 QualType RHSType = RHS.get()->getType(); 11161 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11162 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11163 11164 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11165 if (T.isNull()) { 11166 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11167 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11168 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11169 else 11170 S.InvalidOperands(Loc, LHS, RHS); 11171 return true; 11172 } 11173 11174 return false; 11175 } 11176 11177 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11178 ExprResult &LHS, 11179 ExprResult &RHS, 11180 bool IsError) { 11181 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11182 : diag::ext_typecheck_comparison_of_fptr_to_void) 11183 << LHS.get()->getType() << RHS.get()->getType() 11184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11185 } 11186 11187 static bool isObjCObjectLiteral(ExprResult &E) { 11188 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11189 case Stmt::ObjCArrayLiteralClass: 11190 case Stmt::ObjCDictionaryLiteralClass: 11191 case Stmt::ObjCStringLiteralClass: 11192 case Stmt::ObjCBoxedExprClass: 11193 return true; 11194 default: 11195 // Note that ObjCBoolLiteral is NOT an object literal! 11196 return false; 11197 } 11198 } 11199 11200 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11201 const ObjCObjectPointerType *Type = 11202 LHS->getType()->getAs<ObjCObjectPointerType>(); 11203 11204 // If this is not actually an Objective-C object, bail out. 11205 if (!Type) 11206 return false; 11207 11208 // Get the LHS object's interface type. 11209 QualType InterfaceType = Type->getPointeeType(); 11210 11211 // If the RHS isn't an Objective-C object, bail out. 11212 if (!RHS->getType()->isObjCObjectPointerType()) 11213 return false; 11214 11215 // Try to find the -isEqual: method. 11216 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11217 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11218 InterfaceType, 11219 /*IsInstance=*/true); 11220 if (!Method) { 11221 if (Type->isObjCIdType()) { 11222 // For 'id', just check the global pool. 11223 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11224 /*receiverId=*/true); 11225 } else { 11226 // Check protocols. 11227 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11228 /*IsInstance=*/true); 11229 } 11230 } 11231 11232 if (!Method) 11233 return false; 11234 11235 QualType T = Method->parameters()[0]->getType(); 11236 if (!T->isObjCObjectPointerType()) 11237 return false; 11238 11239 QualType R = Method->getReturnType(); 11240 if (!R->isScalarType()) 11241 return false; 11242 11243 return true; 11244 } 11245 11246 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11247 FromE = FromE->IgnoreParenImpCasts(); 11248 switch (FromE->getStmtClass()) { 11249 default: 11250 break; 11251 case Stmt::ObjCStringLiteralClass: 11252 // "string literal" 11253 return LK_String; 11254 case Stmt::ObjCArrayLiteralClass: 11255 // "array literal" 11256 return LK_Array; 11257 case Stmt::ObjCDictionaryLiteralClass: 11258 // "dictionary literal" 11259 return LK_Dictionary; 11260 case Stmt::BlockExprClass: 11261 return LK_Block; 11262 case Stmt::ObjCBoxedExprClass: { 11263 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11264 switch (Inner->getStmtClass()) { 11265 case Stmt::IntegerLiteralClass: 11266 case Stmt::FloatingLiteralClass: 11267 case Stmt::CharacterLiteralClass: 11268 case Stmt::ObjCBoolLiteralExprClass: 11269 case Stmt::CXXBoolLiteralExprClass: 11270 // "numeric literal" 11271 return LK_Numeric; 11272 case Stmt::ImplicitCastExprClass: { 11273 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11274 // Boolean literals can be represented by implicit casts. 11275 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11276 return LK_Numeric; 11277 break; 11278 } 11279 default: 11280 break; 11281 } 11282 return LK_Boxed; 11283 } 11284 } 11285 return LK_None; 11286 } 11287 11288 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11289 ExprResult &LHS, ExprResult &RHS, 11290 BinaryOperator::Opcode Opc){ 11291 Expr *Literal; 11292 Expr *Other; 11293 if (isObjCObjectLiteral(LHS)) { 11294 Literal = LHS.get(); 11295 Other = RHS.get(); 11296 } else { 11297 Literal = RHS.get(); 11298 Other = LHS.get(); 11299 } 11300 11301 // Don't warn on comparisons against nil. 11302 Other = Other->IgnoreParenCasts(); 11303 if (Other->isNullPointerConstant(S.getASTContext(), 11304 Expr::NPC_ValueDependentIsNotNull)) 11305 return; 11306 11307 // This should be kept in sync with warn_objc_literal_comparison. 11308 // LK_String should always be after the other literals, since it has its own 11309 // warning flag. 11310 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11311 assert(LiteralKind != Sema::LK_Block); 11312 if (LiteralKind == Sema::LK_None) { 11313 llvm_unreachable("Unknown Objective-C object literal kind"); 11314 } 11315 11316 if (LiteralKind == Sema::LK_String) 11317 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11318 << Literal->getSourceRange(); 11319 else 11320 S.Diag(Loc, diag::warn_objc_literal_comparison) 11321 << LiteralKind << Literal->getSourceRange(); 11322 11323 if (BinaryOperator::isEqualityOp(Opc) && 11324 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11325 SourceLocation Start = LHS.get()->getBeginLoc(); 11326 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11327 CharSourceRange OpRange = 11328 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11329 11330 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11331 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11332 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11333 << FixItHint::CreateInsertion(End, "]"); 11334 } 11335 } 11336 11337 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11338 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11339 ExprResult &RHS, SourceLocation Loc, 11340 BinaryOperatorKind Opc) { 11341 // Check that left hand side is !something. 11342 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11343 if (!UO || UO->getOpcode() != UO_LNot) return; 11344 11345 // Only check if the right hand side is non-bool arithmetic type. 11346 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11347 11348 // Make sure that the something in !something is not bool. 11349 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11350 if (SubExpr->isKnownToHaveBooleanValue()) return; 11351 11352 // Emit warning. 11353 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11354 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11355 << Loc << IsBitwiseOp; 11356 11357 // First note suggest !(x < y) 11358 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11359 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11360 FirstClose = S.getLocForEndOfToken(FirstClose); 11361 if (FirstClose.isInvalid()) 11362 FirstOpen = SourceLocation(); 11363 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11364 << IsBitwiseOp 11365 << FixItHint::CreateInsertion(FirstOpen, "(") 11366 << FixItHint::CreateInsertion(FirstClose, ")"); 11367 11368 // Second note suggests (!x) < y 11369 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11370 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11371 SecondClose = S.getLocForEndOfToken(SecondClose); 11372 if (SecondClose.isInvalid()) 11373 SecondOpen = SourceLocation(); 11374 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11375 << FixItHint::CreateInsertion(SecondOpen, "(") 11376 << FixItHint::CreateInsertion(SecondClose, ")"); 11377 } 11378 11379 // Returns true if E refers to a non-weak array. 11380 static bool checkForArray(const Expr *E) { 11381 const ValueDecl *D = nullptr; 11382 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11383 D = DR->getDecl(); 11384 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11385 if (Mem->isImplicitAccess()) 11386 D = Mem->getMemberDecl(); 11387 } 11388 if (!D) 11389 return false; 11390 return D->getType()->isArrayType() && !D->isWeak(); 11391 } 11392 11393 /// Diagnose some forms of syntactically-obvious tautological comparison. 11394 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11395 Expr *LHS, Expr *RHS, 11396 BinaryOperatorKind Opc) { 11397 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11398 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11399 11400 QualType LHSType = LHS->getType(); 11401 QualType RHSType = RHS->getType(); 11402 if (LHSType->hasFloatingRepresentation() || 11403 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11404 S.inTemplateInstantiation()) 11405 return; 11406 11407 // Comparisons between two array types are ill-formed for operator<=>, so 11408 // we shouldn't emit any additional warnings about it. 11409 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11410 return; 11411 11412 // For non-floating point types, check for self-comparisons of the form 11413 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11414 // often indicate logic errors in the program. 11415 // 11416 // NOTE: Don't warn about comparison expressions resulting from macro 11417 // expansion. Also don't warn about comparisons which are only self 11418 // comparisons within a template instantiation. The warnings should catch 11419 // obvious cases in the definition of the template anyways. The idea is to 11420 // warn when the typed comparison operator will always evaluate to the same 11421 // result. 11422 11423 // Used for indexing into %select in warn_comparison_always 11424 enum { 11425 AlwaysConstant, 11426 AlwaysTrue, 11427 AlwaysFalse, 11428 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11429 }; 11430 11431 // C++2a [depr.array.comp]: 11432 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11433 // operands of array type are deprecated. 11434 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11435 RHSStripped->getType()->isArrayType()) { 11436 S.Diag(Loc, diag::warn_depr_array_comparison) 11437 << LHS->getSourceRange() << RHS->getSourceRange() 11438 << LHSStripped->getType() << RHSStripped->getType(); 11439 // Carry on to produce the tautological comparison warning, if this 11440 // expression is potentially-evaluated, we can resolve the array to a 11441 // non-weak declaration, and so on. 11442 } 11443 11444 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11445 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11446 unsigned Result; 11447 switch (Opc) { 11448 case BO_EQ: 11449 case BO_LE: 11450 case BO_GE: 11451 Result = AlwaysTrue; 11452 break; 11453 case BO_NE: 11454 case BO_LT: 11455 case BO_GT: 11456 Result = AlwaysFalse; 11457 break; 11458 case BO_Cmp: 11459 Result = AlwaysEqual; 11460 break; 11461 default: 11462 Result = AlwaysConstant; 11463 break; 11464 } 11465 S.DiagRuntimeBehavior(Loc, nullptr, 11466 S.PDiag(diag::warn_comparison_always) 11467 << 0 /*self-comparison*/ 11468 << Result); 11469 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11470 // What is it always going to evaluate to? 11471 unsigned Result; 11472 switch (Opc) { 11473 case BO_EQ: // e.g. array1 == array2 11474 Result = AlwaysFalse; 11475 break; 11476 case BO_NE: // e.g. array1 != array2 11477 Result = AlwaysTrue; 11478 break; 11479 default: // e.g. array1 <= array2 11480 // The best we can say is 'a constant' 11481 Result = AlwaysConstant; 11482 break; 11483 } 11484 S.DiagRuntimeBehavior(Loc, nullptr, 11485 S.PDiag(diag::warn_comparison_always) 11486 << 1 /*array comparison*/ 11487 << Result); 11488 } 11489 } 11490 11491 if (isa<CastExpr>(LHSStripped)) 11492 LHSStripped = LHSStripped->IgnoreParenCasts(); 11493 if (isa<CastExpr>(RHSStripped)) 11494 RHSStripped = RHSStripped->IgnoreParenCasts(); 11495 11496 // Warn about comparisons against a string constant (unless the other 11497 // operand is null); the user probably wants string comparison function. 11498 Expr *LiteralString = nullptr; 11499 Expr *LiteralStringStripped = nullptr; 11500 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11501 !RHSStripped->isNullPointerConstant(S.Context, 11502 Expr::NPC_ValueDependentIsNull)) { 11503 LiteralString = LHS; 11504 LiteralStringStripped = LHSStripped; 11505 } else if ((isa<StringLiteral>(RHSStripped) || 11506 isa<ObjCEncodeExpr>(RHSStripped)) && 11507 !LHSStripped->isNullPointerConstant(S.Context, 11508 Expr::NPC_ValueDependentIsNull)) { 11509 LiteralString = RHS; 11510 LiteralStringStripped = RHSStripped; 11511 } 11512 11513 if (LiteralString) { 11514 S.DiagRuntimeBehavior(Loc, nullptr, 11515 S.PDiag(diag::warn_stringcompare) 11516 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11517 << LiteralString->getSourceRange()); 11518 } 11519 } 11520 11521 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11522 switch (CK) { 11523 default: { 11524 #ifndef NDEBUG 11525 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11526 << "\n"; 11527 #endif 11528 llvm_unreachable("unhandled cast kind"); 11529 } 11530 case CK_UserDefinedConversion: 11531 return ICK_Identity; 11532 case CK_LValueToRValue: 11533 return ICK_Lvalue_To_Rvalue; 11534 case CK_ArrayToPointerDecay: 11535 return ICK_Array_To_Pointer; 11536 case CK_FunctionToPointerDecay: 11537 return ICK_Function_To_Pointer; 11538 case CK_IntegralCast: 11539 return ICK_Integral_Conversion; 11540 case CK_FloatingCast: 11541 return ICK_Floating_Conversion; 11542 case CK_IntegralToFloating: 11543 case CK_FloatingToIntegral: 11544 return ICK_Floating_Integral; 11545 case CK_IntegralComplexCast: 11546 case CK_FloatingComplexCast: 11547 case CK_FloatingComplexToIntegralComplex: 11548 case CK_IntegralComplexToFloatingComplex: 11549 return ICK_Complex_Conversion; 11550 case CK_FloatingComplexToReal: 11551 case CK_FloatingRealToComplex: 11552 case CK_IntegralComplexToReal: 11553 case CK_IntegralRealToComplex: 11554 return ICK_Complex_Real; 11555 } 11556 } 11557 11558 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11559 QualType FromType, 11560 SourceLocation Loc) { 11561 // Check for a narrowing implicit conversion. 11562 StandardConversionSequence SCS; 11563 SCS.setAsIdentityConversion(); 11564 SCS.setToType(0, FromType); 11565 SCS.setToType(1, ToType); 11566 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11567 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11568 11569 APValue PreNarrowingValue; 11570 QualType PreNarrowingType; 11571 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11572 PreNarrowingType, 11573 /*IgnoreFloatToIntegralConversion*/ true)) { 11574 case NK_Dependent_Narrowing: 11575 // Implicit conversion to a narrower type, but the expression is 11576 // value-dependent so we can't tell whether it's actually narrowing. 11577 case NK_Not_Narrowing: 11578 return false; 11579 11580 case NK_Constant_Narrowing: 11581 // Implicit conversion to a narrower type, and the value is not a constant 11582 // expression. 11583 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11584 << /*Constant*/ 1 11585 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11586 return true; 11587 11588 case NK_Variable_Narrowing: 11589 // Implicit conversion to a narrower type, and the value is not a constant 11590 // expression. 11591 case NK_Type_Narrowing: 11592 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11593 << /*Constant*/ 0 << FromType << ToType; 11594 // TODO: It's not a constant expression, but what if the user intended it 11595 // to be? Can we produce notes to help them figure out why it isn't? 11596 return true; 11597 } 11598 llvm_unreachable("unhandled case in switch"); 11599 } 11600 11601 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11602 ExprResult &LHS, 11603 ExprResult &RHS, 11604 SourceLocation Loc) { 11605 QualType LHSType = LHS.get()->getType(); 11606 QualType RHSType = RHS.get()->getType(); 11607 // Dig out the original argument type and expression before implicit casts 11608 // were applied. These are the types/expressions we need to check the 11609 // [expr.spaceship] requirements against. 11610 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11611 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11612 QualType LHSStrippedType = LHSStripped.get()->getType(); 11613 QualType RHSStrippedType = RHSStripped.get()->getType(); 11614 11615 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11616 // other is not, the program is ill-formed. 11617 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11618 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11619 return QualType(); 11620 } 11621 11622 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11623 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11624 RHSStrippedType->isEnumeralType(); 11625 if (NumEnumArgs == 1) { 11626 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11627 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11628 if (OtherTy->hasFloatingRepresentation()) { 11629 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11630 return QualType(); 11631 } 11632 } 11633 if (NumEnumArgs == 2) { 11634 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11635 // type E, the operator yields the result of converting the operands 11636 // to the underlying type of E and applying <=> to the converted operands. 11637 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11638 S.InvalidOperands(Loc, LHS, RHS); 11639 return QualType(); 11640 } 11641 QualType IntType = 11642 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11643 assert(IntType->isArithmeticType()); 11644 11645 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11646 // promote the boolean type, and all other promotable integer types, to 11647 // avoid this. 11648 if (IntType->isPromotableIntegerType()) 11649 IntType = S.Context.getPromotedIntegerType(IntType); 11650 11651 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11652 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11653 LHSType = RHSType = IntType; 11654 } 11655 11656 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11657 // usual arithmetic conversions are applied to the operands. 11658 QualType Type = 11659 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11660 if (LHS.isInvalid() || RHS.isInvalid()) 11661 return QualType(); 11662 if (Type.isNull()) 11663 return S.InvalidOperands(Loc, LHS, RHS); 11664 11665 Optional<ComparisonCategoryType> CCT = 11666 getComparisonCategoryForBuiltinCmp(Type); 11667 if (!CCT) 11668 return S.InvalidOperands(Loc, LHS, RHS); 11669 11670 bool HasNarrowing = checkThreeWayNarrowingConversion( 11671 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11672 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11673 RHS.get()->getBeginLoc()); 11674 if (HasNarrowing) 11675 return QualType(); 11676 11677 assert(!Type.isNull() && "composite type for <=> has not been set"); 11678 11679 return S.CheckComparisonCategoryType( 11680 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11681 } 11682 11683 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11684 ExprResult &RHS, 11685 SourceLocation Loc, 11686 BinaryOperatorKind Opc) { 11687 if (Opc == BO_Cmp) 11688 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11689 11690 // C99 6.5.8p3 / C99 6.5.9p4 11691 QualType Type = 11692 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11693 if (LHS.isInvalid() || RHS.isInvalid()) 11694 return QualType(); 11695 if (Type.isNull()) 11696 return S.InvalidOperands(Loc, LHS, RHS); 11697 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11698 11699 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11700 return S.InvalidOperands(Loc, LHS, RHS); 11701 11702 // Check for comparisons of floating point operands using != and ==. 11703 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11704 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11705 11706 // The result of comparisons is 'bool' in C++, 'int' in C. 11707 return S.Context.getLogicalOperationType(); 11708 } 11709 11710 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11711 if (!NullE.get()->getType()->isAnyPointerType()) 11712 return; 11713 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11714 if (!E.get()->getType()->isAnyPointerType() && 11715 E.get()->isNullPointerConstant(Context, 11716 Expr::NPC_ValueDependentIsNotNull) == 11717 Expr::NPCK_ZeroExpression) { 11718 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11719 if (CL->getValue() == 0) 11720 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11721 << NullValue 11722 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11723 NullValue ? "NULL" : "(void *)0"); 11724 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11725 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11726 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11727 if (T == Context.CharTy) 11728 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11729 << NullValue 11730 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11731 NullValue ? "NULL" : "(void *)0"); 11732 } 11733 } 11734 } 11735 11736 // C99 6.5.8, C++ [expr.rel] 11737 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11738 SourceLocation Loc, 11739 BinaryOperatorKind Opc) { 11740 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11741 bool IsThreeWay = Opc == BO_Cmp; 11742 bool IsOrdered = IsRelational || IsThreeWay; 11743 auto IsAnyPointerType = [](ExprResult E) { 11744 QualType Ty = E.get()->getType(); 11745 return Ty->isPointerType() || Ty->isMemberPointerType(); 11746 }; 11747 11748 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11749 // type, array-to-pointer, ..., conversions are performed on both operands to 11750 // bring them to their composite type. 11751 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11752 // any type-related checks. 11753 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11754 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11755 if (LHS.isInvalid()) 11756 return QualType(); 11757 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11758 if (RHS.isInvalid()) 11759 return QualType(); 11760 } else { 11761 LHS = DefaultLvalueConversion(LHS.get()); 11762 if (LHS.isInvalid()) 11763 return QualType(); 11764 RHS = DefaultLvalueConversion(RHS.get()); 11765 if (RHS.isInvalid()) 11766 return QualType(); 11767 } 11768 11769 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11770 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11771 CheckPtrComparisonWithNullChar(LHS, RHS); 11772 CheckPtrComparisonWithNullChar(RHS, LHS); 11773 } 11774 11775 // Handle vector comparisons separately. 11776 if (LHS.get()->getType()->isVectorType() || 11777 RHS.get()->getType()->isVectorType()) 11778 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11779 11780 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11781 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11782 11783 QualType LHSType = LHS.get()->getType(); 11784 QualType RHSType = RHS.get()->getType(); 11785 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11786 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11787 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11788 11789 const Expr::NullPointerConstantKind LHSNullKind = 11790 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11791 const Expr::NullPointerConstantKind RHSNullKind = 11792 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11793 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11794 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11795 11796 auto computeResultTy = [&]() { 11797 if (Opc != BO_Cmp) 11798 return Context.getLogicalOperationType(); 11799 assert(getLangOpts().CPlusPlus); 11800 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11801 11802 QualType CompositeTy = LHS.get()->getType(); 11803 assert(!CompositeTy->isReferenceType()); 11804 11805 Optional<ComparisonCategoryType> CCT = 11806 getComparisonCategoryForBuiltinCmp(CompositeTy); 11807 if (!CCT) 11808 return InvalidOperands(Loc, LHS, RHS); 11809 11810 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11811 // P0946R0: Comparisons between a null pointer constant and an object 11812 // pointer result in std::strong_equality, which is ill-formed under 11813 // P1959R0. 11814 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11815 << (LHSIsNull ? LHS.get()->getSourceRange() 11816 : RHS.get()->getSourceRange()); 11817 return QualType(); 11818 } 11819 11820 return CheckComparisonCategoryType( 11821 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11822 }; 11823 11824 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11825 bool IsEquality = Opc == BO_EQ; 11826 if (RHSIsNull) 11827 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11828 RHS.get()->getSourceRange()); 11829 else 11830 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11831 LHS.get()->getSourceRange()); 11832 } 11833 11834 if (IsOrdered && LHSType->isFunctionPointerType() && 11835 RHSType->isFunctionPointerType()) { 11836 // Valid unless a relational comparison of function pointers 11837 bool IsError = Opc == BO_Cmp; 11838 auto DiagID = 11839 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11840 : getLangOpts().CPlusPlus 11841 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11842 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11843 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11844 << RHS.get()->getSourceRange(); 11845 if (IsError) 11846 return QualType(); 11847 } 11848 11849 if ((LHSType->isIntegerType() && !LHSIsNull) || 11850 (RHSType->isIntegerType() && !RHSIsNull)) { 11851 // Skip normal pointer conversion checks in this case; we have better 11852 // diagnostics for this below. 11853 } else if (getLangOpts().CPlusPlus) { 11854 // Equality comparison of a function pointer to a void pointer is invalid, 11855 // but we allow it as an extension. 11856 // FIXME: If we really want to allow this, should it be part of composite 11857 // pointer type computation so it works in conditionals too? 11858 if (!IsOrdered && 11859 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11860 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11861 // This is a gcc extension compatibility comparison. 11862 // In a SFINAE context, we treat this as a hard error to maintain 11863 // conformance with the C++ standard. 11864 diagnoseFunctionPointerToVoidComparison( 11865 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11866 11867 if (isSFINAEContext()) 11868 return QualType(); 11869 11870 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11871 return computeResultTy(); 11872 } 11873 11874 // C++ [expr.eq]p2: 11875 // If at least one operand is a pointer [...] bring them to their 11876 // composite pointer type. 11877 // C++ [expr.spaceship]p6 11878 // If at least one of the operands is of pointer type, [...] bring them 11879 // to their composite pointer type. 11880 // C++ [expr.rel]p2: 11881 // If both operands are pointers, [...] bring them to their composite 11882 // pointer type. 11883 // For <=>, the only valid non-pointer types are arrays and functions, and 11884 // we already decayed those, so this is really the same as the relational 11885 // comparison rule. 11886 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11887 (IsOrdered ? 2 : 1) && 11888 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11889 RHSType->isObjCObjectPointerType()))) { 11890 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11891 return QualType(); 11892 return computeResultTy(); 11893 } 11894 } else if (LHSType->isPointerType() && 11895 RHSType->isPointerType()) { // C99 6.5.8p2 11896 // All of the following pointer-related warnings are GCC extensions, except 11897 // when handling null pointer constants. 11898 QualType LCanPointeeTy = 11899 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11900 QualType RCanPointeeTy = 11901 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11902 11903 // C99 6.5.9p2 and C99 6.5.8p2 11904 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11905 RCanPointeeTy.getUnqualifiedType())) { 11906 if (IsRelational) { 11907 // Pointers both need to point to complete or incomplete types 11908 if ((LCanPointeeTy->isIncompleteType() != 11909 RCanPointeeTy->isIncompleteType()) && 11910 !getLangOpts().C11) { 11911 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11912 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11913 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11914 << RCanPointeeTy->isIncompleteType(); 11915 } 11916 } 11917 } else if (!IsRelational && 11918 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11919 // Valid unless comparison between non-null pointer and function pointer 11920 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11921 && !LHSIsNull && !RHSIsNull) 11922 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11923 /*isError*/false); 11924 } else { 11925 // Invalid 11926 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11927 } 11928 if (LCanPointeeTy != RCanPointeeTy) { 11929 // Treat NULL constant as a special case in OpenCL. 11930 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11931 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11932 Diag(Loc, 11933 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11934 << LHSType << RHSType << 0 /* comparison */ 11935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11936 } 11937 } 11938 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11939 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11940 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11941 : CK_BitCast; 11942 if (LHSIsNull && !RHSIsNull) 11943 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11944 else 11945 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11946 } 11947 return computeResultTy(); 11948 } 11949 11950 if (getLangOpts().CPlusPlus) { 11951 // C++ [expr.eq]p4: 11952 // Two operands of type std::nullptr_t or one operand of type 11953 // std::nullptr_t and the other a null pointer constant compare equal. 11954 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11955 if (LHSType->isNullPtrType()) { 11956 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11957 return computeResultTy(); 11958 } 11959 if (RHSType->isNullPtrType()) { 11960 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11961 return computeResultTy(); 11962 } 11963 } 11964 11965 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11966 // These aren't covered by the composite pointer type rules. 11967 if (!IsOrdered && RHSType->isNullPtrType() && 11968 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11969 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11970 return computeResultTy(); 11971 } 11972 if (!IsOrdered && LHSType->isNullPtrType() && 11973 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11974 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11975 return computeResultTy(); 11976 } 11977 11978 if (IsRelational && 11979 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11980 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11981 // HACK: Relational comparison of nullptr_t against a pointer type is 11982 // invalid per DR583, but we allow it within std::less<> and friends, 11983 // since otherwise common uses of it break. 11984 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11985 // friends to have std::nullptr_t overload candidates. 11986 DeclContext *DC = CurContext; 11987 if (isa<FunctionDecl>(DC)) 11988 DC = DC->getParent(); 11989 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11990 if (CTSD->isInStdNamespace() && 11991 llvm::StringSwitch<bool>(CTSD->getName()) 11992 .Cases("less", "less_equal", "greater", "greater_equal", true) 11993 .Default(false)) { 11994 if (RHSType->isNullPtrType()) 11995 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11996 else 11997 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11998 return computeResultTy(); 11999 } 12000 } 12001 } 12002 12003 // C++ [expr.eq]p2: 12004 // If at least one operand is a pointer to member, [...] bring them to 12005 // their composite pointer type. 12006 if (!IsOrdered && 12007 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12008 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12009 return QualType(); 12010 else 12011 return computeResultTy(); 12012 } 12013 } 12014 12015 // Handle block pointer types. 12016 if (!IsOrdered && LHSType->isBlockPointerType() && 12017 RHSType->isBlockPointerType()) { 12018 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12019 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12020 12021 if (!LHSIsNull && !RHSIsNull && 12022 !Context.typesAreCompatible(lpointee, rpointee)) { 12023 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12024 << LHSType << RHSType << LHS.get()->getSourceRange() 12025 << RHS.get()->getSourceRange(); 12026 } 12027 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12028 return computeResultTy(); 12029 } 12030 12031 // Allow block pointers to be compared with null pointer constants. 12032 if (!IsOrdered 12033 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12034 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12035 if (!LHSIsNull && !RHSIsNull) { 12036 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12037 ->getPointeeType()->isVoidType()) 12038 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12039 ->getPointeeType()->isVoidType()))) 12040 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12041 << LHSType << RHSType << LHS.get()->getSourceRange() 12042 << RHS.get()->getSourceRange(); 12043 } 12044 if (LHSIsNull && !RHSIsNull) 12045 LHS = ImpCastExprToType(LHS.get(), RHSType, 12046 RHSType->isPointerType() ? CK_BitCast 12047 : CK_AnyPointerToBlockPointerCast); 12048 else 12049 RHS = ImpCastExprToType(RHS.get(), LHSType, 12050 LHSType->isPointerType() ? CK_BitCast 12051 : CK_AnyPointerToBlockPointerCast); 12052 return computeResultTy(); 12053 } 12054 12055 if (LHSType->isObjCObjectPointerType() || 12056 RHSType->isObjCObjectPointerType()) { 12057 const PointerType *LPT = LHSType->getAs<PointerType>(); 12058 const PointerType *RPT = RHSType->getAs<PointerType>(); 12059 if (LPT || RPT) { 12060 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12061 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12062 12063 if (!LPtrToVoid && !RPtrToVoid && 12064 !Context.typesAreCompatible(LHSType, RHSType)) { 12065 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12066 /*isError*/false); 12067 } 12068 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12069 // the RHS, but we have test coverage for this behavior. 12070 // FIXME: Consider using convertPointersToCompositeType in C++. 12071 if (LHSIsNull && !RHSIsNull) { 12072 Expr *E = LHS.get(); 12073 if (getLangOpts().ObjCAutoRefCount) 12074 CheckObjCConversion(SourceRange(), RHSType, E, 12075 CCK_ImplicitConversion); 12076 LHS = ImpCastExprToType(E, RHSType, 12077 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12078 } 12079 else { 12080 Expr *E = RHS.get(); 12081 if (getLangOpts().ObjCAutoRefCount) 12082 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12083 /*Diagnose=*/true, 12084 /*DiagnoseCFAudited=*/false, Opc); 12085 RHS = ImpCastExprToType(E, LHSType, 12086 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12087 } 12088 return computeResultTy(); 12089 } 12090 if (LHSType->isObjCObjectPointerType() && 12091 RHSType->isObjCObjectPointerType()) { 12092 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12093 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12094 /*isError*/false); 12095 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12096 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12097 12098 if (LHSIsNull && !RHSIsNull) 12099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12100 else 12101 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12102 return computeResultTy(); 12103 } 12104 12105 if (!IsOrdered && LHSType->isBlockPointerType() && 12106 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12107 LHS = ImpCastExprToType(LHS.get(), RHSType, 12108 CK_BlockPointerToObjCPointerCast); 12109 return computeResultTy(); 12110 } else if (!IsOrdered && 12111 LHSType->isBlockCompatibleObjCPointerType(Context) && 12112 RHSType->isBlockPointerType()) { 12113 RHS = ImpCastExprToType(RHS.get(), LHSType, 12114 CK_BlockPointerToObjCPointerCast); 12115 return computeResultTy(); 12116 } 12117 } 12118 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12119 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12120 unsigned DiagID = 0; 12121 bool isError = false; 12122 if (LangOpts.DebuggerSupport) { 12123 // Under a debugger, allow the comparison of pointers to integers, 12124 // since users tend to want to compare addresses. 12125 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12126 (RHSIsNull && RHSType->isIntegerType())) { 12127 if (IsOrdered) { 12128 isError = getLangOpts().CPlusPlus; 12129 DiagID = 12130 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12131 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12132 } 12133 } else if (getLangOpts().CPlusPlus) { 12134 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12135 isError = true; 12136 } else if (IsOrdered) 12137 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12138 else 12139 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12140 12141 if (DiagID) { 12142 Diag(Loc, DiagID) 12143 << LHSType << RHSType << LHS.get()->getSourceRange() 12144 << RHS.get()->getSourceRange(); 12145 if (isError) 12146 return QualType(); 12147 } 12148 12149 if (LHSType->isIntegerType()) 12150 LHS = ImpCastExprToType(LHS.get(), RHSType, 12151 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12152 else 12153 RHS = ImpCastExprToType(RHS.get(), LHSType, 12154 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12155 return computeResultTy(); 12156 } 12157 12158 // Handle block pointers. 12159 if (!IsOrdered && RHSIsNull 12160 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12162 return computeResultTy(); 12163 } 12164 if (!IsOrdered && LHSIsNull 12165 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12166 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12167 return computeResultTy(); 12168 } 12169 12170 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12171 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12172 return computeResultTy(); 12173 } 12174 12175 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12176 return computeResultTy(); 12177 } 12178 12179 if (LHSIsNull && RHSType->isQueueT()) { 12180 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12181 return computeResultTy(); 12182 } 12183 12184 if (LHSType->isQueueT() && RHSIsNull) { 12185 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12186 return computeResultTy(); 12187 } 12188 } 12189 12190 return InvalidOperands(Loc, LHS, RHS); 12191 } 12192 12193 // Return a signed ext_vector_type that is of identical size and number of 12194 // elements. For floating point vectors, return an integer type of identical 12195 // size and number of elements. In the non ext_vector_type case, search from 12196 // the largest type to the smallest type to avoid cases where long long == long, 12197 // where long gets picked over long long. 12198 QualType Sema::GetSignedVectorType(QualType V) { 12199 const VectorType *VTy = V->castAs<VectorType>(); 12200 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12201 12202 if (isa<ExtVectorType>(VTy)) { 12203 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12204 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12205 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12206 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12207 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12208 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12209 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12210 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12211 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12212 "Unhandled vector element size in vector compare"); 12213 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12214 } 12215 12216 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12217 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12218 VectorType::GenericVector); 12219 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12220 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12221 VectorType::GenericVector); 12222 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12223 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12224 VectorType::GenericVector); 12225 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12226 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12227 VectorType::GenericVector); 12228 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12229 "Unhandled vector element size in vector compare"); 12230 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12231 VectorType::GenericVector); 12232 } 12233 12234 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12235 /// operates on extended vector types. Instead of producing an IntTy result, 12236 /// like a scalar comparison, a vector comparison produces a vector of integer 12237 /// types. 12238 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12239 SourceLocation Loc, 12240 BinaryOperatorKind Opc) { 12241 if (Opc == BO_Cmp) { 12242 Diag(Loc, diag::err_three_way_vector_comparison); 12243 return QualType(); 12244 } 12245 12246 // Check to make sure we're operating on vectors of the same type and width, 12247 // Allowing one side to be a scalar of element type. 12248 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12249 /*AllowBothBool*/true, 12250 /*AllowBoolConversions*/getLangOpts().ZVector); 12251 if (vType.isNull()) 12252 return vType; 12253 12254 QualType LHSType = LHS.get()->getType(); 12255 12256 // Determine the return type of a vector compare. By default clang will return 12257 // a scalar for all vector compares except vector bool and vector pixel. 12258 // With the gcc compiler we will always return a vector type and with the xl 12259 // compiler we will always return a scalar type. This switch allows choosing 12260 // which behavior is prefered. 12261 if (getLangOpts().AltiVec) { 12262 switch (getLangOpts().getAltivecSrcCompat()) { 12263 case LangOptions::AltivecSrcCompatKind::Mixed: 12264 // If AltiVec, the comparison results in a numeric type, i.e. 12265 // bool for C++, int for C 12266 if (vType->castAs<VectorType>()->getVectorKind() == 12267 VectorType::AltiVecVector) 12268 return Context.getLogicalOperationType(); 12269 else 12270 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12271 break; 12272 case LangOptions::AltivecSrcCompatKind::GCC: 12273 // For GCC we always return the vector type. 12274 break; 12275 case LangOptions::AltivecSrcCompatKind::XL: 12276 return Context.getLogicalOperationType(); 12277 break; 12278 } 12279 } 12280 12281 // For non-floating point types, check for self-comparisons of the form 12282 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12283 // often indicate logic errors in the program. 12284 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12285 12286 // Check for comparisons of floating point operands using != and ==. 12287 if (BinaryOperator::isEqualityOp(Opc) && 12288 LHSType->hasFloatingRepresentation()) { 12289 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12290 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12291 } 12292 12293 // Return a signed type for the vector. 12294 return GetSignedVectorType(vType); 12295 } 12296 12297 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12298 const ExprResult &XorRHS, 12299 const SourceLocation Loc) { 12300 // Do not diagnose macros. 12301 if (Loc.isMacroID()) 12302 return; 12303 12304 // Do not diagnose if both LHS and RHS are macros. 12305 if (XorLHS.get()->getExprLoc().isMacroID() && 12306 XorRHS.get()->getExprLoc().isMacroID()) 12307 return; 12308 12309 bool Negative = false; 12310 bool ExplicitPlus = false; 12311 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12312 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12313 12314 if (!LHSInt) 12315 return; 12316 if (!RHSInt) { 12317 // Check negative literals. 12318 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12319 UnaryOperatorKind Opc = UO->getOpcode(); 12320 if (Opc != UO_Minus && Opc != UO_Plus) 12321 return; 12322 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12323 if (!RHSInt) 12324 return; 12325 Negative = (Opc == UO_Minus); 12326 ExplicitPlus = !Negative; 12327 } else { 12328 return; 12329 } 12330 } 12331 12332 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12333 llvm::APInt RightSideValue = RHSInt->getValue(); 12334 if (LeftSideValue != 2 && LeftSideValue != 10) 12335 return; 12336 12337 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12338 return; 12339 12340 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12341 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12342 llvm::StringRef ExprStr = 12343 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12344 12345 CharSourceRange XorRange = 12346 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12347 llvm::StringRef XorStr = 12348 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12349 // Do not diagnose if xor keyword/macro is used. 12350 if (XorStr == "xor") 12351 return; 12352 12353 std::string LHSStr = std::string(Lexer::getSourceText( 12354 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12355 S.getSourceManager(), S.getLangOpts())); 12356 std::string RHSStr = std::string(Lexer::getSourceText( 12357 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12358 S.getSourceManager(), S.getLangOpts())); 12359 12360 if (Negative) { 12361 RightSideValue = -RightSideValue; 12362 RHSStr = "-" + RHSStr; 12363 } else if (ExplicitPlus) { 12364 RHSStr = "+" + RHSStr; 12365 } 12366 12367 StringRef LHSStrRef = LHSStr; 12368 StringRef RHSStrRef = RHSStr; 12369 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12370 // literals. 12371 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12372 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12373 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12374 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12375 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12376 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12377 LHSStrRef.find('\'') != StringRef::npos || 12378 RHSStrRef.find('\'') != StringRef::npos) 12379 return; 12380 12381 bool SuggestXor = 12382 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12383 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12384 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12385 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12386 std::string SuggestedExpr = "1 << " + RHSStr; 12387 bool Overflow = false; 12388 llvm::APInt One = (LeftSideValue - 1); 12389 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12390 if (Overflow) { 12391 if (RightSideIntValue < 64) 12392 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12393 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12394 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12395 else if (RightSideIntValue == 64) 12396 S.Diag(Loc, diag::warn_xor_used_as_pow) 12397 << ExprStr << toString(XorValue, 10, true); 12398 else 12399 return; 12400 } else { 12401 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12402 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12403 << toString(PowValue, 10, true) 12404 << FixItHint::CreateReplacement( 12405 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12406 } 12407 12408 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12409 << ("0x2 ^ " + RHSStr) << SuggestXor; 12410 } else if (LeftSideValue == 10) { 12411 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12412 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12413 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12414 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12415 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12416 << ("0xA ^ " + RHSStr) << SuggestXor; 12417 } 12418 } 12419 12420 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12421 SourceLocation Loc) { 12422 // Ensure that either both operands are of the same vector type, or 12423 // one operand is of a vector type and the other is of its element type. 12424 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12425 /*AllowBothBool*/true, 12426 /*AllowBoolConversions*/false); 12427 if (vType.isNull()) 12428 return InvalidOperands(Loc, LHS, RHS); 12429 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12430 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12431 return InvalidOperands(Loc, LHS, RHS); 12432 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12433 // usage of the logical operators && and || with vectors in C. This 12434 // check could be notionally dropped. 12435 if (!getLangOpts().CPlusPlus && 12436 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12437 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12438 12439 return GetSignedVectorType(LHS.get()->getType()); 12440 } 12441 12442 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12443 SourceLocation Loc, 12444 bool IsCompAssign) { 12445 if (!IsCompAssign) { 12446 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12447 if (LHS.isInvalid()) 12448 return QualType(); 12449 } 12450 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12451 if (RHS.isInvalid()) 12452 return QualType(); 12453 12454 // For conversion purposes, we ignore any qualifiers. 12455 // For example, "const float" and "float" are equivalent. 12456 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12457 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12458 12459 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12460 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12461 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12462 12463 if (Context.hasSameType(LHSType, RHSType)) 12464 return LHSType; 12465 12466 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12467 // case we have to return InvalidOperands. 12468 ExprResult OriginalLHS = LHS; 12469 ExprResult OriginalRHS = RHS; 12470 if (LHSMatType && !RHSMatType) { 12471 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12472 if (!RHS.isInvalid()) 12473 return LHSType; 12474 12475 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12476 } 12477 12478 if (!LHSMatType && RHSMatType) { 12479 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12480 if (!LHS.isInvalid()) 12481 return RHSType; 12482 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12483 } 12484 12485 return InvalidOperands(Loc, LHS, RHS); 12486 } 12487 12488 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12489 SourceLocation Loc, 12490 bool IsCompAssign) { 12491 if (!IsCompAssign) { 12492 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12493 if (LHS.isInvalid()) 12494 return QualType(); 12495 } 12496 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12497 if (RHS.isInvalid()) 12498 return QualType(); 12499 12500 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12501 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12502 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12503 12504 if (LHSMatType && RHSMatType) { 12505 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12506 return InvalidOperands(Loc, LHS, RHS); 12507 12508 if (!Context.hasSameType(LHSMatType->getElementType(), 12509 RHSMatType->getElementType())) 12510 return InvalidOperands(Loc, LHS, RHS); 12511 12512 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12513 LHSMatType->getNumRows(), 12514 RHSMatType->getNumColumns()); 12515 } 12516 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12517 } 12518 12519 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12520 SourceLocation Loc, 12521 BinaryOperatorKind Opc) { 12522 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12523 12524 bool IsCompAssign = 12525 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12526 12527 if (LHS.get()->getType()->isVectorType() || 12528 RHS.get()->getType()->isVectorType()) { 12529 if (LHS.get()->getType()->hasIntegerRepresentation() && 12530 RHS.get()->getType()->hasIntegerRepresentation()) 12531 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12532 /*AllowBothBool*/true, 12533 /*AllowBoolConversions*/getLangOpts().ZVector); 12534 return InvalidOperands(Loc, LHS, RHS); 12535 } 12536 12537 if (Opc == BO_And) 12538 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12539 12540 if (LHS.get()->getType()->hasFloatingRepresentation() || 12541 RHS.get()->getType()->hasFloatingRepresentation()) 12542 return InvalidOperands(Loc, LHS, RHS); 12543 12544 ExprResult LHSResult = LHS, RHSResult = RHS; 12545 QualType compType = UsualArithmeticConversions( 12546 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12547 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12548 return QualType(); 12549 LHS = LHSResult.get(); 12550 RHS = RHSResult.get(); 12551 12552 if (Opc == BO_Xor) 12553 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12554 12555 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12556 return compType; 12557 return InvalidOperands(Loc, LHS, RHS); 12558 } 12559 12560 // C99 6.5.[13,14] 12561 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12562 SourceLocation Loc, 12563 BinaryOperatorKind Opc) { 12564 // Check vector operands differently. 12565 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12566 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12567 12568 bool EnumConstantInBoolContext = false; 12569 for (const ExprResult &HS : {LHS, RHS}) { 12570 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12571 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12572 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12573 EnumConstantInBoolContext = true; 12574 } 12575 } 12576 12577 if (EnumConstantInBoolContext) 12578 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12579 12580 // Diagnose cases where the user write a logical and/or but probably meant a 12581 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12582 // is a constant. 12583 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12584 !LHS.get()->getType()->isBooleanType() && 12585 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12586 // Don't warn in macros or template instantiations. 12587 !Loc.isMacroID() && !inTemplateInstantiation()) { 12588 // If the RHS can be constant folded, and if it constant folds to something 12589 // that isn't 0 or 1 (which indicate a potential logical operation that 12590 // happened to fold to true/false) then warn. 12591 // Parens on the RHS are ignored. 12592 Expr::EvalResult EVResult; 12593 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12594 llvm::APSInt Result = EVResult.Val.getInt(); 12595 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12596 !RHS.get()->getExprLoc().isMacroID()) || 12597 (Result != 0 && Result != 1)) { 12598 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12599 << RHS.get()->getSourceRange() 12600 << (Opc == BO_LAnd ? "&&" : "||"); 12601 // Suggest replacing the logical operator with the bitwise version 12602 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12603 << (Opc == BO_LAnd ? "&" : "|") 12604 << FixItHint::CreateReplacement(SourceRange( 12605 Loc, getLocForEndOfToken(Loc)), 12606 Opc == BO_LAnd ? "&" : "|"); 12607 if (Opc == BO_LAnd) 12608 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12609 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12610 << FixItHint::CreateRemoval( 12611 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12612 RHS.get()->getEndLoc())); 12613 } 12614 } 12615 } 12616 12617 if (!Context.getLangOpts().CPlusPlus) { 12618 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12619 // not operate on the built-in scalar and vector float types. 12620 if (Context.getLangOpts().OpenCL && 12621 Context.getLangOpts().OpenCLVersion < 120) { 12622 if (LHS.get()->getType()->isFloatingType() || 12623 RHS.get()->getType()->isFloatingType()) 12624 return InvalidOperands(Loc, LHS, RHS); 12625 } 12626 12627 LHS = UsualUnaryConversions(LHS.get()); 12628 if (LHS.isInvalid()) 12629 return QualType(); 12630 12631 RHS = UsualUnaryConversions(RHS.get()); 12632 if (RHS.isInvalid()) 12633 return QualType(); 12634 12635 if (!LHS.get()->getType()->isScalarType() || 12636 !RHS.get()->getType()->isScalarType()) 12637 return InvalidOperands(Loc, LHS, RHS); 12638 12639 return Context.IntTy; 12640 } 12641 12642 // The following is safe because we only use this method for 12643 // non-overloadable operands. 12644 12645 // C++ [expr.log.and]p1 12646 // C++ [expr.log.or]p1 12647 // The operands are both contextually converted to type bool. 12648 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12649 if (LHSRes.isInvalid()) 12650 return InvalidOperands(Loc, LHS, RHS); 12651 LHS = LHSRes; 12652 12653 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12654 if (RHSRes.isInvalid()) 12655 return InvalidOperands(Loc, LHS, RHS); 12656 RHS = RHSRes; 12657 12658 // C++ [expr.log.and]p2 12659 // C++ [expr.log.or]p2 12660 // The result is a bool. 12661 return Context.BoolTy; 12662 } 12663 12664 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12665 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12666 if (!ME) return false; 12667 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12668 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12669 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12670 if (!Base) return false; 12671 return Base->getMethodDecl() != nullptr; 12672 } 12673 12674 /// Is the given expression (which must be 'const') a reference to a 12675 /// variable which was originally non-const, but which has become 12676 /// 'const' due to being captured within a block? 12677 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12678 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12679 assert(E->isLValue() && E->getType().isConstQualified()); 12680 E = E->IgnoreParens(); 12681 12682 // Must be a reference to a declaration from an enclosing scope. 12683 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12684 if (!DRE) return NCCK_None; 12685 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12686 12687 // The declaration must be a variable which is not declared 'const'. 12688 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12689 if (!var) return NCCK_None; 12690 if (var->getType().isConstQualified()) return NCCK_None; 12691 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12692 12693 // Decide whether the first capture was for a block or a lambda. 12694 DeclContext *DC = S.CurContext, *Prev = nullptr; 12695 // Decide whether the first capture was for a block or a lambda. 12696 while (DC) { 12697 // For init-capture, it is possible that the variable belongs to the 12698 // template pattern of the current context. 12699 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12700 if (var->isInitCapture() && 12701 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12702 break; 12703 if (DC == var->getDeclContext()) 12704 break; 12705 Prev = DC; 12706 DC = DC->getParent(); 12707 } 12708 // Unless we have an init-capture, we've gone one step too far. 12709 if (!var->isInitCapture()) 12710 DC = Prev; 12711 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12712 } 12713 12714 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12715 Ty = Ty.getNonReferenceType(); 12716 if (IsDereference && Ty->isPointerType()) 12717 Ty = Ty->getPointeeType(); 12718 return !Ty.isConstQualified(); 12719 } 12720 12721 // Update err_typecheck_assign_const and note_typecheck_assign_const 12722 // when this enum is changed. 12723 enum { 12724 ConstFunction, 12725 ConstVariable, 12726 ConstMember, 12727 ConstMethod, 12728 NestedConstMember, 12729 ConstUnknown, // Keep as last element 12730 }; 12731 12732 /// Emit the "read-only variable not assignable" error and print notes to give 12733 /// more information about why the variable is not assignable, such as pointing 12734 /// to the declaration of a const variable, showing that a method is const, or 12735 /// that the function is returning a const reference. 12736 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12737 SourceLocation Loc) { 12738 SourceRange ExprRange = E->getSourceRange(); 12739 12740 // Only emit one error on the first const found. All other consts will emit 12741 // a note to the error. 12742 bool DiagnosticEmitted = false; 12743 12744 // Track if the current expression is the result of a dereference, and if the 12745 // next checked expression is the result of a dereference. 12746 bool IsDereference = false; 12747 bool NextIsDereference = false; 12748 12749 // Loop to process MemberExpr chains. 12750 while (true) { 12751 IsDereference = NextIsDereference; 12752 12753 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12754 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12755 NextIsDereference = ME->isArrow(); 12756 const ValueDecl *VD = ME->getMemberDecl(); 12757 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12758 // Mutable fields can be modified even if the class is const. 12759 if (Field->isMutable()) { 12760 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12761 break; 12762 } 12763 12764 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12765 if (!DiagnosticEmitted) { 12766 S.Diag(Loc, diag::err_typecheck_assign_const) 12767 << ExprRange << ConstMember << false /*static*/ << Field 12768 << Field->getType(); 12769 DiagnosticEmitted = true; 12770 } 12771 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12772 << ConstMember << false /*static*/ << Field << Field->getType() 12773 << Field->getSourceRange(); 12774 } 12775 E = ME->getBase(); 12776 continue; 12777 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12778 if (VDecl->getType().isConstQualified()) { 12779 if (!DiagnosticEmitted) { 12780 S.Diag(Loc, diag::err_typecheck_assign_const) 12781 << ExprRange << ConstMember << true /*static*/ << VDecl 12782 << VDecl->getType(); 12783 DiagnosticEmitted = true; 12784 } 12785 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12786 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12787 << VDecl->getSourceRange(); 12788 } 12789 // Static fields do not inherit constness from parents. 12790 break; 12791 } 12792 break; // End MemberExpr 12793 } else if (const ArraySubscriptExpr *ASE = 12794 dyn_cast<ArraySubscriptExpr>(E)) { 12795 E = ASE->getBase()->IgnoreParenImpCasts(); 12796 continue; 12797 } else if (const ExtVectorElementExpr *EVE = 12798 dyn_cast<ExtVectorElementExpr>(E)) { 12799 E = EVE->getBase()->IgnoreParenImpCasts(); 12800 continue; 12801 } 12802 break; 12803 } 12804 12805 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12806 // Function calls 12807 const FunctionDecl *FD = CE->getDirectCallee(); 12808 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12809 if (!DiagnosticEmitted) { 12810 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12811 << ConstFunction << FD; 12812 DiagnosticEmitted = true; 12813 } 12814 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12815 diag::note_typecheck_assign_const) 12816 << ConstFunction << FD << FD->getReturnType() 12817 << FD->getReturnTypeSourceRange(); 12818 } 12819 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12820 // Point to variable declaration. 12821 if (const ValueDecl *VD = DRE->getDecl()) { 12822 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12823 if (!DiagnosticEmitted) { 12824 S.Diag(Loc, diag::err_typecheck_assign_const) 12825 << ExprRange << ConstVariable << VD << VD->getType(); 12826 DiagnosticEmitted = true; 12827 } 12828 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12829 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12830 } 12831 } 12832 } else if (isa<CXXThisExpr>(E)) { 12833 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12834 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12835 if (MD->isConst()) { 12836 if (!DiagnosticEmitted) { 12837 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12838 << ConstMethod << MD; 12839 DiagnosticEmitted = true; 12840 } 12841 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12842 << ConstMethod << MD << MD->getSourceRange(); 12843 } 12844 } 12845 } 12846 } 12847 12848 if (DiagnosticEmitted) 12849 return; 12850 12851 // Can't determine a more specific message, so display the generic error. 12852 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12853 } 12854 12855 enum OriginalExprKind { 12856 OEK_Variable, 12857 OEK_Member, 12858 OEK_LValue 12859 }; 12860 12861 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12862 const RecordType *Ty, 12863 SourceLocation Loc, SourceRange Range, 12864 OriginalExprKind OEK, 12865 bool &DiagnosticEmitted) { 12866 std::vector<const RecordType *> RecordTypeList; 12867 RecordTypeList.push_back(Ty); 12868 unsigned NextToCheckIndex = 0; 12869 // We walk the record hierarchy breadth-first to ensure that we print 12870 // diagnostics in field nesting order. 12871 while (RecordTypeList.size() > NextToCheckIndex) { 12872 bool IsNested = NextToCheckIndex > 0; 12873 for (const FieldDecl *Field : 12874 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12875 // First, check every field for constness. 12876 QualType FieldTy = Field->getType(); 12877 if (FieldTy.isConstQualified()) { 12878 if (!DiagnosticEmitted) { 12879 S.Diag(Loc, diag::err_typecheck_assign_const) 12880 << Range << NestedConstMember << OEK << VD 12881 << IsNested << Field; 12882 DiagnosticEmitted = true; 12883 } 12884 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12885 << NestedConstMember << IsNested << Field 12886 << FieldTy << Field->getSourceRange(); 12887 } 12888 12889 // Then we append it to the list to check next in order. 12890 FieldTy = FieldTy.getCanonicalType(); 12891 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12892 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12893 RecordTypeList.push_back(FieldRecTy); 12894 } 12895 } 12896 ++NextToCheckIndex; 12897 } 12898 } 12899 12900 /// Emit an error for the case where a record we are trying to assign to has a 12901 /// const-qualified field somewhere in its hierarchy. 12902 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12903 SourceLocation Loc) { 12904 QualType Ty = E->getType(); 12905 assert(Ty->isRecordType() && "lvalue was not record?"); 12906 SourceRange Range = E->getSourceRange(); 12907 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12908 bool DiagEmitted = false; 12909 12910 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12911 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12912 Range, OEK_Member, DiagEmitted); 12913 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12914 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12915 Range, OEK_Variable, DiagEmitted); 12916 else 12917 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12918 Range, OEK_LValue, DiagEmitted); 12919 if (!DiagEmitted) 12920 DiagnoseConstAssignment(S, E, Loc); 12921 } 12922 12923 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12924 /// emit an error and return true. If so, return false. 12925 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12926 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12927 12928 S.CheckShadowingDeclModification(E, Loc); 12929 12930 SourceLocation OrigLoc = Loc; 12931 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12932 &Loc); 12933 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12934 IsLV = Expr::MLV_InvalidMessageExpression; 12935 if (IsLV == Expr::MLV_Valid) 12936 return false; 12937 12938 unsigned DiagID = 0; 12939 bool NeedType = false; 12940 switch (IsLV) { // C99 6.5.16p2 12941 case Expr::MLV_ConstQualified: 12942 // Use a specialized diagnostic when we're assigning to an object 12943 // from an enclosing function or block. 12944 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12945 if (NCCK == NCCK_Block) 12946 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12947 else 12948 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12949 break; 12950 } 12951 12952 // In ARC, use some specialized diagnostics for occasions where we 12953 // infer 'const'. These are always pseudo-strong variables. 12954 if (S.getLangOpts().ObjCAutoRefCount) { 12955 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12956 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12957 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12958 12959 // Use the normal diagnostic if it's pseudo-__strong but the 12960 // user actually wrote 'const'. 12961 if (var->isARCPseudoStrong() && 12962 (!var->getTypeSourceInfo() || 12963 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12964 // There are three pseudo-strong cases: 12965 // - self 12966 ObjCMethodDecl *method = S.getCurMethodDecl(); 12967 if (method && var == method->getSelfDecl()) { 12968 DiagID = method->isClassMethod() 12969 ? diag::err_typecheck_arc_assign_self_class_method 12970 : diag::err_typecheck_arc_assign_self; 12971 12972 // - Objective-C externally_retained attribute. 12973 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12974 isa<ParmVarDecl>(var)) { 12975 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12976 12977 // - fast enumeration variables 12978 } else { 12979 DiagID = diag::err_typecheck_arr_assign_enumeration; 12980 } 12981 12982 SourceRange Assign; 12983 if (Loc != OrigLoc) 12984 Assign = SourceRange(OrigLoc, OrigLoc); 12985 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12986 // We need to preserve the AST regardless, so migration tool 12987 // can do its job. 12988 return false; 12989 } 12990 } 12991 } 12992 12993 // If none of the special cases above are triggered, then this is a 12994 // simple const assignment. 12995 if (DiagID == 0) { 12996 DiagnoseConstAssignment(S, E, Loc); 12997 return true; 12998 } 12999 13000 break; 13001 case Expr::MLV_ConstAddrSpace: 13002 DiagnoseConstAssignment(S, E, Loc); 13003 return true; 13004 case Expr::MLV_ConstQualifiedField: 13005 DiagnoseRecursiveConstFields(S, E, Loc); 13006 return true; 13007 case Expr::MLV_ArrayType: 13008 case Expr::MLV_ArrayTemporary: 13009 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13010 NeedType = true; 13011 break; 13012 case Expr::MLV_NotObjectType: 13013 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13014 NeedType = true; 13015 break; 13016 case Expr::MLV_LValueCast: 13017 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13018 break; 13019 case Expr::MLV_Valid: 13020 llvm_unreachable("did not take early return for MLV_Valid"); 13021 case Expr::MLV_InvalidExpression: 13022 case Expr::MLV_MemberFunction: 13023 case Expr::MLV_ClassTemporary: 13024 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13025 break; 13026 case Expr::MLV_IncompleteType: 13027 case Expr::MLV_IncompleteVoidType: 13028 return S.RequireCompleteType(Loc, E->getType(), 13029 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13030 case Expr::MLV_DuplicateVectorComponents: 13031 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13032 break; 13033 case Expr::MLV_NoSetterProperty: 13034 llvm_unreachable("readonly properties should be processed differently"); 13035 case Expr::MLV_InvalidMessageExpression: 13036 DiagID = diag::err_readonly_message_assignment; 13037 break; 13038 case Expr::MLV_SubObjCPropertySetting: 13039 DiagID = diag::err_no_subobject_property_setting; 13040 break; 13041 } 13042 13043 SourceRange Assign; 13044 if (Loc != OrigLoc) 13045 Assign = SourceRange(OrigLoc, OrigLoc); 13046 if (NeedType) 13047 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13048 else 13049 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13050 return true; 13051 } 13052 13053 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13054 SourceLocation Loc, 13055 Sema &Sema) { 13056 if (Sema.inTemplateInstantiation()) 13057 return; 13058 if (Sema.isUnevaluatedContext()) 13059 return; 13060 if (Loc.isInvalid() || Loc.isMacroID()) 13061 return; 13062 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13063 return; 13064 13065 // C / C++ fields 13066 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13067 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13068 if (ML && MR) { 13069 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13070 return; 13071 const ValueDecl *LHSDecl = 13072 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13073 const ValueDecl *RHSDecl = 13074 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13075 if (LHSDecl != RHSDecl) 13076 return; 13077 if (LHSDecl->getType().isVolatileQualified()) 13078 return; 13079 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13080 if (RefTy->getPointeeType().isVolatileQualified()) 13081 return; 13082 13083 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13084 } 13085 13086 // Objective-C instance variables 13087 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13088 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13089 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13090 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13091 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13092 if (RL && RR && RL->getDecl() == RR->getDecl()) 13093 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13094 } 13095 } 13096 13097 // C99 6.5.16.1 13098 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13099 SourceLocation Loc, 13100 QualType CompoundType) { 13101 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13102 13103 // Verify that LHS is a modifiable lvalue, and emit error if not. 13104 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13105 return QualType(); 13106 13107 QualType LHSType = LHSExpr->getType(); 13108 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13109 CompoundType; 13110 // OpenCL v1.2 s6.1.1.1 p2: 13111 // The half data type can only be used to declare a pointer to a buffer that 13112 // contains half values 13113 if (getLangOpts().OpenCL && 13114 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13115 LHSType->isHalfType()) { 13116 Diag(Loc, diag::err_opencl_half_load_store) << 1 13117 << LHSType.getUnqualifiedType(); 13118 return QualType(); 13119 } 13120 13121 AssignConvertType ConvTy; 13122 if (CompoundType.isNull()) { 13123 Expr *RHSCheck = RHS.get(); 13124 13125 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13126 13127 QualType LHSTy(LHSType); 13128 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13129 if (RHS.isInvalid()) 13130 return QualType(); 13131 // Special case of NSObject attributes on c-style pointer types. 13132 if (ConvTy == IncompatiblePointer && 13133 ((Context.isObjCNSObjectType(LHSType) && 13134 RHSType->isObjCObjectPointerType()) || 13135 (Context.isObjCNSObjectType(RHSType) && 13136 LHSType->isObjCObjectPointerType()))) 13137 ConvTy = Compatible; 13138 13139 if (ConvTy == Compatible && 13140 LHSType->isObjCObjectType()) 13141 Diag(Loc, diag::err_objc_object_assignment) 13142 << LHSType; 13143 13144 // If the RHS is a unary plus or minus, check to see if they = and + are 13145 // right next to each other. If so, the user may have typo'd "x =+ 4" 13146 // instead of "x += 4". 13147 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13148 RHSCheck = ICE->getSubExpr(); 13149 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13150 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13151 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13152 // Only if the two operators are exactly adjacent. 13153 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13154 // And there is a space or other character before the subexpr of the 13155 // unary +/-. We don't want to warn on "x=-1". 13156 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13157 UO->getSubExpr()->getBeginLoc().isFileID()) { 13158 Diag(Loc, diag::warn_not_compound_assign) 13159 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13160 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13161 } 13162 } 13163 13164 if (ConvTy == Compatible) { 13165 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13166 // Warn about retain cycles where a block captures the LHS, but 13167 // not if the LHS is a simple variable into which the block is 13168 // being stored...unless that variable can be captured by reference! 13169 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13170 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13171 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13172 checkRetainCycles(LHSExpr, RHS.get()); 13173 } 13174 13175 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13176 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13177 // It is safe to assign a weak reference into a strong variable. 13178 // Although this code can still have problems: 13179 // id x = self.weakProp; 13180 // id y = self.weakProp; 13181 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13182 // paths through the function. This should be revisited if 13183 // -Wrepeated-use-of-weak is made flow-sensitive. 13184 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13185 // variable, which will be valid for the current autorelease scope. 13186 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13187 RHS.get()->getBeginLoc())) 13188 getCurFunction()->markSafeWeakUse(RHS.get()); 13189 13190 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13191 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13192 } 13193 } 13194 } else { 13195 // Compound assignment "x += y" 13196 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13197 } 13198 13199 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13200 RHS.get(), AA_Assigning)) 13201 return QualType(); 13202 13203 CheckForNullPointerDereference(*this, LHSExpr); 13204 13205 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13206 if (CompoundType.isNull()) { 13207 // C++2a [expr.ass]p5: 13208 // A simple-assignment whose left operand is of a volatile-qualified 13209 // type is deprecated unless the assignment is either a discarded-value 13210 // expression or an unevaluated operand 13211 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13212 } else { 13213 // C++2a [expr.ass]p6: 13214 // [Compound-assignment] expressions are deprecated if E1 has 13215 // volatile-qualified type 13216 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13217 } 13218 } 13219 13220 // C99 6.5.16p3: The type of an assignment expression is the type of the 13221 // left operand unless the left operand has qualified type, in which case 13222 // it is the unqualified version of the type of the left operand. 13223 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13224 // is converted to the type of the assignment expression (above). 13225 // C++ 5.17p1: the type of the assignment expression is that of its left 13226 // operand. 13227 return (getLangOpts().CPlusPlus 13228 ? LHSType : LHSType.getUnqualifiedType()); 13229 } 13230 13231 // Only ignore explicit casts to void. 13232 static bool IgnoreCommaOperand(const Expr *E) { 13233 E = E->IgnoreParens(); 13234 13235 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13236 if (CE->getCastKind() == CK_ToVoid) { 13237 return true; 13238 } 13239 13240 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13241 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13242 CE->getSubExpr()->getType()->isDependentType()) { 13243 return true; 13244 } 13245 } 13246 13247 return false; 13248 } 13249 13250 // Look for instances where it is likely the comma operator is confused with 13251 // another operator. There is an explicit list of acceptable expressions for 13252 // the left hand side of the comma operator, otherwise emit a warning. 13253 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13254 // No warnings in macros 13255 if (Loc.isMacroID()) 13256 return; 13257 13258 // Don't warn in template instantiations. 13259 if (inTemplateInstantiation()) 13260 return; 13261 13262 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13263 // instead, skip more than needed, then call back into here with the 13264 // CommaVisitor in SemaStmt.cpp. 13265 // The listed locations are the initialization and increment portions 13266 // of a for loop. The additional checks are on the condition of 13267 // if statements, do/while loops, and for loops. 13268 // Differences in scope flags for C89 mode requires the extra logic. 13269 const unsigned ForIncrementFlags = 13270 getLangOpts().C99 || getLangOpts().CPlusPlus 13271 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13272 : Scope::ContinueScope | Scope::BreakScope; 13273 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13274 const unsigned ScopeFlags = getCurScope()->getFlags(); 13275 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13276 (ScopeFlags & ForInitFlags) == ForInitFlags) 13277 return; 13278 13279 // If there are multiple comma operators used together, get the RHS of the 13280 // of the comma operator as the LHS. 13281 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13282 if (BO->getOpcode() != BO_Comma) 13283 break; 13284 LHS = BO->getRHS(); 13285 } 13286 13287 // Only allow some expressions on LHS to not warn. 13288 if (IgnoreCommaOperand(LHS)) 13289 return; 13290 13291 Diag(Loc, diag::warn_comma_operator); 13292 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13293 << LHS->getSourceRange() 13294 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13295 LangOpts.CPlusPlus ? "static_cast<void>(" 13296 : "(void)(") 13297 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13298 ")"); 13299 } 13300 13301 // C99 6.5.17 13302 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13303 SourceLocation Loc) { 13304 LHS = S.CheckPlaceholderExpr(LHS.get()); 13305 RHS = S.CheckPlaceholderExpr(RHS.get()); 13306 if (LHS.isInvalid() || RHS.isInvalid()) 13307 return QualType(); 13308 13309 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13310 // operands, but not unary promotions. 13311 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13312 13313 // So we treat the LHS as a ignored value, and in C++ we allow the 13314 // containing site to determine what should be done with the RHS. 13315 LHS = S.IgnoredValueConversions(LHS.get()); 13316 if (LHS.isInvalid()) 13317 return QualType(); 13318 13319 S.DiagnoseUnusedExprResult(LHS.get()); 13320 13321 if (!S.getLangOpts().CPlusPlus) { 13322 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13323 if (RHS.isInvalid()) 13324 return QualType(); 13325 if (!RHS.get()->getType()->isVoidType()) 13326 S.RequireCompleteType(Loc, RHS.get()->getType(), 13327 diag::err_incomplete_type); 13328 } 13329 13330 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13331 S.DiagnoseCommaOperator(LHS.get(), Loc); 13332 13333 return RHS.get()->getType(); 13334 } 13335 13336 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13337 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13338 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13339 ExprValueKind &VK, 13340 ExprObjectKind &OK, 13341 SourceLocation OpLoc, 13342 bool IsInc, bool IsPrefix) { 13343 if (Op->isTypeDependent()) 13344 return S.Context.DependentTy; 13345 13346 QualType ResType = Op->getType(); 13347 // Atomic types can be used for increment / decrement where the non-atomic 13348 // versions can, so ignore the _Atomic() specifier for the purpose of 13349 // checking. 13350 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13351 ResType = ResAtomicType->getValueType(); 13352 13353 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13354 13355 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13356 // Decrement of bool is not allowed. 13357 if (!IsInc) { 13358 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13359 return QualType(); 13360 } 13361 // Increment of bool sets it to true, but is deprecated. 13362 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13363 : diag::warn_increment_bool) 13364 << Op->getSourceRange(); 13365 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13366 // Error on enum increments and decrements in C++ mode 13367 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13368 return QualType(); 13369 } else if (ResType->isRealType()) { 13370 // OK! 13371 } else if (ResType->isPointerType()) { 13372 // C99 6.5.2.4p2, 6.5.6p2 13373 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13374 return QualType(); 13375 } else if (ResType->isObjCObjectPointerType()) { 13376 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13377 // Otherwise, we just need a complete type. 13378 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13379 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13380 return QualType(); 13381 } else if (ResType->isAnyComplexType()) { 13382 // C99 does not support ++/-- on complex types, we allow as an extension. 13383 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13384 << ResType << Op->getSourceRange(); 13385 } else if (ResType->isPlaceholderType()) { 13386 ExprResult PR = S.CheckPlaceholderExpr(Op); 13387 if (PR.isInvalid()) return QualType(); 13388 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13389 IsInc, IsPrefix); 13390 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13391 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13392 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13393 (ResType->castAs<VectorType>()->getVectorKind() != 13394 VectorType::AltiVecBool)) { 13395 // The z vector extensions allow ++ and -- for non-bool vectors. 13396 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13397 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13398 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13399 } else { 13400 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13401 << ResType << int(IsInc) << Op->getSourceRange(); 13402 return QualType(); 13403 } 13404 // At this point, we know we have a real, complex or pointer type. 13405 // Now make sure the operand is a modifiable lvalue. 13406 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13407 return QualType(); 13408 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13409 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13410 // An operand with volatile-qualified type is deprecated 13411 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13412 << IsInc << ResType; 13413 } 13414 // In C++, a prefix increment is the same type as the operand. Otherwise 13415 // (in C or with postfix), the increment is the unqualified type of the 13416 // operand. 13417 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13418 VK = VK_LValue; 13419 OK = Op->getObjectKind(); 13420 return ResType; 13421 } else { 13422 VK = VK_PRValue; 13423 return ResType.getUnqualifiedType(); 13424 } 13425 } 13426 13427 13428 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13429 /// This routine allows us to typecheck complex/recursive expressions 13430 /// where the declaration is needed for type checking. We only need to 13431 /// handle cases when the expression references a function designator 13432 /// or is an lvalue. Here are some examples: 13433 /// - &(x) => x 13434 /// - &*****f => f for f a function designator. 13435 /// - &s.xx => s 13436 /// - &s.zz[1].yy -> s, if zz is an array 13437 /// - *(x + 1) -> x, if x is an array 13438 /// - &"123"[2] -> 0 13439 /// - & __real__ x -> x 13440 /// 13441 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13442 /// members. 13443 static ValueDecl *getPrimaryDecl(Expr *E) { 13444 switch (E->getStmtClass()) { 13445 case Stmt::DeclRefExprClass: 13446 return cast<DeclRefExpr>(E)->getDecl(); 13447 case Stmt::MemberExprClass: 13448 // If this is an arrow operator, the address is an offset from 13449 // the base's value, so the object the base refers to is 13450 // irrelevant. 13451 if (cast<MemberExpr>(E)->isArrow()) 13452 return nullptr; 13453 // Otherwise, the expression refers to a part of the base 13454 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13455 case Stmt::ArraySubscriptExprClass: { 13456 // FIXME: This code shouldn't be necessary! We should catch the implicit 13457 // promotion of register arrays earlier. 13458 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13459 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13460 if (ICE->getSubExpr()->getType()->isArrayType()) 13461 return getPrimaryDecl(ICE->getSubExpr()); 13462 } 13463 return nullptr; 13464 } 13465 case Stmt::UnaryOperatorClass: { 13466 UnaryOperator *UO = cast<UnaryOperator>(E); 13467 13468 switch(UO->getOpcode()) { 13469 case UO_Real: 13470 case UO_Imag: 13471 case UO_Extension: 13472 return getPrimaryDecl(UO->getSubExpr()); 13473 default: 13474 return nullptr; 13475 } 13476 } 13477 case Stmt::ParenExprClass: 13478 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13479 case Stmt::ImplicitCastExprClass: 13480 // If the result of an implicit cast is an l-value, we care about 13481 // the sub-expression; otherwise, the result here doesn't matter. 13482 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13483 case Stmt::CXXUuidofExprClass: 13484 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13485 default: 13486 return nullptr; 13487 } 13488 } 13489 13490 namespace { 13491 enum { 13492 AO_Bit_Field = 0, 13493 AO_Vector_Element = 1, 13494 AO_Property_Expansion = 2, 13495 AO_Register_Variable = 3, 13496 AO_Matrix_Element = 4, 13497 AO_No_Error = 5 13498 }; 13499 } 13500 /// Diagnose invalid operand for address of operations. 13501 /// 13502 /// \param Type The type of operand which cannot have its address taken. 13503 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13504 Expr *E, unsigned Type) { 13505 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13506 } 13507 13508 /// CheckAddressOfOperand - The operand of & must be either a function 13509 /// designator or an lvalue designating an object. If it is an lvalue, the 13510 /// object cannot be declared with storage class register or be a bit field. 13511 /// Note: The usual conversions are *not* applied to the operand of the & 13512 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13513 /// In C++, the operand might be an overloaded function name, in which case 13514 /// we allow the '&' but retain the overloaded-function type. 13515 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13516 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13517 if (PTy->getKind() == BuiltinType::Overload) { 13518 Expr *E = OrigOp.get()->IgnoreParens(); 13519 if (!isa<OverloadExpr>(E)) { 13520 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13521 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13522 << OrigOp.get()->getSourceRange(); 13523 return QualType(); 13524 } 13525 13526 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13527 if (isa<UnresolvedMemberExpr>(Ovl)) 13528 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13529 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13530 << OrigOp.get()->getSourceRange(); 13531 return QualType(); 13532 } 13533 13534 return Context.OverloadTy; 13535 } 13536 13537 if (PTy->getKind() == BuiltinType::UnknownAny) 13538 return Context.UnknownAnyTy; 13539 13540 if (PTy->getKind() == BuiltinType::BoundMember) { 13541 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13542 << OrigOp.get()->getSourceRange(); 13543 return QualType(); 13544 } 13545 13546 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13547 if (OrigOp.isInvalid()) return QualType(); 13548 } 13549 13550 if (OrigOp.get()->isTypeDependent()) 13551 return Context.DependentTy; 13552 13553 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13554 13555 // Make sure to ignore parentheses in subsequent checks 13556 Expr *op = OrigOp.get()->IgnoreParens(); 13557 13558 // In OpenCL captures for blocks called as lambda functions 13559 // are located in the private address space. Blocks used in 13560 // enqueue_kernel can be located in a different address space 13561 // depending on a vendor implementation. Thus preventing 13562 // taking an address of the capture to avoid invalid AS casts. 13563 if (LangOpts.OpenCL) { 13564 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13565 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13566 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13567 return QualType(); 13568 } 13569 } 13570 13571 if (getLangOpts().C99) { 13572 // Implement C99-only parts of addressof rules. 13573 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13574 if (uOp->getOpcode() == UO_Deref) 13575 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13576 // (assuming the deref expression is valid). 13577 return uOp->getSubExpr()->getType(); 13578 } 13579 // Technically, there should be a check for array subscript 13580 // expressions here, but the result of one is always an lvalue anyway. 13581 } 13582 ValueDecl *dcl = getPrimaryDecl(op); 13583 13584 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13585 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13586 op->getBeginLoc())) 13587 return QualType(); 13588 13589 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13590 unsigned AddressOfError = AO_No_Error; 13591 13592 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13593 bool sfinae = (bool)isSFINAEContext(); 13594 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13595 : diag::ext_typecheck_addrof_temporary) 13596 << op->getType() << op->getSourceRange(); 13597 if (sfinae) 13598 return QualType(); 13599 // Materialize the temporary as an lvalue so that we can take its address. 13600 OrigOp = op = 13601 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13602 } else if (isa<ObjCSelectorExpr>(op)) { 13603 return Context.getPointerType(op->getType()); 13604 } else if (lval == Expr::LV_MemberFunction) { 13605 // If it's an instance method, make a member pointer. 13606 // The expression must have exactly the form &A::foo. 13607 13608 // If the underlying expression isn't a decl ref, give up. 13609 if (!isa<DeclRefExpr>(op)) { 13610 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13611 << OrigOp.get()->getSourceRange(); 13612 return QualType(); 13613 } 13614 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13615 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13616 13617 // The id-expression was parenthesized. 13618 if (OrigOp.get() != DRE) { 13619 Diag(OpLoc, diag::err_parens_pointer_member_function) 13620 << OrigOp.get()->getSourceRange(); 13621 13622 // The method was named without a qualifier. 13623 } else if (!DRE->getQualifier()) { 13624 if (MD->getParent()->getName().empty()) 13625 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13626 << op->getSourceRange(); 13627 else { 13628 SmallString<32> Str; 13629 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13630 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13631 << op->getSourceRange() 13632 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13633 } 13634 } 13635 13636 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13637 if (isa<CXXDestructorDecl>(MD)) 13638 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13639 13640 QualType MPTy = Context.getMemberPointerType( 13641 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13642 // Under the MS ABI, lock down the inheritance model now. 13643 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13644 (void)isCompleteType(OpLoc, MPTy); 13645 return MPTy; 13646 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13647 // C99 6.5.3.2p1 13648 // The operand must be either an l-value or a function designator 13649 if (!op->getType()->isFunctionType()) { 13650 // Use a special diagnostic for loads from property references. 13651 if (isa<PseudoObjectExpr>(op)) { 13652 AddressOfError = AO_Property_Expansion; 13653 } else { 13654 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13655 << op->getType() << op->getSourceRange(); 13656 return QualType(); 13657 } 13658 } 13659 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13660 // The operand cannot be a bit-field 13661 AddressOfError = AO_Bit_Field; 13662 } else if (op->getObjectKind() == OK_VectorComponent) { 13663 // The operand cannot be an element of a vector 13664 AddressOfError = AO_Vector_Element; 13665 } else if (op->getObjectKind() == OK_MatrixComponent) { 13666 // The operand cannot be an element of a matrix. 13667 AddressOfError = AO_Matrix_Element; 13668 } else if (dcl) { // C99 6.5.3.2p1 13669 // We have an lvalue with a decl. Make sure the decl is not declared 13670 // with the register storage-class specifier. 13671 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13672 // in C++ it is not error to take address of a register 13673 // variable (c++03 7.1.1P3) 13674 if (vd->getStorageClass() == SC_Register && 13675 !getLangOpts().CPlusPlus) { 13676 AddressOfError = AO_Register_Variable; 13677 } 13678 } else if (isa<MSPropertyDecl>(dcl)) { 13679 AddressOfError = AO_Property_Expansion; 13680 } else if (isa<FunctionTemplateDecl>(dcl)) { 13681 return Context.OverloadTy; 13682 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13683 // Okay: we can take the address of a field. 13684 // Could be a pointer to member, though, if there is an explicit 13685 // scope qualifier for the class. 13686 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13687 DeclContext *Ctx = dcl->getDeclContext(); 13688 if (Ctx && Ctx->isRecord()) { 13689 if (dcl->getType()->isReferenceType()) { 13690 Diag(OpLoc, 13691 diag::err_cannot_form_pointer_to_member_of_reference_type) 13692 << dcl->getDeclName() << dcl->getType(); 13693 return QualType(); 13694 } 13695 13696 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13697 Ctx = Ctx->getParent(); 13698 13699 QualType MPTy = Context.getMemberPointerType( 13700 op->getType(), 13701 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13702 // Under the MS ABI, lock down the inheritance model now. 13703 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13704 (void)isCompleteType(OpLoc, MPTy); 13705 return MPTy; 13706 } 13707 } 13708 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13709 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13710 llvm_unreachable("Unknown/unexpected decl type"); 13711 } 13712 13713 if (AddressOfError != AO_No_Error) { 13714 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13715 return QualType(); 13716 } 13717 13718 if (lval == Expr::LV_IncompleteVoidType) { 13719 // Taking the address of a void variable is technically illegal, but we 13720 // allow it in cases which are otherwise valid. 13721 // Example: "extern void x; void* y = &x;". 13722 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13723 } 13724 13725 // If the operand has type "type", the result has type "pointer to type". 13726 if (op->getType()->isObjCObjectType()) 13727 return Context.getObjCObjectPointerType(op->getType()); 13728 13729 CheckAddressOfPackedMember(op); 13730 13731 return Context.getPointerType(op->getType()); 13732 } 13733 13734 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13735 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13736 if (!DRE) 13737 return; 13738 const Decl *D = DRE->getDecl(); 13739 if (!D) 13740 return; 13741 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13742 if (!Param) 13743 return; 13744 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13745 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13746 return; 13747 if (FunctionScopeInfo *FD = S.getCurFunction()) 13748 if (!FD->ModifiedNonNullParams.count(Param)) 13749 FD->ModifiedNonNullParams.insert(Param); 13750 } 13751 13752 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13753 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13754 SourceLocation OpLoc) { 13755 if (Op->isTypeDependent()) 13756 return S.Context.DependentTy; 13757 13758 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13759 if (ConvResult.isInvalid()) 13760 return QualType(); 13761 Op = ConvResult.get(); 13762 QualType OpTy = Op->getType(); 13763 QualType Result; 13764 13765 if (isa<CXXReinterpretCastExpr>(Op)) { 13766 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13767 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13768 Op->getSourceRange()); 13769 } 13770 13771 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13772 { 13773 Result = PT->getPointeeType(); 13774 } 13775 else if (const ObjCObjectPointerType *OPT = 13776 OpTy->getAs<ObjCObjectPointerType>()) 13777 Result = OPT->getPointeeType(); 13778 else { 13779 ExprResult PR = S.CheckPlaceholderExpr(Op); 13780 if (PR.isInvalid()) return QualType(); 13781 if (PR.get() != Op) 13782 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13783 } 13784 13785 if (Result.isNull()) { 13786 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13787 << OpTy << Op->getSourceRange(); 13788 return QualType(); 13789 } 13790 13791 // Note that per both C89 and C99, indirection is always legal, even if Result 13792 // is an incomplete type or void. It would be possible to warn about 13793 // dereferencing a void pointer, but it's completely well-defined, and such a 13794 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13795 // for pointers to 'void' but is fine for any other pointer type: 13796 // 13797 // C++ [expr.unary.op]p1: 13798 // [...] the expression to which [the unary * operator] is applied shall 13799 // be a pointer to an object type, or a pointer to a function type 13800 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13801 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13802 << OpTy << Op->getSourceRange(); 13803 13804 // Dereferences are usually l-values... 13805 VK = VK_LValue; 13806 13807 // ...except that certain expressions are never l-values in C. 13808 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13809 VK = VK_PRValue; 13810 13811 return Result; 13812 } 13813 13814 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13815 BinaryOperatorKind Opc; 13816 switch (Kind) { 13817 default: llvm_unreachable("Unknown binop!"); 13818 case tok::periodstar: Opc = BO_PtrMemD; break; 13819 case tok::arrowstar: Opc = BO_PtrMemI; break; 13820 case tok::star: Opc = BO_Mul; break; 13821 case tok::slash: Opc = BO_Div; break; 13822 case tok::percent: Opc = BO_Rem; break; 13823 case tok::plus: Opc = BO_Add; break; 13824 case tok::minus: Opc = BO_Sub; break; 13825 case tok::lessless: Opc = BO_Shl; break; 13826 case tok::greatergreater: Opc = BO_Shr; break; 13827 case tok::lessequal: Opc = BO_LE; break; 13828 case tok::less: Opc = BO_LT; break; 13829 case tok::greaterequal: Opc = BO_GE; break; 13830 case tok::greater: Opc = BO_GT; break; 13831 case tok::exclaimequal: Opc = BO_NE; break; 13832 case tok::equalequal: Opc = BO_EQ; break; 13833 case tok::spaceship: Opc = BO_Cmp; break; 13834 case tok::amp: Opc = BO_And; break; 13835 case tok::caret: Opc = BO_Xor; break; 13836 case tok::pipe: Opc = BO_Or; break; 13837 case tok::ampamp: Opc = BO_LAnd; break; 13838 case tok::pipepipe: Opc = BO_LOr; break; 13839 case tok::equal: Opc = BO_Assign; break; 13840 case tok::starequal: Opc = BO_MulAssign; break; 13841 case tok::slashequal: Opc = BO_DivAssign; break; 13842 case tok::percentequal: Opc = BO_RemAssign; break; 13843 case tok::plusequal: Opc = BO_AddAssign; break; 13844 case tok::minusequal: Opc = BO_SubAssign; break; 13845 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13846 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13847 case tok::ampequal: Opc = BO_AndAssign; break; 13848 case tok::caretequal: Opc = BO_XorAssign; break; 13849 case tok::pipeequal: Opc = BO_OrAssign; break; 13850 case tok::comma: Opc = BO_Comma; break; 13851 } 13852 return Opc; 13853 } 13854 13855 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13856 tok::TokenKind Kind) { 13857 UnaryOperatorKind Opc; 13858 switch (Kind) { 13859 default: llvm_unreachable("Unknown unary op!"); 13860 case tok::plusplus: Opc = UO_PreInc; break; 13861 case tok::minusminus: Opc = UO_PreDec; break; 13862 case tok::amp: Opc = UO_AddrOf; break; 13863 case tok::star: Opc = UO_Deref; break; 13864 case tok::plus: Opc = UO_Plus; break; 13865 case tok::minus: Opc = UO_Minus; break; 13866 case tok::tilde: Opc = UO_Not; break; 13867 case tok::exclaim: Opc = UO_LNot; break; 13868 case tok::kw___real: Opc = UO_Real; break; 13869 case tok::kw___imag: Opc = UO_Imag; break; 13870 case tok::kw___extension__: Opc = UO_Extension; break; 13871 } 13872 return Opc; 13873 } 13874 13875 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13876 /// This warning suppressed in the event of macro expansions. 13877 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13878 SourceLocation OpLoc, bool IsBuiltin) { 13879 if (S.inTemplateInstantiation()) 13880 return; 13881 if (S.isUnevaluatedContext()) 13882 return; 13883 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13884 return; 13885 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13886 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13887 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13888 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13889 if (!LHSDeclRef || !RHSDeclRef || 13890 LHSDeclRef->getLocation().isMacroID() || 13891 RHSDeclRef->getLocation().isMacroID()) 13892 return; 13893 const ValueDecl *LHSDecl = 13894 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13895 const ValueDecl *RHSDecl = 13896 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13897 if (LHSDecl != RHSDecl) 13898 return; 13899 if (LHSDecl->getType().isVolatileQualified()) 13900 return; 13901 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13902 if (RefTy->getPointeeType().isVolatileQualified()) 13903 return; 13904 13905 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13906 : diag::warn_self_assignment_overloaded) 13907 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13908 << RHSExpr->getSourceRange(); 13909 } 13910 13911 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13912 /// is usually indicative of introspection within the Objective-C pointer. 13913 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13914 SourceLocation OpLoc) { 13915 if (!S.getLangOpts().ObjC) 13916 return; 13917 13918 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13919 const Expr *LHS = L.get(); 13920 const Expr *RHS = R.get(); 13921 13922 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13923 ObjCPointerExpr = LHS; 13924 OtherExpr = RHS; 13925 } 13926 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13927 ObjCPointerExpr = RHS; 13928 OtherExpr = LHS; 13929 } 13930 13931 // This warning is deliberately made very specific to reduce false 13932 // positives with logic that uses '&' for hashing. This logic mainly 13933 // looks for code trying to introspect into tagged pointers, which 13934 // code should generally never do. 13935 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13936 unsigned Diag = diag::warn_objc_pointer_masking; 13937 // Determine if we are introspecting the result of performSelectorXXX. 13938 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13939 // Special case messages to -performSelector and friends, which 13940 // can return non-pointer values boxed in a pointer value. 13941 // Some clients may wish to silence warnings in this subcase. 13942 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13943 Selector S = ME->getSelector(); 13944 StringRef SelArg0 = S.getNameForSlot(0); 13945 if (SelArg0.startswith("performSelector")) 13946 Diag = diag::warn_objc_pointer_masking_performSelector; 13947 } 13948 13949 S.Diag(OpLoc, Diag) 13950 << ObjCPointerExpr->getSourceRange(); 13951 } 13952 } 13953 13954 static NamedDecl *getDeclFromExpr(Expr *E) { 13955 if (!E) 13956 return nullptr; 13957 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13958 return DRE->getDecl(); 13959 if (auto *ME = dyn_cast<MemberExpr>(E)) 13960 return ME->getMemberDecl(); 13961 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13962 return IRE->getDecl(); 13963 return nullptr; 13964 } 13965 13966 // This helper function promotes a binary operator's operands (which are of a 13967 // half vector type) to a vector of floats and then truncates the result to 13968 // a vector of either half or short. 13969 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13970 BinaryOperatorKind Opc, QualType ResultTy, 13971 ExprValueKind VK, ExprObjectKind OK, 13972 bool IsCompAssign, SourceLocation OpLoc, 13973 FPOptionsOverride FPFeatures) { 13974 auto &Context = S.getASTContext(); 13975 assert((isVector(ResultTy, Context.HalfTy) || 13976 isVector(ResultTy, Context.ShortTy)) && 13977 "Result must be a vector of half or short"); 13978 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13979 isVector(RHS.get()->getType(), Context.HalfTy) && 13980 "both operands expected to be a half vector"); 13981 13982 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13983 QualType BinOpResTy = RHS.get()->getType(); 13984 13985 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13986 // change BinOpResTy to a vector of ints. 13987 if (isVector(ResultTy, Context.ShortTy)) 13988 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13989 13990 if (IsCompAssign) 13991 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13992 ResultTy, VK, OK, OpLoc, FPFeatures, 13993 BinOpResTy, BinOpResTy); 13994 13995 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13996 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13997 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13998 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13999 } 14000 14001 static std::pair<ExprResult, ExprResult> 14002 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14003 Expr *RHSExpr) { 14004 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14005 if (!S.Context.isDependenceAllowed()) { 14006 // C cannot handle TypoExpr nodes on either side of a binop because it 14007 // doesn't handle dependent types properly, so make sure any TypoExprs have 14008 // been dealt with before checking the operands. 14009 LHS = S.CorrectDelayedTyposInExpr(LHS); 14010 RHS = S.CorrectDelayedTyposInExpr( 14011 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14012 [Opc, LHS](Expr *E) { 14013 if (Opc != BO_Assign) 14014 return ExprResult(E); 14015 // Avoid correcting the RHS to the same Expr as the LHS. 14016 Decl *D = getDeclFromExpr(E); 14017 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14018 }); 14019 } 14020 return std::make_pair(LHS, RHS); 14021 } 14022 14023 /// Returns true if conversion between vectors of halfs and vectors of floats 14024 /// is needed. 14025 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14026 Expr *E0, Expr *E1 = nullptr) { 14027 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14028 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14029 return false; 14030 14031 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14032 QualType Ty = E->IgnoreImplicit()->getType(); 14033 14034 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14035 // to vectors of floats. Although the element type of the vectors is __fp16, 14036 // the vectors shouldn't be treated as storage-only types. See the 14037 // discussion here: https://reviews.llvm.org/rG825235c140e7 14038 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14039 if (VT->getVectorKind() == VectorType::NeonVector) 14040 return false; 14041 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14042 } 14043 return false; 14044 }; 14045 14046 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14047 } 14048 14049 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14050 /// operator @p Opc at location @c TokLoc. This routine only supports 14051 /// built-in operations; ActOnBinOp handles overloaded operators. 14052 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14053 BinaryOperatorKind Opc, 14054 Expr *LHSExpr, Expr *RHSExpr) { 14055 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14056 // The syntax only allows initializer lists on the RHS of assignment, 14057 // so we don't need to worry about accepting invalid code for 14058 // non-assignment operators. 14059 // C++11 5.17p9: 14060 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14061 // of x = {} is x = T(). 14062 InitializationKind Kind = InitializationKind::CreateDirectList( 14063 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14064 InitializedEntity Entity = 14065 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14066 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14067 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14068 if (Init.isInvalid()) 14069 return Init; 14070 RHSExpr = Init.get(); 14071 } 14072 14073 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14074 QualType ResultTy; // Result type of the binary operator. 14075 // The following two variables are used for compound assignment operators 14076 QualType CompLHSTy; // Type of LHS after promotions for computation 14077 QualType CompResultTy; // Type of computation result 14078 ExprValueKind VK = VK_PRValue; 14079 ExprObjectKind OK = OK_Ordinary; 14080 bool ConvertHalfVec = false; 14081 14082 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14083 if (!LHS.isUsable() || !RHS.isUsable()) 14084 return ExprError(); 14085 14086 if (getLangOpts().OpenCL) { 14087 QualType LHSTy = LHSExpr->getType(); 14088 QualType RHSTy = RHSExpr->getType(); 14089 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14090 // the ATOMIC_VAR_INIT macro. 14091 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14092 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14093 if (BO_Assign == Opc) 14094 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14095 else 14096 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14097 return ExprError(); 14098 } 14099 14100 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14101 // only with a builtin functions and therefore should be disallowed here. 14102 if (LHSTy->isImageType() || RHSTy->isImageType() || 14103 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14104 LHSTy->isPipeType() || RHSTy->isPipeType() || 14105 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14106 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14107 return ExprError(); 14108 } 14109 } 14110 14111 switch (Opc) { 14112 case BO_Assign: 14113 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14114 if (getLangOpts().CPlusPlus && 14115 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14116 VK = LHS.get()->getValueKind(); 14117 OK = LHS.get()->getObjectKind(); 14118 } 14119 if (!ResultTy.isNull()) { 14120 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14121 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14122 14123 // Avoid copying a block to the heap if the block is assigned to a local 14124 // auto variable that is declared in the same scope as the block. This 14125 // optimization is unsafe if the local variable is declared in an outer 14126 // scope. For example: 14127 // 14128 // BlockTy b; 14129 // { 14130 // b = ^{...}; 14131 // } 14132 // // It is unsafe to invoke the block here if it wasn't copied to the 14133 // // heap. 14134 // b(); 14135 14136 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14137 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14138 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14139 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14140 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14141 14142 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14143 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14144 NTCUC_Assignment, NTCUK_Copy); 14145 } 14146 RecordModifiableNonNullParam(*this, LHS.get()); 14147 break; 14148 case BO_PtrMemD: 14149 case BO_PtrMemI: 14150 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14151 Opc == BO_PtrMemI); 14152 break; 14153 case BO_Mul: 14154 case BO_Div: 14155 ConvertHalfVec = true; 14156 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14157 Opc == BO_Div); 14158 break; 14159 case BO_Rem: 14160 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14161 break; 14162 case BO_Add: 14163 ConvertHalfVec = true; 14164 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14165 break; 14166 case BO_Sub: 14167 ConvertHalfVec = true; 14168 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14169 break; 14170 case BO_Shl: 14171 case BO_Shr: 14172 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14173 break; 14174 case BO_LE: 14175 case BO_LT: 14176 case BO_GE: 14177 case BO_GT: 14178 ConvertHalfVec = true; 14179 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14180 break; 14181 case BO_EQ: 14182 case BO_NE: 14183 ConvertHalfVec = true; 14184 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14185 break; 14186 case BO_Cmp: 14187 ConvertHalfVec = true; 14188 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14189 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14190 break; 14191 case BO_And: 14192 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14193 LLVM_FALLTHROUGH; 14194 case BO_Xor: 14195 case BO_Or: 14196 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14197 break; 14198 case BO_LAnd: 14199 case BO_LOr: 14200 ConvertHalfVec = true; 14201 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14202 break; 14203 case BO_MulAssign: 14204 case BO_DivAssign: 14205 ConvertHalfVec = true; 14206 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14207 Opc == BO_DivAssign); 14208 CompLHSTy = CompResultTy; 14209 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14210 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14211 break; 14212 case BO_RemAssign: 14213 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14214 CompLHSTy = CompResultTy; 14215 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14216 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14217 break; 14218 case BO_AddAssign: 14219 ConvertHalfVec = true; 14220 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14221 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14222 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14223 break; 14224 case BO_SubAssign: 14225 ConvertHalfVec = true; 14226 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14227 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14228 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14229 break; 14230 case BO_ShlAssign: 14231 case BO_ShrAssign: 14232 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14233 CompLHSTy = CompResultTy; 14234 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14235 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14236 break; 14237 case BO_AndAssign: 14238 case BO_OrAssign: // fallthrough 14239 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14240 LLVM_FALLTHROUGH; 14241 case BO_XorAssign: 14242 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14243 CompLHSTy = CompResultTy; 14244 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14245 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14246 break; 14247 case BO_Comma: 14248 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14249 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14250 VK = RHS.get()->getValueKind(); 14251 OK = RHS.get()->getObjectKind(); 14252 } 14253 break; 14254 } 14255 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14256 return ExprError(); 14257 14258 // Some of the binary operations require promoting operands of half vector to 14259 // float vectors and truncating the result back to half vector. For now, we do 14260 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14261 // arm64). 14262 assert( 14263 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14264 isVector(LHS.get()->getType(), Context.HalfTy)) && 14265 "both sides are half vectors or neither sides are"); 14266 ConvertHalfVec = 14267 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14268 14269 // Check for array bounds violations for both sides of the BinaryOperator 14270 CheckArrayAccess(LHS.get()); 14271 CheckArrayAccess(RHS.get()); 14272 14273 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14274 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14275 &Context.Idents.get("object_setClass"), 14276 SourceLocation(), LookupOrdinaryName); 14277 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14278 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14279 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14280 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14281 "object_setClass(") 14282 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14283 ",") 14284 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14285 } 14286 else 14287 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14288 } 14289 else if (const ObjCIvarRefExpr *OIRE = 14290 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14291 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14292 14293 // Opc is not a compound assignment if CompResultTy is null. 14294 if (CompResultTy.isNull()) { 14295 if (ConvertHalfVec) 14296 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14297 OpLoc, CurFPFeatureOverrides()); 14298 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14299 VK, OK, OpLoc, CurFPFeatureOverrides()); 14300 } 14301 14302 // Handle compound assignments. 14303 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14304 OK_ObjCProperty) { 14305 VK = VK_LValue; 14306 OK = LHS.get()->getObjectKind(); 14307 } 14308 14309 // The LHS is not converted to the result type for fixed-point compound 14310 // assignment as the common type is computed on demand. Reset the CompLHSTy 14311 // to the LHS type we would have gotten after unary conversions. 14312 if (CompResultTy->isFixedPointType()) 14313 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14314 14315 if (ConvertHalfVec) 14316 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14317 OpLoc, CurFPFeatureOverrides()); 14318 14319 return CompoundAssignOperator::Create( 14320 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14321 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14322 } 14323 14324 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14325 /// operators are mixed in a way that suggests that the programmer forgot that 14326 /// comparison operators have higher precedence. The most typical example of 14327 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14328 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14329 SourceLocation OpLoc, Expr *LHSExpr, 14330 Expr *RHSExpr) { 14331 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14332 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14333 14334 // Check that one of the sides is a comparison operator and the other isn't. 14335 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14336 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14337 if (isLeftComp == isRightComp) 14338 return; 14339 14340 // Bitwise operations are sometimes used as eager logical ops. 14341 // Don't diagnose this. 14342 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14343 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14344 if (isLeftBitwise || isRightBitwise) 14345 return; 14346 14347 SourceRange DiagRange = isLeftComp 14348 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14349 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14350 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14351 SourceRange ParensRange = 14352 isLeftComp 14353 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14354 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14355 14356 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14357 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14358 SuggestParentheses(Self, OpLoc, 14359 Self.PDiag(diag::note_precedence_silence) << OpStr, 14360 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14361 SuggestParentheses(Self, OpLoc, 14362 Self.PDiag(diag::note_precedence_bitwise_first) 14363 << BinaryOperator::getOpcodeStr(Opc), 14364 ParensRange); 14365 } 14366 14367 /// It accepts a '&&' expr that is inside a '||' one. 14368 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14369 /// in parentheses. 14370 static void 14371 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14372 BinaryOperator *Bop) { 14373 assert(Bop->getOpcode() == BO_LAnd); 14374 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14375 << Bop->getSourceRange() << OpLoc; 14376 SuggestParentheses(Self, Bop->getOperatorLoc(), 14377 Self.PDiag(diag::note_precedence_silence) 14378 << Bop->getOpcodeStr(), 14379 Bop->getSourceRange()); 14380 } 14381 14382 /// Returns true if the given expression can be evaluated as a constant 14383 /// 'true'. 14384 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14385 bool Res; 14386 return !E->isValueDependent() && 14387 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14388 } 14389 14390 /// Returns true if the given expression can be evaluated as a constant 14391 /// 'false'. 14392 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14393 bool Res; 14394 return !E->isValueDependent() && 14395 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14396 } 14397 14398 /// Look for '&&' in the left hand of a '||' expr. 14399 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14400 Expr *LHSExpr, Expr *RHSExpr) { 14401 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14402 if (Bop->getOpcode() == BO_LAnd) { 14403 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14404 if (EvaluatesAsFalse(S, RHSExpr)) 14405 return; 14406 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14407 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14408 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14409 } else if (Bop->getOpcode() == BO_LOr) { 14410 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14411 // If it's "a || b && 1 || c" we didn't warn earlier for 14412 // "a || b && 1", but warn now. 14413 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14414 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14415 } 14416 } 14417 } 14418 } 14419 14420 /// Look for '&&' in the right hand of a '||' expr. 14421 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14422 Expr *LHSExpr, Expr *RHSExpr) { 14423 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14424 if (Bop->getOpcode() == BO_LAnd) { 14425 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14426 if (EvaluatesAsFalse(S, LHSExpr)) 14427 return; 14428 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14429 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14430 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14431 } 14432 } 14433 } 14434 14435 /// Look for bitwise op in the left or right hand of a bitwise op with 14436 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14437 /// the '&' expression in parentheses. 14438 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14439 SourceLocation OpLoc, Expr *SubExpr) { 14440 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14441 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14442 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14443 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14444 << Bop->getSourceRange() << OpLoc; 14445 SuggestParentheses(S, Bop->getOperatorLoc(), 14446 S.PDiag(diag::note_precedence_silence) 14447 << Bop->getOpcodeStr(), 14448 Bop->getSourceRange()); 14449 } 14450 } 14451 } 14452 14453 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14454 Expr *SubExpr, StringRef Shift) { 14455 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14456 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14457 StringRef Op = Bop->getOpcodeStr(); 14458 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14459 << Bop->getSourceRange() << OpLoc << Shift << Op; 14460 SuggestParentheses(S, Bop->getOperatorLoc(), 14461 S.PDiag(diag::note_precedence_silence) << Op, 14462 Bop->getSourceRange()); 14463 } 14464 } 14465 } 14466 14467 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14468 Expr *LHSExpr, Expr *RHSExpr) { 14469 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14470 if (!OCE) 14471 return; 14472 14473 FunctionDecl *FD = OCE->getDirectCallee(); 14474 if (!FD || !FD->isOverloadedOperator()) 14475 return; 14476 14477 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14478 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14479 return; 14480 14481 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14482 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14483 << (Kind == OO_LessLess); 14484 SuggestParentheses(S, OCE->getOperatorLoc(), 14485 S.PDiag(diag::note_precedence_silence) 14486 << (Kind == OO_LessLess ? "<<" : ">>"), 14487 OCE->getSourceRange()); 14488 SuggestParentheses( 14489 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14490 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14491 } 14492 14493 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14494 /// precedence. 14495 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14496 SourceLocation OpLoc, Expr *LHSExpr, 14497 Expr *RHSExpr){ 14498 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14499 if (BinaryOperator::isBitwiseOp(Opc)) 14500 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14501 14502 // Diagnose "arg1 & arg2 | arg3" 14503 if ((Opc == BO_Or || Opc == BO_Xor) && 14504 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14505 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14506 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14507 } 14508 14509 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14510 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14511 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14512 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14513 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14514 } 14515 14516 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14517 || Opc == BO_Shr) { 14518 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14519 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14520 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14521 } 14522 14523 // Warn on overloaded shift operators and comparisons, such as: 14524 // cout << 5 == 4; 14525 if (BinaryOperator::isComparisonOp(Opc)) 14526 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14527 } 14528 14529 // Binary Operators. 'Tok' is the token for the operator. 14530 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14531 tok::TokenKind Kind, 14532 Expr *LHSExpr, Expr *RHSExpr) { 14533 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14534 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14535 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14536 14537 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14538 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14539 14540 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14541 } 14542 14543 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14544 UnresolvedSetImpl &Functions) { 14545 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14546 if (OverOp != OO_None && OverOp != OO_Equal) 14547 LookupOverloadedOperatorName(OverOp, S, Functions); 14548 14549 // In C++20 onwards, we may have a second operator to look up. 14550 if (getLangOpts().CPlusPlus20) { 14551 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14552 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14553 } 14554 } 14555 14556 /// Build an overloaded binary operator expression in the given scope. 14557 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14558 BinaryOperatorKind Opc, 14559 Expr *LHS, Expr *RHS) { 14560 switch (Opc) { 14561 case BO_Assign: 14562 case BO_DivAssign: 14563 case BO_RemAssign: 14564 case BO_SubAssign: 14565 case BO_AndAssign: 14566 case BO_OrAssign: 14567 case BO_XorAssign: 14568 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14569 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14570 break; 14571 default: 14572 break; 14573 } 14574 14575 // Find all of the overloaded operators visible from this point. 14576 UnresolvedSet<16> Functions; 14577 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14578 14579 // Build the (potentially-overloaded, potentially-dependent) 14580 // binary operation. 14581 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14582 } 14583 14584 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14585 BinaryOperatorKind Opc, 14586 Expr *LHSExpr, Expr *RHSExpr) { 14587 ExprResult LHS, RHS; 14588 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14589 if (!LHS.isUsable() || !RHS.isUsable()) 14590 return ExprError(); 14591 LHSExpr = LHS.get(); 14592 RHSExpr = RHS.get(); 14593 14594 // We want to end up calling one of checkPseudoObjectAssignment 14595 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14596 // both expressions are overloadable or either is type-dependent), 14597 // or CreateBuiltinBinOp (in any other case). We also want to get 14598 // any placeholder types out of the way. 14599 14600 // Handle pseudo-objects in the LHS. 14601 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14602 // Assignments with a pseudo-object l-value need special analysis. 14603 if (pty->getKind() == BuiltinType::PseudoObject && 14604 BinaryOperator::isAssignmentOp(Opc)) 14605 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14606 14607 // Don't resolve overloads if the other type is overloadable. 14608 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14609 // We can't actually test that if we still have a placeholder, 14610 // though. Fortunately, none of the exceptions we see in that 14611 // code below are valid when the LHS is an overload set. Note 14612 // that an overload set can be dependently-typed, but it never 14613 // instantiates to having an overloadable type. 14614 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14615 if (resolvedRHS.isInvalid()) return ExprError(); 14616 RHSExpr = resolvedRHS.get(); 14617 14618 if (RHSExpr->isTypeDependent() || 14619 RHSExpr->getType()->isOverloadableType()) 14620 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14621 } 14622 14623 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14624 // template, diagnose the missing 'template' keyword instead of diagnosing 14625 // an invalid use of a bound member function. 14626 // 14627 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14628 // to C++1z [over.over]/1.4, but we already checked for that case above. 14629 if (Opc == BO_LT && inTemplateInstantiation() && 14630 (pty->getKind() == BuiltinType::BoundMember || 14631 pty->getKind() == BuiltinType::Overload)) { 14632 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14633 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14634 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14635 return isa<FunctionTemplateDecl>(ND); 14636 })) { 14637 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14638 : OE->getNameLoc(), 14639 diag::err_template_kw_missing) 14640 << OE->getName().getAsString() << ""; 14641 return ExprError(); 14642 } 14643 } 14644 14645 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14646 if (LHS.isInvalid()) return ExprError(); 14647 LHSExpr = LHS.get(); 14648 } 14649 14650 // Handle pseudo-objects in the RHS. 14651 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14652 // An overload in the RHS can potentially be resolved by the type 14653 // being assigned to. 14654 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14655 if (getLangOpts().CPlusPlus && 14656 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14657 LHSExpr->getType()->isOverloadableType())) 14658 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14659 14660 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14661 } 14662 14663 // Don't resolve overloads if the other type is overloadable. 14664 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14665 LHSExpr->getType()->isOverloadableType()) 14666 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14667 14668 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14669 if (!resolvedRHS.isUsable()) return ExprError(); 14670 RHSExpr = resolvedRHS.get(); 14671 } 14672 14673 if (getLangOpts().CPlusPlus) { 14674 // If either expression is type-dependent, always build an 14675 // overloaded op. 14676 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14677 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14678 14679 // Otherwise, build an overloaded op if either expression has an 14680 // overloadable type. 14681 if (LHSExpr->getType()->isOverloadableType() || 14682 RHSExpr->getType()->isOverloadableType()) 14683 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14684 } 14685 14686 if (getLangOpts().RecoveryAST && 14687 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14688 assert(!getLangOpts().CPlusPlus); 14689 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14690 "Should only occur in error-recovery path."); 14691 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14692 // C [6.15.16] p3: 14693 // An assignment expression has the value of the left operand after the 14694 // assignment, but is not an lvalue. 14695 return CompoundAssignOperator::Create( 14696 Context, LHSExpr, RHSExpr, Opc, 14697 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14698 OpLoc, CurFPFeatureOverrides()); 14699 QualType ResultType; 14700 switch (Opc) { 14701 case BO_Assign: 14702 ResultType = LHSExpr->getType().getUnqualifiedType(); 14703 break; 14704 case BO_LT: 14705 case BO_GT: 14706 case BO_LE: 14707 case BO_GE: 14708 case BO_EQ: 14709 case BO_NE: 14710 case BO_LAnd: 14711 case BO_LOr: 14712 // These operators have a fixed result type regardless of operands. 14713 ResultType = Context.IntTy; 14714 break; 14715 case BO_Comma: 14716 ResultType = RHSExpr->getType(); 14717 break; 14718 default: 14719 ResultType = Context.DependentTy; 14720 break; 14721 } 14722 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14723 VK_PRValue, OK_Ordinary, OpLoc, 14724 CurFPFeatureOverrides()); 14725 } 14726 14727 // Build a built-in binary operation. 14728 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14729 } 14730 14731 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14732 if (T.isNull() || T->isDependentType()) 14733 return false; 14734 14735 if (!T->isPromotableIntegerType()) 14736 return true; 14737 14738 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14739 } 14740 14741 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14742 UnaryOperatorKind Opc, 14743 Expr *InputExpr) { 14744 ExprResult Input = InputExpr; 14745 ExprValueKind VK = VK_PRValue; 14746 ExprObjectKind OK = OK_Ordinary; 14747 QualType resultType; 14748 bool CanOverflow = false; 14749 14750 bool ConvertHalfVec = false; 14751 if (getLangOpts().OpenCL) { 14752 QualType Ty = InputExpr->getType(); 14753 // The only legal unary operation for atomics is '&'. 14754 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14755 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14756 // only with a builtin functions and therefore should be disallowed here. 14757 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14758 || Ty->isBlockPointerType())) { 14759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14760 << InputExpr->getType() 14761 << Input.get()->getSourceRange()); 14762 } 14763 } 14764 14765 switch (Opc) { 14766 case UO_PreInc: 14767 case UO_PreDec: 14768 case UO_PostInc: 14769 case UO_PostDec: 14770 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14771 OpLoc, 14772 Opc == UO_PreInc || 14773 Opc == UO_PostInc, 14774 Opc == UO_PreInc || 14775 Opc == UO_PreDec); 14776 CanOverflow = isOverflowingIntegerType(Context, resultType); 14777 break; 14778 case UO_AddrOf: 14779 resultType = CheckAddressOfOperand(Input, OpLoc); 14780 CheckAddressOfNoDeref(InputExpr); 14781 RecordModifiableNonNullParam(*this, InputExpr); 14782 break; 14783 case UO_Deref: { 14784 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14785 if (Input.isInvalid()) return ExprError(); 14786 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14787 break; 14788 } 14789 case UO_Plus: 14790 case UO_Minus: 14791 CanOverflow = Opc == UO_Minus && 14792 isOverflowingIntegerType(Context, Input.get()->getType()); 14793 Input = UsualUnaryConversions(Input.get()); 14794 if (Input.isInvalid()) return ExprError(); 14795 // Unary plus and minus require promoting an operand of half vector to a 14796 // float vector and truncating the result back to a half vector. For now, we 14797 // do this only when HalfArgsAndReturns is set (that is, when the target is 14798 // arm or arm64). 14799 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14800 14801 // If the operand is a half vector, promote it to a float vector. 14802 if (ConvertHalfVec) 14803 Input = convertVector(Input.get(), Context.FloatTy, *this); 14804 resultType = Input.get()->getType(); 14805 if (resultType->isDependentType()) 14806 break; 14807 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14808 break; 14809 else if (resultType->isVectorType() && 14810 // The z vector extensions don't allow + or - with bool vectors. 14811 (!Context.getLangOpts().ZVector || 14812 resultType->castAs<VectorType>()->getVectorKind() != 14813 VectorType::AltiVecBool)) 14814 break; 14815 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14816 Opc == UO_Plus && 14817 resultType->isPointerType()) 14818 break; 14819 14820 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14821 << resultType << Input.get()->getSourceRange()); 14822 14823 case UO_Not: // bitwise complement 14824 Input = UsualUnaryConversions(Input.get()); 14825 if (Input.isInvalid()) 14826 return ExprError(); 14827 resultType = Input.get()->getType(); 14828 if (resultType->isDependentType()) 14829 break; 14830 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14831 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14832 // C99 does not support '~' for complex conjugation. 14833 Diag(OpLoc, diag::ext_integer_complement_complex) 14834 << resultType << Input.get()->getSourceRange(); 14835 else if (resultType->hasIntegerRepresentation()) 14836 break; 14837 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14838 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14839 // on vector float types. 14840 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14841 if (!T->isIntegerType()) 14842 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14843 << resultType << Input.get()->getSourceRange()); 14844 } else { 14845 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14846 << resultType << Input.get()->getSourceRange()); 14847 } 14848 break; 14849 14850 case UO_LNot: // logical negation 14851 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14852 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14853 if (Input.isInvalid()) return ExprError(); 14854 resultType = Input.get()->getType(); 14855 14856 // Though we still have to promote half FP to float... 14857 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14858 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14859 resultType = Context.FloatTy; 14860 } 14861 14862 if (resultType->isDependentType()) 14863 break; 14864 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14865 // C99 6.5.3.3p1: ok, fallthrough; 14866 if (Context.getLangOpts().CPlusPlus) { 14867 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14868 // operand contextually converted to bool. 14869 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14870 ScalarTypeToBooleanCastKind(resultType)); 14871 } else if (Context.getLangOpts().OpenCL && 14872 Context.getLangOpts().OpenCLVersion < 120) { 14873 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14874 // operate on scalar float types. 14875 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14876 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14877 << resultType << Input.get()->getSourceRange()); 14878 } 14879 } else if (resultType->isExtVectorType()) { 14880 if (Context.getLangOpts().OpenCL && 14881 Context.getLangOpts().OpenCLVersion < 120 && 14882 !Context.getLangOpts().OpenCLCPlusPlus) { 14883 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14884 // operate on vector float types. 14885 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14886 if (!T->isIntegerType()) 14887 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14888 << resultType << Input.get()->getSourceRange()); 14889 } 14890 // Vector logical not returns the signed variant of the operand type. 14891 resultType = GetSignedVectorType(resultType); 14892 break; 14893 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14894 const VectorType *VTy = resultType->castAs<VectorType>(); 14895 if (VTy->getVectorKind() != VectorType::GenericVector) 14896 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14897 << resultType << Input.get()->getSourceRange()); 14898 14899 // Vector logical not returns the signed variant of the operand type. 14900 resultType = GetSignedVectorType(resultType); 14901 break; 14902 } else { 14903 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14904 << resultType << Input.get()->getSourceRange()); 14905 } 14906 14907 // LNot always has type int. C99 6.5.3.3p5. 14908 // In C++, it's bool. C++ 5.3.1p8 14909 resultType = Context.getLogicalOperationType(); 14910 break; 14911 case UO_Real: 14912 case UO_Imag: 14913 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14914 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14915 // complex l-values to ordinary l-values and all other values to r-values. 14916 if (Input.isInvalid()) return ExprError(); 14917 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14918 if (Input.get()->getValueKind() != VK_PRValue && 14919 Input.get()->getObjectKind() == OK_Ordinary) 14920 VK = Input.get()->getValueKind(); 14921 } else if (!getLangOpts().CPlusPlus) { 14922 // In C, a volatile scalar is read by __imag. In C++, it is not. 14923 Input = DefaultLvalueConversion(Input.get()); 14924 } 14925 break; 14926 case UO_Extension: 14927 resultType = Input.get()->getType(); 14928 VK = Input.get()->getValueKind(); 14929 OK = Input.get()->getObjectKind(); 14930 break; 14931 case UO_Coawait: 14932 // It's unnecessary to represent the pass-through operator co_await in the 14933 // AST; just return the input expression instead. 14934 assert(!Input.get()->getType()->isDependentType() && 14935 "the co_await expression must be non-dependant before " 14936 "building operator co_await"); 14937 return Input; 14938 } 14939 if (resultType.isNull() || Input.isInvalid()) 14940 return ExprError(); 14941 14942 // Check for array bounds violations in the operand of the UnaryOperator, 14943 // except for the '*' and '&' operators that have to be handled specially 14944 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14945 // that are explicitly defined as valid by the standard). 14946 if (Opc != UO_AddrOf && Opc != UO_Deref) 14947 CheckArrayAccess(Input.get()); 14948 14949 auto *UO = 14950 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14951 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14952 14953 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14954 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14955 !isUnevaluatedContext()) 14956 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14957 14958 // Convert the result back to a half vector. 14959 if (ConvertHalfVec) 14960 return convertVector(UO, Context.HalfTy, *this); 14961 return UO; 14962 } 14963 14964 /// Determine whether the given expression is a qualified member 14965 /// access expression, of a form that could be turned into a pointer to member 14966 /// with the address-of operator. 14967 bool Sema::isQualifiedMemberAccess(Expr *E) { 14968 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14969 if (!DRE->getQualifier()) 14970 return false; 14971 14972 ValueDecl *VD = DRE->getDecl(); 14973 if (!VD->isCXXClassMember()) 14974 return false; 14975 14976 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14977 return true; 14978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14979 return Method->isInstance(); 14980 14981 return false; 14982 } 14983 14984 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14985 if (!ULE->getQualifier()) 14986 return false; 14987 14988 for (NamedDecl *D : ULE->decls()) { 14989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14990 if (Method->isInstance()) 14991 return true; 14992 } else { 14993 // Overload set does not contain methods. 14994 break; 14995 } 14996 } 14997 14998 return false; 14999 } 15000 15001 return false; 15002 } 15003 15004 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15005 UnaryOperatorKind Opc, Expr *Input) { 15006 // First things first: handle placeholders so that the 15007 // overloaded-operator check considers the right type. 15008 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15009 // Increment and decrement of pseudo-object references. 15010 if (pty->getKind() == BuiltinType::PseudoObject && 15011 UnaryOperator::isIncrementDecrementOp(Opc)) 15012 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15013 15014 // extension is always a builtin operator. 15015 if (Opc == UO_Extension) 15016 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15017 15018 // & gets special logic for several kinds of placeholder. 15019 // The builtin code knows what to do. 15020 if (Opc == UO_AddrOf && 15021 (pty->getKind() == BuiltinType::Overload || 15022 pty->getKind() == BuiltinType::UnknownAny || 15023 pty->getKind() == BuiltinType::BoundMember)) 15024 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15025 15026 // Anything else needs to be handled now. 15027 ExprResult Result = CheckPlaceholderExpr(Input); 15028 if (Result.isInvalid()) return ExprError(); 15029 Input = Result.get(); 15030 } 15031 15032 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15033 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15034 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15035 // Find all of the overloaded operators visible from this point. 15036 UnresolvedSet<16> Functions; 15037 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15038 if (S && OverOp != OO_None) 15039 LookupOverloadedOperatorName(OverOp, S, Functions); 15040 15041 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15042 } 15043 15044 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15045 } 15046 15047 // Unary Operators. 'Tok' is the token for the operator. 15048 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15049 tok::TokenKind Op, Expr *Input) { 15050 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15051 } 15052 15053 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15054 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15055 LabelDecl *TheDecl) { 15056 TheDecl->markUsed(Context); 15057 // Create the AST node. The address of a label always has type 'void*'. 15058 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15059 Context.getPointerType(Context.VoidTy)); 15060 } 15061 15062 void Sema::ActOnStartStmtExpr() { 15063 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15064 } 15065 15066 void Sema::ActOnStmtExprError() { 15067 // Note that function is also called by TreeTransform when leaving a 15068 // StmtExpr scope without rebuilding anything. 15069 15070 DiscardCleanupsInEvaluationContext(); 15071 PopExpressionEvaluationContext(); 15072 } 15073 15074 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15075 SourceLocation RPLoc) { 15076 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15077 } 15078 15079 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15080 SourceLocation RPLoc, unsigned TemplateDepth) { 15081 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15082 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15083 15084 if (hasAnyUnrecoverableErrorsInThisFunction()) 15085 DiscardCleanupsInEvaluationContext(); 15086 assert(!Cleanup.exprNeedsCleanups() && 15087 "cleanups within StmtExpr not correctly bound!"); 15088 PopExpressionEvaluationContext(); 15089 15090 // FIXME: there are a variety of strange constraints to enforce here, for 15091 // example, it is not possible to goto into a stmt expression apparently. 15092 // More semantic analysis is needed. 15093 15094 // If there are sub-stmts in the compound stmt, take the type of the last one 15095 // as the type of the stmtexpr. 15096 QualType Ty = Context.VoidTy; 15097 bool StmtExprMayBindToTemp = false; 15098 if (!Compound->body_empty()) { 15099 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15100 if (const auto *LastStmt = 15101 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15102 if (const Expr *Value = LastStmt->getExprStmt()) { 15103 StmtExprMayBindToTemp = true; 15104 Ty = Value->getType(); 15105 } 15106 } 15107 } 15108 15109 // FIXME: Check that expression type is complete/non-abstract; statement 15110 // expressions are not lvalues. 15111 Expr *ResStmtExpr = 15112 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15113 if (StmtExprMayBindToTemp) 15114 return MaybeBindToTemporary(ResStmtExpr); 15115 return ResStmtExpr; 15116 } 15117 15118 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15119 if (ER.isInvalid()) 15120 return ExprError(); 15121 15122 // Do function/array conversion on the last expression, but not 15123 // lvalue-to-rvalue. However, initialize an unqualified type. 15124 ER = DefaultFunctionArrayConversion(ER.get()); 15125 if (ER.isInvalid()) 15126 return ExprError(); 15127 Expr *E = ER.get(); 15128 15129 if (E->isTypeDependent()) 15130 return E; 15131 15132 // In ARC, if the final expression ends in a consume, splice 15133 // the consume out and bind it later. In the alternate case 15134 // (when dealing with a retainable type), the result 15135 // initialization will create a produce. In both cases the 15136 // result will be +1, and we'll need to balance that out with 15137 // a bind. 15138 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15139 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15140 return Cast->getSubExpr(); 15141 15142 // FIXME: Provide a better location for the initialization. 15143 return PerformCopyInitialization( 15144 InitializedEntity::InitializeStmtExprResult( 15145 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15146 SourceLocation(), E); 15147 } 15148 15149 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15150 TypeSourceInfo *TInfo, 15151 ArrayRef<OffsetOfComponent> Components, 15152 SourceLocation RParenLoc) { 15153 QualType ArgTy = TInfo->getType(); 15154 bool Dependent = ArgTy->isDependentType(); 15155 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15156 15157 // We must have at least one component that refers to the type, and the first 15158 // one is known to be a field designator. Verify that the ArgTy represents 15159 // a struct/union/class. 15160 if (!Dependent && !ArgTy->isRecordType()) 15161 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15162 << ArgTy << TypeRange); 15163 15164 // Type must be complete per C99 7.17p3 because a declaring a variable 15165 // with an incomplete type would be ill-formed. 15166 if (!Dependent 15167 && RequireCompleteType(BuiltinLoc, ArgTy, 15168 diag::err_offsetof_incomplete_type, TypeRange)) 15169 return ExprError(); 15170 15171 bool DidWarnAboutNonPOD = false; 15172 QualType CurrentType = ArgTy; 15173 SmallVector<OffsetOfNode, 4> Comps; 15174 SmallVector<Expr*, 4> Exprs; 15175 for (const OffsetOfComponent &OC : Components) { 15176 if (OC.isBrackets) { 15177 // Offset of an array sub-field. TODO: Should we allow vector elements? 15178 if (!CurrentType->isDependentType()) { 15179 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15180 if(!AT) 15181 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15182 << CurrentType); 15183 CurrentType = AT->getElementType(); 15184 } else 15185 CurrentType = Context.DependentTy; 15186 15187 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15188 if (IdxRval.isInvalid()) 15189 return ExprError(); 15190 Expr *Idx = IdxRval.get(); 15191 15192 // The expression must be an integral expression. 15193 // FIXME: An integral constant expression? 15194 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15195 !Idx->getType()->isIntegerType()) 15196 return ExprError( 15197 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15198 << Idx->getSourceRange()); 15199 15200 // Record this array index. 15201 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15202 Exprs.push_back(Idx); 15203 continue; 15204 } 15205 15206 // Offset of a field. 15207 if (CurrentType->isDependentType()) { 15208 // We have the offset of a field, but we can't look into the dependent 15209 // type. Just record the identifier of the field. 15210 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15211 CurrentType = Context.DependentTy; 15212 continue; 15213 } 15214 15215 // We need to have a complete type to look into. 15216 if (RequireCompleteType(OC.LocStart, CurrentType, 15217 diag::err_offsetof_incomplete_type)) 15218 return ExprError(); 15219 15220 // Look for the designated field. 15221 const RecordType *RC = CurrentType->getAs<RecordType>(); 15222 if (!RC) 15223 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15224 << CurrentType); 15225 RecordDecl *RD = RC->getDecl(); 15226 15227 // C++ [lib.support.types]p5: 15228 // The macro offsetof accepts a restricted set of type arguments in this 15229 // International Standard. type shall be a POD structure or a POD union 15230 // (clause 9). 15231 // C++11 [support.types]p4: 15232 // If type is not a standard-layout class (Clause 9), the results are 15233 // undefined. 15234 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15235 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15236 unsigned DiagID = 15237 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15238 : diag::ext_offsetof_non_pod_type; 15239 15240 if (!IsSafe && !DidWarnAboutNonPOD && 15241 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15242 PDiag(DiagID) 15243 << SourceRange(Components[0].LocStart, OC.LocEnd) 15244 << CurrentType)) 15245 DidWarnAboutNonPOD = true; 15246 } 15247 15248 // Look for the field. 15249 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15250 LookupQualifiedName(R, RD); 15251 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15252 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15253 if (!MemberDecl) { 15254 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15255 MemberDecl = IndirectMemberDecl->getAnonField(); 15256 } 15257 15258 if (!MemberDecl) 15259 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15260 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15261 OC.LocEnd)); 15262 15263 // C99 7.17p3: 15264 // (If the specified member is a bit-field, the behavior is undefined.) 15265 // 15266 // We diagnose this as an error. 15267 if (MemberDecl->isBitField()) { 15268 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15269 << MemberDecl->getDeclName() 15270 << SourceRange(BuiltinLoc, RParenLoc); 15271 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15272 return ExprError(); 15273 } 15274 15275 RecordDecl *Parent = MemberDecl->getParent(); 15276 if (IndirectMemberDecl) 15277 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15278 15279 // If the member was found in a base class, introduce OffsetOfNodes for 15280 // the base class indirections. 15281 CXXBasePaths Paths; 15282 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15283 Paths)) { 15284 if (Paths.getDetectedVirtual()) { 15285 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15286 << MemberDecl->getDeclName() 15287 << SourceRange(BuiltinLoc, RParenLoc); 15288 return ExprError(); 15289 } 15290 15291 CXXBasePath &Path = Paths.front(); 15292 for (const CXXBasePathElement &B : Path) 15293 Comps.push_back(OffsetOfNode(B.Base)); 15294 } 15295 15296 if (IndirectMemberDecl) { 15297 for (auto *FI : IndirectMemberDecl->chain()) { 15298 assert(isa<FieldDecl>(FI)); 15299 Comps.push_back(OffsetOfNode(OC.LocStart, 15300 cast<FieldDecl>(FI), OC.LocEnd)); 15301 } 15302 } else 15303 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15304 15305 CurrentType = MemberDecl->getType().getNonReferenceType(); 15306 } 15307 15308 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15309 Comps, Exprs, RParenLoc); 15310 } 15311 15312 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15313 SourceLocation BuiltinLoc, 15314 SourceLocation TypeLoc, 15315 ParsedType ParsedArgTy, 15316 ArrayRef<OffsetOfComponent> Components, 15317 SourceLocation RParenLoc) { 15318 15319 TypeSourceInfo *ArgTInfo; 15320 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15321 if (ArgTy.isNull()) 15322 return ExprError(); 15323 15324 if (!ArgTInfo) 15325 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15326 15327 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15328 } 15329 15330 15331 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15332 Expr *CondExpr, 15333 Expr *LHSExpr, Expr *RHSExpr, 15334 SourceLocation RPLoc) { 15335 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15336 15337 ExprValueKind VK = VK_PRValue; 15338 ExprObjectKind OK = OK_Ordinary; 15339 QualType resType; 15340 bool CondIsTrue = false; 15341 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15342 resType = Context.DependentTy; 15343 } else { 15344 // The conditional expression is required to be a constant expression. 15345 llvm::APSInt condEval(32); 15346 ExprResult CondICE = VerifyIntegerConstantExpression( 15347 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15348 if (CondICE.isInvalid()) 15349 return ExprError(); 15350 CondExpr = CondICE.get(); 15351 CondIsTrue = condEval.getZExtValue(); 15352 15353 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15354 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15355 15356 resType = ActiveExpr->getType(); 15357 VK = ActiveExpr->getValueKind(); 15358 OK = ActiveExpr->getObjectKind(); 15359 } 15360 15361 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15362 resType, VK, OK, RPLoc, CondIsTrue); 15363 } 15364 15365 //===----------------------------------------------------------------------===// 15366 // Clang Extensions. 15367 //===----------------------------------------------------------------------===// 15368 15369 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15370 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15371 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15372 15373 if (LangOpts.CPlusPlus) { 15374 MangleNumberingContext *MCtx; 15375 Decl *ManglingContextDecl; 15376 std::tie(MCtx, ManglingContextDecl) = 15377 getCurrentMangleNumberContext(Block->getDeclContext()); 15378 if (MCtx) { 15379 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15380 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15381 } 15382 } 15383 15384 PushBlockScope(CurScope, Block); 15385 CurContext->addDecl(Block); 15386 if (CurScope) 15387 PushDeclContext(CurScope, Block); 15388 else 15389 CurContext = Block; 15390 15391 getCurBlock()->HasImplicitReturnType = true; 15392 15393 // Enter a new evaluation context to insulate the block from any 15394 // cleanups from the enclosing full-expression. 15395 PushExpressionEvaluationContext( 15396 ExpressionEvaluationContext::PotentiallyEvaluated); 15397 } 15398 15399 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15400 Scope *CurScope) { 15401 assert(ParamInfo.getIdentifier() == nullptr && 15402 "block-id should have no identifier!"); 15403 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15404 BlockScopeInfo *CurBlock = getCurBlock(); 15405 15406 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15407 QualType T = Sig->getType(); 15408 15409 // FIXME: We should allow unexpanded parameter packs here, but that would, 15410 // in turn, make the block expression contain unexpanded parameter packs. 15411 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15412 // Drop the parameters. 15413 FunctionProtoType::ExtProtoInfo EPI; 15414 EPI.HasTrailingReturn = false; 15415 EPI.TypeQuals.addConst(); 15416 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15417 Sig = Context.getTrivialTypeSourceInfo(T); 15418 } 15419 15420 // GetTypeForDeclarator always produces a function type for a block 15421 // literal signature. Furthermore, it is always a FunctionProtoType 15422 // unless the function was written with a typedef. 15423 assert(T->isFunctionType() && 15424 "GetTypeForDeclarator made a non-function block signature"); 15425 15426 // Look for an explicit signature in that function type. 15427 FunctionProtoTypeLoc ExplicitSignature; 15428 15429 if ((ExplicitSignature = Sig->getTypeLoc() 15430 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15431 15432 // Check whether that explicit signature was synthesized by 15433 // GetTypeForDeclarator. If so, don't save that as part of the 15434 // written signature. 15435 if (ExplicitSignature.getLocalRangeBegin() == 15436 ExplicitSignature.getLocalRangeEnd()) { 15437 // This would be much cheaper if we stored TypeLocs instead of 15438 // TypeSourceInfos. 15439 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15440 unsigned Size = Result.getFullDataSize(); 15441 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15442 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15443 15444 ExplicitSignature = FunctionProtoTypeLoc(); 15445 } 15446 } 15447 15448 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15449 CurBlock->FunctionType = T; 15450 15451 const auto *Fn = T->castAs<FunctionType>(); 15452 QualType RetTy = Fn->getReturnType(); 15453 bool isVariadic = 15454 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15455 15456 CurBlock->TheDecl->setIsVariadic(isVariadic); 15457 15458 // Context.DependentTy is used as a placeholder for a missing block 15459 // return type. TODO: what should we do with declarators like: 15460 // ^ * { ... } 15461 // If the answer is "apply template argument deduction".... 15462 if (RetTy != Context.DependentTy) { 15463 CurBlock->ReturnType = RetTy; 15464 CurBlock->TheDecl->setBlockMissingReturnType(false); 15465 CurBlock->HasImplicitReturnType = false; 15466 } 15467 15468 // Push block parameters from the declarator if we had them. 15469 SmallVector<ParmVarDecl*, 8> Params; 15470 if (ExplicitSignature) { 15471 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15472 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15473 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15474 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15475 // Diagnose this as an extension in C17 and earlier. 15476 if (!getLangOpts().C2x) 15477 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15478 } 15479 Params.push_back(Param); 15480 } 15481 15482 // Fake up parameter variables if we have a typedef, like 15483 // ^ fntype { ... } 15484 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15485 for (const auto &I : Fn->param_types()) { 15486 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15487 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15488 Params.push_back(Param); 15489 } 15490 } 15491 15492 // Set the parameters on the block decl. 15493 if (!Params.empty()) { 15494 CurBlock->TheDecl->setParams(Params); 15495 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15496 /*CheckParameterNames=*/false); 15497 } 15498 15499 // Finally we can process decl attributes. 15500 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15501 15502 // Put the parameter variables in scope. 15503 for (auto AI : CurBlock->TheDecl->parameters()) { 15504 AI->setOwningFunction(CurBlock->TheDecl); 15505 15506 // If this has an identifier, add it to the scope stack. 15507 if (AI->getIdentifier()) { 15508 CheckShadow(CurBlock->TheScope, AI); 15509 15510 PushOnScopeChains(AI, CurBlock->TheScope); 15511 } 15512 } 15513 } 15514 15515 /// ActOnBlockError - If there is an error parsing a block, this callback 15516 /// is invoked to pop the information about the block from the action impl. 15517 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15518 // Leave the expression-evaluation context. 15519 DiscardCleanupsInEvaluationContext(); 15520 PopExpressionEvaluationContext(); 15521 15522 // Pop off CurBlock, handle nested blocks. 15523 PopDeclContext(); 15524 PopFunctionScopeInfo(); 15525 } 15526 15527 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15528 /// literal was successfully completed. ^(int x){...} 15529 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15530 Stmt *Body, Scope *CurScope) { 15531 // If blocks are disabled, emit an error. 15532 if (!LangOpts.Blocks) 15533 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15534 15535 // Leave the expression-evaluation context. 15536 if (hasAnyUnrecoverableErrorsInThisFunction()) 15537 DiscardCleanupsInEvaluationContext(); 15538 assert(!Cleanup.exprNeedsCleanups() && 15539 "cleanups within block not correctly bound!"); 15540 PopExpressionEvaluationContext(); 15541 15542 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15543 BlockDecl *BD = BSI->TheDecl; 15544 15545 if (BSI->HasImplicitReturnType) 15546 deduceClosureReturnType(*BSI); 15547 15548 QualType RetTy = Context.VoidTy; 15549 if (!BSI->ReturnType.isNull()) 15550 RetTy = BSI->ReturnType; 15551 15552 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15553 QualType BlockTy; 15554 15555 // If the user wrote a function type in some form, try to use that. 15556 if (!BSI->FunctionType.isNull()) { 15557 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15558 15559 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15560 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15561 15562 // Turn protoless block types into nullary block types. 15563 if (isa<FunctionNoProtoType>(FTy)) { 15564 FunctionProtoType::ExtProtoInfo EPI; 15565 EPI.ExtInfo = Ext; 15566 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15567 15568 // Otherwise, if we don't need to change anything about the function type, 15569 // preserve its sugar structure. 15570 } else if (FTy->getReturnType() == RetTy && 15571 (!NoReturn || FTy->getNoReturnAttr())) { 15572 BlockTy = BSI->FunctionType; 15573 15574 // Otherwise, make the minimal modifications to the function type. 15575 } else { 15576 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15577 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15578 EPI.TypeQuals = Qualifiers(); 15579 EPI.ExtInfo = Ext; 15580 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15581 } 15582 15583 // If we don't have a function type, just build one from nothing. 15584 } else { 15585 FunctionProtoType::ExtProtoInfo EPI; 15586 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15587 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15588 } 15589 15590 DiagnoseUnusedParameters(BD->parameters()); 15591 BlockTy = Context.getBlockPointerType(BlockTy); 15592 15593 // If needed, diagnose invalid gotos and switches in the block. 15594 if (getCurFunction()->NeedsScopeChecking() && 15595 !PP.isCodeCompletionEnabled()) 15596 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15597 15598 BD->setBody(cast<CompoundStmt>(Body)); 15599 15600 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15601 DiagnoseUnguardedAvailabilityViolations(BD); 15602 15603 // Try to apply the named return value optimization. We have to check again 15604 // if we can do this, though, because blocks keep return statements around 15605 // to deduce an implicit return type. 15606 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15607 !BD->isDependentContext()) 15608 computeNRVO(Body, BSI); 15609 15610 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15611 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15612 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15613 NTCUK_Destruct|NTCUK_Copy); 15614 15615 PopDeclContext(); 15616 15617 // Set the captured variables on the block. 15618 SmallVector<BlockDecl::Capture, 4> Captures; 15619 for (Capture &Cap : BSI->Captures) { 15620 if (Cap.isInvalid() || Cap.isThisCapture()) 15621 continue; 15622 15623 VarDecl *Var = Cap.getVariable(); 15624 Expr *CopyExpr = nullptr; 15625 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15626 if (const RecordType *Record = 15627 Cap.getCaptureType()->getAs<RecordType>()) { 15628 // The capture logic needs the destructor, so make sure we mark it. 15629 // Usually this is unnecessary because most local variables have 15630 // their destructors marked at declaration time, but parameters are 15631 // an exception because it's technically only the call site that 15632 // actually requires the destructor. 15633 if (isa<ParmVarDecl>(Var)) 15634 FinalizeVarWithDestructor(Var, Record); 15635 15636 // Enter a separate potentially-evaluated context while building block 15637 // initializers to isolate their cleanups from those of the block 15638 // itself. 15639 // FIXME: Is this appropriate even when the block itself occurs in an 15640 // unevaluated operand? 15641 EnterExpressionEvaluationContext EvalContext( 15642 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15643 15644 SourceLocation Loc = Cap.getLocation(); 15645 15646 ExprResult Result = BuildDeclarationNameExpr( 15647 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15648 15649 // According to the blocks spec, the capture of a variable from 15650 // the stack requires a const copy constructor. This is not true 15651 // of the copy/move done to move a __block variable to the heap. 15652 if (!Result.isInvalid() && 15653 !Result.get()->getType().isConstQualified()) { 15654 Result = ImpCastExprToType(Result.get(), 15655 Result.get()->getType().withConst(), 15656 CK_NoOp, VK_LValue); 15657 } 15658 15659 if (!Result.isInvalid()) { 15660 Result = PerformCopyInitialization( 15661 InitializedEntity::InitializeBlock(Var->getLocation(), 15662 Cap.getCaptureType(), false), 15663 Loc, Result.get()); 15664 } 15665 15666 // Build a full-expression copy expression if initialization 15667 // succeeded and used a non-trivial constructor. Recover from 15668 // errors by pretending that the copy isn't necessary. 15669 if (!Result.isInvalid() && 15670 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15671 ->isTrivial()) { 15672 Result = MaybeCreateExprWithCleanups(Result); 15673 CopyExpr = Result.get(); 15674 } 15675 } 15676 } 15677 15678 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15679 CopyExpr); 15680 Captures.push_back(NewCap); 15681 } 15682 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15683 15684 // Pop the block scope now but keep it alive to the end of this function. 15685 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15686 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15687 15688 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15689 15690 // If the block isn't obviously global, i.e. it captures anything at 15691 // all, then we need to do a few things in the surrounding context: 15692 if (Result->getBlockDecl()->hasCaptures()) { 15693 // First, this expression has a new cleanup object. 15694 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15695 Cleanup.setExprNeedsCleanups(true); 15696 15697 // It also gets a branch-protected scope if any of the captured 15698 // variables needs destruction. 15699 for (const auto &CI : Result->getBlockDecl()->captures()) { 15700 const VarDecl *var = CI.getVariable(); 15701 if (var->getType().isDestructedType() != QualType::DK_none) { 15702 setFunctionHasBranchProtectedScope(); 15703 break; 15704 } 15705 } 15706 } 15707 15708 if (getCurFunction()) 15709 getCurFunction()->addBlock(BD); 15710 15711 return Result; 15712 } 15713 15714 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15715 SourceLocation RPLoc) { 15716 TypeSourceInfo *TInfo; 15717 GetTypeFromParser(Ty, &TInfo); 15718 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15719 } 15720 15721 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15722 Expr *E, TypeSourceInfo *TInfo, 15723 SourceLocation RPLoc) { 15724 Expr *OrigExpr = E; 15725 bool IsMS = false; 15726 15727 // CUDA device code does not support varargs. 15728 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15729 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15730 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15731 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15732 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15733 } 15734 } 15735 15736 // NVPTX does not support va_arg expression. 15737 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15738 Context.getTargetInfo().getTriple().isNVPTX()) 15739 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15740 15741 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15742 // as Microsoft ABI on an actual Microsoft platform, where 15743 // __builtin_ms_va_list and __builtin_va_list are the same.) 15744 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15745 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15746 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15747 if (Context.hasSameType(MSVaListType, E->getType())) { 15748 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15749 return ExprError(); 15750 IsMS = true; 15751 } 15752 } 15753 15754 // Get the va_list type 15755 QualType VaListType = Context.getBuiltinVaListType(); 15756 if (!IsMS) { 15757 if (VaListType->isArrayType()) { 15758 // Deal with implicit array decay; for example, on x86-64, 15759 // va_list is an array, but it's supposed to decay to 15760 // a pointer for va_arg. 15761 VaListType = Context.getArrayDecayedType(VaListType); 15762 // Make sure the input expression also decays appropriately. 15763 ExprResult Result = UsualUnaryConversions(E); 15764 if (Result.isInvalid()) 15765 return ExprError(); 15766 E = Result.get(); 15767 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15768 // If va_list is a record type and we are compiling in C++ mode, 15769 // check the argument using reference binding. 15770 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15771 Context, Context.getLValueReferenceType(VaListType), false); 15772 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15773 if (Init.isInvalid()) 15774 return ExprError(); 15775 E = Init.getAs<Expr>(); 15776 } else { 15777 // Otherwise, the va_list argument must be an l-value because 15778 // it is modified by va_arg. 15779 if (!E->isTypeDependent() && 15780 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15781 return ExprError(); 15782 } 15783 } 15784 15785 if (!IsMS && !E->isTypeDependent() && 15786 !Context.hasSameType(VaListType, E->getType())) 15787 return ExprError( 15788 Diag(E->getBeginLoc(), 15789 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15790 << OrigExpr->getType() << E->getSourceRange()); 15791 15792 if (!TInfo->getType()->isDependentType()) { 15793 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15794 diag::err_second_parameter_to_va_arg_incomplete, 15795 TInfo->getTypeLoc())) 15796 return ExprError(); 15797 15798 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15799 TInfo->getType(), 15800 diag::err_second_parameter_to_va_arg_abstract, 15801 TInfo->getTypeLoc())) 15802 return ExprError(); 15803 15804 if (!TInfo->getType().isPODType(Context)) { 15805 Diag(TInfo->getTypeLoc().getBeginLoc(), 15806 TInfo->getType()->isObjCLifetimeType() 15807 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15808 : diag::warn_second_parameter_to_va_arg_not_pod) 15809 << TInfo->getType() 15810 << TInfo->getTypeLoc().getSourceRange(); 15811 } 15812 15813 // Check for va_arg where arguments of the given type will be promoted 15814 // (i.e. this va_arg is guaranteed to have undefined behavior). 15815 QualType PromoteType; 15816 if (TInfo->getType()->isPromotableIntegerType()) { 15817 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15818 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15819 // and C2x 7.16.1.1p2 says, in part: 15820 // If type is not compatible with the type of the actual next argument 15821 // (as promoted according to the default argument promotions), the 15822 // behavior is undefined, except for the following cases: 15823 // - both types are pointers to qualified or unqualified versions of 15824 // compatible types; 15825 // - one type is a signed integer type, the other type is the 15826 // corresponding unsigned integer type, and the value is 15827 // representable in both types; 15828 // - one type is pointer to qualified or unqualified void and the 15829 // other is a pointer to a qualified or unqualified character type. 15830 // Given that type compatibility is the primary requirement (ignoring 15831 // qualifications), you would think we could call typesAreCompatible() 15832 // directly to test this. However, in C++, that checks for *same type*, 15833 // which causes false positives when passing an enumeration type to 15834 // va_arg. Instead, get the underlying type of the enumeration and pass 15835 // that. 15836 QualType UnderlyingType = TInfo->getType(); 15837 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15838 UnderlyingType = ET->getDecl()->getIntegerType(); 15839 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15840 /*CompareUnqualified*/ true)) 15841 PromoteType = QualType(); 15842 15843 // If the types are still not compatible, we need to test whether the 15844 // promoted type and the underlying type are the same except for 15845 // signedness. Ask the AST for the correctly corresponding type and see 15846 // if that's compatible. 15847 if (!PromoteType.isNull() && 15848 PromoteType->isUnsignedIntegerType() != 15849 UnderlyingType->isUnsignedIntegerType()) { 15850 UnderlyingType = 15851 UnderlyingType->isUnsignedIntegerType() 15852 ? Context.getCorrespondingSignedType(UnderlyingType) 15853 : Context.getCorrespondingUnsignedType(UnderlyingType); 15854 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15855 /*CompareUnqualified*/ true)) 15856 PromoteType = QualType(); 15857 } 15858 } 15859 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15860 PromoteType = Context.DoubleTy; 15861 if (!PromoteType.isNull()) 15862 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15863 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15864 << TInfo->getType() 15865 << PromoteType 15866 << TInfo->getTypeLoc().getSourceRange()); 15867 } 15868 15869 QualType T = TInfo->getType().getNonLValueExprType(Context); 15870 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15871 } 15872 15873 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15874 // The type of __null will be int or long, depending on the size of 15875 // pointers on the target. 15876 QualType Ty; 15877 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15878 if (pw == Context.getTargetInfo().getIntWidth()) 15879 Ty = Context.IntTy; 15880 else if (pw == Context.getTargetInfo().getLongWidth()) 15881 Ty = Context.LongTy; 15882 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15883 Ty = Context.LongLongTy; 15884 else { 15885 llvm_unreachable("I don't know size of pointer!"); 15886 } 15887 15888 return new (Context) GNUNullExpr(Ty, TokenLoc); 15889 } 15890 15891 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15892 SourceLocation BuiltinLoc, 15893 SourceLocation RPLoc) { 15894 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15895 } 15896 15897 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15898 SourceLocation BuiltinLoc, 15899 SourceLocation RPLoc, 15900 DeclContext *ParentContext) { 15901 return new (Context) 15902 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15903 } 15904 15905 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15906 bool Diagnose) { 15907 if (!getLangOpts().ObjC) 15908 return false; 15909 15910 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15911 if (!PT) 15912 return false; 15913 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15914 15915 // Ignore any parens, implicit casts (should only be 15916 // array-to-pointer decays), and not-so-opaque values. The last is 15917 // important for making this trigger for property assignments. 15918 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15919 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15920 if (OV->getSourceExpr()) 15921 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15922 15923 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15924 if (!PT->isObjCIdType() && 15925 !(ID && ID->getIdentifier()->isStr("NSString"))) 15926 return false; 15927 if (!SL->isAscii()) 15928 return false; 15929 15930 if (Diagnose) { 15931 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15932 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15933 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15934 } 15935 return true; 15936 } 15937 15938 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15939 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15940 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15941 !SrcExpr->isNullPointerConstant( 15942 getASTContext(), Expr::NPC_NeverValueDependent)) { 15943 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15944 return false; 15945 if (Diagnose) { 15946 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15947 << /*number*/1 15948 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15949 Expr *NumLit = 15950 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15951 if (NumLit) 15952 Exp = NumLit; 15953 } 15954 return true; 15955 } 15956 15957 return false; 15958 } 15959 15960 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15961 const Expr *SrcExpr) { 15962 if (!DstType->isFunctionPointerType() || 15963 !SrcExpr->getType()->isFunctionType()) 15964 return false; 15965 15966 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15967 if (!DRE) 15968 return false; 15969 15970 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15971 if (!FD) 15972 return false; 15973 15974 return !S.checkAddressOfFunctionIsAvailable(FD, 15975 /*Complain=*/true, 15976 SrcExpr->getBeginLoc()); 15977 } 15978 15979 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15980 SourceLocation Loc, 15981 QualType DstType, QualType SrcType, 15982 Expr *SrcExpr, AssignmentAction Action, 15983 bool *Complained) { 15984 if (Complained) 15985 *Complained = false; 15986 15987 // Decode the result (notice that AST's are still created for extensions). 15988 bool CheckInferredResultType = false; 15989 bool isInvalid = false; 15990 unsigned DiagKind = 0; 15991 ConversionFixItGenerator ConvHints; 15992 bool MayHaveConvFixit = false; 15993 bool MayHaveFunctionDiff = false; 15994 const ObjCInterfaceDecl *IFace = nullptr; 15995 const ObjCProtocolDecl *PDecl = nullptr; 15996 15997 switch (ConvTy) { 15998 case Compatible: 15999 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16000 return false; 16001 16002 case PointerToInt: 16003 if (getLangOpts().CPlusPlus) { 16004 DiagKind = diag::err_typecheck_convert_pointer_int; 16005 isInvalid = true; 16006 } else { 16007 DiagKind = diag::ext_typecheck_convert_pointer_int; 16008 } 16009 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16010 MayHaveConvFixit = true; 16011 break; 16012 case IntToPointer: 16013 if (getLangOpts().CPlusPlus) { 16014 DiagKind = diag::err_typecheck_convert_int_pointer; 16015 isInvalid = true; 16016 } else { 16017 DiagKind = diag::ext_typecheck_convert_int_pointer; 16018 } 16019 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16020 MayHaveConvFixit = true; 16021 break; 16022 case IncompatibleFunctionPointer: 16023 if (getLangOpts().CPlusPlus) { 16024 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16025 isInvalid = true; 16026 } else { 16027 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16028 } 16029 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16030 MayHaveConvFixit = true; 16031 break; 16032 case IncompatiblePointer: 16033 if (Action == AA_Passing_CFAudited) { 16034 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16035 } else if (getLangOpts().CPlusPlus) { 16036 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16037 isInvalid = true; 16038 } else { 16039 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16040 } 16041 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16042 SrcType->isObjCObjectPointerType(); 16043 if (!CheckInferredResultType) { 16044 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16045 } else if (CheckInferredResultType) { 16046 SrcType = SrcType.getUnqualifiedType(); 16047 DstType = DstType.getUnqualifiedType(); 16048 } 16049 MayHaveConvFixit = true; 16050 break; 16051 case IncompatiblePointerSign: 16052 if (getLangOpts().CPlusPlus) { 16053 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16054 isInvalid = true; 16055 } else { 16056 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16057 } 16058 break; 16059 case FunctionVoidPointer: 16060 if (getLangOpts().CPlusPlus) { 16061 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16062 isInvalid = true; 16063 } else { 16064 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16065 } 16066 break; 16067 case IncompatiblePointerDiscardsQualifiers: { 16068 // Perform array-to-pointer decay if necessary. 16069 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16070 16071 isInvalid = true; 16072 16073 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16074 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16075 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16076 DiagKind = diag::err_typecheck_incompatible_address_space; 16077 break; 16078 16079 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16080 DiagKind = diag::err_typecheck_incompatible_ownership; 16081 break; 16082 } 16083 16084 llvm_unreachable("unknown error case for discarding qualifiers!"); 16085 // fallthrough 16086 } 16087 case CompatiblePointerDiscardsQualifiers: 16088 // If the qualifiers lost were because we were applying the 16089 // (deprecated) C++ conversion from a string literal to a char* 16090 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16091 // Ideally, this check would be performed in 16092 // checkPointerTypesForAssignment. However, that would require a 16093 // bit of refactoring (so that the second argument is an 16094 // expression, rather than a type), which should be done as part 16095 // of a larger effort to fix checkPointerTypesForAssignment for 16096 // C++ semantics. 16097 if (getLangOpts().CPlusPlus && 16098 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16099 return false; 16100 if (getLangOpts().CPlusPlus) { 16101 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16102 isInvalid = true; 16103 } else { 16104 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16105 } 16106 16107 break; 16108 case IncompatibleNestedPointerQualifiers: 16109 if (getLangOpts().CPlusPlus) { 16110 isInvalid = true; 16111 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16112 } else { 16113 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16114 } 16115 break; 16116 case IncompatibleNestedPointerAddressSpaceMismatch: 16117 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16118 isInvalid = true; 16119 break; 16120 case IntToBlockPointer: 16121 DiagKind = diag::err_int_to_block_pointer; 16122 isInvalid = true; 16123 break; 16124 case IncompatibleBlockPointer: 16125 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16126 isInvalid = true; 16127 break; 16128 case IncompatibleObjCQualifiedId: { 16129 if (SrcType->isObjCQualifiedIdType()) { 16130 const ObjCObjectPointerType *srcOPT = 16131 SrcType->castAs<ObjCObjectPointerType>(); 16132 for (auto *srcProto : srcOPT->quals()) { 16133 PDecl = srcProto; 16134 break; 16135 } 16136 if (const ObjCInterfaceType *IFaceT = 16137 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16138 IFace = IFaceT->getDecl(); 16139 } 16140 else if (DstType->isObjCQualifiedIdType()) { 16141 const ObjCObjectPointerType *dstOPT = 16142 DstType->castAs<ObjCObjectPointerType>(); 16143 for (auto *dstProto : dstOPT->quals()) { 16144 PDecl = dstProto; 16145 break; 16146 } 16147 if (const ObjCInterfaceType *IFaceT = 16148 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16149 IFace = IFaceT->getDecl(); 16150 } 16151 if (getLangOpts().CPlusPlus) { 16152 DiagKind = diag::err_incompatible_qualified_id; 16153 isInvalid = true; 16154 } else { 16155 DiagKind = diag::warn_incompatible_qualified_id; 16156 } 16157 break; 16158 } 16159 case IncompatibleVectors: 16160 if (getLangOpts().CPlusPlus) { 16161 DiagKind = diag::err_incompatible_vectors; 16162 isInvalid = true; 16163 } else { 16164 DiagKind = diag::warn_incompatible_vectors; 16165 } 16166 break; 16167 case IncompatibleObjCWeakRef: 16168 DiagKind = diag::err_arc_weak_unavailable_assign; 16169 isInvalid = true; 16170 break; 16171 case Incompatible: 16172 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16173 if (Complained) 16174 *Complained = true; 16175 return true; 16176 } 16177 16178 DiagKind = diag::err_typecheck_convert_incompatible; 16179 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16180 MayHaveConvFixit = true; 16181 isInvalid = true; 16182 MayHaveFunctionDiff = true; 16183 break; 16184 } 16185 16186 QualType FirstType, SecondType; 16187 switch (Action) { 16188 case AA_Assigning: 16189 case AA_Initializing: 16190 // The destination type comes first. 16191 FirstType = DstType; 16192 SecondType = SrcType; 16193 break; 16194 16195 case AA_Returning: 16196 case AA_Passing: 16197 case AA_Passing_CFAudited: 16198 case AA_Converting: 16199 case AA_Sending: 16200 case AA_Casting: 16201 // The source type comes first. 16202 FirstType = SrcType; 16203 SecondType = DstType; 16204 break; 16205 } 16206 16207 PartialDiagnostic FDiag = PDiag(DiagKind); 16208 if (Action == AA_Passing_CFAudited) 16209 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16210 else 16211 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16212 16213 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16214 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16215 auto isPlainChar = [](const clang::Type *Type) { 16216 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16217 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16218 }; 16219 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16220 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16221 } 16222 16223 // If we can fix the conversion, suggest the FixIts. 16224 if (!ConvHints.isNull()) { 16225 for (FixItHint &H : ConvHints.Hints) 16226 FDiag << H; 16227 } 16228 16229 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16230 16231 if (MayHaveFunctionDiff) 16232 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16233 16234 Diag(Loc, FDiag); 16235 if ((DiagKind == diag::warn_incompatible_qualified_id || 16236 DiagKind == diag::err_incompatible_qualified_id) && 16237 PDecl && IFace && !IFace->hasDefinition()) 16238 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16239 << IFace << PDecl; 16240 16241 if (SecondType == Context.OverloadTy) 16242 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16243 FirstType, /*TakingAddress=*/true); 16244 16245 if (CheckInferredResultType) 16246 EmitRelatedResultTypeNote(SrcExpr); 16247 16248 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16249 EmitRelatedResultTypeNoteForReturn(DstType); 16250 16251 if (Complained) 16252 *Complained = true; 16253 return isInvalid; 16254 } 16255 16256 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16257 llvm::APSInt *Result, 16258 AllowFoldKind CanFold) { 16259 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16260 public: 16261 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16262 QualType T) override { 16263 return S.Diag(Loc, diag::err_ice_not_integral) 16264 << T << S.LangOpts.CPlusPlus; 16265 } 16266 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16267 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16268 } 16269 } Diagnoser; 16270 16271 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16272 } 16273 16274 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16275 llvm::APSInt *Result, 16276 unsigned DiagID, 16277 AllowFoldKind CanFold) { 16278 class IDDiagnoser : public VerifyICEDiagnoser { 16279 unsigned DiagID; 16280 16281 public: 16282 IDDiagnoser(unsigned DiagID) 16283 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16284 16285 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16286 return S.Diag(Loc, DiagID); 16287 } 16288 } Diagnoser(DiagID); 16289 16290 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16291 } 16292 16293 Sema::SemaDiagnosticBuilder 16294 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16295 QualType T) { 16296 return diagnoseNotICE(S, Loc); 16297 } 16298 16299 Sema::SemaDiagnosticBuilder 16300 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16301 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16302 } 16303 16304 ExprResult 16305 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16306 VerifyICEDiagnoser &Diagnoser, 16307 AllowFoldKind CanFold) { 16308 SourceLocation DiagLoc = E->getBeginLoc(); 16309 16310 if (getLangOpts().CPlusPlus11) { 16311 // C++11 [expr.const]p5: 16312 // If an expression of literal class type is used in a context where an 16313 // integral constant expression is required, then that class type shall 16314 // have a single non-explicit conversion function to an integral or 16315 // unscoped enumeration type 16316 ExprResult Converted; 16317 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16318 VerifyICEDiagnoser &BaseDiagnoser; 16319 public: 16320 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16321 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16322 BaseDiagnoser.Suppress, true), 16323 BaseDiagnoser(BaseDiagnoser) {} 16324 16325 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16326 QualType T) override { 16327 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16328 } 16329 16330 SemaDiagnosticBuilder diagnoseIncomplete( 16331 Sema &S, SourceLocation Loc, QualType T) override { 16332 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16333 } 16334 16335 SemaDiagnosticBuilder diagnoseExplicitConv( 16336 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16337 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16338 } 16339 16340 SemaDiagnosticBuilder noteExplicitConv( 16341 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16342 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16343 << ConvTy->isEnumeralType() << ConvTy; 16344 } 16345 16346 SemaDiagnosticBuilder diagnoseAmbiguous( 16347 Sema &S, SourceLocation Loc, QualType T) override { 16348 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16349 } 16350 16351 SemaDiagnosticBuilder noteAmbiguous( 16352 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16353 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16354 << ConvTy->isEnumeralType() << ConvTy; 16355 } 16356 16357 SemaDiagnosticBuilder diagnoseConversion( 16358 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16359 llvm_unreachable("conversion functions are permitted"); 16360 } 16361 } ConvertDiagnoser(Diagnoser); 16362 16363 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16364 ConvertDiagnoser); 16365 if (Converted.isInvalid()) 16366 return Converted; 16367 E = Converted.get(); 16368 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16369 return ExprError(); 16370 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16371 // An ICE must be of integral or unscoped enumeration type. 16372 if (!Diagnoser.Suppress) 16373 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16374 << E->getSourceRange(); 16375 return ExprError(); 16376 } 16377 16378 ExprResult RValueExpr = DefaultLvalueConversion(E); 16379 if (RValueExpr.isInvalid()) 16380 return ExprError(); 16381 16382 E = RValueExpr.get(); 16383 16384 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16385 // in the non-ICE case. 16386 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16387 if (Result) 16388 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16389 if (!isa<ConstantExpr>(E)) 16390 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16391 : ConstantExpr::Create(Context, E); 16392 return E; 16393 } 16394 16395 Expr::EvalResult EvalResult; 16396 SmallVector<PartialDiagnosticAt, 8> Notes; 16397 EvalResult.Diag = &Notes; 16398 16399 // Try to evaluate the expression, and produce diagnostics explaining why it's 16400 // not a constant expression as a side-effect. 16401 bool Folded = 16402 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16403 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16404 16405 if (!isa<ConstantExpr>(E)) 16406 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16407 16408 // In C++11, we can rely on diagnostics being produced for any expression 16409 // which is not a constant expression. If no diagnostics were produced, then 16410 // this is a constant expression. 16411 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16412 if (Result) 16413 *Result = EvalResult.Val.getInt(); 16414 return E; 16415 } 16416 16417 // If our only note is the usual "invalid subexpression" note, just point 16418 // the caret at its location rather than producing an essentially 16419 // redundant note. 16420 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16421 diag::note_invalid_subexpr_in_const_expr) { 16422 DiagLoc = Notes[0].first; 16423 Notes.clear(); 16424 } 16425 16426 if (!Folded || !CanFold) { 16427 if (!Diagnoser.Suppress) { 16428 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16429 for (const PartialDiagnosticAt &Note : Notes) 16430 Diag(Note.first, Note.second); 16431 } 16432 16433 return ExprError(); 16434 } 16435 16436 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16437 for (const PartialDiagnosticAt &Note : Notes) 16438 Diag(Note.first, Note.second); 16439 16440 if (Result) 16441 *Result = EvalResult.Val.getInt(); 16442 return E; 16443 } 16444 16445 namespace { 16446 // Handle the case where we conclude a expression which we speculatively 16447 // considered to be unevaluated is actually evaluated. 16448 class TransformToPE : public TreeTransform<TransformToPE> { 16449 typedef TreeTransform<TransformToPE> BaseTransform; 16450 16451 public: 16452 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16453 16454 // Make sure we redo semantic analysis 16455 bool AlwaysRebuild() { return true; } 16456 bool ReplacingOriginal() { return true; } 16457 16458 // We need to special-case DeclRefExprs referring to FieldDecls which 16459 // are not part of a member pointer formation; normal TreeTransforming 16460 // doesn't catch this case because of the way we represent them in the AST. 16461 // FIXME: This is a bit ugly; is it really the best way to handle this 16462 // case? 16463 // 16464 // Error on DeclRefExprs referring to FieldDecls. 16465 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16466 if (isa<FieldDecl>(E->getDecl()) && 16467 !SemaRef.isUnevaluatedContext()) 16468 return SemaRef.Diag(E->getLocation(), 16469 diag::err_invalid_non_static_member_use) 16470 << E->getDecl() << E->getSourceRange(); 16471 16472 return BaseTransform::TransformDeclRefExpr(E); 16473 } 16474 16475 // Exception: filter out member pointer formation 16476 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16477 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16478 return E; 16479 16480 return BaseTransform::TransformUnaryOperator(E); 16481 } 16482 16483 // The body of a lambda-expression is in a separate expression evaluation 16484 // context so never needs to be transformed. 16485 // FIXME: Ideally we wouldn't transform the closure type either, and would 16486 // just recreate the capture expressions and lambda expression. 16487 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16488 return SkipLambdaBody(E, Body); 16489 } 16490 }; 16491 } 16492 16493 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16494 assert(isUnevaluatedContext() && 16495 "Should only transform unevaluated expressions"); 16496 ExprEvalContexts.back().Context = 16497 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16498 if (isUnevaluatedContext()) 16499 return E; 16500 return TransformToPE(*this).TransformExpr(E); 16501 } 16502 16503 void 16504 Sema::PushExpressionEvaluationContext( 16505 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16506 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16507 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16508 LambdaContextDecl, ExprContext); 16509 Cleanup.reset(); 16510 if (!MaybeODRUseExprs.empty()) 16511 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16512 } 16513 16514 void 16515 Sema::PushExpressionEvaluationContext( 16516 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16517 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16518 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16519 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16520 } 16521 16522 namespace { 16523 16524 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16525 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16526 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16527 if (E->getOpcode() == UO_Deref) 16528 return CheckPossibleDeref(S, E->getSubExpr()); 16529 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16530 return CheckPossibleDeref(S, E->getBase()); 16531 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16532 return CheckPossibleDeref(S, E->getBase()); 16533 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16534 QualType Inner; 16535 QualType Ty = E->getType(); 16536 if (const auto *Ptr = Ty->getAs<PointerType>()) 16537 Inner = Ptr->getPointeeType(); 16538 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16539 Inner = Arr->getElementType(); 16540 else 16541 return nullptr; 16542 16543 if (Inner->hasAttr(attr::NoDeref)) 16544 return E; 16545 } 16546 return nullptr; 16547 } 16548 16549 } // namespace 16550 16551 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16552 for (const Expr *E : Rec.PossibleDerefs) { 16553 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16554 if (DeclRef) { 16555 const ValueDecl *Decl = DeclRef->getDecl(); 16556 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16557 << Decl->getName() << E->getSourceRange(); 16558 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16559 } else { 16560 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16561 << E->getSourceRange(); 16562 } 16563 } 16564 Rec.PossibleDerefs.clear(); 16565 } 16566 16567 /// Check whether E, which is either a discarded-value expression or an 16568 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16569 /// and if so, remove it from the list of volatile-qualified assignments that 16570 /// we are going to warn are deprecated. 16571 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16572 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16573 return; 16574 16575 // Note: ignoring parens here is not justified by the standard rules, but 16576 // ignoring parentheses seems like a more reasonable approach, and this only 16577 // drives a deprecation warning so doesn't affect conformance. 16578 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16579 if (BO->getOpcode() == BO_Assign) { 16580 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16581 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16582 LHSs.end()); 16583 } 16584 } 16585 } 16586 16587 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16588 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16589 RebuildingImmediateInvocation) 16590 return E; 16591 16592 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16593 /// It's OK if this fails; we'll also remove this in 16594 /// HandleImmediateInvocations, but catching it here allows us to avoid 16595 /// walking the AST looking for it in simple cases. 16596 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16597 if (auto *DeclRef = 16598 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16599 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16600 16601 E = MaybeCreateExprWithCleanups(E); 16602 16603 ConstantExpr *Res = ConstantExpr::Create( 16604 getASTContext(), E.get(), 16605 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16606 getASTContext()), 16607 /*IsImmediateInvocation*/ true); 16608 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16609 return Res; 16610 } 16611 16612 static void EvaluateAndDiagnoseImmediateInvocation( 16613 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16614 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16615 Expr::EvalResult Eval; 16616 Eval.Diag = &Notes; 16617 ConstantExpr *CE = Candidate.getPointer(); 16618 bool Result = CE->EvaluateAsConstantExpr( 16619 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16620 if (!Result || !Notes.empty()) { 16621 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16622 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16623 InnerExpr = FunctionalCast->getSubExpr(); 16624 FunctionDecl *FD = nullptr; 16625 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16626 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16627 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16628 FD = Call->getConstructor(); 16629 else 16630 llvm_unreachable("unhandled decl kind"); 16631 assert(FD->isConsteval()); 16632 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16633 for (auto &Note : Notes) 16634 SemaRef.Diag(Note.first, Note.second); 16635 return; 16636 } 16637 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16638 } 16639 16640 static void RemoveNestedImmediateInvocation( 16641 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16642 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16643 struct ComplexRemove : TreeTransform<ComplexRemove> { 16644 using Base = TreeTransform<ComplexRemove>; 16645 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16646 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16647 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16648 CurrentII; 16649 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16650 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16651 SmallVector<Sema::ImmediateInvocationCandidate, 16652 4>::reverse_iterator Current) 16653 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16654 void RemoveImmediateInvocation(ConstantExpr* E) { 16655 auto It = std::find_if(CurrentII, IISet.rend(), 16656 [E](Sema::ImmediateInvocationCandidate Elem) { 16657 return Elem.getPointer() == E; 16658 }); 16659 assert(It != IISet.rend() && 16660 "ConstantExpr marked IsImmediateInvocation should " 16661 "be present"); 16662 It->setInt(1); // Mark as deleted 16663 } 16664 ExprResult TransformConstantExpr(ConstantExpr *E) { 16665 if (!E->isImmediateInvocation()) 16666 return Base::TransformConstantExpr(E); 16667 RemoveImmediateInvocation(E); 16668 return Base::TransformExpr(E->getSubExpr()); 16669 } 16670 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16671 /// we need to remove its DeclRefExpr from the DRSet. 16672 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16673 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16674 return Base::TransformCXXOperatorCallExpr(E); 16675 } 16676 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16677 /// here. 16678 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16679 if (!Init) 16680 return Init; 16681 /// ConstantExpr are the first layer of implicit node to be removed so if 16682 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16683 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16684 if (CE->isImmediateInvocation()) 16685 RemoveImmediateInvocation(CE); 16686 return Base::TransformInitializer(Init, NotCopyInit); 16687 } 16688 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16689 DRSet.erase(E); 16690 return E; 16691 } 16692 bool AlwaysRebuild() { return false; } 16693 bool ReplacingOriginal() { return true; } 16694 bool AllowSkippingCXXConstructExpr() { 16695 bool Res = AllowSkippingFirstCXXConstructExpr; 16696 AllowSkippingFirstCXXConstructExpr = true; 16697 return Res; 16698 } 16699 bool AllowSkippingFirstCXXConstructExpr = true; 16700 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16701 Rec.ImmediateInvocationCandidates, It); 16702 16703 /// CXXConstructExpr with a single argument are getting skipped by 16704 /// TreeTransform in some situtation because they could be implicit. This 16705 /// can only occur for the top-level CXXConstructExpr because it is used 16706 /// nowhere in the expression being transformed therefore will not be rebuilt. 16707 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16708 /// skipping the first CXXConstructExpr. 16709 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16710 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16711 16712 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16713 assert(Res.isUsable()); 16714 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16715 It->getPointer()->setSubExpr(Res.get()); 16716 } 16717 16718 static void 16719 HandleImmediateInvocations(Sema &SemaRef, 16720 Sema::ExpressionEvaluationContextRecord &Rec) { 16721 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16722 Rec.ReferenceToConsteval.size() == 0) || 16723 SemaRef.RebuildingImmediateInvocation) 16724 return; 16725 16726 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16727 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16728 /// need to remove ReferenceToConsteval in the immediate invocation. 16729 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16730 16731 /// Prevent sema calls during the tree transform from adding pointers that 16732 /// are already in the sets. 16733 llvm::SaveAndRestore<bool> DisableIITracking( 16734 SemaRef.RebuildingImmediateInvocation, true); 16735 16736 /// Prevent diagnostic during tree transfrom as they are duplicates 16737 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16738 16739 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16740 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16741 if (!It->getInt()) 16742 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16743 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16744 Rec.ReferenceToConsteval.size()) { 16745 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16746 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16747 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16748 bool VisitDeclRefExpr(DeclRefExpr *E) { 16749 DRSet.erase(E); 16750 return DRSet.size(); 16751 } 16752 } Visitor(Rec.ReferenceToConsteval); 16753 Visitor.TraverseStmt( 16754 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16755 } 16756 for (auto CE : Rec.ImmediateInvocationCandidates) 16757 if (!CE.getInt()) 16758 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16759 for (auto DR : Rec.ReferenceToConsteval) { 16760 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16761 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16762 << FD; 16763 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16764 } 16765 } 16766 16767 void Sema::PopExpressionEvaluationContext() { 16768 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16769 unsigned NumTypos = Rec.NumTypos; 16770 16771 if (!Rec.Lambdas.empty()) { 16772 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16773 if (!getLangOpts().CPlusPlus20 && 16774 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16775 Rec.isUnevaluated() || 16776 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16777 unsigned D; 16778 if (Rec.isUnevaluated()) { 16779 // C++11 [expr.prim.lambda]p2: 16780 // A lambda-expression shall not appear in an unevaluated operand 16781 // (Clause 5). 16782 D = diag::err_lambda_unevaluated_operand; 16783 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16784 // C++1y [expr.const]p2: 16785 // A conditional-expression e is a core constant expression unless the 16786 // evaluation of e, following the rules of the abstract machine, would 16787 // evaluate [...] a lambda-expression. 16788 D = diag::err_lambda_in_constant_expression; 16789 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16790 // C++17 [expr.prim.lamda]p2: 16791 // A lambda-expression shall not appear [...] in a template-argument. 16792 D = diag::err_lambda_in_invalid_context; 16793 } else 16794 llvm_unreachable("Couldn't infer lambda error message."); 16795 16796 for (const auto *L : Rec.Lambdas) 16797 Diag(L->getBeginLoc(), D); 16798 } 16799 } 16800 16801 WarnOnPendingNoDerefs(Rec); 16802 HandleImmediateInvocations(*this, Rec); 16803 16804 // Warn on any volatile-qualified simple-assignments that are not discarded- 16805 // value expressions nor unevaluated operands (those cases get removed from 16806 // this list by CheckUnusedVolatileAssignment). 16807 for (auto *BO : Rec.VolatileAssignmentLHSs) 16808 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16809 << BO->getType(); 16810 16811 // When are coming out of an unevaluated context, clear out any 16812 // temporaries that we may have created as part of the evaluation of 16813 // the expression in that context: they aren't relevant because they 16814 // will never be constructed. 16815 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16816 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16817 ExprCleanupObjects.end()); 16818 Cleanup = Rec.ParentCleanup; 16819 CleanupVarDeclMarking(); 16820 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16821 // Otherwise, merge the contexts together. 16822 } else { 16823 Cleanup.mergeFrom(Rec.ParentCleanup); 16824 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16825 Rec.SavedMaybeODRUseExprs.end()); 16826 } 16827 16828 // Pop the current expression evaluation context off the stack. 16829 ExprEvalContexts.pop_back(); 16830 16831 // The global expression evaluation context record is never popped. 16832 ExprEvalContexts.back().NumTypos += NumTypos; 16833 } 16834 16835 void Sema::DiscardCleanupsInEvaluationContext() { 16836 ExprCleanupObjects.erase( 16837 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16838 ExprCleanupObjects.end()); 16839 Cleanup.reset(); 16840 MaybeODRUseExprs.clear(); 16841 } 16842 16843 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16844 ExprResult Result = CheckPlaceholderExpr(E); 16845 if (Result.isInvalid()) 16846 return ExprError(); 16847 E = Result.get(); 16848 if (!E->getType()->isVariablyModifiedType()) 16849 return E; 16850 return TransformToPotentiallyEvaluated(E); 16851 } 16852 16853 /// Are we in a context that is potentially constant evaluated per C++20 16854 /// [expr.const]p12? 16855 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16856 /// C++2a [expr.const]p12: 16857 // An expression or conversion is potentially constant evaluated if it is 16858 switch (SemaRef.ExprEvalContexts.back().Context) { 16859 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16860 // -- a manifestly constant-evaluated expression, 16861 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16862 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16863 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16864 // -- a potentially-evaluated expression, 16865 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16866 // -- an immediate subexpression of a braced-init-list, 16867 16868 // -- [FIXME] an expression of the form & cast-expression that occurs 16869 // within a templated entity 16870 // -- a subexpression of one of the above that is not a subexpression of 16871 // a nested unevaluated operand. 16872 return true; 16873 16874 case Sema::ExpressionEvaluationContext::Unevaluated: 16875 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16876 // Expressions in this context are never evaluated. 16877 return false; 16878 } 16879 llvm_unreachable("Invalid context"); 16880 } 16881 16882 /// Return true if this function has a calling convention that requires mangling 16883 /// in the size of the parameter pack. 16884 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16885 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16886 // we don't need parameter type sizes. 16887 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16888 if (!TT.isOSWindows() || !TT.isX86()) 16889 return false; 16890 16891 // If this is C++ and this isn't an extern "C" function, parameters do not 16892 // need to be complete. In this case, C++ mangling will apply, which doesn't 16893 // use the size of the parameters. 16894 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16895 return false; 16896 16897 // Stdcall, fastcall, and vectorcall need this special treatment. 16898 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16899 switch (CC) { 16900 case CC_X86StdCall: 16901 case CC_X86FastCall: 16902 case CC_X86VectorCall: 16903 return true; 16904 default: 16905 break; 16906 } 16907 return false; 16908 } 16909 16910 /// Require that all of the parameter types of function be complete. Normally, 16911 /// parameter types are only required to be complete when a function is called 16912 /// or defined, but to mangle functions with certain calling conventions, the 16913 /// mangler needs to know the size of the parameter list. In this situation, 16914 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16915 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16916 /// result in a linker error. Clang doesn't implement this behavior, and instead 16917 /// attempts to error at compile time. 16918 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16919 SourceLocation Loc) { 16920 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16921 FunctionDecl *FD; 16922 ParmVarDecl *Param; 16923 16924 public: 16925 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16926 : FD(FD), Param(Param) {} 16927 16928 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16929 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16930 StringRef CCName; 16931 switch (CC) { 16932 case CC_X86StdCall: 16933 CCName = "stdcall"; 16934 break; 16935 case CC_X86FastCall: 16936 CCName = "fastcall"; 16937 break; 16938 case CC_X86VectorCall: 16939 CCName = "vectorcall"; 16940 break; 16941 default: 16942 llvm_unreachable("CC does not need mangling"); 16943 } 16944 16945 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16946 << Param->getDeclName() << FD->getDeclName() << CCName; 16947 } 16948 }; 16949 16950 for (ParmVarDecl *Param : FD->parameters()) { 16951 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16952 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16953 } 16954 } 16955 16956 namespace { 16957 enum class OdrUseContext { 16958 /// Declarations in this context are not odr-used. 16959 None, 16960 /// Declarations in this context are formally odr-used, but this is a 16961 /// dependent context. 16962 Dependent, 16963 /// Declarations in this context are odr-used but not actually used (yet). 16964 FormallyOdrUsed, 16965 /// Declarations in this context are used. 16966 Used 16967 }; 16968 } 16969 16970 /// Are we within a context in which references to resolved functions or to 16971 /// variables result in odr-use? 16972 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16973 OdrUseContext Result; 16974 16975 switch (SemaRef.ExprEvalContexts.back().Context) { 16976 case Sema::ExpressionEvaluationContext::Unevaluated: 16977 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16978 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16979 return OdrUseContext::None; 16980 16981 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16982 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16983 Result = OdrUseContext::Used; 16984 break; 16985 16986 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16987 Result = OdrUseContext::FormallyOdrUsed; 16988 break; 16989 16990 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16991 // A default argument formally results in odr-use, but doesn't actually 16992 // result in a use in any real sense until it itself is used. 16993 Result = OdrUseContext::FormallyOdrUsed; 16994 break; 16995 } 16996 16997 if (SemaRef.CurContext->isDependentContext()) 16998 return OdrUseContext::Dependent; 16999 17000 return Result; 17001 } 17002 17003 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17004 if (!Func->isConstexpr()) 17005 return false; 17006 17007 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17008 return true; 17009 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17010 return CCD && CCD->getInheritedConstructor(); 17011 } 17012 17013 /// Mark a function referenced, and check whether it is odr-used 17014 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17015 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17016 bool MightBeOdrUse) { 17017 assert(Func && "No function?"); 17018 17019 Func->setReferenced(); 17020 17021 // Recursive functions aren't really used until they're used from some other 17022 // context. 17023 bool IsRecursiveCall = CurContext == Func; 17024 17025 // C++11 [basic.def.odr]p3: 17026 // A function whose name appears as a potentially-evaluated expression is 17027 // odr-used if it is the unique lookup result or the selected member of a 17028 // set of overloaded functions [...]. 17029 // 17030 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17031 // can just check that here. 17032 OdrUseContext OdrUse = 17033 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17034 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17035 OdrUse = OdrUseContext::FormallyOdrUsed; 17036 17037 // Trivial default constructors and destructors are never actually used. 17038 // FIXME: What about other special members? 17039 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17040 OdrUse == OdrUseContext::Used) { 17041 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17042 if (Constructor->isDefaultConstructor()) 17043 OdrUse = OdrUseContext::FormallyOdrUsed; 17044 if (isa<CXXDestructorDecl>(Func)) 17045 OdrUse = OdrUseContext::FormallyOdrUsed; 17046 } 17047 17048 // C++20 [expr.const]p12: 17049 // A function [...] is needed for constant evaluation if it is [...] a 17050 // constexpr function that is named by an expression that is potentially 17051 // constant evaluated 17052 bool NeededForConstantEvaluation = 17053 isPotentiallyConstantEvaluatedContext(*this) && 17054 isImplicitlyDefinableConstexprFunction(Func); 17055 17056 // Determine whether we require a function definition to exist, per 17057 // C++11 [temp.inst]p3: 17058 // Unless a function template specialization has been explicitly 17059 // instantiated or explicitly specialized, the function template 17060 // specialization is implicitly instantiated when the specialization is 17061 // referenced in a context that requires a function definition to exist. 17062 // C++20 [temp.inst]p7: 17063 // The existence of a definition of a [...] function is considered to 17064 // affect the semantics of the program if the [...] function is needed for 17065 // constant evaluation by an expression 17066 // C++20 [basic.def.odr]p10: 17067 // Every program shall contain exactly one definition of every non-inline 17068 // function or variable that is odr-used in that program outside of a 17069 // discarded statement 17070 // C++20 [special]p1: 17071 // The implementation will implicitly define [defaulted special members] 17072 // if they are odr-used or needed for constant evaluation. 17073 // 17074 // Note that we skip the implicit instantiation of templates that are only 17075 // used in unused default arguments or by recursive calls to themselves. 17076 // This is formally non-conforming, but seems reasonable in practice. 17077 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17078 NeededForConstantEvaluation); 17079 17080 // C++14 [temp.expl.spec]p6: 17081 // If a template [...] is explicitly specialized then that specialization 17082 // shall be declared before the first use of that specialization that would 17083 // cause an implicit instantiation to take place, in every translation unit 17084 // in which such a use occurs 17085 if (NeedDefinition && 17086 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17087 Func->getMemberSpecializationInfo())) 17088 checkSpecializationVisibility(Loc, Func); 17089 17090 if (getLangOpts().CUDA) 17091 CheckCUDACall(Loc, Func); 17092 17093 if (getLangOpts().SYCLIsDevice) 17094 checkSYCLDeviceFunction(Loc, Func); 17095 17096 // If we need a definition, try to create one. 17097 if (NeedDefinition && !Func->getBody()) { 17098 runWithSufficientStackSpace(Loc, [&] { 17099 if (CXXConstructorDecl *Constructor = 17100 dyn_cast<CXXConstructorDecl>(Func)) { 17101 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17102 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17103 if (Constructor->isDefaultConstructor()) { 17104 if (Constructor->isTrivial() && 17105 !Constructor->hasAttr<DLLExportAttr>()) 17106 return; 17107 DefineImplicitDefaultConstructor(Loc, Constructor); 17108 } else if (Constructor->isCopyConstructor()) { 17109 DefineImplicitCopyConstructor(Loc, Constructor); 17110 } else if (Constructor->isMoveConstructor()) { 17111 DefineImplicitMoveConstructor(Loc, Constructor); 17112 } 17113 } else if (Constructor->getInheritedConstructor()) { 17114 DefineInheritingConstructor(Loc, Constructor); 17115 } 17116 } else if (CXXDestructorDecl *Destructor = 17117 dyn_cast<CXXDestructorDecl>(Func)) { 17118 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17119 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17120 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17121 return; 17122 DefineImplicitDestructor(Loc, Destructor); 17123 } 17124 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17125 MarkVTableUsed(Loc, Destructor->getParent()); 17126 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17127 if (MethodDecl->isOverloadedOperator() && 17128 MethodDecl->getOverloadedOperator() == OO_Equal) { 17129 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17130 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17131 if (MethodDecl->isCopyAssignmentOperator()) 17132 DefineImplicitCopyAssignment(Loc, MethodDecl); 17133 else if (MethodDecl->isMoveAssignmentOperator()) 17134 DefineImplicitMoveAssignment(Loc, MethodDecl); 17135 } 17136 } else if (isa<CXXConversionDecl>(MethodDecl) && 17137 MethodDecl->getParent()->isLambda()) { 17138 CXXConversionDecl *Conversion = 17139 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17140 if (Conversion->isLambdaToBlockPointerConversion()) 17141 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17142 else 17143 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17144 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17145 MarkVTableUsed(Loc, MethodDecl->getParent()); 17146 } 17147 17148 if (Func->isDefaulted() && !Func->isDeleted()) { 17149 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17150 if (DCK != DefaultedComparisonKind::None) 17151 DefineDefaultedComparison(Loc, Func, DCK); 17152 } 17153 17154 // Implicit instantiation of function templates and member functions of 17155 // class templates. 17156 if (Func->isImplicitlyInstantiable()) { 17157 TemplateSpecializationKind TSK = 17158 Func->getTemplateSpecializationKindForInstantiation(); 17159 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17160 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17161 if (FirstInstantiation) { 17162 PointOfInstantiation = Loc; 17163 if (auto *MSI = Func->getMemberSpecializationInfo()) 17164 MSI->setPointOfInstantiation(Loc); 17165 // FIXME: Notify listener. 17166 else 17167 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17168 } else if (TSK != TSK_ImplicitInstantiation) { 17169 // Use the point of use as the point of instantiation, instead of the 17170 // point of explicit instantiation (which we track as the actual point 17171 // of instantiation). This gives better backtraces in diagnostics. 17172 PointOfInstantiation = Loc; 17173 } 17174 17175 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17176 Func->isConstexpr()) { 17177 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17178 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17179 CodeSynthesisContexts.size()) 17180 PendingLocalImplicitInstantiations.push_back( 17181 std::make_pair(Func, PointOfInstantiation)); 17182 else if (Func->isConstexpr()) 17183 // Do not defer instantiations of constexpr functions, to avoid the 17184 // expression evaluator needing to call back into Sema if it sees a 17185 // call to such a function. 17186 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17187 else { 17188 Func->setInstantiationIsPending(true); 17189 PendingInstantiations.push_back( 17190 std::make_pair(Func, PointOfInstantiation)); 17191 // Notify the consumer that a function was implicitly instantiated. 17192 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17193 } 17194 } 17195 } else { 17196 // Walk redefinitions, as some of them may be instantiable. 17197 for (auto i : Func->redecls()) { 17198 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17199 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17200 } 17201 } 17202 }); 17203 } 17204 17205 // C++14 [except.spec]p17: 17206 // An exception-specification is considered to be needed when: 17207 // - the function is odr-used or, if it appears in an unevaluated operand, 17208 // would be odr-used if the expression were potentially-evaluated; 17209 // 17210 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17211 // function is a pure virtual function we're calling, and in that case the 17212 // function was selected by overload resolution and we need to resolve its 17213 // exception specification for a different reason. 17214 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17215 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17216 ResolveExceptionSpec(Loc, FPT); 17217 17218 // If this is the first "real" use, act on that. 17219 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17220 // Keep track of used but undefined functions. 17221 if (!Func->isDefined()) { 17222 if (mightHaveNonExternalLinkage(Func)) 17223 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17224 else if (Func->getMostRecentDecl()->isInlined() && 17225 !LangOpts.GNUInline && 17226 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17227 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17228 else if (isExternalWithNoLinkageType(Func)) 17229 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17230 } 17231 17232 // Some x86 Windows calling conventions mangle the size of the parameter 17233 // pack into the name. Computing the size of the parameters requires the 17234 // parameter types to be complete. Check that now. 17235 if (funcHasParameterSizeMangling(*this, Func)) 17236 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17237 17238 // In the MS C++ ABI, the compiler emits destructor variants where they are 17239 // used. If the destructor is used here but defined elsewhere, mark the 17240 // virtual base destructors referenced. If those virtual base destructors 17241 // are inline, this will ensure they are defined when emitting the complete 17242 // destructor variant. This checking may be redundant if the destructor is 17243 // provided later in this TU. 17244 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17245 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17246 CXXRecordDecl *Parent = Dtor->getParent(); 17247 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17248 CheckCompleteDestructorVariant(Loc, Dtor); 17249 } 17250 } 17251 17252 Func->markUsed(Context); 17253 } 17254 } 17255 17256 /// Directly mark a variable odr-used. Given a choice, prefer to use 17257 /// MarkVariableReferenced since it does additional checks and then 17258 /// calls MarkVarDeclODRUsed. 17259 /// If the variable must be captured: 17260 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17261 /// - else capture it in the DeclContext that maps to the 17262 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17263 static void 17264 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17265 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17266 // Keep track of used but undefined variables. 17267 // FIXME: We shouldn't suppress this warning for static data members. 17268 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17269 (!Var->isExternallyVisible() || Var->isInline() || 17270 SemaRef.isExternalWithNoLinkageType(Var)) && 17271 !(Var->isStaticDataMember() && Var->hasInit())) { 17272 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17273 if (old.isInvalid()) 17274 old = Loc; 17275 } 17276 QualType CaptureType, DeclRefType; 17277 if (SemaRef.LangOpts.OpenMP) 17278 SemaRef.tryCaptureOpenMPLambdas(Var); 17279 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17280 /*EllipsisLoc*/ SourceLocation(), 17281 /*BuildAndDiagnose*/ true, 17282 CaptureType, DeclRefType, 17283 FunctionScopeIndexToStopAt); 17284 17285 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17286 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17287 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17288 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17289 if (VarTarget == Sema::CVT_Host && 17290 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17291 UserTarget == Sema::CFT_Global)) { 17292 // Diagnose ODR-use of host global variables in device functions. 17293 // Reference of device global variables in host functions is allowed 17294 // through shadow variables therefore it is not diagnosed. 17295 if (SemaRef.LangOpts.CUDAIsDevice) { 17296 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17297 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17298 SemaRef.targetDiag(Var->getLocation(), 17299 Var->getType().isConstQualified() 17300 ? diag::note_cuda_const_var_unpromoted 17301 : diag::note_cuda_host_var); 17302 } 17303 } else if (VarTarget == Sema::CVT_Device && 17304 (UserTarget == Sema::CFT_Host || 17305 UserTarget == Sema::CFT_HostDevice) && 17306 !Var->hasExternalStorage()) { 17307 // Record a CUDA/HIP device side variable if it is ODR-used 17308 // by host code. This is done conservatively, when the variable is 17309 // referenced in any of the following contexts: 17310 // - a non-function context 17311 // - a host function 17312 // - a host device function 17313 // This makes the ODR-use of the device side variable by host code to 17314 // be visible in the device compilation for the compiler to be able to 17315 // emit template variables instantiated by host code only and to 17316 // externalize the static device side variable ODR-used by host code. 17317 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17318 } 17319 } 17320 17321 Var->markUsed(SemaRef.Context); 17322 } 17323 17324 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17325 SourceLocation Loc, 17326 unsigned CapturingScopeIndex) { 17327 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17328 } 17329 17330 static void 17331 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17332 ValueDecl *var, DeclContext *DC) { 17333 DeclContext *VarDC = var->getDeclContext(); 17334 17335 // If the parameter still belongs to the translation unit, then 17336 // we're actually just using one parameter in the declaration of 17337 // the next. 17338 if (isa<ParmVarDecl>(var) && 17339 isa<TranslationUnitDecl>(VarDC)) 17340 return; 17341 17342 // For C code, don't diagnose about capture if we're not actually in code 17343 // right now; it's impossible to write a non-constant expression outside of 17344 // function context, so we'll get other (more useful) diagnostics later. 17345 // 17346 // For C++, things get a bit more nasty... it would be nice to suppress this 17347 // diagnostic for certain cases like using a local variable in an array bound 17348 // for a member of a local class, but the correct predicate is not obvious. 17349 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17350 return; 17351 17352 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17353 unsigned ContextKind = 3; // unknown 17354 if (isa<CXXMethodDecl>(VarDC) && 17355 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17356 ContextKind = 2; 17357 } else if (isa<FunctionDecl>(VarDC)) { 17358 ContextKind = 0; 17359 } else if (isa<BlockDecl>(VarDC)) { 17360 ContextKind = 1; 17361 } 17362 17363 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17364 << var << ValueKind << ContextKind << VarDC; 17365 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17366 << var; 17367 17368 // FIXME: Add additional diagnostic info about class etc. which prevents 17369 // capture. 17370 } 17371 17372 17373 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17374 bool &SubCapturesAreNested, 17375 QualType &CaptureType, 17376 QualType &DeclRefType) { 17377 // Check whether we've already captured it. 17378 if (CSI->CaptureMap.count(Var)) { 17379 // If we found a capture, any subcaptures are nested. 17380 SubCapturesAreNested = true; 17381 17382 // Retrieve the capture type for this variable. 17383 CaptureType = CSI->getCapture(Var).getCaptureType(); 17384 17385 // Compute the type of an expression that refers to this variable. 17386 DeclRefType = CaptureType.getNonReferenceType(); 17387 17388 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17389 // are mutable in the sense that user can change their value - they are 17390 // private instances of the captured declarations. 17391 const Capture &Cap = CSI->getCapture(Var); 17392 if (Cap.isCopyCapture() && 17393 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17394 !(isa<CapturedRegionScopeInfo>(CSI) && 17395 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17396 DeclRefType.addConst(); 17397 return true; 17398 } 17399 return false; 17400 } 17401 17402 // Only block literals, captured statements, and lambda expressions can 17403 // capture; other scopes don't work. 17404 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17405 SourceLocation Loc, 17406 const bool Diagnose, Sema &S) { 17407 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17408 return getLambdaAwareParentOfDeclContext(DC); 17409 else if (Var->hasLocalStorage()) { 17410 if (Diagnose) 17411 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17412 } 17413 return nullptr; 17414 } 17415 17416 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17417 // certain types of variables (unnamed, variably modified types etc.) 17418 // so check for eligibility. 17419 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17420 SourceLocation Loc, 17421 const bool Diagnose, Sema &S) { 17422 17423 bool IsBlock = isa<BlockScopeInfo>(CSI); 17424 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17425 17426 // Lambdas are not allowed to capture unnamed variables 17427 // (e.g. anonymous unions). 17428 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17429 // assuming that's the intent. 17430 if (IsLambda && !Var->getDeclName()) { 17431 if (Diagnose) { 17432 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17433 S.Diag(Var->getLocation(), diag::note_declared_at); 17434 } 17435 return false; 17436 } 17437 17438 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17439 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17440 if (Diagnose) { 17441 S.Diag(Loc, diag::err_ref_vm_type); 17442 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17443 } 17444 return false; 17445 } 17446 // Prohibit structs with flexible array members too. 17447 // We cannot capture what is in the tail end of the struct. 17448 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17449 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17450 if (Diagnose) { 17451 if (IsBlock) 17452 S.Diag(Loc, diag::err_ref_flexarray_type); 17453 else 17454 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17455 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17456 } 17457 return false; 17458 } 17459 } 17460 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17461 // Lambdas and captured statements are not allowed to capture __block 17462 // variables; they don't support the expected semantics. 17463 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17464 if (Diagnose) { 17465 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17466 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17467 } 17468 return false; 17469 } 17470 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17471 if (S.getLangOpts().OpenCL && IsBlock && 17472 Var->getType()->isBlockPointerType()) { 17473 if (Diagnose) 17474 S.Diag(Loc, diag::err_opencl_block_ref_block); 17475 return false; 17476 } 17477 17478 return true; 17479 } 17480 17481 // Returns true if the capture by block was successful. 17482 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17483 SourceLocation Loc, 17484 const bool BuildAndDiagnose, 17485 QualType &CaptureType, 17486 QualType &DeclRefType, 17487 const bool Nested, 17488 Sema &S, bool Invalid) { 17489 bool ByRef = false; 17490 17491 // Blocks are not allowed to capture arrays, excepting OpenCL. 17492 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17493 // (decayed to pointers). 17494 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17495 if (BuildAndDiagnose) { 17496 S.Diag(Loc, diag::err_ref_array_type); 17497 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17498 Invalid = true; 17499 } else { 17500 return false; 17501 } 17502 } 17503 17504 // Forbid the block-capture of autoreleasing variables. 17505 if (!Invalid && 17506 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17507 if (BuildAndDiagnose) { 17508 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17509 << /*block*/ 0; 17510 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17511 Invalid = true; 17512 } else { 17513 return false; 17514 } 17515 } 17516 17517 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17518 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17519 QualType PointeeTy = PT->getPointeeType(); 17520 17521 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17522 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17523 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17524 if (BuildAndDiagnose) { 17525 SourceLocation VarLoc = Var->getLocation(); 17526 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17527 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17528 } 17529 } 17530 } 17531 17532 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17533 if (HasBlocksAttr || CaptureType->isReferenceType() || 17534 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17535 // Block capture by reference does not change the capture or 17536 // declaration reference types. 17537 ByRef = true; 17538 } else { 17539 // Block capture by copy introduces 'const'. 17540 CaptureType = CaptureType.getNonReferenceType().withConst(); 17541 DeclRefType = CaptureType; 17542 } 17543 17544 // Actually capture the variable. 17545 if (BuildAndDiagnose) 17546 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17547 CaptureType, Invalid); 17548 17549 return !Invalid; 17550 } 17551 17552 17553 /// Capture the given variable in the captured region. 17554 static bool captureInCapturedRegion( 17555 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17556 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17557 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17558 bool IsTopScope, Sema &S, bool Invalid) { 17559 // By default, capture variables by reference. 17560 bool ByRef = true; 17561 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17562 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17563 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17564 // Using an LValue reference type is consistent with Lambdas (see below). 17565 if (S.isOpenMPCapturedDecl(Var)) { 17566 bool HasConst = DeclRefType.isConstQualified(); 17567 DeclRefType = DeclRefType.getUnqualifiedType(); 17568 // Don't lose diagnostics about assignments to const. 17569 if (HasConst) 17570 DeclRefType.addConst(); 17571 } 17572 // Do not capture firstprivates in tasks. 17573 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17574 OMPC_unknown) 17575 return true; 17576 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17577 RSI->OpenMPCaptureLevel); 17578 } 17579 17580 if (ByRef) 17581 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17582 else 17583 CaptureType = DeclRefType; 17584 17585 // Actually capture the variable. 17586 if (BuildAndDiagnose) 17587 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17588 Loc, SourceLocation(), CaptureType, Invalid); 17589 17590 return !Invalid; 17591 } 17592 17593 /// Capture the given variable in the lambda. 17594 static bool captureInLambda(LambdaScopeInfo *LSI, 17595 VarDecl *Var, 17596 SourceLocation Loc, 17597 const bool BuildAndDiagnose, 17598 QualType &CaptureType, 17599 QualType &DeclRefType, 17600 const bool RefersToCapturedVariable, 17601 const Sema::TryCaptureKind Kind, 17602 SourceLocation EllipsisLoc, 17603 const bool IsTopScope, 17604 Sema &S, bool Invalid) { 17605 // Determine whether we are capturing by reference or by value. 17606 bool ByRef = false; 17607 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17608 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17609 } else { 17610 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17611 } 17612 17613 // Compute the type of the field that will capture this variable. 17614 if (ByRef) { 17615 // C++11 [expr.prim.lambda]p15: 17616 // An entity is captured by reference if it is implicitly or 17617 // explicitly captured but not captured by copy. It is 17618 // unspecified whether additional unnamed non-static data 17619 // members are declared in the closure type for entities 17620 // captured by reference. 17621 // 17622 // FIXME: It is not clear whether we want to build an lvalue reference 17623 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17624 // to do the former, while EDG does the latter. Core issue 1249 will 17625 // clarify, but for now we follow GCC because it's a more permissive and 17626 // easily defensible position. 17627 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17628 } else { 17629 // C++11 [expr.prim.lambda]p14: 17630 // For each entity captured by copy, an unnamed non-static 17631 // data member is declared in the closure type. The 17632 // declaration order of these members is unspecified. The type 17633 // of such a data member is the type of the corresponding 17634 // captured entity if the entity is not a reference to an 17635 // object, or the referenced type otherwise. [Note: If the 17636 // captured entity is a reference to a function, the 17637 // corresponding data member is also a reference to a 17638 // function. - end note ] 17639 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17640 if (!RefType->getPointeeType()->isFunctionType()) 17641 CaptureType = RefType->getPointeeType(); 17642 } 17643 17644 // Forbid the lambda copy-capture of autoreleasing variables. 17645 if (!Invalid && 17646 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17647 if (BuildAndDiagnose) { 17648 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17649 S.Diag(Var->getLocation(), diag::note_previous_decl) 17650 << Var->getDeclName(); 17651 Invalid = true; 17652 } else { 17653 return false; 17654 } 17655 } 17656 17657 // Make sure that by-copy captures are of a complete and non-abstract type. 17658 if (!Invalid && BuildAndDiagnose) { 17659 if (!CaptureType->isDependentType() && 17660 S.RequireCompleteSizedType( 17661 Loc, CaptureType, 17662 diag::err_capture_of_incomplete_or_sizeless_type, 17663 Var->getDeclName())) 17664 Invalid = true; 17665 else if (S.RequireNonAbstractType(Loc, CaptureType, 17666 diag::err_capture_of_abstract_type)) 17667 Invalid = true; 17668 } 17669 } 17670 17671 // Compute the type of a reference to this captured variable. 17672 if (ByRef) 17673 DeclRefType = CaptureType.getNonReferenceType(); 17674 else { 17675 // C++ [expr.prim.lambda]p5: 17676 // The closure type for a lambda-expression has a public inline 17677 // function call operator [...]. This function call operator is 17678 // declared const (9.3.1) if and only if the lambda-expression's 17679 // parameter-declaration-clause is not followed by mutable. 17680 DeclRefType = CaptureType.getNonReferenceType(); 17681 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17682 DeclRefType.addConst(); 17683 } 17684 17685 // Add the capture. 17686 if (BuildAndDiagnose) 17687 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17688 Loc, EllipsisLoc, CaptureType, Invalid); 17689 17690 return !Invalid; 17691 } 17692 17693 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17694 // Offer a Copy fix even if the type is dependent. 17695 if (Var->getType()->isDependentType()) 17696 return true; 17697 QualType T = Var->getType().getNonReferenceType(); 17698 if (T.isTriviallyCopyableType(Context)) 17699 return true; 17700 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17701 17702 if (!(RD = RD->getDefinition())) 17703 return false; 17704 if (RD->hasSimpleCopyConstructor()) 17705 return true; 17706 if (RD->hasUserDeclaredCopyConstructor()) 17707 for (CXXConstructorDecl *Ctor : RD->ctors()) 17708 if (Ctor->isCopyConstructor()) 17709 return !Ctor->isDeleted(); 17710 } 17711 return false; 17712 } 17713 17714 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17715 /// default capture. Fixes may be omitted if they aren't allowed by the 17716 /// standard, for example we can't emit a default copy capture fix-it if we 17717 /// already explicitly copy capture capture another variable. 17718 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17719 VarDecl *Var) { 17720 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17721 // Don't offer Capture by copy of default capture by copy fixes if Var is 17722 // known not to be copy constructible. 17723 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17724 17725 SmallString<32> FixBuffer; 17726 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17727 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17728 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17729 if (ShouldOfferCopyFix) { 17730 // Offer fixes to insert an explicit capture for the variable. 17731 // [] -> [VarName] 17732 // [OtherCapture] -> [OtherCapture, VarName] 17733 FixBuffer.assign({Separator, Var->getName()}); 17734 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17735 << Var << /*value*/ 0 17736 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17737 } 17738 // As above but capture by reference. 17739 FixBuffer.assign({Separator, "&", Var->getName()}); 17740 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17741 << Var << /*reference*/ 1 17742 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17743 } 17744 17745 // Only try to offer default capture if there are no captures excluding this 17746 // and init captures. 17747 // [this]: OK. 17748 // [X = Y]: OK. 17749 // [&A, &B]: Don't offer. 17750 // [A, B]: Don't offer. 17751 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17752 return !C.isThisCapture() && !C.isInitCapture(); 17753 })) 17754 return; 17755 17756 // The default capture specifiers, '=' or '&', must appear first in the 17757 // capture body. 17758 SourceLocation DefaultInsertLoc = 17759 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17760 17761 if (ShouldOfferCopyFix) { 17762 bool CanDefaultCopyCapture = true; 17763 // [=, *this] OK since c++17 17764 // [=, this] OK since c++20 17765 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17766 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17767 ? LSI->getCXXThisCapture().isCopyCapture() 17768 : false; 17769 // We can't use default capture by copy if any captures already specified 17770 // capture by copy. 17771 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17772 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17773 })) { 17774 FixBuffer.assign({"=", Separator}); 17775 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17776 << /*value*/ 0 17777 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17778 } 17779 } 17780 17781 // We can't use default capture by reference if any captures already specified 17782 // capture by reference. 17783 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17784 return !C.isInitCapture() && C.isReferenceCapture() && 17785 !C.isThisCapture(); 17786 })) { 17787 FixBuffer.assign({"&", Separator}); 17788 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17789 << /*reference*/ 1 17790 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17791 } 17792 } 17793 17794 bool Sema::tryCaptureVariable( 17795 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17796 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17797 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17798 // An init-capture is notionally from the context surrounding its 17799 // declaration, but its parent DC is the lambda class. 17800 DeclContext *VarDC = Var->getDeclContext(); 17801 if (Var->isInitCapture()) 17802 VarDC = VarDC->getParent(); 17803 17804 DeclContext *DC = CurContext; 17805 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17806 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17807 // We need to sync up the Declaration Context with the 17808 // FunctionScopeIndexToStopAt 17809 if (FunctionScopeIndexToStopAt) { 17810 unsigned FSIndex = FunctionScopes.size() - 1; 17811 while (FSIndex != MaxFunctionScopesIndex) { 17812 DC = getLambdaAwareParentOfDeclContext(DC); 17813 --FSIndex; 17814 } 17815 } 17816 17817 17818 // If the variable is declared in the current context, there is no need to 17819 // capture it. 17820 if (VarDC == DC) return true; 17821 17822 // Capture global variables if it is required to use private copy of this 17823 // variable. 17824 bool IsGlobal = !Var->hasLocalStorage(); 17825 if (IsGlobal && 17826 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17827 MaxFunctionScopesIndex))) 17828 return true; 17829 Var = Var->getCanonicalDecl(); 17830 17831 // Walk up the stack to determine whether we can capture the variable, 17832 // performing the "simple" checks that don't depend on type. We stop when 17833 // we've either hit the declared scope of the variable or find an existing 17834 // capture of that variable. We start from the innermost capturing-entity 17835 // (the DC) and ensure that all intervening capturing-entities 17836 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17837 // declcontext can either capture the variable or have already captured 17838 // the variable. 17839 CaptureType = Var->getType(); 17840 DeclRefType = CaptureType.getNonReferenceType(); 17841 bool Nested = false; 17842 bool Explicit = (Kind != TryCapture_Implicit); 17843 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17844 do { 17845 // Only block literals, captured statements, and lambda expressions can 17846 // capture; other scopes don't work. 17847 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17848 ExprLoc, 17849 BuildAndDiagnose, 17850 *this); 17851 // We need to check for the parent *first* because, if we *have* 17852 // private-captured a global variable, we need to recursively capture it in 17853 // intermediate blocks, lambdas, etc. 17854 if (!ParentDC) { 17855 if (IsGlobal) { 17856 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17857 break; 17858 } 17859 return true; 17860 } 17861 17862 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17863 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17864 17865 17866 // Check whether we've already captured it. 17867 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17868 DeclRefType)) { 17869 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17870 break; 17871 } 17872 // If we are instantiating a generic lambda call operator body, 17873 // we do not want to capture new variables. What was captured 17874 // during either a lambdas transformation or initial parsing 17875 // should be used. 17876 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17877 if (BuildAndDiagnose) { 17878 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17879 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17880 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17881 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17882 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17883 buildLambdaCaptureFixit(*this, LSI, Var); 17884 } else 17885 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17886 } 17887 return true; 17888 } 17889 17890 // Try to capture variable-length arrays types. 17891 if (Var->getType()->isVariablyModifiedType()) { 17892 // We're going to walk down into the type and look for VLA 17893 // expressions. 17894 QualType QTy = Var->getType(); 17895 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17896 QTy = PVD->getOriginalType(); 17897 captureVariablyModifiedType(Context, QTy, CSI); 17898 } 17899 17900 if (getLangOpts().OpenMP) { 17901 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17902 // OpenMP private variables should not be captured in outer scope, so 17903 // just break here. Similarly, global variables that are captured in a 17904 // target region should not be captured outside the scope of the region. 17905 if (RSI->CapRegionKind == CR_OpenMP) { 17906 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17907 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17908 // If the variable is private (i.e. not captured) and has variably 17909 // modified type, we still need to capture the type for correct 17910 // codegen in all regions, associated with the construct. Currently, 17911 // it is captured in the innermost captured region only. 17912 if (IsOpenMPPrivateDecl != OMPC_unknown && 17913 Var->getType()->isVariablyModifiedType()) { 17914 QualType QTy = Var->getType(); 17915 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17916 QTy = PVD->getOriginalType(); 17917 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17918 I < E; ++I) { 17919 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17920 FunctionScopes[FunctionScopesIndex - I]); 17921 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17922 "Wrong number of captured regions associated with the " 17923 "OpenMP construct."); 17924 captureVariablyModifiedType(Context, QTy, OuterRSI); 17925 } 17926 } 17927 bool IsTargetCap = 17928 IsOpenMPPrivateDecl != OMPC_private && 17929 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17930 RSI->OpenMPCaptureLevel); 17931 // Do not capture global if it is not privatized in outer regions. 17932 bool IsGlobalCap = 17933 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17934 RSI->OpenMPCaptureLevel); 17935 17936 // When we detect target captures we are looking from inside the 17937 // target region, therefore we need to propagate the capture from the 17938 // enclosing region. Therefore, the capture is not initially nested. 17939 if (IsTargetCap) 17940 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17941 17942 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17943 (IsGlobal && !IsGlobalCap)) { 17944 Nested = !IsTargetCap; 17945 bool HasConst = DeclRefType.isConstQualified(); 17946 DeclRefType = DeclRefType.getUnqualifiedType(); 17947 // Don't lose diagnostics about assignments to const. 17948 if (HasConst) 17949 DeclRefType.addConst(); 17950 CaptureType = Context.getLValueReferenceType(DeclRefType); 17951 break; 17952 } 17953 } 17954 } 17955 } 17956 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17957 // No capture-default, and this is not an explicit capture 17958 // so cannot capture this variable. 17959 if (BuildAndDiagnose) { 17960 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17961 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17962 auto *LSI = cast<LambdaScopeInfo>(CSI); 17963 if (LSI->Lambda) { 17964 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17965 buildLambdaCaptureFixit(*this, LSI, Var); 17966 } 17967 // FIXME: If we error out because an outer lambda can not implicitly 17968 // capture a variable that an inner lambda explicitly captures, we 17969 // should have the inner lambda do the explicit capture - because 17970 // it makes for cleaner diagnostics later. This would purely be done 17971 // so that the diagnostic does not misleadingly claim that a variable 17972 // can not be captured by a lambda implicitly even though it is captured 17973 // explicitly. Suggestion: 17974 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17975 // at the function head 17976 // - cache the StartingDeclContext - this must be a lambda 17977 // - captureInLambda in the innermost lambda the variable. 17978 } 17979 return true; 17980 } 17981 17982 FunctionScopesIndex--; 17983 DC = ParentDC; 17984 Explicit = false; 17985 } while (!VarDC->Equals(DC)); 17986 17987 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17988 // computing the type of the capture at each step, checking type-specific 17989 // requirements, and adding captures if requested. 17990 // If the variable had already been captured previously, we start capturing 17991 // at the lambda nested within that one. 17992 bool Invalid = false; 17993 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17994 ++I) { 17995 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17996 17997 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17998 // certain types of variables (unnamed, variably modified types etc.) 17999 // so check for eligibility. 18000 if (!Invalid) 18001 Invalid = 18002 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18003 18004 // After encountering an error, if we're actually supposed to capture, keep 18005 // capturing in nested contexts to suppress any follow-on diagnostics. 18006 if (Invalid && !BuildAndDiagnose) 18007 return true; 18008 18009 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18010 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18011 DeclRefType, Nested, *this, Invalid); 18012 Nested = true; 18013 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18014 Invalid = !captureInCapturedRegion( 18015 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18016 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18017 Nested = true; 18018 } else { 18019 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18020 Invalid = 18021 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18022 DeclRefType, Nested, Kind, EllipsisLoc, 18023 /*IsTopScope*/ I == N - 1, *this, Invalid); 18024 Nested = true; 18025 } 18026 18027 if (Invalid && !BuildAndDiagnose) 18028 return true; 18029 } 18030 return Invalid; 18031 } 18032 18033 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18034 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18035 QualType CaptureType; 18036 QualType DeclRefType; 18037 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18038 /*BuildAndDiagnose=*/true, CaptureType, 18039 DeclRefType, nullptr); 18040 } 18041 18042 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18043 QualType CaptureType; 18044 QualType DeclRefType; 18045 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18046 /*BuildAndDiagnose=*/false, CaptureType, 18047 DeclRefType, nullptr); 18048 } 18049 18050 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18051 QualType CaptureType; 18052 QualType DeclRefType; 18053 18054 // Determine whether we can capture this variable. 18055 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18056 /*BuildAndDiagnose=*/false, CaptureType, 18057 DeclRefType, nullptr)) 18058 return QualType(); 18059 18060 return DeclRefType; 18061 } 18062 18063 namespace { 18064 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18065 // The produced TemplateArgumentListInfo* points to data stored within this 18066 // object, so should only be used in contexts where the pointer will not be 18067 // used after the CopiedTemplateArgs object is destroyed. 18068 class CopiedTemplateArgs { 18069 bool HasArgs; 18070 TemplateArgumentListInfo TemplateArgStorage; 18071 public: 18072 template<typename RefExpr> 18073 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18074 if (HasArgs) 18075 E->copyTemplateArgumentsInto(TemplateArgStorage); 18076 } 18077 operator TemplateArgumentListInfo*() 18078 #ifdef __has_cpp_attribute 18079 #if __has_cpp_attribute(clang::lifetimebound) 18080 [[clang::lifetimebound]] 18081 #endif 18082 #endif 18083 { 18084 return HasArgs ? &TemplateArgStorage : nullptr; 18085 } 18086 }; 18087 } 18088 18089 /// Walk the set of potential results of an expression and mark them all as 18090 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18091 /// 18092 /// \return A new expression if we found any potential results, ExprEmpty() if 18093 /// not, and ExprError() if we diagnosed an error. 18094 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18095 NonOdrUseReason NOUR) { 18096 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18097 // an object that satisfies the requirements for appearing in a 18098 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18099 // is immediately applied." This function handles the lvalue-to-rvalue 18100 // conversion part. 18101 // 18102 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18103 // transform it into the relevant kind of non-odr-use node and rebuild the 18104 // tree of nodes leading to it. 18105 // 18106 // This is a mini-TreeTransform that only transforms a restricted subset of 18107 // nodes (and only certain operands of them). 18108 18109 // Rebuild a subexpression. 18110 auto Rebuild = [&](Expr *Sub) { 18111 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18112 }; 18113 18114 // Check whether a potential result satisfies the requirements of NOUR. 18115 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18116 // Any entity other than a VarDecl is always odr-used whenever it's named 18117 // in a potentially-evaluated expression. 18118 auto *VD = dyn_cast<VarDecl>(D); 18119 if (!VD) 18120 return true; 18121 18122 // C++2a [basic.def.odr]p4: 18123 // A variable x whose name appears as a potentially-evalauted expression 18124 // e is odr-used by e unless 18125 // -- x is a reference that is usable in constant expressions, or 18126 // -- x is a variable of non-reference type that is usable in constant 18127 // expressions and has no mutable subobjects, and e is an element of 18128 // the set of potential results of an expression of 18129 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18130 // conversion is applied, or 18131 // -- x is a variable of non-reference type, and e is an element of the 18132 // set of potential results of a discarded-value expression to which 18133 // the lvalue-to-rvalue conversion is not applied 18134 // 18135 // We check the first bullet and the "potentially-evaluated" condition in 18136 // BuildDeclRefExpr. We check the type requirements in the second bullet 18137 // in CheckLValueToRValueConversionOperand below. 18138 switch (NOUR) { 18139 case NOUR_None: 18140 case NOUR_Unevaluated: 18141 llvm_unreachable("unexpected non-odr-use-reason"); 18142 18143 case NOUR_Constant: 18144 // Constant references were handled when they were built. 18145 if (VD->getType()->isReferenceType()) 18146 return true; 18147 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18148 if (RD->hasMutableFields()) 18149 return true; 18150 if (!VD->isUsableInConstantExpressions(S.Context)) 18151 return true; 18152 break; 18153 18154 case NOUR_Discarded: 18155 if (VD->getType()->isReferenceType()) 18156 return true; 18157 break; 18158 } 18159 return false; 18160 }; 18161 18162 // Mark that this expression does not constitute an odr-use. 18163 auto MarkNotOdrUsed = [&] { 18164 S.MaybeODRUseExprs.remove(E); 18165 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18166 LSI->markVariableExprAsNonODRUsed(E); 18167 }; 18168 18169 // C++2a [basic.def.odr]p2: 18170 // The set of potential results of an expression e is defined as follows: 18171 switch (E->getStmtClass()) { 18172 // -- If e is an id-expression, ... 18173 case Expr::DeclRefExprClass: { 18174 auto *DRE = cast<DeclRefExpr>(E); 18175 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18176 break; 18177 18178 // Rebuild as a non-odr-use DeclRefExpr. 18179 MarkNotOdrUsed(); 18180 return DeclRefExpr::Create( 18181 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18182 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18183 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18184 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18185 } 18186 18187 case Expr::FunctionParmPackExprClass: { 18188 auto *FPPE = cast<FunctionParmPackExpr>(E); 18189 // If any of the declarations in the pack is odr-used, then the expression 18190 // as a whole constitutes an odr-use. 18191 for (VarDecl *D : *FPPE) 18192 if (IsPotentialResultOdrUsed(D)) 18193 return ExprEmpty(); 18194 18195 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18196 // nothing cares about whether we marked this as an odr-use, but it might 18197 // be useful for non-compiler tools. 18198 MarkNotOdrUsed(); 18199 break; 18200 } 18201 18202 // -- If e is a subscripting operation with an array operand... 18203 case Expr::ArraySubscriptExprClass: { 18204 auto *ASE = cast<ArraySubscriptExpr>(E); 18205 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18206 if (!OldBase->getType()->isArrayType()) 18207 break; 18208 ExprResult Base = Rebuild(OldBase); 18209 if (!Base.isUsable()) 18210 return Base; 18211 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18212 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18213 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18214 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18215 ASE->getRBracketLoc()); 18216 } 18217 18218 case Expr::MemberExprClass: { 18219 auto *ME = cast<MemberExpr>(E); 18220 // -- If e is a class member access expression [...] naming a non-static 18221 // data member... 18222 if (isa<FieldDecl>(ME->getMemberDecl())) { 18223 ExprResult Base = Rebuild(ME->getBase()); 18224 if (!Base.isUsable()) 18225 return Base; 18226 return MemberExpr::Create( 18227 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18228 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18229 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18230 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18231 ME->getObjectKind(), ME->isNonOdrUse()); 18232 } 18233 18234 if (ME->getMemberDecl()->isCXXInstanceMember()) 18235 break; 18236 18237 // -- If e is a class member access expression naming a static data member, 18238 // ... 18239 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18240 break; 18241 18242 // Rebuild as a non-odr-use MemberExpr. 18243 MarkNotOdrUsed(); 18244 return MemberExpr::Create( 18245 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18246 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18247 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18248 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18249 return ExprEmpty(); 18250 } 18251 18252 case Expr::BinaryOperatorClass: { 18253 auto *BO = cast<BinaryOperator>(E); 18254 Expr *LHS = BO->getLHS(); 18255 Expr *RHS = BO->getRHS(); 18256 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18257 if (BO->getOpcode() == BO_PtrMemD) { 18258 ExprResult Sub = Rebuild(LHS); 18259 if (!Sub.isUsable()) 18260 return Sub; 18261 LHS = Sub.get(); 18262 // -- If e is a comma expression, ... 18263 } else if (BO->getOpcode() == BO_Comma) { 18264 ExprResult Sub = Rebuild(RHS); 18265 if (!Sub.isUsable()) 18266 return Sub; 18267 RHS = Sub.get(); 18268 } else { 18269 break; 18270 } 18271 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18272 LHS, RHS); 18273 } 18274 18275 // -- If e has the form (e1)... 18276 case Expr::ParenExprClass: { 18277 auto *PE = cast<ParenExpr>(E); 18278 ExprResult Sub = Rebuild(PE->getSubExpr()); 18279 if (!Sub.isUsable()) 18280 return Sub; 18281 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18282 } 18283 18284 // -- If e is a glvalue conditional expression, ... 18285 // We don't apply this to a binary conditional operator. FIXME: Should we? 18286 case Expr::ConditionalOperatorClass: { 18287 auto *CO = cast<ConditionalOperator>(E); 18288 ExprResult LHS = Rebuild(CO->getLHS()); 18289 if (LHS.isInvalid()) 18290 return ExprError(); 18291 ExprResult RHS = Rebuild(CO->getRHS()); 18292 if (RHS.isInvalid()) 18293 return ExprError(); 18294 if (!LHS.isUsable() && !RHS.isUsable()) 18295 return ExprEmpty(); 18296 if (!LHS.isUsable()) 18297 LHS = CO->getLHS(); 18298 if (!RHS.isUsable()) 18299 RHS = CO->getRHS(); 18300 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18301 CO->getCond(), LHS.get(), RHS.get()); 18302 } 18303 18304 // [Clang extension] 18305 // -- If e has the form __extension__ e1... 18306 case Expr::UnaryOperatorClass: { 18307 auto *UO = cast<UnaryOperator>(E); 18308 if (UO->getOpcode() != UO_Extension) 18309 break; 18310 ExprResult Sub = Rebuild(UO->getSubExpr()); 18311 if (!Sub.isUsable()) 18312 return Sub; 18313 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18314 Sub.get()); 18315 } 18316 18317 // [Clang extension] 18318 // -- If e has the form _Generic(...), the set of potential results is the 18319 // union of the sets of potential results of the associated expressions. 18320 case Expr::GenericSelectionExprClass: { 18321 auto *GSE = cast<GenericSelectionExpr>(E); 18322 18323 SmallVector<Expr *, 4> AssocExprs; 18324 bool AnyChanged = false; 18325 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18326 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18327 if (AssocExpr.isInvalid()) 18328 return ExprError(); 18329 if (AssocExpr.isUsable()) { 18330 AssocExprs.push_back(AssocExpr.get()); 18331 AnyChanged = true; 18332 } else { 18333 AssocExprs.push_back(OrigAssocExpr); 18334 } 18335 } 18336 18337 return AnyChanged ? S.CreateGenericSelectionExpr( 18338 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18339 GSE->getRParenLoc(), GSE->getControllingExpr(), 18340 GSE->getAssocTypeSourceInfos(), AssocExprs) 18341 : ExprEmpty(); 18342 } 18343 18344 // [Clang extension] 18345 // -- If e has the form __builtin_choose_expr(...), the set of potential 18346 // results is the union of the sets of potential results of the 18347 // second and third subexpressions. 18348 case Expr::ChooseExprClass: { 18349 auto *CE = cast<ChooseExpr>(E); 18350 18351 ExprResult LHS = Rebuild(CE->getLHS()); 18352 if (LHS.isInvalid()) 18353 return ExprError(); 18354 18355 ExprResult RHS = Rebuild(CE->getLHS()); 18356 if (RHS.isInvalid()) 18357 return ExprError(); 18358 18359 if (!LHS.get() && !RHS.get()) 18360 return ExprEmpty(); 18361 if (!LHS.isUsable()) 18362 LHS = CE->getLHS(); 18363 if (!RHS.isUsable()) 18364 RHS = CE->getRHS(); 18365 18366 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18367 RHS.get(), CE->getRParenLoc()); 18368 } 18369 18370 // Step through non-syntactic nodes. 18371 case Expr::ConstantExprClass: { 18372 auto *CE = cast<ConstantExpr>(E); 18373 ExprResult Sub = Rebuild(CE->getSubExpr()); 18374 if (!Sub.isUsable()) 18375 return Sub; 18376 return ConstantExpr::Create(S.Context, Sub.get()); 18377 } 18378 18379 // We could mostly rely on the recursive rebuilding to rebuild implicit 18380 // casts, but not at the top level, so rebuild them here. 18381 case Expr::ImplicitCastExprClass: { 18382 auto *ICE = cast<ImplicitCastExpr>(E); 18383 // Only step through the narrow set of cast kinds we expect to encounter. 18384 // Anything else suggests we've left the region in which potential results 18385 // can be found. 18386 switch (ICE->getCastKind()) { 18387 case CK_NoOp: 18388 case CK_DerivedToBase: 18389 case CK_UncheckedDerivedToBase: { 18390 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18391 if (!Sub.isUsable()) 18392 return Sub; 18393 CXXCastPath Path(ICE->path()); 18394 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18395 ICE->getValueKind(), &Path); 18396 } 18397 18398 default: 18399 break; 18400 } 18401 break; 18402 } 18403 18404 default: 18405 break; 18406 } 18407 18408 // Can't traverse through this node. Nothing to do. 18409 return ExprEmpty(); 18410 } 18411 18412 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18413 // Check whether the operand is or contains an object of non-trivial C union 18414 // type. 18415 if (E->getType().isVolatileQualified() && 18416 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18417 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18418 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18419 Sema::NTCUC_LValueToRValueVolatile, 18420 NTCUK_Destruct|NTCUK_Copy); 18421 18422 // C++2a [basic.def.odr]p4: 18423 // [...] an expression of non-volatile-qualified non-class type to which 18424 // the lvalue-to-rvalue conversion is applied [...] 18425 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18426 return E; 18427 18428 ExprResult Result = 18429 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18430 if (Result.isInvalid()) 18431 return ExprError(); 18432 return Result.get() ? Result : E; 18433 } 18434 18435 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18436 Res = CorrectDelayedTyposInExpr(Res); 18437 18438 if (!Res.isUsable()) 18439 return Res; 18440 18441 // If a constant-expression is a reference to a variable where we delay 18442 // deciding whether it is an odr-use, just assume we will apply the 18443 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18444 // (a non-type template argument), we have special handling anyway. 18445 return CheckLValueToRValueConversionOperand(Res.get()); 18446 } 18447 18448 void Sema::CleanupVarDeclMarking() { 18449 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18450 // call. 18451 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18452 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18453 18454 for (Expr *E : LocalMaybeODRUseExprs) { 18455 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18456 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18457 DRE->getLocation(), *this); 18458 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18459 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18460 *this); 18461 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18462 for (VarDecl *VD : *FP) 18463 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18464 } else { 18465 llvm_unreachable("Unexpected expression"); 18466 } 18467 } 18468 18469 assert(MaybeODRUseExprs.empty() && 18470 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18471 } 18472 18473 static void DoMarkVarDeclReferenced( 18474 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18475 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18476 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18477 isa<FunctionParmPackExpr>(E)) && 18478 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18479 Var->setReferenced(); 18480 18481 if (Var->isInvalidDecl()) 18482 return; 18483 18484 auto *MSI = Var->getMemberSpecializationInfo(); 18485 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18486 : Var->getTemplateSpecializationKind(); 18487 18488 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18489 bool UsableInConstantExpr = 18490 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18491 18492 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18493 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18494 } 18495 18496 // C++20 [expr.const]p12: 18497 // A variable [...] is needed for constant evaluation if it is [...] a 18498 // variable whose name appears as a potentially constant evaluated 18499 // expression that is either a contexpr variable or is of non-volatile 18500 // const-qualified integral type or of reference type 18501 bool NeededForConstantEvaluation = 18502 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18503 18504 bool NeedDefinition = 18505 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18506 18507 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18508 "Can't instantiate a partial template specialization."); 18509 18510 // If this might be a member specialization of a static data member, check 18511 // the specialization is visible. We already did the checks for variable 18512 // template specializations when we created them. 18513 if (NeedDefinition && TSK != TSK_Undeclared && 18514 !isa<VarTemplateSpecializationDecl>(Var)) 18515 SemaRef.checkSpecializationVisibility(Loc, Var); 18516 18517 // Perform implicit instantiation of static data members, static data member 18518 // templates of class templates, and variable template specializations. Delay 18519 // instantiations of variable templates, except for those that could be used 18520 // in a constant expression. 18521 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18522 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18523 // instantiation declaration if a variable is usable in a constant 18524 // expression (among other cases). 18525 bool TryInstantiating = 18526 TSK == TSK_ImplicitInstantiation || 18527 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18528 18529 if (TryInstantiating) { 18530 SourceLocation PointOfInstantiation = 18531 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18532 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18533 if (FirstInstantiation) { 18534 PointOfInstantiation = Loc; 18535 if (MSI) 18536 MSI->setPointOfInstantiation(PointOfInstantiation); 18537 // FIXME: Notify listener. 18538 else 18539 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18540 } 18541 18542 if (UsableInConstantExpr) { 18543 // Do not defer instantiations of variables that could be used in a 18544 // constant expression. 18545 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18546 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18547 }); 18548 18549 // Re-set the member to trigger a recomputation of the dependence bits 18550 // for the expression. 18551 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18552 DRE->setDecl(DRE->getDecl()); 18553 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18554 ME->setMemberDecl(ME->getMemberDecl()); 18555 } else if (FirstInstantiation || 18556 isa<VarTemplateSpecializationDecl>(Var)) { 18557 // FIXME: For a specialization of a variable template, we don't 18558 // distinguish between "declaration and type implicitly instantiated" 18559 // and "implicit instantiation of definition requested", so we have 18560 // no direct way to avoid enqueueing the pending instantiation 18561 // multiple times. 18562 SemaRef.PendingInstantiations 18563 .push_back(std::make_pair(Var, PointOfInstantiation)); 18564 } 18565 } 18566 } 18567 18568 // C++2a [basic.def.odr]p4: 18569 // A variable x whose name appears as a potentially-evaluated expression e 18570 // is odr-used by e unless 18571 // -- x is a reference that is usable in constant expressions 18572 // -- x is a variable of non-reference type that is usable in constant 18573 // expressions and has no mutable subobjects [FIXME], and e is an 18574 // element of the set of potential results of an expression of 18575 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18576 // conversion is applied 18577 // -- x is a variable of non-reference type, and e is an element of the set 18578 // of potential results of a discarded-value expression to which the 18579 // lvalue-to-rvalue conversion is not applied [FIXME] 18580 // 18581 // We check the first part of the second bullet here, and 18582 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18583 // FIXME: To get the third bullet right, we need to delay this even for 18584 // variables that are not usable in constant expressions. 18585 18586 // If we already know this isn't an odr-use, there's nothing more to do. 18587 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18588 if (DRE->isNonOdrUse()) 18589 return; 18590 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18591 if (ME->isNonOdrUse()) 18592 return; 18593 18594 switch (OdrUse) { 18595 case OdrUseContext::None: 18596 assert((!E || isa<FunctionParmPackExpr>(E)) && 18597 "missing non-odr-use marking for unevaluated decl ref"); 18598 break; 18599 18600 case OdrUseContext::FormallyOdrUsed: 18601 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18602 // behavior. 18603 break; 18604 18605 case OdrUseContext::Used: 18606 // If we might later find that this expression isn't actually an odr-use, 18607 // delay the marking. 18608 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18609 SemaRef.MaybeODRUseExprs.insert(E); 18610 else 18611 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18612 break; 18613 18614 case OdrUseContext::Dependent: 18615 // If this is a dependent context, we don't need to mark variables as 18616 // odr-used, but we may still need to track them for lambda capture. 18617 // FIXME: Do we also need to do this inside dependent typeid expressions 18618 // (which are modeled as unevaluated at this point)? 18619 const bool RefersToEnclosingScope = 18620 (SemaRef.CurContext != Var->getDeclContext() && 18621 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18622 if (RefersToEnclosingScope) { 18623 LambdaScopeInfo *const LSI = 18624 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18625 if (LSI && (!LSI->CallOperator || 18626 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18627 // If a variable could potentially be odr-used, defer marking it so 18628 // until we finish analyzing the full expression for any 18629 // lvalue-to-rvalue 18630 // or discarded value conversions that would obviate odr-use. 18631 // Add it to the list of potential captures that will be analyzed 18632 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18633 // unless the variable is a reference that was initialized by a constant 18634 // expression (this will never need to be captured or odr-used). 18635 // 18636 // FIXME: We can simplify this a lot after implementing P0588R1. 18637 assert(E && "Capture variable should be used in an expression."); 18638 if (!Var->getType()->isReferenceType() || 18639 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18640 LSI->addPotentialCapture(E->IgnoreParens()); 18641 } 18642 } 18643 break; 18644 } 18645 } 18646 18647 /// Mark a variable referenced, and check whether it is odr-used 18648 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18649 /// used directly for normal expressions referring to VarDecl. 18650 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18651 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18652 } 18653 18654 static void 18655 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18656 bool MightBeOdrUse, 18657 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18658 if (SemaRef.isInOpenMPDeclareTargetContext()) 18659 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18660 18661 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18662 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18663 return; 18664 } 18665 18666 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18667 18668 // If this is a call to a method via a cast, also mark the method in the 18669 // derived class used in case codegen can devirtualize the call. 18670 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18671 if (!ME) 18672 return; 18673 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18674 if (!MD) 18675 return; 18676 // Only attempt to devirtualize if this is truly a virtual call. 18677 bool IsVirtualCall = MD->isVirtual() && 18678 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18679 if (!IsVirtualCall) 18680 return; 18681 18682 // If it's possible to devirtualize the call, mark the called function 18683 // referenced. 18684 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18685 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18686 if (DM) 18687 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18688 } 18689 18690 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18691 /// 18692 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18693 /// handled with care if the DeclRefExpr is not newly-created. 18694 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18695 // TODO: update this with DR# once a defect report is filed. 18696 // C++11 defect. The address of a pure member should not be an ODR use, even 18697 // if it's a qualified reference. 18698 bool OdrUse = true; 18699 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18700 if (Method->isVirtual() && 18701 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18702 OdrUse = false; 18703 18704 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18705 if (!isConstantEvaluated() && FD->isConsteval() && 18706 !RebuildingImmediateInvocation) 18707 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18708 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18709 RefsMinusAssignments); 18710 } 18711 18712 /// Perform reference-marking and odr-use handling for a MemberExpr. 18713 void Sema::MarkMemberReferenced(MemberExpr *E) { 18714 // C++11 [basic.def.odr]p2: 18715 // A non-overloaded function whose name appears as a potentially-evaluated 18716 // expression or a member of a set of candidate functions, if selected by 18717 // overload resolution when referred to from a potentially-evaluated 18718 // expression, is odr-used, unless it is a pure virtual function and its 18719 // name is not explicitly qualified. 18720 bool MightBeOdrUse = true; 18721 if (E->performsVirtualDispatch(getLangOpts())) { 18722 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18723 if (Method->isPure()) 18724 MightBeOdrUse = false; 18725 } 18726 SourceLocation Loc = 18727 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18728 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18729 RefsMinusAssignments); 18730 } 18731 18732 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18733 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18734 for (VarDecl *VD : *E) 18735 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18736 RefsMinusAssignments); 18737 } 18738 18739 /// Perform marking for a reference to an arbitrary declaration. It 18740 /// marks the declaration referenced, and performs odr-use checking for 18741 /// functions and variables. This method should not be used when building a 18742 /// normal expression which refers to a variable. 18743 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18744 bool MightBeOdrUse) { 18745 if (MightBeOdrUse) { 18746 if (auto *VD = dyn_cast<VarDecl>(D)) { 18747 MarkVariableReferenced(Loc, VD); 18748 return; 18749 } 18750 } 18751 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18752 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18753 return; 18754 } 18755 D->setReferenced(); 18756 } 18757 18758 namespace { 18759 // Mark all of the declarations used by a type as referenced. 18760 // FIXME: Not fully implemented yet! We need to have a better understanding 18761 // of when we're entering a context we should not recurse into. 18762 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18763 // TreeTransforms rebuilding the type in a new context. Rather than 18764 // duplicating the TreeTransform logic, we should consider reusing it here. 18765 // Currently that causes problems when rebuilding LambdaExprs. 18766 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18767 Sema &S; 18768 SourceLocation Loc; 18769 18770 public: 18771 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18772 18773 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18774 18775 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18776 }; 18777 } 18778 18779 bool MarkReferencedDecls::TraverseTemplateArgument( 18780 const TemplateArgument &Arg) { 18781 { 18782 // A non-type template argument is a constant-evaluated context. 18783 EnterExpressionEvaluationContext Evaluated( 18784 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18785 if (Arg.getKind() == TemplateArgument::Declaration) { 18786 if (Decl *D = Arg.getAsDecl()) 18787 S.MarkAnyDeclReferenced(Loc, D, true); 18788 } else if (Arg.getKind() == TemplateArgument::Expression) { 18789 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18790 } 18791 } 18792 18793 return Inherited::TraverseTemplateArgument(Arg); 18794 } 18795 18796 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18797 MarkReferencedDecls Marker(*this, Loc); 18798 Marker.TraverseType(T); 18799 } 18800 18801 namespace { 18802 /// Helper class that marks all of the declarations referenced by 18803 /// potentially-evaluated subexpressions as "referenced". 18804 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18805 public: 18806 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18807 bool SkipLocalVariables; 18808 18809 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18810 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18811 18812 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18813 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18814 } 18815 18816 void VisitDeclRefExpr(DeclRefExpr *E) { 18817 // If we were asked not to visit local variables, don't. 18818 if (SkipLocalVariables) { 18819 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18820 if (VD->hasLocalStorage()) 18821 return; 18822 } 18823 18824 // FIXME: This can trigger the instantiation of the initializer of a 18825 // variable, which can cause the expression to become value-dependent 18826 // or error-dependent. Do we need to propagate the new dependence bits? 18827 S.MarkDeclRefReferenced(E); 18828 } 18829 18830 void VisitMemberExpr(MemberExpr *E) { 18831 S.MarkMemberReferenced(E); 18832 Visit(E->getBase()); 18833 } 18834 }; 18835 } // namespace 18836 18837 /// Mark any declarations that appear within this expression or any 18838 /// potentially-evaluated subexpressions as "referenced". 18839 /// 18840 /// \param SkipLocalVariables If true, don't mark local variables as 18841 /// 'referenced'. 18842 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18843 bool SkipLocalVariables) { 18844 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18845 } 18846 18847 /// Emit a diagnostic that describes an effect on the run-time behavior 18848 /// of the program being compiled. 18849 /// 18850 /// This routine emits the given diagnostic when the code currently being 18851 /// type-checked is "potentially evaluated", meaning that there is a 18852 /// possibility that the code will actually be executable. Code in sizeof() 18853 /// expressions, code used only during overload resolution, etc., are not 18854 /// potentially evaluated. This routine will suppress such diagnostics or, 18855 /// in the absolutely nutty case of potentially potentially evaluated 18856 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18857 /// later. 18858 /// 18859 /// This routine should be used for all diagnostics that describe the run-time 18860 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18861 /// Failure to do so will likely result in spurious diagnostics or failures 18862 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18863 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18864 const PartialDiagnostic &PD) { 18865 switch (ExprEvalContexts.back().Context) { 18866 case ExpressionEvaluationContext::Unevaluated: 18867 case ExpressionEvaluationContext::UnevaluatedList: 18868 case ExpressionEvaluationContext::UnevaluatedAbstract: 18869 case ExpressionEvaluationContext::DiscardedStatement: 18870 // The argument will never be evaluated, so don't complain. 18871 break; 18872 18873 case ExpressionEvaluationContext::ConstantEvaluated: 18874 // Relevant diagnostics should be produced by constant evaluation. 18875 break; 18876 18877 case ExpressionEvaluationContext::PotentiallyEvaluated: 18878 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18879 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18880 FunctionScopes.back()->PossiblyUnreachableDiags. 18881 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18882 return true; 18883 } 18884 18885 // The initializer of a constexpr variable or of the first declaration of a 18886 // static data member is not syntactically a constant evaluated constant, 18887 // but nonetheless is always required to be a constant expression, so we 18888 // can skip diagnosing. 18889 // FIXME: Using the mangling context here is a hack. 18890 if (auto *VD = dyn_cast_or_null<VarDecl>( 18891 ExprEvalContexts.back().ManglingContextDecl)) { 18892 if (VD->isConstexpr() || 18893 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18894 break; 18895 // FIXME: For any other kind of variable, we should build a CFG for its 18896 // initializer and check whether the context in question is reachable. 18897 } 18898 18899 Diag(Loc, PD); 18900 return true; 18901 } 18902 18903 return false; 18904 } 18905 18906 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18907 const PartialDiagnostic &PD) { 18908 return DiagRuntimeBehavior( 18909 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18910 } 18911 18912 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18913 CallExpr *CE, FunctionDecl *FD) { 18914 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18915 return false; 18916 18917 // If we're inside a decltype's expression, don't check for a valid return 18918 // type or construct temporaries until we know whether this is the last call. 18919 if (ExprEvalContexts.back().ExprContext == 18920 ExpressionEvaluationContextRecord::EK_Decltype) { 18921 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18922 return false; 18923 } 18924 18925 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18926 FunctionDecl *FD; 18927 CallExpr *CE; 18928 18929 public: 18930 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18931 : FD(FD), CE(CE) { } 18932 18933 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18934 if (!FD) { 18935 S.Diag(Loc, diag::err_call_incomplete_return) 18936 << T << CE->getSourceRange(); 18937 return; 18938 } 18939 18940 S.Diag(Loc, diag::err_call_function_incomplete_return) 18941 << CE->getSourceRange() << FD << T; 18942 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18943 << FD->getDeclName(); 18944 } 18945 } Diagnoser(FD, CE); 18946 18947 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18948 return true; 18949 18950 return false; 18951 } 18952 18953 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18954 // will prevent this condition from triggering, which is what we want. 18955 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18956 SourceLocation Loc; 18957 18958 unsigned diagnostic = diag::warn_condition_is_assignment; 18959 bool IsOrAssign = false; 18960 18961 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18962 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18963 return; 18964 18965 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18966 18967 // Greylist some idioms by putting them into a warning subcategory. 18968 if (ObjCMessageExpr *ME 18969 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18970 Selector Sel = ME->getSelector(); 18971 18972 // self = [<foo> init...] 18973 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18974 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18975 18976 // <foo> = [<bar> nextObject] 18977 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18978 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18979 } 18980 18981 Loc = Op->getOperatorLoc(); 18982 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18983 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18984 return; 18985 18986 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18987 Loc = Op->getOperatorLoc(); 18988 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18989 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18990 else { 18991 // Not an assignment. 18992 return; 18993 } 18994 18995 Diag(Loc, diagnostic) << E->getSourceRange(); 18996 18997 SourceLocation Open = E->getBeginLoc(); 18998 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18999 Diag(Loc, diag::note_condition_assign_silence) 19000 << FixItHint::CreateInsertion(Open, "(") 19001 << FixItHint::CreateInsertion(Close, ")"); 19002 19003 if (IsOrAssign) 19004 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19005 << FixItHint::CreateReplacement(Loc, "!="); 19006 else 19007 Diag(Loc, diag::note_condition_assign_to_comparison) 19008 << FixItHint::CreateReplacement(Loc, "=="); 19009 } 19010 19011 /// Redundant parentheses over an equality comparison can indicate 19012 /// that the user intended an assignment used as condition. 19013 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19014 // Don't warn if the parens came from a macro. 19015 SourceLocation parenLoc = ParenE->getBeginLoc(); 19016 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19017 return; 19018 // Don't warn for dependent expressions. 19019 if (ParenE->isTypeDependent()) 19020 return; 19021 19022 Expr *E = ParenE->IgnoreParens(); 19023 19024 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19025 if (opE->getOpcode() == BO_EQ && 19026 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19027 == Expr::MLV_Valid) { 19028 SourceLocation Loc = opE->getOperatorLoc(); 19029 19030 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19031 SourceRange ParenERange = ParenE->getSourceRange(); 19032 Diag(Loc, diag::note_equality_comparison_silence) 19033 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19034 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19035 Diag(Loc, diag::note_equality_comparison_to_assign) 19036 << FixItHint::CreateReplacement(Loc, "="); 19037 } 19038 } 19039 19040 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19041 bool IsConstexpr) { 19042 DiagnoseAssignmentAsCondition(E); 19043 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19044 DiagnoseEqualityWithExtraParens(parenE); 19045 19046 ExprResult result = CheckPlaceholderExpr(E); 19047 if (result.isInvalid()) return ExprError(); 19048 E = result.get(); 19049 19050 if (!E->isTypeDependent()) { 19051 if (getLangOpts().CPlusPlus) 19052 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19053 19054 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19055 if (ERes.isInvalid()) 19056 return ExprError(); 19057 E = ERes.get(); 19058 19059 QualType T = E->getType(); 19060 if (!T->isScalarType()) { // C99 6.8.4.1p1 19061 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19062 << T << E->getSourceRange(); 19063 return ExprError(); 19064 } 19065 CheckBoolLikeConversion(E, Loc); 19066 } 19067 19068 return E; 19069 } 19070 19071 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19072 Expr *SubExpr, ConditionKind CK) { 19073 // Empty conditions are valid in for-statements. 19074 if (!SubExpr) 19075 return ConditionResult(); 19076 19077 ExprResult Cond; 19078 switch (CK) { 19079 case ConditionKind::Boolean: 19080 Cond = CheckBooleanCondition(Loc, SubExpr); 19081 break; 19082 19083 case ConditionKind::ConstexprIf: 19084 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19085 break; 19086 19087 case ConditionKind::Switch: 19088 Cond = CheckSwitchCondition(Loc, SubExpr); 19089 break; 19090 } 19091 if (Cond.isInvalid()) { 19092 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19093 {SubExpr}); 19094 if (!Cond.get()) 19095 return ConditionError(); 19096 } 19097 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19098 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19099 if (!FullExpr.get()) 19100 return ConditionError(); 19101 19102 return ConditionResult(*this, nullptr, FullExpr, 19103 CK == ConditionKind::ConstexprIf); 19104 } 19105 19106 namespace { 19107 /// A visitor for rebuilding a call to an __unknown_any expression 19108 /// to have an appropriate type. 19109 struct RebuildUnknownAnyFunction 19110 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19111 19112 Sema &S; 19113 19114 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19115 19116 ExprResult VisitStmt(Stmt *S) { 19117 llvm_unreachable("unexpected statement!"); 19118 } 19119 19120 ExprResult VisitExpr(Expr *E) { 19121 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19122 << E->getSourceRange(); 19123 return ExprError(); 19124 } 19125 19126 /// Rebuild an expression which simply semantically wraps another 19127 /// expression which it shares the type and value kind of. 19128 template <class T> ExprResult rebuildSugarExpr(T *E) { 19129 ExprResult SubResult = Visit(E->getSubExpr()); 19130 if (SubResult.isInvalid()) return ExprError(); 19131 19132 Expr *SubExpr = SubResult.get(); 19133 E->setSubExpr(SubExpr); 19134 E->setType(SubExpr->getType()); 19135 E->setValueKind(SubExpr->getValueKind()); 19136 assert(E->getObjectKind() == OK_Ordinary); 19137 return E; 19138 } 19139 19140 ExprResult VisitParenExpr(ParenExpr *E) { 19141 return rebuildSugarExpr(E); 19142 } 19143 19144 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19145 return rebuildSugarExpr(E); 19146 } 19147 19148 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19149 ExprResult SubResult = Visit(E->getSubExpr()); 19150 if (SubResult.isInvalid()) return ExprError(); 19151 19152 Expr *SubExpr = SubResult.get(); 19153 E->setSubExpr(SubExpr); 19154 E->setType(S.Context.getPointerType(SubExpr->getType())); 19155 assert(E->getValueKind() == VK_PRValue); 19156 assert(E->getObjectKind() == OK_Ordinary); 19157 return E; 19158 } 19159 19160 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19161 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19162 19163 E->setType(VD->getType()); 19164 19165 assert(E->getValueKind() == VK_PRValue); 19166 if (S.getLangOpts().CPlusPlus && 19167 !(isa<CXXMethodDecl>(VD) && 19168 cast<CXXMethodDecl>(VD)->isInstance())) 19169 E->setValueKind(VK_LValue); 19170 19171 return E; 19172 } 19173 19174 ExprResult VisitMemberExpr(MemberExpr *E) { 19175 return resolveDecl(E, E->getMemberDecl()); 19176 } 19177 19178 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19179 return resolveDecl(E, E->getDecl()); 19180 } 19181 }; 19182 } 19183 19184 /// Given a function expression of unknown-any type, try to rebuild it 19185 /// to have a function type. 19186 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19187 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19188 if (Result.isInvalid()) return ExprError(); 19189 return S.DefaultFunctionArrayConversion(Result.get()); 19190 } 19191 19192 namespace { 19193 /// A visitor for rebuilding an expression of type __unknown_anytype 19194 /// into one which resolves the type directly on the referring 19195 /// expression. Strict preservation of the original source 19196 /// structure is not a goal. 19197 struct RebuildUnknownAnyExpr 19198 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19199 19200 Sema &S; 19201 19202 /// The current destination type. 19203 QualType DestType; 19204 19205 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19206 : S(S), DestType(CastType) {} 19207 19208 ExprResult VisitStmt(Stmt *S) { 19209 llvm_unreachable("unexpected statement!"); 19210 } 19211 19212 ExprResult VisitExpr(Expr *E) { 19213 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19214 << E->getSourceRange(); 19215 return ExprError(); 19216 } 19217 19218 ExprResult VisitCallExpr(CallExpr *E); 19219 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19220 19221 /// Rebuild an expression which simply semantically wraps another 19222 /// expression which it shares the type and value kind of. 19223 template <class T> ExprResult rebuildSugarExpr(T *E) { 19224 ExprResult SubResult = Visit(E->getSubExpr()); 19225 if (SubResult.isInvalid()) return ExprError(); 19226 Expr *SubExpr = SubResult.get(); 19227 E->setSubExpr(SubExpr); 19228 E->setType(SubExpr->getType()); 19229 E->setValueKind(SubExpr->getValueKind()); 19230 assert(E->getObjectKind() == OK_Ordinary); 19231 return E; 19232 } 19233 19234 ExprResult VisitParenExpr(ParenExpr *E) { 19235 return rebuildSugarExpr(E); 19236 } 19237 19238 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19239 return rebuildSugarExpr(E); 19240 } 19241 19242 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19243 const PointerType *Ptr = DestType->getAs<PointerType>(); 19244 if (!Ptr) { 19245 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19246 << E->getSourceRange(); 19247 return ExprError(); 19248 } 19249 19250 if (isa<CallExpr>(E->getSubExpr())) { 19251 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19252 << E->getSourceRange(); 19253 return ExprError(); 19254 } 19255 19256 assert(E->getValueKind() == VK_PRValue); 19257 assert(E->getObjectKind() == OK_Ordinary); 19258 E->setType(DestType); 19259 19260 // Build the sub-expression as if it were an object of the pointee type. 19261 DestType = Ptr->getPointeeType(); 19262 ExprResult SubResult = Visit(E->getSubExpr()); 19263 if (SubResult.isInvalid()) return ExprError(); 19264 E->setSubExpr(SubResult.get()); 19265 return E; 19266 } 19267 19268 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19269 19270 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19271 19272 ExprResult VisitMemberExpr(MemberExpr *E) { 19273 return resolveDecl(E, E->getMemberDecl()); 19274 } 19275 19276 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19277 return resolveDecl(E, E->getDecl()); 19278 } 19279 }; 19280 } 19281 19282 /// Rebuilds a call expression which yielded __unknown_anytype. 19283 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19284 Expr *CalleeExpr = E->getCallee(); 19285 19286 enum FnKind { 19287 FK_MemberFunction, 19288 FK_FunctionPointer, 19289 FK_BlockPointer 19290 }; 19291 19292 FnKind Kind; 19293 QualType CalleeType = CalleeExpr->getType(); 19294 if (CalleeType == S.Context.BoundMemberTy) { 19295 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19296 Kind = FK_MemberFunction; 19297 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19298 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19299 CalleeType = Ptr->getPointeeType(); 19300 Kind = FK_FunctionPointer; 19301 } else { 19302 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19303 Kind = FK_BlockPointer; 19304 } 19305 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19306 19307 // Verify that this is a legal result type of a function. 19308 if (DestType->isArrayType() || DestType->isFunctionType()) { 19309 unsigned diagID = diag::err_func_returning_array_function; 19310 if (Kind == FK_BlockPointer) 19311 diagID = diag::err_block_returning_array_function; 19312 19313 S.Diag(E->getExprLoc(), diagID) 19314 << DestType->isFunctionType() << DestType; 19315 return ExprError(); 19316 } 19317 19318 // Otherwise, go ahead and set DestType as the call's result. 19319 E->setType(DestType.getNonLValueExprType(S.Context)); 19320 E->setValueKind(Expr::getValueKindForType(DestType)); 19321 assert(E->getObjectKind() == OK_Ordinary); 19322 19323 // Rebuild the function type, replacing the result type with DestType. 19324 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19325 if (Proto) { 19326 // __unknown_anytype(...) is a special case used by the debugger when 19327 // it has no idea what a function's signature is. 19328 // 19329 // We want to build this call essentially under the K&R 19330 // unprototyped rules, but making a FunctionNoProtoType in C++ 19331 // would foul up all sorts of assumptions. However, we cannot 19332 // simply pass all arguments as variadic arguments, nor can we 19333 // portably just call the function under a non-variadic type; see 19334 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19335 // However, it turns out that in practice it is generally safe to 19336 // call a function declared as "A foo(B,C,D);" under the prototype 19337 // "A foo(B,C,D,...);". The only known exception is with the 19338 // Windows ABI, where any variadic function is implicitly cdecl 19339 // regardless of its normal CC. Therefore we change the parameter 19340 // types to match the types of the arguments. 19341 // 19342 // This is a hack, but it is far superior to moving the 19343 // corresponding target-specific code from IR-gen to Sema/AST. 19344 19345 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19346 SmallVector<QualType, 8> ArgTypes; 19347 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19348 ArgTypes.reserve(E->getNumArgs()); 19349 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19350 Expr *Arg = E->getArg(i); 19351 QualType ArgType = Arg->getType(); 19352 if (E->isLValue()) { 19353 ArgType = S.Context.getLValueReferenceType(ArgType); 19354 } else if (E->isXValue()) { 19355 ArgType = S.Context.getRValueReferenceType(ArgType); 19356 } 19357 ArgTypes.push_back(ArgType); 19358 } 19359 ParamTypes = ArgTypes; 19360 } 19361 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19362 Proto->getExtProtoInfo()); 19363 } else { 19364 DestType = S.Context.getFunctionNoProtoType(DestType, 19365 FnType->getExtInfo()); 19366 } 19367 19368 // Rebuild the appropriate pointer-to-function type. 19369 switch (Kind) { 19370 case FK_MemberFunction: 19371 // Nothing to do. 19372 break; 19373 19374 case FK_FunctionPointer: 19375 DestType = S.Context.getPointerType(DestType); 19376 break; 19377 19378 case FK_BlockPointer: 19379 DestType = S.Context.getBlockPointerType(DestType); 19380 break; 19381 } 19382 19383 // Finally, we can recurse. 19384 ExprResult CalleeResult = Visit(CalleeExpr); 19385 if (!CalleeResult.isUsable()) return ExprError(); 19386 E->setCallee(CalleeResult.get()); 19387 19388 // Bind a temporary if necessary. 19389 return S.MaybeBindToTemporary(E); 19390 } 19391 19392 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19393 // Verify that this is a legal result type of a call. 19394 if (DestType->isArrayType() || DestType->isFunctionType()) { 19395 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19396 << DestType->isFunctionType() << DestType; 19397 return ExprError(); 19398 } 19399 19400 // Rewrite the method result type if available. 19401 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19402 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19403 Method->setReturnType(DestType); 19404 } 19405 19406 // Change the type of the message. 19407 E->setType(DestType.getNonReferenceType()); 19408 E->setValueKind(Expr::getValueKindForType(DestType)); 19409 19410 return S.MaybeBindToTemporary(E); 19411 } 19412 19413 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19414 // The only case we should ever see here is a function-to-pointer decay. 19415 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19416 assert(E->getValueKind() == VK_PRValue); 19417 assert(E->getObjectKind() == OK_Ordinary); 19418 19419 E->setType(DestType); 19420 19421 // Rebuild the sub-expression as the pointee (function) type. 19422 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19423 19424 ExprResult Result = Visit(E->getSubExpr()); 19425 if (!Result.isUsable()) return ExprError(); 19426 19427 E->setSubExpr(Result.get()); 19428 return E; 19429 } else if (E->getCastKind() == CK_LValueToRValue) { 19430 assert(E->getValueKind() == VK_PRValue); 19431 assert(E->getObjectKind() == OK_Ordinary); 19432 19433 assert(isa<BlockPointerType>(E->getType())); 19434 19435 E->setType(DestType); 19436 19437 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19438 DestType = S.Context.getLValueReferenceType(DestType); 19439 19440 ExprResult Result = Visit(E->getSubExpr()); 19441 if (!Result.isUsable()) return ExprError(); 19442 19443 E->setSubExpr(Result.get()); 19444 return E; 19445 } else { 19446 llvm_unreachable("Unhandled cast type!"); 19447 } 19448 } 19449 19450 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19451 ExprValueKind ValueKind = VK_LValue; 19452 QualType Type = DestType; 19453 19454 // We know how to make this work for certain kinds of decls: 19455 19456 // - functions 19457 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19458 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19459 DestType = Ptr->getPointeeType(); 19460 ExprResult Result = resolveDecl(E, VD); 19461 if (Result.isInvalid()) return ExprError(); 19462 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19463 VK_PRValue); 19464 } 19465 19466 if (!Type->isFunctionType()) { 19467 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19468 << VD << E->getSourceRange(); 19469 return ExprError(); 19470 } 19471 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19472 // We must match the FunctionDecl's type to the hack introduced in 19473 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19474 // type. See the lengthy commentary in that routine. 19475 QualType FDT = FD->getType(); 19476 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19477 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19478 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19479 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19480 SourceLocation Loc = FD->getLocation(); 19481 FunctionDecl *NewFD = FunctionDecl::Create( 19482 S.Context, FD->getDeclContext(), Loc, Loc, 19483 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19484 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19485 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19486 19487 if (FD->getQualifier()) 19488 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19489 19490 SmallVector<ParmVarDecl*, 16> Params; 19491 for (const auto &AI : FT->param_types()) { 19492 ParmVarDecl *Param = 19493 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19494 Param->setScopeInfo(0, Params.size()); 19495 Params.push_back(Param); 19496 } 19497 NewFD->setParams(Params); 19498 DRE->setDecl(NewFD); 19499 VD = DRE->getDecl(); 19500 } 19501 } 19502 19503 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19504 if (MD->isInstance()) { 19505 ValueKind = VK_PRValue; 19506 Type = S.Context.BoundMemberTy; 19507 } 19508 19509 // Function references aren't l-values in C. 19510 if (!S.getLangOpts().CPlusPlus) 19511 ValueKind = VK_PRValue; 19512 19513 // - variables 19514 } else if (isa<VarDecl>(VD)) { 19515 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19516 Type = RefTy->getPointeeType(); 19517 } else if (Type->isFunctionType()) { 19518 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19519 << VD << E->getSourceRange(); 19520 return ExprError(); 19521 } 19522 19523 // - nothing else 19524 } else { 19525 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19526 << VD << E->getSourceRange(); 19527 return ExprError(); 19528 } 19529 19530 // Modifying the declaration like this is friendly to IR-gen but 19531 // also really dangerous. 19532 VD->setType(DestType); 19533 E->setType(Type); 19534 E->setValueKind(ValueKind); 19535 return E; 19536 } 19537 19538 /// Check a cast of an unknown-any type. We intentionally only 19539 /// trigger this for C-style casts. 19540 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19541 Expr *CastExpr, CastKind &CastKind, 19542 ExprValueKind &VK, CXXCastPath &Path) { 19543 // The type we're casting to must be either void or complete. 19544 if (!CastType->isVoidType() && 19545 RequireCompleteType(TypeRange.getBegin(), CastType, 19546 diag::err_typecheck_cast_to_incomplete)) 19547 return ExprError(); 19548 19549 // Rewrite the casted expression from scratch. 19550 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19551 if (!result.isUsable()) return ExprError(); 19552 19553 CastExpr = result.get(); 19554 VK = CastExpr->getValueKind(); 19555 CastKind = CK_NoOp; 19556 19557 return CastExpr; 19558 } 19559 19560 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19561 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19562 } 19563 19564 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19565 Expr *arg, QualType ¶mType) { 19566 // If the syntactic form of the argument is not an explicit cast of 19567 // any sort, just do default argument promotion. 19568 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19569 if (!castArg) { 19570 ExprResult result = DefaultArgumentPromotion(arg); 19571 if (result.isInvalid()) return ExprError(); 19572 paramType = result.get()->getType(); 19573 return result; 19574 } 19575 19576 // Otherwise, use the type that was written in the explicit cast. 19577 assert(!arg->hasPlaceholderType()); 19578 paramType = castArg->getTypeAsWritten(); 19579 19580 // Copy-initialize a parameter of that type. 19581 InitializedEntity entity = 19582 InitializedEntity::InitializeParameter(Context, paramType, 19583 /*consumed*/ false); 19584 return PerformCopyInitialization(entity, callLoc, arg); 19585 } 19586 19587 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19588 Expr *orig = E; 19589 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19590 while (true) { 19591 E = E->IgnoreParenImpCasts(); 19592 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19593 E = call->getCallee(); 19594 diagID = diag::err_uncasted_call_of_unknown_any; 19595 } else { 19596 break; 19597 } 19598 } 19599 19600 SourceLocation loc; 19601 NamedDecl *d; 19602 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19603 loc = ref->getLocation(); 19604 d = ref->getDecl(); 19605 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19606 loc = mem->getMemberLoc(); 19607 d = mem->getMemberDecl(); 19608 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19609 diagID = diag::err_uncasted_call_of_unknown_any; 19610 loc = msg->getSelectorStartLoc(); 19611 d = msg->getMethodDecl(); 19612 if (!d) { 19613 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19614 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19615 << orig->getSourceRange(); 19616 return ExprError(); 19617 } 19618 } else { 19619 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19620 << E->getSourceRange(); 19621 return ExprError(); 19622 } 19623 19624 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19625 19626 // Never recoverable. 19627 return ExprError(); 19628 } 19629 19630 /// Check for operands with placeholder types and complain if found. 19631 /// Returns ExprError() if there was an error and no recovery was possible. 19632 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19633 if (!Context.isDependenceAllowed()) { 19634 // C cannot handle TypoExpr nodes on either side of a binop because it 19635 // doesn't handle dependent types properly, so make sure any TypoExprs have 19636 // been dealt with before checking the operands. 19637 ExprResult Result = CorrectDelayedTyposInExpr(E); 19638 if (!Result.isUsable()) return ExprError(); 19639 E = Result.get(); 19640 } 19641 19642 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19643 if (!placeholderType) return E; 19644 19645 switch (placeholderType->getKind()) { 19646 19647 // Overloaded expressions. 19648 case BuiltinType::Overload: { 19649 // Try to resolve a single function template specialization. 19650 // This is obligatory. 19651 ExprResult Result = E; 19652 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19653 return Result; 19654 19655 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19656 // leaves Result unchanged on failure. 19657 Result = E; 19658 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19659 return Result; 19660 19661 // If that failed, try to recover with a call. 19662 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19663 /*complain*/ true); 19664 return Result; 19665 } 19666 19667 // Bound member functions. 19668 case BuiltinType::BoundMember: { 19669 ExprResult result = E; 19670 const Expr *BME = E->IgnoreParens(); 19671 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19672 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19673 if (isa<CXXPseudoDestructorExpr>(BME)) { 19674 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19675 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19676 if (ME->getMemberNameInfo().getName().getNameKind() == 19677 DeclarationName::CXXDestructorName) 19678 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19679 } 19680 tryToRecoverWithCall(result, PD, 19681 /*complain*/ true); 19682 return result; 19683 } 19684 19685 // ARC unbridged casts. 19686 case BuiltinType::ARCUnbridgedCast: { 19687 Expr *realCast = stripARCUnbridgedCast(E); 19688 diagnoseARCUnbridgedCast(realCast); 19689 return realCast; 19690 } 19691 19692 // Expressions of unknown type. 19693 case BuiltinType::UnknownAny: 19694 return diagnoseUnknownAnyExpr(*this, E); 19695 19696 // Pseudo-objects. 19697 case BuiltinType::PseudoObject: 19698 return checkPseudoObjectRValue(E); 19699 19700 case BuiltinType::BuiltinFn: { 19701 // Accept __noop without parens by implicitly converting it to a call expr. 19702 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19703 if (DRE) { 19704 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19705 if (FD->getBuiltinID() == Builtin::BI__noop) { 19706 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19707 CK_BuiltinFnToFnPtr) 19708 .get(); 19709 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19710 VK_PRValue, SourceLocation(), 19711 FPOptionsOverride()); 19712 } 19713 } 19714 19715 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19716 return ExprError(); 19717 } 19718 19719 case BuiltinType::IncompleteMatrixIdx: 19720 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19721 ->getRowIdx() 19722 ->getBeginLoc(), 19723 diag::err_matrix_incomplete_index); 19724 return ExprError(); 19725 19726 // Expressions of unknown type. 19727 case BuiltinType::OMPArraySection: 19728 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19729 return ExprError(); 19730 19731 // Expressions of unknown type. 19732 case BuiltinType::OMPArrayShaping: 19733 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19734 19735 case BuiltinType::OMPIterator: 19736 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19737 19738 // Everything else should be impossible. 19739 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19740 case BuiltinType::Id: 19741 #include "clang/Basic/OpenCLImageTypes.def" 19742 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19743 case BuiltinType::Id: 19744 #include "clang/Basic/OpenCLExtensionTypes.def" 19745 #define SVE_TYPE(Name, Id, SingletonId) \ 19746 case BuiltinType::Id: 19747 #include "clang/Basic/AArch64SVEACLETypes.def" 19748 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19749 case BuiltinType::Id: 19750 #include "clang/Basic/PPCTypes.def" 19751 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19752 #include "clang/Basic/RISCVVTypes.def" 19753 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19754 #define PLACEHOLDER_TYPE(Id, SingletonId) 19755 #include "clang/AST/BuiltinTypes.def" 19756 break; 19757 } 19758 19759 llvm_unreachable("invalid placeholder type!"); 19760 } 19761 19762 bool Sema::CheckCaseExpression(Expr *E) { 19763 if (E->isTypeDependent()) 19764 return true; 19765 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19766 return E->getType()->isIntegralOrEnumerationType(); 19767 return false; 19768 } 19769 19770 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19771 ExprResult 19772 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19773 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19774 "Unknown Objective-C Boolean value!"); 19775 QualType BoolT = Context.ObjCBuiltinBoolTy; 19776 if (!Context.getBOOLDecl()) { 19777 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19778 Sema::LookupOrdinaryName); 19779 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19780 NamedDecl *ND = Result.getFoundDecl(); 19781 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19782 Context.setBOOLDecl(TD); 19783 } 19784 } 19785 if (Context.getBOOLDecl()) 19786 BoolT = Context.getBOOLType(); 19787 return new (Context) 19788 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19789 } 19790 19791 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19792 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19793 SourceLocation RParen) { 19794 19795 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19796 19797 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19798 return Spec.getPlatform() == Platform; 19799 }); 19800 19801 VersionTuple Version; 19802 if (Spec != AvailSpecs.end()) 19803 Version = Spec->getVersion(); 19804 19805 // The use of `@available` in the enclosing context should be analyzed to 19806 // warn when it's used inappropriately (i.e. not if(@available)). 19807 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19808 Context->HasPotentialAvailabilityViolations = true; 19809 19810 return new (Context) 19811 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19812 } 19813 19814 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19815 ArrayRef<Expr *> SubExprs, QualType T) { 19816 if (!Context.getLangOpts().RecoveryAST) 19817 return ExprError(); 19818 19819 if (isSFINAEContext()) 19820 return ExprError(); 19821 19822 if (T.isNull() || T->isUndeducedType() || 19823 !Context.getLangOpts().RecoveryASTType) 19824 // We don't know the concrete type, fallback to dependent type. 19825 T = Context.DependentTy; 19826 19827 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19828 } 19829