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/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 if (LangOpts.OpenMP && isa<VarDecl>(D) && 343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 345 << getOpenMPDeclareMapperVarName(); 346 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 347 return true; 348 } 349 350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 351 AvoidPartialAvailabilityChecks, ClassReceiver); 352 353 DiagnoseUnusedOfDecl(*this, D, Loc); 354 355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 356 357 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 358 if (const auto *VD = dyn_cast<ValueDecl>(D)) 359 checkDeviceDecl(VD, Loc); 360 361 if (!Context.getTargetInfo().isTLSSupported()) 362 if (const auto *VD = dyn_cast<VarDecl>(D)) 363 if (VD->getTLSKind() != VarDecl::TLS_None) 364 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 365 } 366 367 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 368 !isUnevaluatedContext()) { 369 // C++ [expr.prim.req.nested] p3 370 // A local parameter shall only appear as an unevaluated operand 371 // (Clause 8) within the constraint-expression. 372 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 373 << D; 374 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 375 return true; 376 } 377 378 return false; 379 } 380 381 /// DiagnoseSentinelCalls - This routine checks whether a call or 382 /// message-send is to a declaration with the sentinel attribute, and 383 /// if so, it checks that the requirements of the sentinel are 384 /// satisfied. 385 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 386 ArrayRef<Expr *> Args) { 387 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 388 if (!attr) 389 return; 390 391 // The number of formal parameters of the declaration. 392 unsigned numFormalParams; 393 394 // The kind of declaration. This is also an index into a %select in 395 // the diagnostic. 396 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 397 398 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 399 numFormalParams = MD->param_size(); 400 calleeType = CT_Method; 401 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 402 numFormalParams = FD->param_size(); 403 calleeType = CT_Function; 404 } else if (isa<VarDecl>(D)) { 405 QualType type = cast<ValueDecl>(D)->getType(); 406 const FunctionType *fn = nullptr; 407 if (const PointerType *ptr = type->getAs<PointerType>()) { 408 fn = ptr->getPointeeType()->getAs<FunctionType>(); 409 if (!fn) return; 410 calleeType = CT_Function; 411 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 412 fn = ptr->getPointeeType()->castAs<FunctionType>(); 413 calleeType = CT_Block; 414 } else { 415 return; 416 } 417 418 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 419 numFormalParams = proto->getNumParams(); 420 } else { 421 numFormalParams = 0; 422 } 423 } else { 424 return; 425 } 426 427 // "nullPos" is the number of formal parameters at the end which 428 // effectively count as part of the variadic arguments. This is 429 // useful if you would prefer to not have *any* formal parameters, 430 // but the language forces you to have at least one. 431 unsigned nullPos = attr->getNullPos(); 432 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 433 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 434 435 // The number of arguments which should follow the sentinel. 436 unsigned numArgsAfterSentinel = attr->getSentinel(); 437 438 // If there aren't enough arguments for all the formal parameters, 439 // the sentinel, and the args after the sentinel, complain. 440 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 441 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 442 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 443 return; 444 } 445 446 // Otherwise, find the sentinel expression. 447 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 448 if (!sentinelExpr) return; 449 if (sentinelExpr->isValueDependent()) return; 450 if (Context.isSentinelNullExpr(sentinelExpr)) return; 451 452 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 453 // or 'NULL' if those are actually defined in the context. Only use 454 // 'nil' for ObjC methods, where it's much more likely that the 455 // variadic arguments form a list of object pointers. 456 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 457 std::string NullValue; 458 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 459 NullValue = "nil"; 460 else if (getLangOpts().CPlusPlus11) 461 NullValue = "nullptr"; 462 else if (PP.isMacroDefined("NULL")) 463 NullValue = "NULL"; 464 else 465 NullValue = "(void*) 0"; 466 467 if (MissingNilLoc.isInvalid()) 468 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 469 else 470 Diag(MissingNilLoc, diag::warn_missing_sentinel) 471 << int(calleeType) 472 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 474 } 475 476 SourceRange Sema::getExprRange(Expr *E) const { 477 return E ? E->getSourceRange() : SourceRange(); 478 } 479 480 //===----------------------------------------------------------------------===// 481 // Standard Promotions and Conversions 482 //===----------------------------------------------------------------------===// 483 484 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 485 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 486 // Handle any placeholder expressions which made it here. 487 if (E->getType()->isPlaceholderType()) { 488 ExprResult result = CheckPlaceholderExpr(E); 489 if (result.isInvalid()) return ExprError(); 490 E = result.get(); 491 } 492 493 QualType Ty = E->getType(); 494 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 495 496 if (Ty->isFunctionType()) { 497 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 498 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 499 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 500 return ExprError(); 501 502 E = ImpCastExprToType(E, Context.getPointerType(Ty), 503 CK_FunctionToPointerDecay).get(); 504 } else if (Ty->isArrayType()) { 505 // In C90 mode, arrays only promote to pointers if the array expression is 506 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 507 // type 'array of type' is converted to an expression that has type 'pointer 508 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 509 // that has type 'array of type' ...". The relevant change is "an lvalue" 510 // (C90) to "an expression" (C99). 511 // 512 // C++ 4.2p1: 513 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 514 // T" can be converted to an rvalue of type "pointer to T". 515 // 516 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 517 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 518 CK_ArrayToPointerDecay).get(); 519 } 520 return E; 521 } 522 523 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 524 // Check to see if we are dereferencing a null pointer. If so, 525 // and if not volatile-qualified, this is undefined behavior that the 526 // optimizer will delete, so warn about it. People sometimes try to use this 527 // to get a deterministic trap and are surprised by clang's behavior. This 528 // only handles the pattern "*null", which is a very syntactic check. 529 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 530 if (UO && UO->getOpcode() == UO_Deref && 531 UO->getSubExpr()->getType()->isPointerType()) { 532 const LangAS AS = 533 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 534 if ((!isTargetAddressSpace(AS) || 535 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 536 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 537 S.Context, Expr::NPC_ValueDependentIsNotNull) && 538 !UO->getType().isVolatileQualified()) { 539 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 540 S.PDiag(diag::warn_indirection_through_null) 541 << UO->getSubExpr()->getSourceRange()); 542 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 543 S.PDiag(diag::note_indirection_through_null)); 544 } 545 } 546 } 547 548 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 549 SourceLocation AssignLoc, 550 const Expr* RHS) { 551 const ObjCIvarDecl *IV = OIRE->getDecl(); 552 if (!IV) 553 return; 554 555 DeclarationName MemberName = IV->getDeclName(); 556 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 557 if (!Member || !Member->isStr("isa")) 558 return; 559 560 const Expr *Base = OIRE->getBase(); 561 QualType BaseType = Base->getType(); 562 if (OIRE->isArrow()) 563 BaseType = BaseType->getPointeeType(); 564 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 565 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 566 ObjCInterfaceDecl *ClassDeclared = nullptr; 567 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 568 if (!ClassDeclared->getSuperClass() 569 && (*ClassDeclared->ivar_begin()) == IV) { 570 if (RHS) { 571 NamedDecl *ObjectSetClass = 572 S.LookupSingleName(S.TUScope, 573 &S.Context.Idents.get("object_setClass"), 574 SourceLocation(), S.LookupOrdinaryName); 575 if (ObjectSetClass) { 576 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 577 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 578 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 579 "object_setClass(") 580 << FixItHint::CreateReplacement( 581 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 582 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 583 } 584 else 585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 586 } else { 587 NamedDecl *ObjectGetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_getClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectGetClass) 592 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 593 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 594 "object_getClass(") 595 << FixItHint::CreateReplacement( 596 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 597 else 598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 599 } 600 S.Diag(IV->getLocation(), diag::note_ivar_decl); 601 } 602 } 603 } 604 605 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 606 // Handle any placeholder expressions which made it here. 607 if (E->getType()->isPlaceholderType()) { 608 ExprResult result = CheckPlaceholderExpr(E); 609 if (result.isInvalid()) return ExprError(); 610 E = result.get(); 611 } 612 613 // C++ [conv.lval]p1: 614 // A glvalue of a non-function, non-array type T can be 615 // converted to a prvalue. 616 if (!E->isGLValue()) return E; 617 618 QualType T = E->getType(); 619 assert(!T.isNull() && "r-value conversion on typeless expression?"); 620 621 // lvalue-to-rvalue conversion cannot be applied to function or array types. 622 if (T->isFunctionType() || T->isArrayType()) 623 return E; 624 625 // We don't want to throw lvalue-to-rvalue casts on top of 626 // expressions of certain types in C++. 627 if (getLangOpts().CPlusPlus && 628 (E->getType() == Context.OverloadTy || 629 T->isDependentType() || 630 T->isRecordType())) 631 return E; 632 633 // The C standard is actually really unclear on this point, and 634 // DR106 tells us what the result should be but not why. It's 635 // generally best to say that void types just doesn't undergo 636 // lvalue-to-rvalue at all. Note that expressions of unqualified 637 // 'void' type are never l-values, but qualified void can be. 638 if (T->isVoidType()) 639 return E; 640 641 // OpenCL usually rejects direct accesses to values of 'half' type. 642 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 643 T->isHalfType()) { 644 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 645 << 0 << T; 646 return ExprError(); 647 } 648 649 CheckForNullPointerDereference(*this, E); 650 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 651 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 652 &Context.Idents.get("object_getClass"), 653 SourceLocation(), LookupOrdinaryName); 654 if (ObjectGetClass) 655 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 656 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 657 << FixItHint::CreateReplacement( 658 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 659 else 660 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 661 } 662 else if (const ObjCIvarRefExpr *OIRE = 663 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 664 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 665 666 // C++ [conv.lval]p1: 667 // [...] If T is a non-class type, the type of the prvalue is the 668 // cv-unqualified version of T. Otherwise, the type of the 669 // rvalue is T. 670 // 671 // C99 6.3.2.1p2: 672 // If the lvalue has qualified type, the value has the unqualified 673 // version of the type of the lvalue; otherwise, the value has the 674 // type of the lvalue. 675 if (T.hasQualifiers()) 676 T = T.getUnqualifiedType(); 677 678 // Under the MS ABI, lock down the inheritance model now. 679 if (T->isMemberPointerType() && 680 Context.getTargetInfo().getCXXABI().isMicrosoft()) 681 (void)isCompleteType(E->getExprLoc(), T); 682 683 ExprResult Res = CheckLValueToRValueConversionOperand(E); 684 if (Res.isInvalid()) 685 return Res; 686 E = Res.get(); 687 688 // Loading a __weak object implicitly retains the value, so we need a cleanup to 689 // balance that. 690 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 691 Cleanup.setExprNeedsCleanups(true); 692 693 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 694 Cleanup.setExprNeedsCleanups(true); 695 696 // C++ [conv.lval]p3: 697 // If T is cv std::nullptr_t, the result is a null pointer constant. 698 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 699 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 700 FPOptionsOverride()); 701 702 // C11 6.3.2.1p2: 703 // ... if the lvalue has atomic type, the value has the non-atomic version 704 // of the type of the lvalue ... 705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 706 T = Atomic->getValueType().getUnqualifiedType(); 707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 708 nullptr, VK_RValue, FPOptionsOverride()); 709 } 710 711 return Res; 712 } 713 714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 716 if (Res.isInvalid()) 717 return ExprError(); 718 Res = DefaultLvalueConversion(Res.get()); 719 if (Res.isInvalid()) 720 return ExprError(); 721 return Res; 722 } 723 724 /// CallExprUnaryConversions - a special case of an unary conversion 725 /// performed on a function designator of a call expression. 726 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 727 QualType Ty = E->getType(); 728 ExprResult Res = E; 729 // Only do implicit cast for a function type, but not for a pointer 730 // to function type. 731 if (Ty->isFunctionType()) { 732 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 733 CK_FunctionToPointerDecay); 734 if (Res.isInvalid()) 735 return ExprError(); 736 } 737 Res = DefaultLvalueConversion(Res.get()); 738 if (Res.isInvalid()) 739 return ExprError(); 740 return Res.get(); 741 } 742 743 /// UsualUnaryConversions - Performs various conversions that are common to most 744 /// operators (C99 6.3). The conversions of array and function types are 745 /// sometimes suppressed. For example, the array->pointer conversion doesn't 746 /// apply if the array is an argument to the sizeof or address (&) operators. 747 /// In these instances, this routine should *not* be called. 748 ExprResult Sema::UsualUnaryConversions(Expr *E) { 749 // First, convert to an r-value. 750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 751 if (Res.isInvalid()) 752 return ExprError(); 753 E = Res.get(); 754 755 QualType Ty = E->getType(); 756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 757 758 // Half FP have to be promoted to float unless it is natively supported 759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 761 762 // Try to perform integral promotions if the object has a theoretically 763 // promotable type. 764 if (Ty->isIntegralOrUnscopedEnumerationType()) { 765 // C99 6.3.1.1p2: 766 // 767 // The following may be used in an expression wherever an int or 768 // unsigned int may be used: 769 // - an object or expression with an integer type whose integer 770 // conversion rank is less than or equal to the rank of int 771 // and unsigned int. 772 // - A bit-field of type _Bool, int, signed int, or unsigned int. 773 // 774 // If an int can represent all values of the original type, the 775 // value is converted to an int; otherwise, it is converted to an 776 // unsigned int. These are called the integer promotions. All 777 // other types are unchanged by the integer promotions. 778 779 QualType PTy = Context.isPromotableBitField(E); 780 if (!PTy.isNull()) { 781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 782 return E; 783 } 784 if (Ty->isPromotableIntegerType()) { 785 QualType PT = Context.getPromotedIntegerType(Ty); 786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 787 return E; 788 } 789 } 790 return E; 791 } 792 793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 794 /// do not have a prototype. Arguments that have type float or __fp16 795 /// are promoted to double. All other argument types are converted by 796 /// UsualUnaryConversions(). 797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 798 QualType Ty = E->getType(); 799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 800 801 ExprResult Res = UsualUnaryConversions(E); 802 if (Res.isInvalid()) 803 return ExprError(); 804 E = Res.get(); 805 806 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 807 // promote to double. 808 // Note that default argument promotion applies only to float (and 809 // half/fp16); it does not apply to _Float16. 810 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 811 if (BTy && (BTy->getKind() == BuiltinType::Half || 812 BTy->getKind() == BuiltinType::Float)) { 813 if (getLangOpts().OpenCL && 814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 815 if (BTy->getKind() == BuiltinType::Half) { 816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 817 } 818 } else { 819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 820 } 821 } 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 868 return VAK_Invalid; 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getBeginLoc(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 910 LLVM_FALLTHROUGH; 911 case VAK_Valid: 912 if (Ty->isRecordType()) { 913 // This is unlikely to be what the user intended. If the class has a 914 // 'c_str' member function, the user probably meant to call that. 915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 916 PDiag(diag::warn_pass_class_arg_to_vararg) 917 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 918 } 919 break; 920 921 case VAK_Undefined: 922 case VAK_MSVCUndefined: 923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 925 << getLangOpts().CPlusPlus11 << Ty << CT); 926 break; 927 928 case VAK_Invalid: 929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 930 Diag(E->getBeginLoc(), 931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 932 << Ty << CT; 933 else if (Ty->isObjCObjectType()) 934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 936 << Ty << CT); 937 else 938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 939 << isa<InitListExpr>(E) << Ty << CT; 940 break; 941 } 942 } 943 944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 945 /// will create a trap if the resulting type is not a POD type. 946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 947 FunctionDecl *FDecl) { 948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 949 // Strip the unbridged-cast placeholder expression off, if applicable. 950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 951 (CT == VariadicMethod || 952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 953 E = stripARCUnbridgedCast(E); 954 955 // Otherwise, do normal placeholder checking. 956 } else { 957 ExprResult ExprRes = CheckPlaceholderExpr(E); 958 if (ExprRes.isInvalid()) 959 return ExprError(); 960 E = ExprRes.get(); 961 } 962 } 963 964 ExprResult ExprRes = DefaultArgumentPromotion(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 968 // Copy blocks to the heap. 969 if (ExprRes.get()->getType()->isBlockPointerType()) 970 maybeExtendBlockObject(ExprRes); 971 972 E = ExprRes.get(); 973 974 // Diagnostics regarding non-POD argument types are 975 // emitted along with format string checking in Sema::CheckFunctionCall(). 976 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 977 // Turn this into a trap. 978 CXXScopeSpec SS; 979 SourceLocation TemplateKWLoc; 980 UnqualifiedId Name; 981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 982 E->getBeginLoc()); 983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 984 /*HasTrailingLParen=*/true, 985 /*IsAddressOfOperand=*/false); 986 if (TrapFn.isInvalid()) 987 return ExprError(); 988 989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 990 None, E->getEndLoc()); 991 if (Call.isInvalid()) 992 return ExprError(); 993 994 ExprResult Comma = 995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 996 if (Comma.isInvalid()) 997 return ExprError(); 998 return Comma.get(); 999 } 1000 1001 if (!getLangOpts().CPlusPlus && 1002 RequireCompleteType(E->getExprLoc(), E->getType(), 1003 diag::err_call_incomplete_argument)) 1004 return ExprError(); 1005 1006 return E; 1007 } 1008 1009 /// Converts an integer to complex float type. Helper function of 1010 /// UsualArithmeticConversions() 1011 /// 1012 /// \return false if the integer expression is an integer type and is 1013 /// successfully converted to the complex type. 1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1015 ExprResult &ComplexExpr, 1016 QualType IntTy, 1017 QualType ComplexTy, 1018 bool SkipCast) { 1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1020 if (SkipCast) return false; 1021 if (IntTy->isIntegerType()) { 1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1025 CK_FloatingRealToComplex); 1026 } else { 1027 assert(IntTy->isComplexIntegerType()); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1029 CK_IntegralComplexToFloatingComplex); 1030 } 1031 return false; 1032 } 1033 1034 /// Handle arithmetic conversion with complex types. Helper function of 1035 /// UsualArithmeticConversions() 1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1037 ExprResult &RHS, QualType LHSType, 1038 QualType RHSType, 1039 bool IsCompAssign) { 1040 // if we have an integer operand, the result is the complex type. 1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1042 /*skipCast*/false)) 1043 return LHSType; 1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1045 /*skipCast*/IsCompAssign)) 1046 return RHSType; 1047 1048 // This handles complex/complex, complex/float, or float/complex. 1049 // When both operands are complex, the shorter operand is converted to the 1050 // type of the longer, and that is the type of the result. This corresponds 1051 // to what is done when combining two real floating-point operands. 1052 // The fun begins when size promotion occur across type domains. 1053 // From H&S 6.3.4: When one operand is complex and the other is a real 1054 // floating-point type, the less precise type is converted, within it's 1055 // real or complex domain, to the precision of the other type. For example, 1056 // when combining a "long double" with a "double _Complex", the 1057 // "double _Complex" is promoted to "long double _Complex". 1058 1059 // Compute the rank of the two types, regardless of whether they are complex. 1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1064 QualType LHSElementType = 1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1066 QualType RHSElementType = 1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1068 1069 QualType ResultType = S.Context.getComplexType(LHSElementType); 1070 if (Order < 0) { 1071 // Promote the precision of the LHS if not an assignment. 1072 ResultType = S.Context.getComplexType(RHSElementType); 1073 if (!IsCompAssign) { 1074 if (LHSComplexType) 1075 LHS = 1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1077 else 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1079 } 1080 } else if (Order > 0) { 1081 // Promote the precision of the RHS. 1082 if (RHSComplexType) 1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1084 else 1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1086 } 1087 return ResultType; 1088 } 1089 1090 /// Handle arithmetic conversion from integer to float. Helper function 1091 /// of UsualArithmeticConversions() 1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1093 ExprResult &IntExpr, 1094 QualType FloatTy, QualType IntTy, 1095 bool ConvertFloat, bool ConvertInt) { 1096 if (IntTy->isIntegerType()) { 1097 if (ConvertInt) 1098 // Convert intExpr to the lhs floating point type. 1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1100 CK_IntegralToFloating); 1101 return FloatTy; 1102 } 1103 1104 // Convert both sides to the appropriate complex float. 1105 assert(IntTy->isComplexIntegerType()); 1106 QualType result = S.Context.getComplexType(FloatTy); 1107 1108 // _Complex int -> _Complex float 1109 if (ConvertInt) 1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1111 CK_IntegralComplexToFloatingComplex); 1112 1113 // float -> _Complex float 1114 if (ConvertFloat) 1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1116 CK_FloatingRealToComplex); 1117 1118 return result; 1119 } 1120 1121 /// Handle arithmethic conversion with floating point types. Helper 1122 /// function of UsualArithmeticConversions() 1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1124 ExprResult &RHS, QualType LHSType, 1125 QualType RHSType, bool IsCompAssign) { 1126 bool LHSFloat = LHSType->isRealFloatingType(); 1127 bool RHSFloat = RHSType->isRealFloatingType(); 1128 1129 // N1169 4.1.4: If one of the operands has a floating type and the other 1130 // operand has a fixed-point type, the fixed-point operand 1131 // is converted to the floating type [...] 1132 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1133 if (LHSFloat) 1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1135 else if (!IsCompAssign) 1136 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1137 return LHSFloat ? LHSType : RHSType; 1138 } 1139 1140 // If we have two real floating types, convert the smaller operand 1141 // to the bigger result. 1142 if (LHSFloat && RHSFloat) { 1143 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1144 if (order > 0) { 1145 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1146 return LHSType; 1147 } 1148 1149 assert(order < 0 && "illegal float comparison"); 1150 if (!IsCompAssign) 1151 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1152 return RHSType; 1153 } 1154 1155 if (LHSFloat) { 1156 // Half FP has to be promoted to float unless it is natively supported 1157 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1158 LHSType = S.Context.FloatTy; 1159 1160 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1161 /*ConvertFloat=*/!IsCompAssign, 1162 /*ConvertInt=*/ true); 1163 } 1164 assert(RHSFloat); 1165 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1166 /*ConvertFloat=*/ true, 1167 /*ConvertInt=*/!IsCompAssign); 1168 } 1169 1170 /// Diagnose attempts to convert between __float128 and long double if 1171 /// there is no support for such conversion. Helper function of 1172 /// UsualArithmeticConversions(). 1173 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1174 QualType RHSType) { 1175 /* No issue converting if at least one of the types is not a floating point 1176 type or the two types have the same rank. 1177 */ 1178 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1179 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1180 return false; 1181 1182 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1183 "The remaining types must be floating point types."); 1184 1185 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1186 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1187 1188 QualType LHSElemType = LHSComplex ? 1189 LHSComplex->getElementType() : LHSType; 1190 QualType RHSElemType = RHSComplex ? 1191 RHSComplex->getElementType() : RHSType; 1192 1193 // No issue if the two types have the same representation 1194 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1195 &S.Context.getFloatTypeSemantics(RHSElemType)) 1196 return false; 1197 1198 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1199 RHSElemType == S.Context.LongDoubleTy); 1200 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1201 RHSElemType == S.Context.Float128Ty); 1202 1203 // We've handled the situation where __float128 and long double have the same 1204 // representation. We allow all conversions for all possible long double types 1205 // except PPC's double double. 1206 return Float128AndLongDouble && 1207 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1208 &llvm::APFloat::PPCDoubleDouble()); 1209 } 1210 1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1212 1213 namespace { 1214 /// These helper callbacks are placed in an anonymous namespace to 1215 /// permit their use as function template parameters. 1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1217 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1218 } 1219 1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1221 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1222 CK_IntegralComplexCast); 1223 } 1224 } 1225 1226 /// Handle integer arithmetic conversions. Helper function of 1227 /// UsualArithmeticConversions() 1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1230 ExprResult &RHS, QualType LHSType, 1231 QualType RHSType, bool IsCompAssign) { 1232 // The rules for this case are in C99 6.3.1.8 1233 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1234 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1235 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1236 if (LHSSigned == RHSSigned) { 1237 // Same signedness; use the higher-ranked type 1238 if (order >= 0) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else if (order != (LHSSigned ? 1 : -1)) { 1245 // The unsigned type has greater than or equal rank to the 1246 // signed type, so use the unsigned type 1247 if (RHSSigned) { 1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1249 return LHSType; 1250 } else if (!IsCompAssign) 1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1252 return RHSType; 1253 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1254 // The two types are different widths; if we are here, that 1255 // means the signed type is larger than the unsigned type, so 1256 // use the signed type. 1257 if (LHSSigned) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else { 1264 // The signed type is higher-ranked than the unsigned type, 1265 // but isn't actually any bigger (like unsigned int and long 1266 // on most 32-bit systems). Use the unsigned type corresponding 1267 // to the signed type. 1268 QualType result = 1269 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1270 RHS = (*doRHSCast)(S, RHS.get(), result); 1271 if (!IsCompAssign) 1272 LHS = (*doLHSCast)(S, LHS.get(), result); 1273 return result; 1274 } 1275 } 1276 1277 /// Handle conversions with GCC complex int extension. Helper function 1278 /// of UsualArithmeticConversions() 1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1280 ExprResult &RHS, QualType LHSType, 1281 QualType RHSType, 1282 bool IsCompAssign) { 1283 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1284 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1285 1286 if (LHSComplexInt && RHSComplexInt) { 1287 QualType LHSEltType = LHSComplexInt->getElementType(); 1288 QualType RHSEltType = RHSComplexInt->getElementType(); 1289 QualType ScalarType = 1290 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1291 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1292 1293 return S.Context.getComplexType(ScalarType); 1294 } 1295 1296 if (LHSComplexInt) { 1297 QualType LHSEltType = LHSComplexInt->getElementType(); 1298 QualType ScalarType = 1299 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1300 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1301 QualType ComplexType = S.Context.getComplexType(ScalarType); 1302 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1303 CK_IntegralRealToComplex); 1304 1305 return ComplexType; 1306 } 1307 1308 assert(RHSComplexInt); 1309 1310 QualType RHSEltType = RHSComplexInt->getElementType(); 1311 QualType ScalarType = 1312 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1313 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1314 QualType ComplexType = S.Context.getComplexType(ScalarType); 1315 1316 if (!IsCompAssign) 1317 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1318 CK_IntegralRealToComplex); 1319 return ComplexType; 1320 } 1321 1322 /// Return the rank of a given fixed point or integer type. The value itself 1323 /// doesn't matter, but the values must be increasing with proper increasing 1324 /// rank as described in N1169 4.1.1. 1325 static unsigned GetFixedPointRank(QualType Ty) { 1326 const auto *BTy = Ty->getAs<BuiltinType>(); 1327 assert(BTy && "Expected a builtin type."); 1328 1329 switch (BTy->getKind()) { 1330 case BuiltinType::ShortFract: 1331 case BuiltinType::UShortFract: 1332 case BuiltinType::SatShortFract: 1333 case BuiltinType::SatUShortFract: 1334 return 1; 1335 case BuiltinType::Fract: 1336 case BuiltinType::UFract: 1337 case BuiltinType::SatFract: 1338 case BuiltinType::SatUFract: 1339 return 2; 1340 case BuiltinType::LongFract: 1341 case BuiltinType::ULongFract: 1342 case BuiltinType::SatLongFract: 1343 case BuiltinType::SatULongFract: 1344 return 3; 1345 case BuiltinType::ShortAccum: 1346 case BuiltinType::UShortAccum: 1347 case BuiltinType::SatShortAccum: 1348 case BuiltinType::SatUShortAccum: 1349 return 4; 1350 case BuiltinType::Accum: 1351 case BuiltinType::UAccum: 1352 case BuiltinType::SatAccum: 1353 case BuiltinType::SatUAccum: 1354 return 5; 1355 case BuiltinType::LongAccum: 1356 case BuiltinType::ULongAccum: 1357 case BuiltinType::SatLongAccum: 1358 case BuiltinType::SatULongAccum: 1359 return 6; 1360 default: 1361 if (BTy->isInteger()) 1362 return 0; 1363 llvm_unreachable("Unexpected fixed point or integer type"); 1364 } 1365 } 1366 1367 /// handleFixedPointConversion - Fixed point operations between fixed 1368 /// point types and integers or other fixed point types do not fall under 1369 /// usual arithmetic conversion since these conversions could result in loss 1370 /// of precsision (N1169 4.1.4). These operations should be calculated with 1371 /// the full precision of their result type (N1169 4.1.6.2.1). 1372 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1373 QualType RHSTy) { 1374 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1375 "Expected at least one of the operands to be a fixed point type"); 1376 assert((LHSTy->isFixedPointOrIntegerType() || 1377 RHSTy->isFixedPointOrIntegerType()) && 1378 "Special fixed point arithmetic operation conversions are only " 1379 "applied to ints or other fixed point types"); 1380 1381 // If one operand has signed fixed-point type and the other operand has 1382 // unsigned fixed-point type, then the unsigned fixed-point operand is 1383 // converted to its corresponding signed fixed-point type and the resulting 1384 // type is the type of the converted operand. 1385 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1386 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1387 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1388 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1389 1390 // The result type is the type with the highest rank, whereby a fixed-point 1391 // conversion rank is always greater than an integer conversion rank; if the 1392 // type of either of the operands is a saturating fixedpoint type, the result 1393 // type shall be the saturating fixed-point type corresponding to the type 1394 // with the highest rank; the resulting value is converted (taking into 1395 // account rounding and overflow) to the precision of the resulting type. 1396 // Same ranks between signed and unsigned types are resolved earlier, so both 1397 // types are either signed or both unsigned at this point. 1398 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1399 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1400 1401 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1402 1403 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1404 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1405 1406 return ResultTy; 1407 } 1408 1409 /// Check that the usual arithmetic conversions can be performed on this pair of 1410 /// expressions that might be of enumeration type. 1411 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1412 SourceLocation Loc, 1413 Sema::ArithConvKind ACK) { 1414 // C++2a [expr.arith.conv]p1: 1415 // If one operand is of enumeration type and the other operand is of a 1416 // different enumeration type or a floating-point type, this behavior is 1417 // deprecated ([depr.arith.conv.enum]). 1418 // 1419 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1420 // Eventually we will presumably reject these cases (in C++23 onwards?). 1421 QualType L = LHS->getType(), R = RHS->getType(); 1422 bool LEnum = L->isUnscopedEnumerationType(), 1423 REnum = R->isUnscopedEnumerationType(); 1424 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1425 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1426 (REnum && L->isFloatingType())) { 1427 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1428 ? diag::warn_arith_conv_enum_float_cxx20 1429 : diag::warn_arith_conv_enum_float) 1430 << LHS->getSourceRange() << RHS->getSourceRange() 1431 << (int)ACK << LEnum << L << R; 1432 } else if (!IsCompAssign && LEnum && REnum && 1433 !S.Context.hasSameUnqualifiedType(L, R)) { 1434 unsigned DiagID; 1435 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1436 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1437 // If either enumeration type is unnamed, it's less likely that the 1438 // user cares about this, but this situation is still deprecated in 1439 // C++2a. Use a different warning group. 1440 DiagID = S.getLangOpts().CPlusPlus20 1441 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1442 : diag::warn_arith_conv_mixed_anon_enum_types; 1443 } else if (ACK == Sema::ACK_Conditional) { 1444 // Conditional expressions are separated out because they have 1445 // historically had a different warning flag. 1446 DiagID = S.getLangOpts().CPlusPlus20 1447 ? diag::warn_conditional_mixed_enum_types_cxx20 1448 : diag::warn_conditional_mixed_enum_types; 1449 } else if (ACK == Sema::ACK_Comparison) { 1450 // Comparison expressions are separated out because they have 1451 // historically had a different warning flag. 1452 DiagID = S.getLangOpts().CPlusPlus20 1453 ? diag::warn_comparison_mixed_enum_types_cxx20 1454 : diag::warn_comparison_mixed_enum_types; 1455 } else { 1456 DiagID = S.getLangOpts().CPlusPlus20 1457 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1458 : diag::warn_arith_conv_mixed_enum_types; 1459 } 1460 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1461 << (int)ACK << L << R; 1462 } 1463 } 1464 1465 /// UsualArithmeticConversions - Performs various conversions that are common to 1466 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1467 /// routine returns the first non-arithmetic type found. The client is 1468 /// responsible for emitting appropriate error diagnostics. 1469 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1470 SourceLocation Loc, 1471 ArithConvKind ACK) { 1472 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1473 1474 if (ACK != ACK_CompAssign) { 1475 LHS = UsualUnaryConversions(LHS.get()); 1476 if (LHS.isInvalid()) 1477 return QualType(); 1478 } 1479 1480 RHS = UsualUnaryConversions(RHS.get()); 1481 if (RHS.isInvalid()) 1482 return QualType(); 1483 1484 // For conversion purposes, we ignore any qualifiers. 1485 // For example, "const float" and "float" are equivalent. 1486 QualType LHSType = 1487 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1488 QualType RHSType = 1489 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1490 1491 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1492 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1493 LHSType = AtomicLHS->getValueType(); 1494 1495 // If both types are identical, no conversion is needed. 1496 if (LHSType == RHSType) 1497 return LHSType; 1498 1499 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1500 // The caller can deal with this (e.g. pointer + int). 1501 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1502 return QualType(); 1503 1504 // Apply unary and bitfield promotions to the LHS's type. 1505 QualType LHSUnpromotedType = LHSType; 1506 if (LHSType->isPromotableIntegerType()) 1507 LHSType = Context.getPromotedIntegerType(LHSType); 1508 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1509 if (!LHSBitfieldPromoteTy.isNull()) 1510 LHSType = LHSBitfieldPromoteTy; 1511 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1512 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1513 1514 // If both types are identical, no conversion is needed. 1515 if (LHSType == RHSType) 1516 return LHSType; 1517 1518 // ExtInt types aren't subject to conversions between them or normal integers, 1519 // so this fails. 1520 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1521 return QualType(); 1522 1523 // At this point, we have two different arithmetic types. 1524 1525 // Diagnose attempts to convert between __float128 and long double where 1526 // such conversions currently can't be handled. 1527 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1528 return QualType(); 1529 1530 // Handle complex types first (C99 6.3.1.8p1). 1531 if (LHSType->isComplexType() || RHSType->isComplexType()) 1532 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1533 ACK == ACK_CompAssign); 1534 1535 // Now handle "real" floating types (i.e. float, double, long double). 1536 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1537 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1538 ACK == ACK_CompAssign); 1539 1540 // Handle GCC complex int extension. 1541 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1542 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1543 ACK == ACK_CompAssign); 1544 1545 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1546 return handleFixedPointConversion(*this, LHSType, RHSType); 1547 1548 // Finally, we have two differing integer types. 1549 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1550 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1551 } 1552 1553 //===----------------------------------------------------------------------===// 1554 // Semantic Analysis for various Expression Types 1555 //===----------------------------------------------------------------------===// 1556 1557 1558 ExprResult 1559 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1560 SourceLocation DefaultLoc, 1561 SourceLocation RParenLoc, 1562 Expr *ControllingExpr, 1563 ArrayRef<ParsedType> ArgTypes, 1564 ArrayRef<Expr *> ArgExprs) { 1565 unsigned NumAssocs = ArgTypes.size(); 1566 assert(NumAssocs == ArgExprs.size()); 1567 1568 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1569 for (unsigned i = 0; i < NumAssocs; ++i) { 1570 if (ArgTypes[i]) 1571 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1572 else 1573 Types[i] = nullptr; 1574 } 1575 1576 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1577 ControllingExpr, 1578 llvm::makeArrayRef(Types, NumAssocs), 1579 ArgExprs); 1580 delete [] Types; 1581 return ER; 1582 } 1583 1584 ExprResult 1585 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1586 SourceLocation DefaultLoc, 1587 SourceLocation RParenLoc, 1588 Expr *ControllingExpr, 1589 ArrayRef<TypeSourceInfo *> Types, 1590 ArrayRef<Expr *> Exprs) { 1591 unsigned NumAssocs = Types.size(); 1592 assert(NumAssocs == Exprs.size()); 1593 1594 // Decay and strip qualifiers for the controlling expression type, and handle 1595 // placeholder type replacement. See committee discussion from WG14 DR423. 1596 { 1597 EnterExpressionEvaluationContext Unevaluated( 1598 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1599 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1600 if (R.isInvalid()) 1601 return ExprError(); 1602 ControllingExpr = R.get(); 1603 } 1604 1605 // The controlling expression is an unevaluated operand, so side effects are 1606 // likely unintended. 1607 if (!inTemplateInstantiation() && 1608 ControllingExpr->HasSideEffects(Context, false)) 1609 Diag(ControllingExpr->getExprLoc(), 1610 diag::warn_side_effects_unevaluated_context); 1611 1612 bool TypeErrorFound = false, 1613 IsResultDependent = ControllingExpr->isTypeDependent(), 1614 ContainsUnexpandedParameterPack 1615 = ControllingExpr->containsUnexpandedParameterPack(); 1616 1617 for (unsigned i = 0; i < NumAssocs; ++i) { 1618 if (Exprs[i]->containsUnexpandedParameterPack()) 1619 ContainsUnexpandedParameterPack = true; 1620 1621 if (Types[i]) { 1622 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1623 ContainsUnexpandedParameterPack = true; 1624 1625 if (Types[i]->getType()->isDependentType()) { 1626 IsResultDependent = true; 1627 } else { 1628 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1629 // complete object type other than a variably modified type." 1630 unsigned D = 0; 1631 if (Types[i]->getType()->isIncompleteType()) 1632 D = diag::err_assoc_type_incomplete; 1633 else if (!Types[i]->getType()->isObjectType()) 1634 D = diag::err_assoc_type_nonobject; 1635 else if (Types[i]->getType()->isVariablyModifiedType()) 1636 D = diag::err_assoc_type_variably_modified; 1637 1638 if (D != 0) { 1639 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1640 << Types[i]->getTypeLoc().getSourceRange() 1641 << Types[i]->getType(); 1642 TypeErrorFound = true; 1643 } 1644 1645 // C11 6.5.1.1p2 "No two generic associations in the same generic 1646 // selection shall specify compatible types." 1647 for (unsigned j = i+1; j < NumAssocs; ++j) 1648 if (Types[j] && !Types[j]->getType()->isDependentType() && 1649 Context.typesAreCompatible(Types[i]->getType(), 1650 Types[j]->getType())) { 1651 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1652 diag::err_assoc_compatible_types) 1653 << Types[j]->getTypeLoc().getSourceRange() 1654 << Types[j]->getType() 1655 << Types[i]->getType(); 1656 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1657 diag::note_compat_assoc) 1658 << Types[i]->getTypeLoc().getSourceRange() 1659 << Types[i]->getType(); 1660 TypeErrorFound = true; 1661 } 1662 } 1663 } 1664 } 1665 if (TypeErrorFound) 1666 return ExprError(); 1667 1668 // If we determined that the generic selection is result-dependent, don't 1669 // try to compute the result expression. 1670 if (IsResultDependent) 1671 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1672 Exprs, DefaultLoc, RParenLoc, 1673 ContainsUnexpandedParameterPack); 1674 1675 SmallVector<unsigned, 1> CompatIndices; 1676 unsigned DefaultIndex = -1U; 1677 for (unsigned i = 0; i < NumAssocs; ++i) { 1678 if (!Types[i]) 1679 DefaultIndex = i; 1680 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1681 Types[i]->getType())) 1682 CompatIndices.push_back(i); 1683 } 1684 1685 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1686 // type compatible with at most one of the types named in its generic 1687 // association list." 1688 if (CompatIndices.size() > 1) { 1689 // We strip parens here because the controlling expression is typically 1690 // parenthesized in macro definitions. 1691 ControllingExpr = ControllingExpr->IgnoreParens(); 1692 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1693 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1694 << (unsigned)CompatIndices.size(); 1695 for (unsigned I : CompatIndices) { 1696 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1697 diag::note_compat_assoc) 1698 << Types[I]->getTypeLoc().getSourceRange() 1699 << Types[I]->getType(); 1700 } 1701 return ExprError(); 1702 } 1703 1704 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1705 // its controlling expression shall have type compatible with exactly one of 1706 // the types named in its generic association list." 1707 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1708 // We strip parens here because the controlling expression is typically 1709 // parenthesized in macro definitions. 1710 ControllingExpr = ControllingExpr->IgnoreParens(); 1711 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1712 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1713 return ExprError(); 1714 } 1715 1716 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1717 // type name that is compatible with the type of the controlling expression, 1718 // then the result expression of the generic selection is the expression 1719 // in that generic association. Otherwise, the result expression of the 1720 // generic selection is the expression in the default generic association." 1721 unsigned ResultIndex = 1722 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1723 1724 return GenericSelectionExpr::Create( 1725 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1726 ContainsUnexpandedParameterPack, ResultIndex); 1727 } 1728 1729 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1730 /// location of the token and the offset of the ud-suffix within it. 1731 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1732 unsigned Offset) { 1733 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1734 S.getLangOpts()); 1735 } 1736 1737 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1738 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1739 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1740 IdentifierInfo *UDSuffix, 1741 SourceLocation UDSuffixLoc, 1742 ArrayRef<Expr*> Args, 1743 SourceLocation LitEndLoc) { 1744 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1745 1746 QualType ArgTy[2]; 1747 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1748 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1749 if (ArgTy[ArgIdx]->isArrayType()) 1750 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1751 } 1752 1753 DeclarationName OpName = 1754 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1755 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1756 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1757 1758 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1759 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1760 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1761 /*AllowStringTemplate*/ false, 1762 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1763 return ExprError(); 1764 1765 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1766 } 1767 1768 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1769 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1770 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1771 /// multiple tokens. However, the common case is that StringToks points to one 1772 /// string. 1773 /// 1774 ExprResult 1775 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1776 assert(!StringToks.empty() && "Must have at least one string!"); 1777 1778 StringLiteralParser Literal(StringToks, PP); 1779 if (Literal.hadError) 1780 return ExprError(); 1781 1782 SmallVector<SourceLocation, 4> StringTokLocs; 1783 for (const Token &Tok : StringToks) 1784 StringTokLocs.push_back(Tok.getLocation()); 1785 1786 QualType CharTy = Context.CharTy; 1787 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1788 if (Literal.isWide()) { 1789 CharTy = Context.getWideCharType(); 1790 Kind = StringLiteral::Wide; 1791 } else if (Literal.isUTF8()) { 1792 if (getLangOpts().Char8) 1793 CharTy = Context.Char8Ty; 1794 Kind = StringLiteral::UTF8; 1795 } else if (Literal.isUTF16()) { 1796 CharTy = Context.Char16Ty; 1797 Kind = StringLiteral::UTF16; 1798 } else if (Literal.isUTF32()) { 1799 CharTy = Context.Char32Ty; 1800 Kind = StringLiteral::UTF32; 1801 } else if (Literal.isPascal()) { 1802 CharTy = Context.UnsignedCharTy; 1803 } 1804 1805 // Warn on initializing an array of char from a u8 string literal; this 1806 // becomes ill-formed in C++2a. 1807 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1808 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1809 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1810 1811 // Create removals for all 'u8' prefixes in the string literal(s). This 1812 // ensures C++2a compatibility (but may change the program behavior when 1813 // built by non-Clang compilers for which the execution character set is 1814 // not always UTF-8). 1815 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1816 SourceLocation RemovalDiagLoc; 1817 for (const Token &Tok : StringToks) { 1818 if (Tok.getKind() == tok::utf8_string_literal) { 1819 if (RemovalDiagLoc.isInvalid()) 1820 RemovalDiagLoc = Tok.getLocation(); 1821 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1822 Tok.getLocation(), 1823 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1824 getSourceManager(), getLangOpts()))); 1825 } 1826 } 1827 Diag(RemovalDiagLoc, RemovalDiag); 1828 } 1829 1830 QualType StrTy = 1831 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1832 1833 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1834 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1835 Kind, Literal.Pascal, StrTy, 1836 &StringTokLocs[0], 1837 StringTokLocs.size()); 1838 if (Literal.getUDSuffix().empty()) 1839 return Lit; 1840 1841 // We're building a user-defined literal. 1842 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1843 SourceLocation UDSuffixLoc = 1844 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1845 Literal.getUDSuffixOffset()); 1846 1847 // Make sure we're allowed user-defined literals here. 1848 if (!UDLScope) 1849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1850 1851 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1852 // operator "" X (str, len) 1853 QualType SizeType = Context.getSizeType(); 1854 1855 DeclarationName OpName = 1856 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1857 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1858 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1859 1860 QualType ArgTy[] = { 1861 Context.getArrayDecayedType(StrTy), SizeType 1862 }; 1863 1864 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1865 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1866 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1867 /*AllowStringTemplate*/ true, 1868 /*DiagnoseMissing*/ true)) { 1869 1870 case LOLR_Cooked: { 1871 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1872 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1873 StringTokLocs[0]); 1874 Expr *Args[] = { Lit, LenArg }; 1875 1876 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1877 } 1878 1879 case LOLR_StringTemplate: { 1880 TemplateArgumentListInfo ExplicitArgs; 1881 1882 unsigned CharBits = Context.getIntWidth(CharTy); 1883 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1884 llvm::APSInt Value(CharBits, CharIsUnsigned); 1885 1886 TemplateArgument TypeArg(CharTy); 1887 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1888 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1889 1890 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1891 Value = Lit->getCodeUnit(I); 1892 TemplateArgument Arg(Context, Value, CharTy); 1893 TemplateArgumentLocInfo ArgInfo; 1894 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1895 } 1896 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1897 &ExplicitArgs); 1898 } 1899 case LOLR_Raw: 1900 case LOLR_Template: 1901 case LOLR_ErrorNoDiagnostic: 1902 llvm_unreachable("unexpected literal operator lookup result"); 1903 case LOLR_Error: 1904 return ExprError(); 1905 } 1906 llvm_unreachable("unexpected literal operator lookup result"); 1907 } 1908 1909 DeclRefExpr * 1910 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1911 SourceLocation Loc, 1912 const CXXScopeSpec *SS) { 1913 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1914 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1915 } 1916 1917 DeclRefExpr * 1918 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1919 const DeclarationNameInfo &NameInfo, 1920 const CXXScopeSpec *SS, NamedDecl *FoundD, 1921 SourceLocation TemplateKWLoc, 1922 const TemplateArgumentListInfo *TemplateArgs) { 1923 NestedNameSpecifierLoc NNS = 1924 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1925 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1926 TemplateArgs); 1927 } 1928 1929 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1930 // A declaration named in an unevaluated operand never constitutes an odr-use. 1931 if (isUnevaluatedContext()) 1932 return NOUR_Unevaluated; 1933 1934 // C++2a [basic.def.odr]p4: 1935 // A variable x whose name appears as a potentially-evaluated expression e 1936 // is odr-used by e unless [...] x is a reference that is usable in 1937 // constant expressions. 1938 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1939 if (VD->getType()->isReferenceType() && 1940 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1941 VD->isUsableInConstantExpressions(Context)) 1942 return NOUR_Constant; 1943 } 1944 1945 // All remaining non-variable cases constitute an odr-use. For variables, we 1946 // need to wait and see how the expression is used. 1947 return NOUR_None; 1948 } 1949 1950 /// BuildDeclRefExpr - Build an expression that references a 1951 /// declaration that does not require a closure capture. 1952 DeclRefExpr * 1953 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1954 const DeclarationNameInfo &NameInfo, 1955 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1956 SourceLocation TemplateKWLoc, 1957 const TemplateArgumentListInfo *TemplateArgs) { 1958 bool RefersToCapturedVariable = 1959 isa<VarDecl>(D) && 1960 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1961 1962 DeclRefExpr *E = DeclRefExpr::Create( 1963 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1964 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1965 MarkDeclRefReferenced(E); 1966 1967 // C++ [except.spec]p17: 1968 // An exception-specification is considered to be needed when: 1969 // - in an expression, the function is the unique lookup result or 1970 // the selected member of a set of overloaded functions. 1971 // 1972 // We delay doing this until after we've built the function reference and 1973 // marked it as used so that: 1974 // a) if the function is defaulted, we get errors from defining it before / 1975 // instead of errors from computing its exception specification, and 1976 // b) if the function is a defaulted comparison, we can use the body we 1977 // build when defining it as input to the exception specification 1978 // computation rather than computing a new body. 1979 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1980 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1981 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1982 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1983 } 1984 } 1985 1986 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1987 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1988 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1989 getCurFunction()->recordUseOfWeak(E); 1990 1991 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1992 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1993 FD = IFD->getAnonField(); 1994 if (FD) { 1995 UnusedPrivateFields.remove(FD); 1996 // Just in case we're building an illegal pointer-to-member. 1997 if (FD->isBitField()) 1998 E->setObjectKind(OK_BitField); 1999 } 2000 2001 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2002 // designates a bit-field. 2003 if (auto *BD = dyn_cast<BindingDecl>(D)) 2004 if (auto *BE = BD->getBinding()) 2005 E->setObjectKind(BE->getObjectKind()); 2006 2007 return E; 2008 } 2009 2010 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2011 /// possibly a list of template arguments. 2012 /// 2013 /// If this produces template arguments, it is permitted to call 2014 /// DecomposeTemplateName. 2015 /// 2016 /// This actually loses a lot of source location information for 2017 /// non-standard name kinds; we should consider preserving that in 2018 /// some way. 2019 void 2020 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2021 TemplateArgumentListInfo &Buffer, 2022 DeclarationNameInfo &NameInfo, 2023 const TemplateArgumentListInfo *&TemplateArgs) { 2024 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2025 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2026 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2027 2028 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2029 Id.TemplateId->NumArgs); 2030 translateTemplateArguments(TemplateArgsPtr, Buffer); 2031 2032 TemplateName TName = Id.TemplateId->Template.get(); 2033 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2034 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2035 TemplateArgs = &Buffer; 2036 } else { 2037 NameInfo = GetNameFromUnqualifiedId(Id); 2038 TemplateArgs = nullptr; 2039 } 2040 } 2041 2042 static void emitEmptyLookupTypoDiagnostic( 2043 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2044 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2045 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2046 DeclContext *Ctx = 2047 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2048 if (!TC) { 2049 // Emit a special diagnostic for failed member lookups. 2050 // FIXME: computing the declaration context might fail here (?) 2051 if (Ctx) 2052 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2053 << SS.getRange(); 2054 else 2055 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2056 return; 2057 } 2058 2059 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2060 bool DroppedSpecifier = 2061 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2062 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2063 ? diag::note_implicit_param_decl 2064 : diag::note_previous_decl; 2065 if (!Ctx) 2066 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2067 SemaRef.PDiag(NoteID)); 2068 else 2069 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2070 << Typo << Ctx << DroppedSpecifier 2071 << SS.getRange(), 2072 SemaRef.PDiag(NoteID)); 2073 } 2074 2075 /// Diagnose an empty lookup. 2076 /// 2077 /// \return false if new lookup candidates were found 2078 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2079 CorrectionCandidateCallback &CCC, 2080 TemplateArgumentListInfo *ExplicitTemplateArgs, 2081 ArrayRef<Expr *> Args, TypoExpr **Out) { 2082 DeclarationName Name = R.getLookupName(); 2083 2084 unsigned diagnostic = diag::err_undeclared_var_use; 2085 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2086 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2087 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2088 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2089 diagnostic = diag::err_undeclared_use; 2090 diagnostic_suggest = diag::err_undeclared_use_suggest; 2091 } 2092 2093 // If the original lookup was an unqualified lookup, fake an 2094 // unqualified lookup. This is useful when (for example) the 2095 // original lookup would not have found something because it was a 2096 // dependent name. 2097 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2098 while (DC) { 2099 if (isa<CXXRecordDecl>(DC)) { 2100 LookupQualifiedName(R, DC); 2101 2102 if (!R.empty()) { 2103 // Don't give errors about ambiguities in this lookup. 2104 R.suppressDiagnostics(); 2105 2106 // During a default argument instantiation the CurContext points 2107 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2108 // function parameter list, hence add an explicit check. 2109 bool isDefaultArgument = 2110 !CodeSynthesisContexts.empty() && 2111 CodeSynthesisContexts.back().Kind == 2112 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2113 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2114 bool isInstance = CurMethod && 2115 CurMethod->isInstance() && 2116 DC == CurMethod->getParent() && !isDefaultArgument; 2117 2118 // Give a code modification hint to insert 'this->'. 2119 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2120 // Actually quite difficult! 2121 if (getLangOpts().MSVCCompat) 2122 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2123 if (isInstance) { 2124 Diag(R.getNameLoc(), diagnostic) << Name 2125 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2126 CheckCXXThisCapture(R.getNameLoc()); 2127 } else { 2128 Diag(R.getNameLoc(), diagnostic) << Name; 2129 } 2130 2131 // Do we really want to note all of these? 2132 for (NamedDecl *D : R) 2133 Diag(D->getLocation(), diag::note_dependent_var_use); 2134 2135 // Return true if we are inside a default argument instantiation 2136 // and the found name refers to an instance member function, otherwise 2137 // the function calling DiagnoseEmptyLookup will try to create an 2138 // implicit member call and this is wrong for default argument. 2139 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2140 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2141 return true; 2142 } 2143 2144 // Tell the callee to try to recover. 2145 return false; 2146 } 2147 2148 R.clear(); 2149 } 2150 2151 DC = DC->getLookupParent(); 2152 } 2153 2154 // We didn't find anything, so try to correct for a typo. 2155 TypoCorrection Corrected; 2156 if (S && Out) { 2157 SourceLocation TypoLoc = R.getNameLoc(); 2158 assert(!ExplicitTemplateArgs && 2159 "Diagnosing an empty lookup with explicit template args!"); 2160 *Out = CorrectTypoDelayed( 2161 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2162 [=](const TypoCorrection &TC) { 2163 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2164 diagnostic, diagnostic_suggest); 2165 }, 2166 nullptr, CTK_ErrorRecovery); 2167 if (*Out) 2168 return true; 2169 } else if (S && 2170 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2171 S, &SS, CCC, CTK_ErrorRecovery))) { 2172 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2173 bool DroppedSpecifier = 2174 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2175 R.setLookupName(Corrected.getCorrection()); 2176 2177 bool AcceptableWithRecovery = false; 2178 bool AcceptableWithoutRecovery = false; 2179 NamedDecl *ND = Corrected.getFoundDecl(); 2180 if (ND) { 2181 if (Corrected.isOverloaded()) { 2182 OverloadCandidateSet OCS(R.getNameLoc(), 2183 OverloadCandidateSet::CSK_Normal); 2184 OverloadCandidateSet::iterator Best; 2185 for (NamedDecl *CD : Corrected) { 2186 if (FunctionTemplateDecl *FTD = 2187 dyn_cast<FunctionTemplateDecl>(CD)) 2188 AddTemplateOverloadCandidate( 2189 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2190 Args, OCS); 2191 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2192 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2193 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2194 Args, OCS); 2195 } 2196 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2197 case OR_Success: 2198 ND = Best->FoundDecl; 2199 Corrected.setCorrectionDecl(ND); 2200 break; 2201 default: 2202 // FIXME: Arbitrarily pick the first declaration for the note. 2203 Corrected.setCorrectionDecl(ND); 2204 break; 2205 } 2206 } 2207 R.addDecl(ND); 2208 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2209 CXXRecordDecl *Record = nullptr; 2210 if (Corrected.getCorrectionSpecifier()) { 2211 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2212 Record = Ty->getAsCXXRecordDecl(); 2213 } 2214 if (!Record) 2215 Record = cast<CXXRecordDecl>( 2216 ND->getDeclContext()->getRedeclContext()); 2217 R.setNamingClass(Record); 2218 } 2219 2220 auto *UnderlyingND = ND->getUnderlyingDecl(); 2221 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2222 isa<FunctionTemplateDecl>(UnderlyingND); 2223 // FIXME: If we ended up with a typo for a type name or 2224 // Objective-C class name, we're in trouble because the parser 2225 // is in the wrong place to recover. Suggest the typo 2226 // correction, but don't make it a fix-it since we're not going 2227 // to recover well anyway. 2228 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2229 getAsTypeTemplateDecl(UnderlyingND) || 2230 isa<ObjCInterfaceDecl>(UnderlyingND); 2231 } else { 2232 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2233 // because we aren't able to recover. 2234 AcceptableWithoutRecovery = true; 2235 } 2236 2237 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2238 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2239 ? diag::note_implicit_param_decl 2240 : diag::note_previous_decl; 2241 if (SS.isEmpty()) 2242 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2243 PDiag(NoteID), AcceptableWithRecovery); 2244 else 2245 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2246 << Name << computeDeclContext(SS, false) 2247 << DroppedSpecifier << SS.getRange(), 2248 PDiag(NoteID), AcceptableWithRecovery); 2249 2250 // Tell the callee whether to try to recover. 2251 return !AcceptableWithRecovery; 2252 } 2253 } 2254 R.clear(); 2255 2256 // Emit a special diagnostic for failed member lookups. 2257 // FIXME: computing the declaration context might fail here (?) 2258 if (!SS.isEmpty()) { 2259 Diag(R.getNameLoc(), diag::err_no_member) 2260 << Name << computeDeclContext(SS, false) 2261 << SS.getRange(); 2262 return true; 2263 } 2264 2265 // Give up, we can't recover. 2266 Diag(R.getNameLoc(), diagnostic) << Name; 2267 return true; 2268 } 2269 2270 /// In Microsoft mode, if we are inside a template class whose parent class has 2271 /// dependent base classes, and we can't resolve an unqualified identifier, then 2272 /// assume the identifier is a member of a dependent base class. We can only 2273 /// recover successfully in static methods, instance methods, and other contexts 2274 /// where 'this' is available. This doesn't precisely match MSVC's 2275 /// instantiation model, but it's close enough. 2276 static Expr * 2277 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2278 DeclarationNameInfo &NameInfo, 2279 SourceLocation TemplateKWLoc, 2280 const TemplateArgumentListInfo *TemplateArgs) { 2281 // Only try to recover from lookup into dependent bases in static methods or 2282 // contexts where 'this' is available. 2283 QualType ThisType = S.getCurrentThisType(); 2284 const CXXRecordDecl *RD = nullptr; 2285 if (!ThisType.isNull()) 2286 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2287 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2288 RD = MD->getParent(); 2289 if (!RD || !RD->hasAnyDependentBases()) 2290 return nullptr; 2291 2292 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2293 // is available, suggest inserting 'this->' as a fixit. 2294 SourceLocation Loc = NameInfo.getLoc(); 2295 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2296 DB << NameInfo.getName() << RD; 2297 2298 if (!ThisType.isNull()) { 2299 DB << FixItHint::CreateInsertion(Loc, "this->"); 2300 return CXXDependentScopeMemberExpr::Create( 2301 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2302 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2303 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2304 } 2305 2306 // Synthesize a fake NNS that points to the derived class. This will 2307 // perform name lookup during template instantiation. 2308 CXXScopeSpec SS; 2309 auto *NNS = 2310 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2311 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2312 return DependentScopeDeclRefExpr::Create( 2313 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2314 TemplateArgs); 2315 } 2316 2317 ExprResult 2318 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2319 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2320 bool HasTrailingLParen, bool IsAddressOfOperand, 2321 CorrectionCandidateCallback *CCC, 2322 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2323 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2324 "cannot be direct & operand and have a trailing lparen"); 2325 if (SS.isInvalid()) 2326 return ExprError(); 2327 2328 TemplateArgumentListInfo TemplateArgsBuffer; 2329 2330 // Decompose the UnqualifiedId into the following data. 2331 DeclarationNameInfo NameInfo; 2332 const TemplateArgumentListInfo *TemplateArgs; 2333 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2334 2335 DeclarationName Name = NameInfo.getName(); 2336 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2337 SourceLocation NameLoc = NameInfo.getLoc(); 2338 2339 if (II && II->isEditorPlaceholder()) { 2340 // FIXME: When typed placeholders are supported we can create a typed 2341 // placeholder expression node. 2342 return ExprError(); 2343 } 2344 2345 // C++ [temp.dep.expr]p3: 2346 // An id-expression is type-dependent if it contains: 2347 // -- an identifier that was declared with a dependent type, 2348 // (note: handled after lookup) 2349 // -- a template-id that is dependent, 2350 // (note: handled in BuildTemplateIdExpr) 2351 // -- a conversion-function-id that specifies a dependent type, 2352 // -- a nested-name-specifier that contains a class-name that 2353 // names a dependent type. 2354 // Determine whether this is a member of an unknown specialization; 2355 // we need to handle these differently. 2356 bool DependentID = false; 2357 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2358 Name.getCXXNameType()->isDependentType()) { 2359 DependentID = true; 2360 } else if (SS.isSet()) { 2361 if (DeclContext *DC = computeDeclContext(SS, false)) { 2362 if (RequireCompleteDeclContext(SS, DC)) 2363 return ExprError(); 2364 } else { 2365 DependentID = true; 2366 } 2367 } 2368 2369 if (DependentID) 2370 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2371 IsAddressOfOperand, TemplateArgs); 2372 2373 // Perform the required lookup. 2374 LookupResult R(*this, NameInfo, 2375 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2376 ? LookupObjCImplicitSelfParam 2377 : LookupOrdinaryName); 2378 if (TemplateKWLoc.isValid() || TemplateArgs) { 2379 // Lookup the template name again to correctly establish the context in 2380 // which it was found. This is really unfortunate as we already did the 2381 // lookup to determine that it was a template name in the first place. If 2382 // this becomes a performance hit, we can work harder to preserve those 2383 // results until we get here but it's likely not worth it. 2384 bool MemberOfUnknownSpecialization; 2385 AssumedTemplateKind AssumedTemplate; 2386 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2387 MemberOfUnknownSpecialization, TemplateKWLoc, 2388 &AssumedTemplate)) 2389 return ExprError(); 2390 2391 if (MemberOfUnknownSpecialization || 2392 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2393 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2394 IsAddressOfOperand, TemplateArgs); 2395 } else { 2396 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2397 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2398 2399 // If the result might be in a dependent base class, this is a dependent 2400 // id-expression. 2401 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2402 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2403 IsAddressOfOperand, TemplateArgs); 2404 2405 // If this reference is in an Objective-C method, then we need to do 2406 // some special Objective-C lookup, too. 2407 if (IvarLookupFollowUp) { 2408 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2409 if (E.isInvalid()) 2410 return ExprError(); 2411 2412 if (Expr *Ex = E.getAs<Expr>()) 2413 return Ex; 2414 } 2415 } 2416 2417 if (R.isAmbiguous()) 2418 return ExprError(); 2419 2420 // This could be an implicitly declared function reference (legal in C90, 2421 // extension in C99, forbidden in C++). 2422 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2423 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2424 if (D) R.addDecl(D); 2425 } 2426 2427 // Determine whether this name might be a candidate for 2428 // argument-dependent lookup. 2429 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2430 2431 if (R.empty() && !ADL) { 2432 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2433 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2434 TemplateKWLoc, TemplateArgs)) 2435 return E; 2436 } 2437 2438 // Don't diagnose an empty lookup for inline assembly. 2439 if (IsInlineAsmIdentifier) 2440 return ExprError(); 2441 2442 // If this name wasn't predeclared and if this is not a function 2443 // call, diagnose the problem. 2444 TypoExpr *TE = nullptr; 2445 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2446 : nullptr); 2447 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2448 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2449 "Typo correction callback misconfigured"); 2450 if (CCC) { 2451 // Make sure the callback knows what the typo being diagnosed is. 2452 CCC->setTypoName(II); 2453 if (SS.isValid()) 2454 CCC->setTypoNNS(SS.getScopeRep()); 2455 } 2456 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2457 // a template name, but we happen to have always already looked up the name 2458 // before we get here if it must be a template name. 2459 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2460 None, &TE)) { 2461 if (TE && KeywordReplacement) { 2462 auto &State = getTypoExprState(TE); 2463 auto BestTC = State.Consumer->getNextCorrection(); 2464 if (BestTC.isKeyword()) { 2465 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2466 if (State.DiagHandler) 2467 State.DiagHandler(BestTC); 2468 KeywordReplacement->startToken(); 2469 KeywordReplacement->setKind(II->getTokenID()); 2470 KeywordReplacement->setIdentifierInfo(II); 2471 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2472 // Clean up the state associated with the TypoExpr, since it has 2473 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2474 clearDelayedTypo(TE); 2475 // Signal that a correction to a keyword was performed by returning a 2476 // valid-but-null ExprResult. 2477 return (Expr*)nullptr; 2478 } 2479 State.Consumer->resetCorrectionStream(); 2480 } 2481 return TE ? TE : ExprError(); 2482 } 2483 2484 assert(!R.empty() && 2485 "DiagnoseEmptyLookup returned false but added no results"); 2486 2487 // If we found an Objective-C instance variable, let 2488 // LookupInObjCMethod build the appropriate expression to 2489 // reference the ivar. 2490 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2491 R.clear(); 2492 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2493 // In a hopelessly buggy code, Objective-C instance variable 2494 // lookup fails and no expression will be built to reference it. 2495 if (!E.isInvalid() && !E.get()) 2496 return ExprError(); 2497 return E; 2498 } 2499 } 2500 2501 // This is guaranteed from this point on. 2502 assert(!R.empty() || ADL); 2503 2504 // Check whether this might be a C++ implicit instance member access. 2505 // C++ [class.mfct.non-static]p3: 2506 // When an id-expression that is not part of a class member access 2507 // syntax and not used to form a pointer to member is used in the 2508 // body of a non-static member function of class X, if name lookup 2509 // resolves the name in the id-expression to a non-static non-type 2510 // member of some class C, the id-expression is transformed into a 2511 // class member access expression using (*this) as the 2512 // postfix-expression to the left of the . operator. 2513 // 2514 // But we don't actually need to do this for '&' operands if R 2515 // resolved to a function or overloaded function set, because the 2516 // expression is ill-formed if it actually works out to be a 2517 // non-static member function: 2518 // 2519 // C++ [expr.ref]p4: 2520 // Otherwise, if E1.E2 refers to a non-static member function. . . 2521 // [t]he expression can be used only as the left-hand operand of a 2522 // member function call. 2523 // 2524 // There are other safeguards against such uses, but it's important 2525 // to get this right here so that we don't end up making a 2526 // spuriously dependent expression if we're inside a dependent 2527 // instance method. 2528 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2529 bool MightBeImplicitMember; 2530 if (!IsAddressOfOperand) 2531 MightBeImplicitMember = true; 2532 else if (!SS.isEmpty()) 2533 MightBeImplicitMember = false; 2534 else if (R.isOverloadedResult()) 2535 MightBeImplicitMember = false; 2536 else if (R.isUnresolvableResult()) 2537 MightBeImplicitMember = true; 2538 else 2539 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2540 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2541 isa<MSPropertyDecl>(R.getFoundDecl()); 2542 2543 if (MightBeImplicitMember) 2544 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2545 R, TemplateArgs, S); 2546 } 2547 2548 if (TemplateArgs || TemplateKWLoc.isValid()) { 2549 2550 // In C++1y, if this is a variable template id, then check it 2551 // in BuildTemplateIdExpr(). 2552 // The single lookup result must be a variable template declaration. 2553 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2554 Id.TemplateId->Kind == TNK_Var_template) { 2555 assert(R.getAsSingle<VarTemplateDecl>() && 2556 "There should only be one declaration found."); 2557 } 2558 2559 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2560 } 2561 2562 return BuildDeclarationNameExpr(SS, R, ADL); 2563 } 2564 2565 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2566 /// declaration name, generally during template instantiation. 2567 /// There's a large number of things which don't need to be done along 2568 /// this path. 2569 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2570 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2571 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2572 DeclContext *DC = computeDeclContext(SS, false); 2573 if (!DC) 2574 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2575 NameInfo, /*TemplateArgs=*/nullptr); 2576 2577 if (RequireCompleteDeclContext(SS, DC)) 2578 return ExprError(); 2579 2580 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2581 LookupQualifiedName(R, DC); 2582 2583 if (R.isAmbiguous()) 2584 return ExprError(); 2585 2586 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2587 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2588 NameInfo, /*TemplateArgs=*/nullptr); 2589 2590 if (R.empty()) { 2591 // Don't diagnose problems with invalid record decl, the secondary no_member 2592 // diagnostic during template instantiation is likely bogus, e.g. if a class 2593 // is invalid because it's derived from an invalid base class, then missing 2594 // members were likely supposed to be inherited. 2595 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2596 if (CD->isInvalidDecl()) 2597 return ExprError(); 2598 Diag(NameInfo.getLoc(), diag::err_no_member) 2599 << NameInfo.getName() << DC << SS.getRange(); 2600 return ExprError(); 2601 } 2602 2603 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2604 // Diagnose a missing typename if this resolved unambiguously to a type in 2605 // a dependent context. If we can recover with a type, downgrade this to 2606 // a warning in Microsoft compatibility mode. 2607 unsigned DiagID = diag::err_typename_missing; 2608 if (RecoveryTSI && getLangOpts().MSVCCompat) 2609 DiagID = diag::ext_typename_missing; 2610 SourceLocation Loc = SS.getBeginLoc(); 2611 auto D = Diag(Loc, DiagID); 2612 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2613 << SourceRange(Loc, NameInfo.getEndLoc()); 2614 2615 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2616 // context. 2617 if (!RecoveryTSI) 2618 return ExprError(); 2619 2620 // Only issue the fixit if we're prepared to recover. 2621 D << FixItHint::CreateInsertion(Loc, "typename "); 2622 2623 // Recover by pretending this was an elaborated type. 2624 QualType Ty = Context.getTypeDeclType(TD); 2625 TypeLocBuilder TLB; 2626 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2627 2628 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2629 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2630 QTL.setElaboratedKeywordLoc(SourceLocation()); 2631 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2632 2633 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2634 2635 return ExprEmpty(); 2636 } 2637 2638 // Defend against this resolving to an implicit member access. We usually 2639 // won't get here if this might be a legitimate a class member (we end up in 2640 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2641 // a pointer-to-member or in an unevaluated context in C++11. 2642 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2643 return BuildPossibleImplicitMemberExpr(SS, 2644 /*TemplateKWLoc=*/SourceLocation(), 2645 R, /*TemplateArgs=*/nullptr, S); 2646 2647 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2648 } 2649 2650 /// The parser has read a name in, and Sema has detected that we're currently 2651 /// inside an ObjC method. Perform some additional checks and determine if we 2652 /// should form a reference to an ivar. 2653 /// 2654 /// Ideally, most of this would be done by lookup, but there's 2655 /// actually quite a lot of extra work involved. 2656 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2657 IdentifierInfo *II) { 2658 SourceLocation Loc = Lookup.getNameLoc(); 2659 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2660 2661 // Check for error condition which is already reported. 2662 if (!CurMethod) 2663 return DeclResult(true); 2664 2665 // There are two cases to handle here. 1) scoped lookup could have failed, 2666 // in which case we should look for an ivar. 2) scoped lookup could have 2667 // found a decl, but that decl is outside the current instance method (i.e. 2668 // a global variable). In these two cases, we do a lookup for an ivar with 2669 // this name, if the lookup sucedes, we replace it our current decl. 2670 2671 // If we're in a class method, we don't normally want to look for 2672 // ivars. But if we don't find anything else, and there's an 2673 // ivar, that's an error. 2674 bool IsClassMethod = CurMethod->isClassMethod(); 2675 2676 bool LookForIvars; 2677 if (Lookup.empty()) 2678 LookForIvars = true; 2679 else if (IsClassMethod) 2680 LookForIvars = false; 2681 else 2682 LookForIvars = (Lookup.isSingleResult() && 2683 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2684 ObjCInterfaceDecl *IFace = nullptr; 2685 if (LookForIvars) { 2686 IFace = CurMethod->getClassInterface(); 2687 ObjCInterfaceDecl *ClassDeclared; 2688 ObjCIvarDecl *IV = nullptr; 2689 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2690 // Diagnose using an ivar in a class method. 2691 if (IsClassMethod) { 2692 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2693 return DeclResult(true); 2694 } 2695 2696 // Diagnose the use of an ivar outside of the declaring class. 2697 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2698 !declaresSameEntity(ClassDeclared, IFace) && 2699 !getLangOpts().DebuggerSupport) 2700 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2701 2702 // Success. 2703 return IV; 2704 } 2705 } else if (CurMethod->isInstanceMethod()) { 2706 // We should warn if a local variable hides an ivar. 2707 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2708 ObjCInterfaceDecl *ClassDeclared; 2709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2710 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2711 declaresSameEntity(IFace, ClassDeclared)) 2712 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2713 } 2714 } 2715 } else if (Lookup.isSingleResult() && 2716 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2717 // If accessing a stand-alone ivar in a class method, this is an error. 2718 if (const ObjCIvarDecl *IV = 2719 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2720 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2721 return DeclResult(true); 2722 } 2723 } 2724 2725 // Didn't encounter an error, didn't find an ivar. 2726 return DeclResult(false); 2727 } 2728 2729 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2730 ObjCIvarDecl *IV) { 2731 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2732 assert(CurMethod && CurMethod->isInstanceMethod() && 2733 "should not reference ivar from this context"); 2734 2735 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2736 assert(IFace && "should not reference ivar from this context"); 2737 2738 // If we're referencing an invalid decl, just return this as a silent 2739 // error node. The error diagnostic was already emitted on the decl. 2740 if (IV->isInvalidDecl()) 2741 return ExprError(); 2742 2743 // Check if referencing a field with __attribute__((deprecated)). 2744 if (DiagnoseUseOfDecl(IV, Loc)) 2745 return ExprError(); 2746 2747 // FIXME: This should use a new expr for a direct reference, don't 2748 // turn this into Self->ivar, just return a BareIVarExpr or something. 2749 IdentifierInfo &II = Context.Idents.get("self"); 2750 UnqualifiedId SelfName; 2751 SelfName.setIdentifier(&II, SourceLocation()); 2752 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2753 CXXScopeSpec SelfScopeSpec; 2754 SourceLocation TemplateKWLoc; 2755 ExprResult SelfExpr = 2756 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2757 /*HasTrailingLParen=*/false, 2758 /*IsAddressOfOperand=*/false); 2759 if (SelfExpr.isInvalid()) 2760 return ExprError(); 2761 2762 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2763 if (SelfExpr.isInvalid()) 2764 return ExprError(); 2765 2766 MarkAnyDeclReferenced(Loc, IV, true); 2767 2768 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2769 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2770 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2771 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2772 2773 ObjCIvarRefExpr *Result = new (Context) 2774 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2775 IV->getLocation(), SelfExpr.get(), true, true); 2776 2777 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2778 if (!isUnevaluatedContext() && 2779 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2780 getCurFunction()->recordUseOfWeak(Result); 2781 } 2782 if (getLangOpts().ObjCAutoRefCount) 2783 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2784 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2785 2786 return Result; 2787 } 2788 2789 /// The parser has read a name in, and Sema has detected that we're currently 2790 /// inside an ObjC method. Perform some additional checks and determine if we 2791 /// should form a reference to an ivar. If so, build an expression referencing 2792 /// that ivar. 2793 ExprResult 2794 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2795 IdentifierInfo *II, bool AllowBuiltinCreation) { 2796 // FIXME: Integrate this lookup step into LookupParsedName. 2797 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2798 if (Ivar.isInvalid()) 2799 return ExprError(); 2800 if (Ivar.isUsable()) 2801 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2802 cast<ObjCIvarDecl>(Ivar.get())); 2803 2804 if (Lookup.empty() && II && AllowBuiltinCreation) 2805 LookupBuiltin(Lookup); 2806 2807 // Sentinel value saying that we didn't do anything special. 2808 return ExprResult(false); 2809 } 2810 2811 /// Cast a base object to a member's actual type. 2812 /// 2813 /// Logically this happens in three phases: 2814 /// 2815 /// * First we cast from the base type to the naming class. 2816 /// The naming class is the class into which we were looking 2817 /// when we found the member; it's the qualifier type if a 2818 /// qualifier was provided, and otherwise it's the base type. 2819 /// 2820 /// * Next we cast from the naming class to the declaring class. 2821 /// If the member we found was brought into a class's scope by 2822 /// a using declaration, this is that class; otherwise it's 2823 /// the class declaring the member. 2824 /// 2825 /// * Finally we cast from the declaring class to the "true" 2826 /// declaring class of the member. This conversion does not 2827 /// obey access control. 2828 ExprResult 2829 Sema::PerformObjectMemberConversion(Expr *From, 2830 NestedNameSpecifier *Qualifier, 2831 NamedDecl *FoundDecl, 2832 NamedDecl *Member) { 2833 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2834 if (!RD) 2835 return From; 2836 2837 QualType DestRecordType; 2838 QualType DestType; 2839 QualType FromRecordType; 2840 QualType FromType = From->getType(); 2841 bool PointerConversions = false; 2842 if (isa<FieldDecl>(Member)) { 2843 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2844 auto FromPtrType = FromType->getAs<PointerType>(); 2845 DestRecordType = Context.getAddrSpaceQualType( 2846 DestRecordType, FromPtrType 2847 ? FromType->getPointeeType().getAddressSpace() 2848 : FromType.getAddressSpace()); 2849 2850 if (FromPtrType) { 2851 DestType = Context.getPointerType(DestRecordType); 2852 FromRecordType = FromPtrType->getPointeeType(); 2853 PointerConversions = true; 2854 } else { 2855 DestType = DestRecordType; 2856 FromRecordType = FromType; 2857 } 2858 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2859 if (Method->isStatic()) 2860 return From; 2861 2862 DestType = Method->getThisType(); 2863 DestRecordType = DestType->getPointeeType(); 2864 2865 if (FromType->getAs<PointerType>()) { 2866 FromRecordType = FromType->getPointeeType(); 2867 PointerConversions = true; 2868 } else { 2869 FromRecordType = FromType; 2870 DestType = DestRecordType; 2871 } 2872 2873 LangAS FromAS = FromRecordType.getAddressSpace(); 2874 LangAS DestAS = DestRecordType.getAddressSpace(); 2875 if (FromAS != DestAS) { 2876 QualType FromRecordTypeWithoutAS = 2877 Context.removeAddrSpaceQualType(FromRecordType); 2878 QualType FromTypeWithDestAS = 2879 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2880 if (PointerConversions) 2881 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2882 From = ImpCastExprToType(From, FromTypeWithDestAS, 2883 CK_AddressSpaceConversion, From->getValueKind()) 2884 .get(); 2885 } 2886 } else { 2887 // No conversion necessary. 2888 return From; 2889 } 2890 2891 if (DestType->isDependentType() || FromType->isDependentType()) 2892 return From; 2893 2894 // If the unqualified types are the same, no conversion is necessary. 2895 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2896 return From; 2897 2898 SourceRange FromRange = From->getSourceRange(); 2899 SourceLocation FromLoc = FromRange.getBegin(); 2900 2901 ExprValueKind VK = From->getValueKind(); 2902 2903 // C++ [class.member.lookup]p8: 2904 // [...] Ambiguities can often be resolved by qualifying a name with its 2905 // class name. 2906 // 2907 // If the member was a qualified name and the qualified referred to a 2908 // specific base subobject type, we'll cast to that intermediate type 2909 // first and then to the object in which the member is declared. That allows 2910 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2911 // 2912 // class Base { public: int x; }; 2913 // class Derived1 : public Base { }; 2914 // class Derived2 : public Base { }; 2915 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2916 // 2917 // void VeryDerived::f() { 2918 // x = 17; // error: ambiguous base subobjects 2919 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2920 // } 2921 if (Qualifier && Qualifier->getAsType()) { 2922 QualType QType = QualType(Qualifier->getAsType(), 0); 2923 assert(QType->isRecordType() && "lookup done with non-record type"); 2924 2925 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2926 2927 // In C++98, the qualifier type doesn't actually have to be a base 2928 // type of the object type, in which case we just ignore it. 2929 // Otherwise build the appropriate casts. 2930 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2931 CXXCastPath BasePath; 2932 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2933 FromLoc, FromRange, &BasePath)) 2934 return ExprError(); 2935 2936 if (PointerConversions) 2937 QType = Context.getPointerType(QType); 2938 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2939 VK, &BasePath).get(); 2940 2941 FromType = QType; 2942 FromRecordType = QRecordType; 2943 2944 // If the qualifier type was the same as the destination type, 2945 // we're done. 2946 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2947 return From; 2948 } 2949 } 2950 2951 bool IgnoreAccess = false; 2952 2953 // If we actually found the member through a using declaration, cast 2954 // down to the using declaration's type. 2955 // 2956 // Pointer equality is fine here because only one declaration of a 2957 // class ever has member declarations. 2958 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2959 assert(isa<UsingShadowDecl>(FoundDecl)); 2960 QualType URecordType = Context.getTypeDeclType( 2961 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2962 2963 // We only need to do this if the naming-class to declaring-class 2964 // conversion is non-trivial. 2965 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2966 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2967 CXXCastPath BasePath; 2968 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2969 FromLoc, FromRange, &BasePath)) 2970 return ExprError(); 2971 2972 QualType UType = URecordType; 2973 if (PointerConversions) 2974 UType = Context.getPointerType(UType); 2975 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2976 VK, &BasePath).get(); 2977 FromType = UType; 2978 FromRecordType = URecordType; 2979 } 2980 2981 // We don't do access control for the conversion from the 2982 // declaring class to the true declaring class. 2983 IgnoreAccess = true; 2984 } 2985 2986 CXXCastPath BasePath; 2987 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2988 FromLoc, FromRange, &BasePath, 2989 IgnoreAccess)) 2990 return ExprError(); 2991 2992 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2993 VK, &BasePath); 2994 } 2995 2996 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2997 const LookupResult &R, 2998 bool HasTrailingLParen) { 2999 // Only when used directly as the postfix-expression of a call. 3000 if (!HasTrailingLParen) 3001 return false; 3002 3003 // Never if a scope specifier was provided. 3004 if (SS.isSet()) 3005 return false; 3006 3007 // Only in C++ or ObjC++. 3008 if (!getLangOpts().CPlusPlus) 3009 return false; 3010 3011 // Turn off ADL when we find certain kinds of declarations during 3012 // normal lookup: 3013 for (NamedDecl *D : R) { 3014 // C++0x [basic.lookup.argdep]p3: 3015 // -- a declaration of a class member 3016 // Since using decls preserve this property, we check this on the 3017 // original decl. 3018 if (D->isCXXClassMember()) 3019 return false; 3020 3021 // C++0x [basic.lookup.argdep]p3: 3022 // -- a block-scope function declaration that is not a 3023 // using-declaration 3024 // NOTE: we also trigger this for function templates (in fact, we 3025 // don't check the decl type at all, since all other decl types 3026 // turn off ADL anyway). 3027 if (isa<UsingShadowDecl>(D)) 3028 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3029 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3030 return false; 3031 3032 // C++0x [basic.lookup.argdep]p3: 3033 // -- a declaration that is neither a function or a function 3034 // template 3035 // And also for builtin functions. 3036 if (isa<FunctionDecl>(D)) { 3037 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3038 3039 // But also builtin functions. 3040 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3041 return false; 3042 } else if (!isa<FunctionTemplateDecl>(D)) 3043 return false; 3044 } 3045 3046 return true; 3047 } 3048 3049 3050 /// Diagnoses obvious problems with the use of the given declaration 3051 /// as an expression. This is only actually called for lookups that 3052 /// were not overloaded, and it doesn't promise that the declaration 3053 /// will in fact be used. 3054 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3055 if (D->isInvalidDecl()) 3056 return true; 3057 3058 if (isa<TypedefNameDecl>(D)) { 3059 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3060 return true; 3061 } 3062 3063 if (isa<ObjCInterfaceDecl>(D)) { 3064 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3065 return true; 3066 } 3067 3068 if (isa<NamespaceDecl>(D)) { 3069 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3070 return true; 3071 } 3072 3073 return false; 3074 } 3075 3076 // Certain multiversion types should be treated as overloaded even when there is 3077 // only one result. 3078 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3079 assert(R.isSingleResult() && "Expected only a single result"); 3080 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3081 return FD && 3082 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3083 } 3084 3085 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3086 LookupResult &R, bool NeedsADL, 3087 bool AcceptInvalidDecl) { 3088 // If this is a single, fully-resolved result and we don't need ADL, 3089 // just build an ordinary singleton decl ref. 3090 if (!NeedsADL && R.isSingleResult() && 3091 !R.getAsSingle<FunctionTemplateDecl>() && 3092 !ShouldLookupResultBeMultiVersionOverload(R)) 3093 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3094 R.getRepresentativeDecl(), nullptr, 3095 AcceptInvalidDecl); 3096 3097 // We only need to check the declaration if there's exactly one 3098 // result, because in the overloaded case the results can only be 3099 // functions and function templates. 3100 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3101 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3102 return ExprError(); 3103 3104 // Otherwise, just build an unresolved lookup expression. Suppress 3105 // any lookup-related diagnostics; we'll hash these out later, when 3106 // we've picked a target. 3107 R.suppressDiagnostics(); 3108 3109 UnresolvedLookupExpr *ULE 3110 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3111 SS.getWithLocInContext(Context), 3112 R.getLookupNameInfo(), 3113 NeedsADL, R.isOverloadedResult(), 3114 R.begin(), R.end()); 3115 3116 return ULE; 3117 } 3118 3119 static void 3120 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3121 ValueDecl *var, DeclContext *DC); 3122 3123 /// Complete semantic analysis for a reference to the given declaration. 3124 ExprResult Sema::BuildDeclarationNameExpr( 3125 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3126 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3127 bool AcceptInvalidDecl) { 3128 assert(D && "Cannot refer to a NULL declaration"); 3129 assert(!isa<FunctionTemplateDecl>(D) && 3130 "Cannot refer unambiguously to a function template"); 3131 3132 SourceLocation Loc = NameInfo.getLoc(); 3133 if (CheckDeclInExpr(*this, Loc, D)) 3134 return ExprError(); 3135 3136 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3137 // Specifically diagnose references to class templates that are missing 3138 // a template argument list. 3139 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3140 return ExprError(); 3141 } 3142 3143 // Make sure that we're referring to a value. 3144 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3145 if (!VD) { 3146 Diag(Loc, diag::err_ref_non_value) 3147 << D << SS.getRange(); 3148 Diag(D->getLocation(), diag::note_declared_at); 3149 return ExprError(); 3150 } 3151 3152 // Check whether this declaration can be used. Note that we suppress 3153 // this check when we're going to perform argument-dependent lookup 3154 // on this function name, because this might not be the function 3155 // that overload resolution actually selects. 3156 if (DiagnoseUseOfDecl(VD, Loc)) 3157 return ExprError(); 3158 3159 // Only create DeclRefExpr's for valid Decl's. 3160 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3161 return ExprError(); 3162 3163 // Handle members of anonymous structs and unions. If we got here, 3164 // and the reference is to a class member indirect field, then this 3165 // must be the subject of a pointer-to-member expression. 3166 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3167 if (!indirectField->isCXXClassMember()) 3168 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3169 indirectField); 3170 3171 { 3172 QualType type = VD->getType(); 3173 if (type.isNull()) 3174 return ExprError(); 3175 ExprValueKind valueKind = VK_RValue; 3176 3177 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3178 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3179 // is expanded by some outer '...' in the context of the use. 3180 type = type.getNonPackExpansionType(); 3181 3182 switch (D->getKind()) { 3183 // Ignore all the non-ValueDecl kinds. 3184 #define ABSTRACT_DECL(kind) 3185 #define VALUE(type, base) 3186 #define DECL(type, base) \ 3187 case Decl::type: 3188 #include "clang/AST/DeclNodes.inc" 3189 llvm_unreachable("invalid value decl kind"); 3190 3191 // These shouldn't make it here. 3192 case Decl::ObjCAtDefsField: 3193 llvm_unreachable("forming non-member reference to ivar?"); 3194 3195 // Enum constants are always r-values and never references. 3196 // Unresolved using declarations are dependent. 3197 case Decl::EnumConstant: 3198 case Decl::UnresolvedUsingValue: 3199 case Decl::OMPDeclareReduction: 3200 case Decl::OMPDeclareMapper: 3201 valueKind = VK_RValue; 3202 break; 3203 3204 // Fields and indirect fields that got here must be for 3205 // pointer-to-member expressions; we just call them l-values for 3206 // internal consistency, because this subexpression doesn't really 3207 // exist in the high-level semantics. 3208 case Decl::Field: 3209 case Decl::IndirectField: 3210 case Decl::ObjCIvar: 3211 assert(getLangOpts().CPlusPlus && 3212 "building reference to field in C?"); 3213 3214 // These can't have reference type in well-formed programs, but 3215 // for internal consistency we do this anyway. 3216 type = type.getNonReferenceType(); 3217 valueKind = VK_LValue; 3218 break; 3219 3220 // Non-type template parameters are either l-values or r-values 3221 // depending on the type. 3222 case Decl::NonTypeTemplateParm: { 3223 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3224 type = reftype->getPointeeType(); 3225 valueKind = VK_LValue; // even if the parameter is an r-value reference 3226 break; 3227 } 3228 3229 // For non-references, we need to strip qualifiers just in case 3230 // the template parameter was declared as 'const int' or whatever. 3231 valueKind = VK_RValue; 3232 type = type.getUnqualifiedType(); 3233 break; 3234 } 3235 3236 case Decl::Var: 3237 case Decl::VarTemplateSpecialization: 3238 case Decl::VarTemplatePartialSpecialization: 3239 case Decl::Decomposition: 3240 case Decl::OMPCapturedExpr: 3241 // In C, "extern void blah;" is valid and is an r-value. 3242 if (!getLangOpts().CPlusPlus && 3243 !type.hasQualifiers() && 3244 type->isVoidType()) { 3245 valueKind = VK_RValue; 3246 break; 3247 } 3248 LLVM_FALLTHROUGH; 3249 3250 case Decl::ImplicitParam: 3251 case Decl::ParmVar: { 3252 // These are always l-values. 3253 valueKind = VK_LValue; 3254 type = type.getNonReferenceType(); 3255 3256 // FIXME: Does the addition of const really only apply in 3257 // potentially-evaluated contexts? Since the variable isn't actually 3258 // captured in an unevaluated context, it seems that the answer is no. 3259 if (!isUnevaluatedContext()) { 3260 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3261 if (!CapturedType.isNull()) 3262 type = CapturedType; 3263 } 3264 3265 break; 3266 } 3267 3268 case Decl::Binding: { 3269 // These are always lvalues. 3270 valueKind = VK_LValue; 3271 type = type.getNonReferenceType(); 3272 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3273 // decides how that's supposed to work. 3274 auto *BD = cast<BindingDecl>(VD); 3275 if (BD->getDeclContext() != CurContext) { 3276 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3277 if (DD && DD->hasLocalStorage()) 3278 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3279 } 3280 break; 3281 } 3282 3283 case Decl::Function: { 3284 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3285 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3286 type = Context.BuiltinFnTy; 3287 valueKind = VK_RValue; 3288 break; 3289 } 3290 } 3291 3292 const FunctionType *fty = type->castAs<FunctionType>(); 3293 3294 // If we're referring to a function with an __unknown_anytype 3295 // result type, make the entire expression __unknown_anytype. 3296 if (fty->getReturnType() == Context.UnknownAnyTy) { 3297 type = Context.UnknownAnyTy; 3298 valueKind = VK_RValue; 3299 break; 3300 } 3301 3302 // Functions are l-values in C++. 3303 if (getLangOpts().CPlusPlus) { 3304 valueKind = VK_LValue; 3305 break; 3306 } 3307 3308 // C99 DR 316 says that, if a function type comes from a 3309 // function definition (without a prototype), that type is only 3310 // used for checking compatibility. Therefore, when referencing 3311 // the function, we pretend that we don't have the full function 3312 // type. 3313 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3314 isa<FunctionProtoType>(fty)) 3315 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3316 fty->getExtInfo()); 3317 3318 // Functions are r-values in C. 3319 valueKind = VK_RValue; 3320 break; 3321 } 3322 3323 case Decl::CXXDeductionGuide: 3324 llvm_unreachable("building reference to deduction guide"); 3325 3326 case Decl::MSProperty: 3327 case Decl::MSGuid: 3328 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3329 // or duplicated between host and device? 3330 valueKind = VK_LValue; 3331 break; 3332 3333 case Decl::CXXMethod: 3334 // If we're referring to a method with an __unknown_anytype 3335 // result type, make the entire expression __unknown_anytype. 3336 // This should only be possible with a type written directly. 3337 if (const FunctionProtoType *proto 3338 = dyn_cast<FunctionProtoType>(VD->getType())) 3339 if (proto->getReturnType() == Context.UnknownAnyTy) { 3340 type = Context.UnknownAnyTy; 3341 valueKind = VK_RValue; 3342 break; 3343 } 3344 3345 // C++ methods are l-values if static, r-values if non-static. 3346 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3347 valueKind = VK_LValue; 3348 break; 3349 } 3350 LLVM_FALLTHROUGH; 3351 3352 case Decl::CXXConversion: 3353 case Decl::CXXDestructor: 3354 case Decl::CXXConstructor: 3355 valueKind = VK_RValue; 3356 break; 3357 } 3358 3359 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3360 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3361 TemplateArgs); 3362 } 3363 } 3364 3365 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3366 SmallString<32> &Target) { 3367 Target.resize(CharByteWidth * (Source.size() + 1)); 3368 char *ResultPtr = &Target[0]; 3369 const llvm::UTF8 *ErrorPtr; 3370 bool success = 3371 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3372 (void)success; 3373 assert(success); 3374 Target.resize(ResultPtr - &Target[0]); 3375 } 3376 3377 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3378 PredefinedExpr::IdentKind IK) { 3379 // Pick the current block, lambda, captured statement or function. 3380 Decl *currentDecl = nullptr; 3381 if (const BlockScopeInfo *BSI = getCurBlock()) 3382 currentDecl = BSI->TheDecl; 3383 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3384 currentDecl = LSI->CallOperator; 3385 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3386 currentDecl = CSI->TheCapturedDecl; 3387 else 3388 currentDecl = getCurFunctionOrMethodDecl(); 3389 3390 if (!currentDecl) { 3391 Diag(Loc, diag::ext_predef_outside_function); 3392 currentDecl = Context.getTranslationUnitDecl(); 3393 } 3394 3395 QualType ResTy; 3396 StringLiteral *SL = nullptr; 3397 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3398 ResTy = Context.DependentTy; 3399 else { 3400 // Pre-defined identifiers are of type char[x], where x is the length of 3401 // the string. 3402 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3403 unsigned Length = Str.length(); 3404 3405 llvm::APInt LengthI(32, Length + 1); 3406 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3407 ResTy = 3408 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3409 SmallString<32> RawChars; 3410 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3411 Str, RawChars); 3412 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3413 ArrayType::Normal, 3414 /*IndexTypeQuals*/ 0); 3415 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3416 /*Pascal*/ false, ResTy, Loc); 3417 } else { 3418 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3419 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3420 ArrayType::Normal, 3421 /*IndexTypeQuals*/ 0); 3422 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3423 /*Pascal*/ false, ResTy, Loc); 3424 } 3425 } 3426 3427 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3428 } 3429 3430 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3431 PredefinedExpr::IdentKind IK; 3432 3433 switch (Kind) { 3434 default: llvm_unreachable("Unknown simple primary expr!"); 3435 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3436 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3437 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3438 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3439 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3440 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3441 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3442 } 3443 3444 return BuildPredefinedExpr(Loc, IK); 3445 } 3446 3447 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3448 SmallString<16> CharBuffer; 3449 bool Invalid = false; 3450 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3451 if (Invalid) 3452 return ExprError(); 3453 3454 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3455 PP, Tok.getKind()); 3456 if (Literal.hadError()) 3457 return ExprError(); 3458 3459 QualType Ty; 3460 if (Literal.isWide()) 3461 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3462 else if (Literal.isUTF8() && getLangOpts().Char8) 3463 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3464 else if (Literal.isUTF16()) 3465 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3466 else if (Literal.isUTF32()) 3467 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3468 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3469 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3470 else 3471 Ty = Context.CharTy; // 'x' -> char in C++ 3472 3473 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3474 if (Literal.isWide()) 3475 Kind = CharacterLiteral::Wide; 3476 else if (Literal.isUTF16()) 3477 Kind = CharacterLiteral::UTF16; 3478 else if (Literal.isUTF32()) 3479 Kind = CharacterLiteral::UTF32; 3480 else if (Literal.isUTF8()) 3481 Kind = CharacterLiteral::UTF8; 3482 3483 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3484 Tok.getLocation()); 3485 3486 if (Literal.getUDSuffix().empty()) 3487 return Lit; 3488 3489 // We're building a user-defined literal. 3490 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3491 SourceLocation UDSuffixLoc = 3492 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3493 3494 // Make sure we're allowed user-defined literals here. 3495 if (!UDLScope) 3496 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3497 3498 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3499 // operator "" X (ch) 3500 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3501 Lit, Tok.getLocation()); 3502 } 3503 3504 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3505 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3506 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3507 Context.IntTy, Loc); 3508 } 3509 3510 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3511 QualType Ty, SourceLocation Loc) { 3512 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3513 3514 using llvm::APFloat; 3515 APFloat Val(Format); 3516 3517 APFloat::opStatus result = Literal.GetFloatValue(Val); 3518 3519 // Overflow is always an error, but underflow is only an error if 3520 // we underflowed to zero (APFloat reports denormals as underflow). 3521 if ((result & APFloat::opOverflow) || 3522 ((result & APFloat::opUnderflow) && Val.isZero())) { 3523 unsigned diagnostic; 3524 SmallString<20> buffer; 3525 if (result & APFloat::opOverflow) { 3526 diagnostic = diag::warn_float_overflow; 3527 APFloat::getLargest(Format).toString(buffer); 3528 } else { 3529 diagnostic = diag::warn_float_underflow; 3530 APFloat::getSmallest(Format).toString(buffer); 3531 } 3532 3533 S.Diag(Loc, diagnostic) 3534 << Ty 3535 << StringRef(buffer.data(), buffer.size()); 3536 } 3537 3538 bool isExact = (result == APFloat::opOK); 3539 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3540 } 3541 3542 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3543 assert(E && "Invalid expression"); 3544 3545 if (E->isValueDependent()) 3546 return false; 3547 3548 QualType QT = E->getType(); 3549 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3550 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3551 return true; 3552 } 3553 3554 llvm::APSInt ValueAPS; 3555 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3556 3557 if (R.isInvalid()) 3558 return true; 3559 3560 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3561 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3562 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3563 << ValueAPS.toString(10) << ValueIsPositive; 3564 return true; 3565 } 3566 3567 return false; 3568 } 3569 3570 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3571 // Fast path for a single digit (which is quite common). A single digit 3572 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3573 if (Tok.getLength() == 1) { 3574 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3575 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3576 } 3577 3578 SmallString<128> SpellingBuffer; 3579 // NumericLiteralParser wants to overread by one character. Add padding to 3580 // the buffer in case the token is copied to the buffer. If getSpelling() 3581 // returns a StringRef to the memory buffer, it should have a null char at 3582 // the EOF, so it is also safe. 3583 SpellingBuffer.resize(Tok.getLength() + 1); 3584 3585 // Get the spelling of the token, which eliminates trigraphs, etc. 3586 bool Invalid = false; 3587 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3588 if (Invalid) 3589 return ExprError(); 3590 3591 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3592 PP.getSourceManager(), PP.getLangOpts(), 3593 PP.getTargetInfo(), PP.getDiagnostics()); 3594 if (Literal.hadError) 3595 return ExprError(); 3596 3597 if (Literal.hasUDSuffix()) { 3598 // We're building a user-defined literal. 3599 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3600 SourceLocation UDSuffixLoc = 3601 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3602 3603 // Make sure we're allowed user-defined literals here. 3604 if (!UDLScope) 3605 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3606 3607 QualType CookedTy; 3608 if (Literal.isFloatingLiteral()) { 3609 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3610 // long double, the literal is treated as a call of the form 3611 // operator "" X (f L) 3612 CookedTy = Context.LongDoubleTy; 3613 } else { 3614 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3615 // unsigned long long, the literal is treated as a call of the form 3616 // operator "" X (n ULL) 3617 CookedTy = Context.UnsignedLongLongTy; 3618 } 3619 3620 DeclarationName OpName = 3621 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3622 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3623 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3624 3625 SourceLocation TokLoc = Tok.getLocation(); 3626 3627 // Perform literal operator lookup to determine if we're building a raw 3628 // literal or a cooked one. 3629 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3630 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3631 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3632 /*AllowStringTemplate*/ false, 3633 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3634 case LOLR_ErrorNoDiagnostic: 3635 // Lookup failure for imaginary constants isn't fatal, there's still the 3636 // GNU extension producing _Complex types. 3637 break; 3638 case LOLR_Error: 3639 return ExprError(); 3640 case LOLR_Cooked: { 3641 Expr *Lit; 3642 if (Literal.isFloatingLiteral()) { 3643 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3644 } else { 3645 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3646 if (Literal.GetIntegerValue(ResultVal)) 3647 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3648 << /* Unsigned */ 1; 3649 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3650 Tok.getLocation()); 3651 } 3652 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3653 } 3654 3655 case LOLR_Raw: { 3656 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3657 // literal is treated as a call of the form 3658 // operator "" X ("n") 3659 unsigned Length = Literal.getUDSuffixOffset(); 3660 QualType StrTy = Context.getConstantArrayType( 3661 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3662 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3663 Expr *Lit = StringLiteral::Create( 3664 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3665 /*Pascal*/false, StrTy, &TokLoc, 1); 3666 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3667 } 3668 3669 case LOLR_Template: { 3670 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3671 // template), L is treated as a call fo the form 3672 // operator "" X <'c1', 'c2', ... 'ck'>() 3673 // where n is the source character sequence c1 c2 ... ck. 3674 TemplateArgumentListInfo ExplicitArgs; 3675 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3676 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3677 llvm::APSInt Value(CharBits, CharIsUnsigned); 3678 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3679 Value = TokSpelling[I]; 3680 TemplateArgument Arg(Context, Value, Context.CharTy); 3681 TemplateArgumentLocInfo ArgInfo; 3682 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3683 } 3684 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3685 &ExplicitArgs); 3686 } 3687 case LOLR_StringTemplate: 3688 llvm_unreachable("unexpected literal operator lookup result"); 3689 } 3690 } 3691 3692 Expr *Res; 3693 3694 if (Literal.isFixedPointLiteral()) { 3695 QualType Ty; 3696 3697 if (Literal.isAccum) { 3698 if (Literal.isHalf) { 3699 Ty = Context.ShortAccumTy; 3700 } else if (Literal.isLong) { 3701 Ty = Context.LongAccumTy; 3702 } else { 3703 Ty = Context.AccumTy; 3704 } 3705 } else if (Literal.isFract) { 3706 if (Literal.isHalf) { 3707 Ty = Context.ShortFractTy; 3708 } else if (Literal.isLong) { 3709 Ty = Context.LongFractTy; 3710 } else { 3711 Ty = Context.FractTy; 3712 } 3713 } 3714 3715 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3716 3717 bool isSigned = !Literal.isUnsigned; 3718 unsigned scale = Context.getFixedPointScale(Ty); 3719 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3720 3721 llvm::APInt Val(bit_width, 0, isSigned); 3722 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3723 bool ValIsZero = Val.isNullValue() && !Overflowed; 3724 3725 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3726 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3727 // Clause 6.4.4 - The value of a constant shall be in the range of 3728 // representable values for its type, with exception for constants of a 3729 // fract type with a value of exactly 1; such a constant shall denote 3730 // the maximal value for the type. 3731 --Val; 3732 else if (Val.ugt(MaxVal) || Overflowed) 3733 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3734 3735 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3736 Tok.getLocation(), scale); 3737 } else if (Literal.isFloatingLiteral()) { 3738 QualType Ty; 3739 if (Literal.isHalf){ 3740 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3741 Ty = Context.HalfTy; 3742 else { 3743 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3744 return ExprError(); 3745 } 3746 } else if (Literal.isFloat) 3747 Ty = Context.FloatTy; 3748 else if (Literal.isLong) 3749 Ty = Context.LongDoubleTy; 3750 else if (Literal.isFloat16) 3751 Ty = Context.Float16Ty; 3752 else if (Literal.isFloat128) 3753 Ty = Context.Float128Ty; 3754 else 3755 Ty = Context.DoubleTy; 3756 3757 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3758 3759 if (Ty == Context.DoubleTy) { 3760 if (getLangOpts().SinglePrecisionConstants) { 3761 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3762 if (BTy->getKind() != BuiltinType::Float) { 3763 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3764 } 3765 } else if (getLangOpts().OpenCL && 3766 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3767 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3768 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3769 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3770 } 3771 } 3772 } else if (!Literal.isIntegerLiteral()) { 3773 return ExprError(); 3774 } else { 3775 QualType Ty; 3776 3777 // 'long long' is a C99 or C++11 feature. 3778 if (!getLangOpts().C99 && Literal.isLongLong) { 3779 if (getLangOpts().CPlusPlus) 3780 Diag(Tok.getLocation(), 3781 getLangOpts().CPlusPlus11 ? 3782 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3783 else 3784 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3785 } 3786 3787 // Get the value in the widest-possible width. 3788 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3789 llvm::APInt ResultVal(MaxWidth, 0); 3790 3791 if (Literal.GetIntegerValue(ResultVal)) { 3792 // If this value didn't fit into uintmax_t, error and force to ull. 3793 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3794 << /* Unsigned */ 1; 3795 Ty = Context.UnsignedLongLongTy; 3796 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3797 "long long is not intmax_t?"); 3798 } else { 3799 // If this value fits into a ULL, try to figure out what else it fits into 3800 // according to the rules of C99 6.4.4.1p5. 3801 3802 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3803 // be an unsigned int. 3804 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3805 3806 // Check from smallest to largest, picking the smallest type we can. 3807 unsigned Width = 0; 3808 3809 // Microsoft specific integer suffixes are explicitly sized. 3810 if (Literal.MicrosoftInteger) { 3811 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3812 Width = 8; 3813 Ty = Context.CharTy; 3814 } else { 3815 Width = Literal.MicrosoftInteger; 3816 Ty = Context.getIntTypeForBitwidth(Width, 3817 /*Signed=*/!Literal.isUnsigned); 3818 } 3819 } 3820 3821 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3822 // Are int/unsigned possibilities? 3823 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3824 3825 // Does it fit in a unsigned int? 3826 if (ResultVal.isIntN(IntSize)) { 3827 // Does it fit in a signed int? 3828 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3829 Ty = Context.IntTy; 3830 else if (AllowUnsigned) 3831 Ty = Context.UnsignedIntTy; 3832 Width = IntSize; 3833 } 3834 } 3835 3836 // Are long/unsigned long possibilities? 3837 if (Ty.isNull() && !Literal.isLongLong) { 3838 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3839 3840 // Does it fit in a unsigned long? 3841 if (ResultVal.isIntN(LongSize)) { 3842 // Does it fit in a signed long? 3843 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3844 Ty = Context.LongTy; 3845 else if (AllowUnsigned) 3846 Ty = Context.UnsignedLongTy; 3847 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3848 // is compatible. 3849 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3850 const unsigned LongLongSize = 3851 Context.getTargetInfo().getLongLongWidth(); 3852 Diag(Tok.getLocation(), 3853 getLangOpts().CPlusPlus 3854 ? Literal.isLong 3855 ? diag::warn_old_implicitly_unsigned_long_cxx 3856 : /*C++98 UB*/ diag:: 3857 ext_old_implicitly_unsigned_long_cxx 3858 : diag::warn_old_implicitly_unsigned_long) 3859 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3860 : /*will be ill-formed*/ 1); 3861 Ty = Context.UnsignedLongTy; 3862 } 3863 Width = LongSize; 3864 } 3865 } 3866 3867 // Check long long if needed. 3868 if (Ty.isNull()) { 3869 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3870 3871 // Does it fit in a unsigned long long? 3872 if (ResultVal.isIntN(LongLongSize)) { 3873 // Does it fit in a signed long long? 3874 // To be compatible with MSVC, hex integer literals ending with the 3875 // LL or i64 suffix are always signed in Microsoft mode. 3876 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3877 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3878 Ty = Context.LongLongTy; 3879 else if (AllowUnsigned) 3880 Ty = Context.UnsignedLongLongTy; 3881 Width = LongLongSize; 3882 } 3883 } 3884 3885 // If we still couldn't decide a type, we probably have something that 3886 // does not fit in a signed long long, but has no U suffix. 3887 if (Ty.isNull()) { 3888 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3889 Ty = Context.UnsignedLongLongTy; 3890 Width = Context.getTargetInfo().getLongLongWidth(); 3891 } 3892 3893 if (ResultVal.getBitWidth() != Width) 3894 ResultVal = ResultVal.trunc(Width); 3895 } 3896 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3897 } 3898 3899 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3900 if (Literal.isImaginary) { 3901 Res = new (Context) ImaginaryLiteral(Res, 3902 Context.getComplexType(Res->getType())); 3903 3904 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3905 } 3906 return Res; 3907 } 3908 3909 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3910 assert(E && "ActOnParenExpr() missing expr"); 3911 return new (Context) ParenExpr(L, R, E); 3912 } 3913 3914 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3915 SourceLocation Loc, 3916 SourceRange ArgRange) { 3917 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3918 // scalar or vector data type argument..." 3919 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3920 // type (C99 6.2.5p18) or void. 3921 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3922 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3923 << T << ArgRange; 3924 return true; 3925 } 3926 3927 assert((T->isVoidType() || !T->isIncompleteType()) && 3928 "Scalar types should always be complete"); 3929 return false; 3930 } 3931 3932 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3933 SourceLocation Loc, 3934 SourceRange ArgRange, 3935 UnaryExprOrTypeTrait TraitKind) { 3936 // Invalid types must be hard errors for SFINAE in C++. 3937 if (S.LangOpts.CPlusPlus) 3938 return true; 3939 3940 // C99 6.5.3.4p1: 3941 if (T->isFunctionType() && 3942 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3943 TraitKind == UETT_PreferredAlignOf)) { 3944 // sizeof(function)/alignof(function) is allowed as an extension. 3945 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3946 << getTraitSpelling(TraitKind) << ArgRange; 3947 return false; 3948 } 3949 3950 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3951 // this is an error (OpenCL v1.1 s6.3.k) 3952 if (T->isVoidType()) { 3953 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3954 : diag::ext_sizeof_alignof_void_type; 3955 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 3956 return false; 3957 } 3958 3959 return true; 3960 } 3961 3962 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3963 SourceLocation Loc, 3964 SourceRange ArgRange, 3965 UnaryExprOrTypeTrait TraitKind) { 3966 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3967 // runtime doesn't allow it. 3968 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3969 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3970 << T << (TraitKind == UETT_SizeOf) 3971 << ArgRange; 3972 return true; 3973 } 3974 3975 return false; 3976 } 3977 3978 /// Check whether E is a pointer from a decayed array type (the decayed 3979 /// pointer type is equal to T) and emit a warning if it is. 3980 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3981 Expr *E) { 3982 // Don't warn if the operation changed the type. 3983 if (T != E->getType()) 3984 return; 3985 3986 // Now look for array decays. 3987 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3988 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3989 return; 3990 3991 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3992 << ICE->getType() 3993 << ICE->getSubExpr()->getType(); 3994 } 3995 3996 /// Check the constraints on expression operands to unary type expression 3997 /// and type traits. 3998 /// 3999 /// Completes any types necessary and validates the constraints on the operand 4000 /// expression. The logic mostly mirrors the type-based overload, but may modify 4001 /// the expression as it completes the type for that expression through template 4002 /// instantiation, etc. 4003 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4004 UnaryExprOrTypeTrait ExprKind) { 4005 QualType ExprTy = E->getType(); 4006 assert(!ExprTy->isReferenceType()); 4007 4008 bool IsUnevaluatedOperand = 4009 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4010 ExprKind == UETT_PreferredAlignOf); 4011 if (IsUnevaluatedOperand) { 4012 ExprResult Result = CheckUnevaluatedOperand(E); 4013 if (Result.isInvalid()) 4014 return true; 4015 E = Result.get(); 4016 } 4017 4018 if (ExprKind == UETT_VecStep) 4019 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4020 E->getSourceRange()); 4021 4022 // Explicitly list some types as extensions. 4023 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4024 E->getSourceRange(), ExprKind)) 4025 return false; 4026 4027 // 'alignof' applied to an expression only requires the base element type of 4028 // the expression to be complete. 'sizeof' requires the expression's type to 4029 // be complete (and will attempt to complete it if it's an array of unknown 4030 // bound). 4031 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4032 if (RequireCompleteSizedType( 4033 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4034 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4035 getTraitSpelling(ExprKind), E->getSourceRange())) 4036 return true; 4037 } else { 4038 if (RequireCompleteSizedExprType( 4039 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4040 getTraitSpelling(ExprKind), E->getSourceRange())) 4041 return true; 4042 } 4043 4044 // Completing the expression's type may have changed it. 4045 ExprTy = E->getType(); 4046 assert(!ExprTy->isReferenceType()); 4047 4048 if (ExprTy->isFunctionType()) { 4049 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4050 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4051 return true; 4052 } 4053 4054 // The operand for sizeof and alignof is in an unevaluated expression context, 4055 // so side effects could result in unintended consequences. 4056 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4057 E->HasSideEffects(Context, false)) 4058 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4059 4060 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4061 E->getSourceRange(), ExprKind)) 4062 return true; 4063 4064 if (ExprKind == UETT_SizeOf) { 4065 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4066 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4067 QualType OType = PVD->getOriginalType(); 4068 QualType Type = PVD->getType(); 4069 if (Type->isPointerType() && OType->isArrayType()) { 4070 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4071 << Type << OType; 4072 Diag(PVD->getLocation(), diag::note_declared_at); 4073 } 4074 } 4075 } 4076 4077 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4078 // decays into a pointer and returns an unintended result. This is most 4079 // likely a typo for "sizeof(array) op x". 4080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4081 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4082 BO->getLHS()); 4083 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4084 BO->getRHS()); 4085 } 4086 } 4087 4088 return false; 4089 } 4090 4091 /// Check the constraints on operands to unary expression and type 4092 /// traits. 4093 /// 4094 /// This will complete any types necessary, and validate the various constraints 4095 /// on those operands. 4096 /// 4097 /// The UsualUnaryConversions() function is *not* called by this routine. 4098 /// C99 6.3.2.1p[2-4] all state: 4099 /// Except when it is the operand of the sizeof operator ... 4100 /// 4101 /// C++ [expr.sizeof]p4 4102 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4103 /// standard conversions are not applied to the operand of sizeof. 4104 /// 4105 /// This policy is followed for all of the unary trait expressions. 4106 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4107 SourceLocation OpLoc, 4108 SourceRange ExprRange, 4109 UnaryExprOrTypeTrait ExprKind) { 4110 if (ExprType->isDependentType()) 4111 return false; 4112 4113 // C++ [expr.sizeof]p2: 4114 // When applied to a reference or a reference type, the result 4115 // is the size of the referenced type. 4116 // C++11 [expr.alignof]p3: 4117 // When alignof is applied to a reference type, the result 4118 // shall be the alignment of the referenced type. 4119 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4120 ExprType = Ref->getPointeeType(); 4121 4122 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4123 // When alignof or _Alignof is applied to an array type, the result 4124 // is the alignment of the element type. 4125 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4126 ExprKind == UETT_OpenMPRequiredSimdAlign) 4127 ExprType = Context.getBaseElementType(ExprType); 4128 4129 if (ExprKind == UETT_VecStep) 4130 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4131 4132 // Explicitly list some types as extensions. 4133 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4134 ExprKind)) 4135 return false; 4136 4137 if (RequireCompleteSizedType( 4138 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4139 getTraitSpelling(ExprKind), ExprRange)) 4140 return true; 4141 4142 if (ExprType->isFunctionType()) { 4143 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4144 << getTraitSpelling(ExprKind) << ExprRange; 4145 return true; 4146 } 4147 4148 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4149 ExprKind)) 4150 return true; 4151 4152 return false; 4153 } 4154 4155 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4156 // Cannot know anything else if the expression is dependent. 4157 if (E->isTypeDependent()) 4158 return false; 4159 4160 if (E->getObjectKind() == OK_BitField) { 4161 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4162 << 1 << E->getSourceRange(); 4163 return true; 4164 } 4165 4166 ValueDecl *D = nullptr; 4167 Expr *Inner = E->IgnoreParens(); 4168 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4169 D = DRE->getDecl(); 4170 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4171 D = ME->getMemberDecl(); 4172 } 4173 4174 // If it's a field, require the containing struct to have a 4175 // complete definition so that we can compute the layout. 4176 // 4177 // This can happen in C++11 onwards, either by naming the member 4178 // in a way that is not transformed into a member access expression 4179 // (in an unevaluated operand, for instance), or by naming the member 4180 // in a trailing-return-type. 4181 // 4182 // For the record, since __alignof__ on expressions is a GCC 4183 // extension, GCC seems to permit this but always gives the 4184 // nonsensical answer 0. 4185 // 4186 // We don't really need the layout here --- we could instead just 4187 // directly check for all the appropriate alignment-lowing 4188 // attributes --- but that would require duplicating a lot of 4189 // logic that just isn't worth duplicating for such a marginal 4190 // use-case. 4191 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4192 // Fast path this check, since we at least know the record has a 4193 // definition if we can find a member of it. 4194 if (!FD->getParent()->isCompleteDefinition()) { 4195 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4196 << E->getSourceRange(); 4197 return true; 4198 } 4199 4200 // Otherwise, if it's a field, and the field doesn't have 4201 // reference type, then it must have a complete type (or be a 4202 // flexible array member, which we explicitly want to 4203 // white-list anyway), which makes the following checks trivial. 4204 if (!FD->getType()->isReferenceType()) 4205 return false; 4206 } 4207 4208 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4209 } 4210 4211 bool Sema::CheckVecStepExpr(Expr *E) { 4212 E = E->IgnoreParens(); 4213 4214 // Cannot know anything else if the expression is dependent. 4215 if (E->isTypeDependent()) 4216 return false; 4217 4218 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4219 } 4220 4221 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4222 CapturingScopeInfo *CSI) { 4223 assert(T->isVariablyModifiedType()); 4224 assert(CSI != nullptr); 4225 4226 // We're going to walk down into the type and look for VLA expressions. 4227 do { 4228 const Type *Ty = T.getTypePtr(); 4229 switch (Ty->getTypeClass()) { 4230 #define TYPE(Class, Base) 4231 #define ABSTRACT_TYPE(Class, Base) 4232 #define NON_CANONICAL_TYPE(Class, Base) 4233 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4234 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4235 #include "clang/AST/TypeNodes.inc" 4236 T = QualType(); 4237 break; 4238 // These types are never variably-modified. 4239 case Type::Builtin: 4240 case Type::Complex: 4241 case Type::Vector: 4242 case Type::ExtVector: 4243 case Type::ConstantMatrix: 4244 case Type::Record: 4245 case Type::Enum: 4246 case Type::Elaborated: 4247 case Type::TemplateSpecialization: 4248 case Type::ObjCObject: 4249 case Type::ObjCInterface: 4250 case Type::ObjCObjectPointer: 4251 case Type::ObjCTypeParam: 4252 case Type::Pipe: 4253 case Type::ExtInt: 4254 llvm_unreachable("type class is never variably-modified!"); 4255 case Type::Adjusted: 4256 T = cast<AdjustedType>(Ty)->getOriginalType(); 4257 break; 4258 case Type::Decayed: 4259 T = cast<DecayedType>(Ty)->getPointeeType(); 4260 break; 4261 case Type::Pointer: 4262 T = cast<PointerType>(Ty)->getPointeeType(); 4263 break; 4264 case Type::BlockPointer: 4265 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4266 break; 4267 case Type::LValueReference: 4268 case Type::RValueReference: 4269 T = cast<ReferenceType>(Ty)->getPointeeType(); 4270 break; 4271 case Type::MemberPointer: 4272 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4273 break; 4274 case Type::ConstantArray: 4275 case Type::IncompleteArray: 4276 // Losing element qualification here is fine. 4277 T = cast<ArrayType>(Ty)->getElementType(); 4278 break; 4279 case Type::VariableArray: { 4280 // Losing element qualification here is fine. 4281 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4282 4283 // Unknown size indication requires no size computation. 4284 // Otherwise, evaluate and record it. 4285 auto Size = VAT->getSizeExpr(); 4286 if (Size && !CSI->isVLATypeCaptured(VAT) && 4287 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4288 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4289 4290 T = VAT->getElementType(); 4291 break; 4292 } 4293 case Type::FunctionProto: 4294 case Type::FunctionNoProto: 4295 T = cast<FunctionType>(Ty)->getReturnType(); 4296 break; 4297 case Type::Paren: 4298 case Type::TypeOf: 4299 case Type::UnaryTransform: 4300 case Type::Attributed: 4301 case Type::SubstTemplateTypeParm: 4302 case Type::MacroQualified: 4303 // Keep walking after single level desugaring. 4304 T = T.getSingleStepDesugaredType(Context); 4305 break; 4306 case Type::Typedef: 4307 T = cast<TypedefType>(Ty)->desugar(); 4308 break; 4309 case Type::Decltype: 4310 T = cast<DecltypeType>(Ty)->desugar(); 4311 break; 4312 case Type::Auto: 4313 case Type::DeducedTemplateSpecialization: 4314 T = cast<DeducedType>(Ty)->getDeducedType(); 4315 break; 4316 case Type::TypeOfExpr: 4317 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4318 break; 4319 case Type::Atomic: 4320 T = cast<AtomicType>(Ty)->getValueType(); 4321 break; 4322 } 4323 } while (!T.isNull() && T->isVariablyModifiedType()); 4324 } 4325 4326 /// Build a sizeof or alignof expression given a type operand. 4327 ExprResult 4328 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4329 SourceLocation OpLoc, 4330 UnaryExprOrTypeTrait ExprKind, 4331 SourceRange R) { 4332 if (!TInfo) 4333 return ExprError(); 4334 4335 QualType T = TInfo->getType(); 4336 4337 if (!T->isDependentType() && 4338 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4339 return ExprError(); 4340 4341 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4342 if (auto *TT = T->getAs<TypedefType>()) { 4343 for (auto I = FunctionScopes.rbegin(), 4344 E = std::prev(FunctionScopes.rend()); 4345 I != E; ++I) { 4346 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4347 if (CSI == nullptr) 4348 break; 4349 DeclContext *DC = nullptr; 4350 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4351 DC = LSI->CallOperator; 4352 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4353 DC = CRSI->TheCapturedDecl; 4354 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4355 DC = BSI->TheDecl; 4356 if (DC) { 4357 if (DC->containsDecl(TT->getDecl())) 4358 break; 4359 captureVariablyModifiedType(Context, T, CSI); 4360 } 4361 } 4362 } 4363 } 4364 4365 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4366 return new (Context) UnaryExprOrTypeTraitExpr( 4367 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4368 } 4369 4370 /// Build a sizeof or alignof expression given an expression 4371 /// operand. 4372 ExprResult 4373 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4374 UnaryExprOrTypeTrait ExprKind) { 4375 ExprResult PE = CheckPlaceholderExpr(E); 4376 if (PE.isInvalid()) 4377 return ExprError(); 4378 4379 E = PE.get(); 4380 4381 // Verify that the operand is valid. 4382 bool isInvalid = false; 4383 if (E->isTypeDependent()) { 4384 // Delay type-checking for type-dependent expressions. 4385 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4386 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4387 } else if (ExprKind == UETT_VecStep) { 4388 isInvalid = CheckVecStepExpr(E); 4389 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4390 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4391 isInvalid = true; 4392 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4393 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4394 isInvalid = true; 4395 } else { 4396 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4397 } 4398 4399 if (isInvalid) 4400 return ExprError(); 4401 4402 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4403 PE = TransformToPotentiallyEvaluated(E); 4404 if (PE.isInvalid()) return ExprError(); 4405 E = PE.get(); 4406 } 4407 4408 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4409 return new (Context) UnaryExprOrTypeTraitExpr( 4410 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4411 } 4412 4413 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4414 /// expr and the same for @c alignof and @c __alignof 4415 /// Note that the ArgRange is invalid if isType is false. 4416 ExprResult 4417 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4418 UnaryExprOrTypeTrait ExprKind, bool IsType, 4419 void *TyOrEx, SourceRange ArgRange) { 4420 // If error parsing type, ignore. 4421 if (!TyOrEx) return ExprError(); 4422 4423 if (IsType) { 4424 TypeSourceInfo *TInfo; 4425 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4426 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4427 } 4428 4429 Expr *ArgEx = (Expr *)TyOrEx; 4430 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4431 return Result; 4432 } 4433 4434 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4435 bool IsReal) { 4436 if (V.get()->isTypeDependent()) 4437 return S.Context.DependentTy; 4438 4439 // _Real and _Imag are only l-values for normal l-values. 4440 if (V.get()->getObjectKind() != OK_Ordinary) { 4441 V = S.DefaultLvalueConversion(V.get()); 4442 if (V.isInvalid()) 4443 return QualType(); 4444 } 4445 4446 // These operators return the element type of a complex type. 4447 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4448 return CT->getElementType(); 4449 4450 // Otherwise they pass through real integer and floating point types here. 4451 if (V.get()->getType()->isArithmeticType()) 4452 return V.get()->getType(); 4453 4454 // Test for placeholders. 4455 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4456 if (PR.isInvalid()) return QualType(); 4457 if (PR.get() != V.get()) { 4458 V = PR; 4459 return CheckRealImagOperand(S, V, Loc, IsReal); 4460 } 4461 4462 // Reject anything else. 4463 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4464 << (IsReal ? "__real" : "__imag"); 4465 return QualType(); 4466 } 4467 4468 4469 4470 ExprResult 4471 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4472 tok::TokenKind Kind, Expr *Input) { 4473 UnaryOperatorKind Opc; 4474 switch (Kind) { 4475 default: llvm_unreachable("Unknown unary op!"); 4476 case tok::plusplus: Opc = UO_PostInc; break; 4477 case tok::minusminus: Opc = UO_PostDec; break; 4478 } 4479 4480 // Since this might is a postfix expression, get rid of ParenListExprs. 4481 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4482 if (Result.isInvalid()) return ExprError(); 4483 Input = Result.get(); 4484 4485 return BuildUnaryOp(S, OpLoc, Opc, Input); 4486 } 4487 4488 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4489 /// 4490 /// \return true on error 4491 static bool checkArithmeticOnObjCPointer(Sema &S, 4492 SourceLocation opLoc, 4493 Expr *op) { 4494 assert(op->getType()->isObjCObjectPointerType()); 4495 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4496 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4497 return false; 4498 4499 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4500 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4501 << op->getSourceRange(); 4502 return true; 4503 } 4504 4505 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4506 auto *BaseNoParens = Base->IgnoreParens(); 4507 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4508 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4509 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4510 } 4511 4512 ExprResult 4513 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4514 Expr *idx, SourceLocation rbLoc) { 4515 if (base && !base->getType().isNull() && 4516 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4517 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4518 SourceLocation(), /*Length*/ nullptr, 4519 /*Stride=*/nullptr, rbLoc); 4520 4521 // Since this might be a postfix expression, get rid of ParenListExprs. 4522 if (isa<ParenListExpr>(base)) { 4523 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4524 if (result.isInvalid()) return ExprError(); 4525 base = result.get(); 4526 } 4527 4528 // Check if base and idx form a MatrixSubscriptExpr. 4529 // 4530 // Helper to check for comma expressions, which are not allowed as indices for 4531 // matrix subscript expressions. 4532 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4533 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4534 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4535 << SourceRange(base->getBeginLoc(), rbLoc); 4536 return true; 4537 } 4538 return false; 4539 }; 4540 // The matrix subscript operator ([][])is considered a single operator. 4541 // Separating the index expressions by parenthesis is not allowed. 4542 if (base->getType()->isSpecificPlaceholderType( 4543 BuiltinType::IncompleteMatrixIdx) && 4544 !isa<MatrixSubscriptExpr>(base)) { 4545 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4546 << SourceRange(base->getBeginLoc(), rbLoc); 4547 return ExprError(); 4548 } 4549 // If the base is a MatrixSubscriptExpr, try to create a new 4550 // MatrixSubscriptExpr. 4551 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4552 if (matSubscriptE) { 4553 if (CheckAndReportCommaError(idx)) 4554 return ExprError(); 4555 4556 assert(matSubscriptE->isIncomplete() && 4557 "base has to be an incomplete matrix subscript"); 4558 return CreateBuiltinMatrixSubscriptExpr( 4559 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4560 } 4561 4562 // Handle any non-overload placeholder types in the base and index 4563 // expressions. We can't handle overloads here because the other 4564 // operand might be an overloadable type, in which case the overload 4565 // resolution for the operator overload should get the first crack 4566 // at the overload. 4567 bool IsMSPropertySubscript = false; 4568 if (base->getType()->isNonOverloadPlaceholderType()) { 4569 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4570 if (!IsMSPropertySubscript) { 4571 ExprResult result = CheckPlaceholderExpr(base); 4572 if (result.isInvalid()) 4573 return ExprError(); 4574 base = result.get(); 4575 } 4576 } 4577 4578 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4579 if (base->getType()->isMatrixType()) { 4580 if (CheckAndReportCommaError(idx)) 4581 return ExprError(); 4582 4583 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4584 } 4585 4586 // A comma-expression as the index is deprecated in C++2a onwards. 4587 if (getLangOpts().CPlusPlus20 && 4588 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4589 (isa<CXXOperatorCallExpr>(idx) && 4590 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4591 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4592 << SourceRange(base->getBeginLoc(), rbLoc); 4593 } 4594 4595 if (idx->getType()->isNonOverloadPlaceholderType()) { 4596 ExprResult result = CheckPlaceholderExpr(idx); 4597 if (result.isInvalid()) return ExprError(); 4598 idx = result.get(); 4599 } 4600 4601 // Build an unanalyzed expression if either operand is type-dependent. 4602 if (getLangOpts().CPlusPlus && 4603 (base->isTypeDependent() || idx->isTypeDependent())) { 4604 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4605 VK_LValue, OK_Ordinary, rbLoc); 4606 } 4607 4608 // MSDN, property (C++) 4609 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4610 // This attribute can also be used in the declaration of an empty array in a 4611 // class or structure definition. For example: 4612 // __declspec(property(get=GetX, put=PutX)) int x[]; 4613 // The above statement indicates that x[] can be used with one or more array 4614 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4615 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4616 if (IsMSPropertySubscript) { 4617 // Build MS property subscript expression if base is MS property reference 4618 // or MS property subscript. 4619 return new (Context) MSPropertySubscriptExpr( 4620 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4621 } 4622 4623 // Use C++ overloaded-operator rules if either operand has record 4624 // type. The spec says to do this if either type is *overloadable*, 4625 // but enum types can't declare subscript operators or conversion 4626 // operators, so there's nothing interesting for overload resolution 4627 // to do if there aren't any record types involved. 4628 // 4629 // ObjC pointers have their own subscripting logic that is not tied 4630 // to overload resolution and so should not take this path. 4631 if (getLangOpts().CPlusPlus && 4632 (base->getType()->isRecordType() || 4633 (!base->getType()->isObjCObjectPointerType() && 4634 idx->getType()->isRecordType()))) { 4635 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4636 } 4637 4638 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4639 4640 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4641 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4642 4643 return Res; 4644 } 4645 4646 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4647 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4648 InitializationKind Kind = 4649 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4650 InitializationSequence InitSeq(*this, Entity, Kind, E); 4651 return InitSeq.Perform(*this, Entity, Kind, E); 4652 } 4653 4654 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4655 Expr *ColumnIdx, 4656 SourceLocation RBLoc) { 4657 ExprResult BaseR = CheckPlaceholderExpr(Base); 4658 if (BaseR.isInvalid()) 4659 return BaseR; 4660 Base = BaseR.get(); 4661 4662 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4663 if (RowR.isInvalid()) 4664 return RowR; 4665 RowIdx = RowR.get(); 4666 4667 if (!ColumnIdx) 4668 return new (Context) MatrixSubscriptExpr( 4669 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4670 4671 // Build an unanalyzed expression if any of the operands is type-dependent. 4672 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4673 ColumnIdx->isTypeDependent()) 4674 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4675 Context.DependentTy, RBLoc); 4676 4677 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4678 if (ColumnR.isInvalid()) 4679 return ColumnR; 4680 ColumnIdx = ColumnR.get(); 4681 4682 // Check that IndexExpr is an integer expression. If it is a constant 4683 // expression, check that it is less than Dim (= the number of elements in the 4684 // corresponding dimension). 4685 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4686 bool IsColumnIdx) -> Expr * { 4687 if (!IndexExpr->getType()->isIntegerType() && 4688 !IndexExpr->isTypeDependent()) { 4689 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4690 << IsColumnIdx; 4691 return nullptr; 4692 } 4693 4694 if (Optional<llvm::APSInt> Idx = 4695 IndexExpr->getIntegerConstantExpr(Context)) { 4696 if ((*Idx < 0 || *Idx >= Dim)) { 4697 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4698 << IsColumnIdx << Dim; 4699 return nullptr; 4700 } 4701 } 4702 4703 ExprResult ConvExpr = 4704 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4705 assert(!ConvExpr.isInvalid() && 4706 "should be able to convert any integer type to size type"); 4707 return ConvExpr.get(); 4708 }; 4709 4710 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4711 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4712 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4713 if (!RowIdx || !ColumnIdx) 4714 return ExprError(); 4715 4716 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4717 MTy->getElementType(), RBLoc); 4718 } 4719 4720 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4721 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4722 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4723 4724 // For expressions like `&(*s).b`, the base is recorded and what should be 4725 // checked. 4726 const MemberExpr *Member = nullptr; 4727 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4728 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4729 4730 LastRecord.PossibleDerefs.erase(StrippedExpr); 4731 } 4732 4733 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4734 QualType ResultTy = E->getType(); 4735 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4736 4737 // Bail if the element is an array since it is not memory access. 4738 if (isa<ArrayType>(ResultTy)) 4739 return; 4740 4741 if (ResultTy->hasAttr(attr::NoDeref)) { 4742 LastRecord.PossibleDerefs.insert(E); 4743 return; 4744 } 4745 4746 // Check if the base type is a pointer to a member access of a struct 4747 // marked with noderef. 4748 const Expr *Base = E->getBase(); 4749 QualType BaseTy = Base->getType(); 4750 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4751 // Not a pointer access 4752 return; 4753 4754 const MemberExpr *Member = nullptr; 4755 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4756 Member->isArrow()) 4757 Base = Member->getBase(); 4758 4759 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4760 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4761 LastRecord.PossibleDerefs.insert(E); 4762 } 4763 } 4764 4765 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4766 Expr *LowerBound, 4767 SourceLocation ColonLocFirst, 4768 SourceLocation ColonLocSecond, 4769 Expr *Length, Expr *Stride, 4770 SourceLocation RBLoc) { 4771 if (Base->getType()->isPlaceholderType() && 4772 !Base->getType()->isSpecificPlaceholderType( 4773 BuiltinType::OMPArraySection)) { 4774 ExprResult Result = CheckPlaceholderExpr(Base); 4775 if (Result.isInvalid()) 4776 return ExprError(); 4777 Base = Result.get(); 4778 } 4779 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4780 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4781 if (Result.isInvalid()) 4782 return ExprError(); 4783 Result = DefaultLvalueConversion(Result.get()); 4784 if (Result.isInvalid()) 4785 return ExprError(); 4786 LowerBound = Result.get(); 4787 } 4788 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4789 ExprResult Result = CheckPlaceholderExpr(Length); 4790 if (Result.isInvalid()) 4791 return ExprError(); 4792 Result = DefaultLvalueConversion(Result.get()); 4793 if (Result.isInvalid()) 4794 return ExprError(); 4795 Length = Result.get(); 4796 } 4797 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4798 ExprResult Result = CheckPlaceholderExpr(Stride); 4799 if (Result.isInvalid()) 4800 return ExprError(); 4801 Result = DefaultLvalueConversion(Result.get()); 4802 if (Result.isInvalid()) 4803 return ExprError(); 4804 Stride = Result.get(); 4805 } 4806 4807 // Build an unanalyzed expression if either operand is type-dependent. 4808 if (Base->isTypeDependent() || 4809 (LowerBound && 4810 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4811 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4812 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4813 return new (Context) OMPArraySectionExpr( 4814 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4815 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4816 } 4817 4818 // Perform default conversions. 4819 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4820 QualType ResultTy; 4821 if (OriginalTy->isAnyPointerType()) { 4822 ResultTy = OriginalTy->getPointeeType(); 4823 } else if (OriginalTy->isArrayType()) { 4824 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4825 } else { 4826 return ExprError( 4827 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4828 << Base->getSourceRange()); 4829 } 4830 // C99 6.5.2.1p1 4831 if (LowerBound) { 4832 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4833 LowerBound); 4834 if (Res.isInvalid()) 4835 return ExprError(Diag(LowerBound->getExprLoc(), 4836 diag::err_omp_typecheck_section_not_integer) 4837 << 0 << LowerBound->getSourceRange()); 4838 LowerBound = Res.get(); 4839 4840 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4841 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4842 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4843 << 0 << LowerBound->getSourceRange(); 4844 } 4845 if (Length) { 4846 auto Res = 4847 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4848 if (Res.isInvalid()) 4849 return ExprError(Diag(Length->getExprLoc(), 4850 diag::err_omp_typecheck_section_not_integer) 4851 << 1 << Length->getSourceRange()); 4852 Length = Res.get(); 4853 4854 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4855 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4856 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4857 << 1 << Length->getSourceRange(); 4858 } 4859 if (Stride) { 4860 ExprResult Res = 4861 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4862 if (Res.isInvalid()) 4863 return ExprError(Diag(Stride->getExprLoc(), 4864 diag::err_omp_typecheck_section_not_integer) 4865 << 1 << Stride->getSourceRange()); 4866 Stride = Res.get(); 4867 4868 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4869 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4870 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4871 << 1 << Stride->getSourceRange(); 4872 } 4873 4874 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4875 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4876 // type. Note that functions are not objects, and that (in C99 parlance) 4877 // incomplete types are not object types. 4878 if (ResultTy->isFunctionType()) { 4879 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4880 << ResultTy << Base->getSourceRange(); 4881 return ExprError(); 4882 } 4883 4884 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4885 diag::err_omp_section_incomplete_type, Base)) 4886 return ExprError(); 4887 4888 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4889 Expr::EvalResult Result; 4890 if (LowerBound->EvaluateAsInt(Result, Context)) { 4891 // OpenMP 5.0, [2.1.5 Array Sections] 4892 // The array section must be a subset of the original array. 4893 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4894 if (LowerBoundValue.isNegative()) { 4895 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4896 << LowerBound->getSourceRange(); 4897 return ExprError(); 4898 } 4899 } 4900 } 4901 4902 if (Length) { 4903 Expr::EvalResult Result; 4904 if (Length->EvaluateAsInt(Result, Context)) { 4905 // OpenMP 5.0, [2.1.5 Array Sections] 4906 // The length must evaluate to non-negative integers. 4907 llvm::APSInt LengthValue = Result.Val.getInt(); 4908 if (LengthValue.isNegative()) { 4909 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4910 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4911 << Length->getSourceRange(); 4912 return ExprError(); 4913 } 4914 } 4915 } else if (ColonLocFirst.isValid() && 4916 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4917 !OriginalTy->isVariableArrayType()))) { 4918 // OpenMP 5.0, [2.1.5 Array Sections] 4919 // When the size of the array dimension is not known, the length must be 4920 // specified explicitly. 4921 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 4922 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4923 return ExprError(); 4924 } 4925 4926 if (Stride) { 4927 Expr::EvalResult Result; 4928 if (Stride->EvaluateAsInt(Result, Context)) { 4929 // OpenMP 5.0, [2.1.5 Array Sections] 4930 // The stride must evaluate to a positive integer. 4931 llvm::APSInt StrideValue = Result.Val.getInt(); 4932 if (!StrideValue.isStrictlyPositive()) { 4933 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 4934 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 4935 << Stride->getSourceRange(); 4936 return ExprError(); 4937 } 4938 } 4939 } 4940 4941 if (!Base->getType()->isSpecificPlaceholderType( 4942 BuiltinType::OMPArraySection)) { 4943 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4944 if (Result.isInvalid()) 4945 return ExprError(); 4946 Base = Result.get(); 4947 } 4948 return new (Context) OMPArraySectionExpr( 4949 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 4950 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4951 } 4952 4953 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4954 SourceLocation RParenLoc, 4955 ArrayRef<Expr *> Dims, 4956 ArrayRef<SourceRange> Brackets) { 4957 if (Base->getType()->isPlaceholderType()) { 4958 ExprResult Result = CheckPlaceholderExpr(Base); 4959 if (Result.isInvalid()) 4960 return ExprError(); 4961 Result = DefaultLvalueConversion(Result.get()); 4962 if (Result.isInvalid()) 4963 return ExprError(); 4964 Base = Result.get(); 4965 } 4966 QualType BaseTy = Base->getType(); 4967 // Delay analysis of the types/expressions if instantiation/specialization is 4968 // required. 4969 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4970 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4971 LParenLoc, RParenLoc, Dims, Brackets); 4972 if (!BaseTy->isPointerType() || 4973 (!Base->isTypeDependent() && 4974 BaseTy->getPointeeType()->isIncompleteType())) 4975 return ExprError(Diag(Base->getExprLoc(), 4976 diag::err_omp_non_pointer_type_array_shaping_base) 4977 << Base->getSourceRange()); 4978 4979 SmallVector<Expr *, 4> NewDims; 4980 bool ErrorFound = false; 4981 for (Expr *Dim : Dims) { 4982 if (Dim->getType()->isPlaceholderType()) { 4983 ExprResult Result = CheckPlaceholderExpr(Dim); 4984 if (Result.isInvalid()) { 4985 ErrorFound = true; 4986 continue; 4987 } 4988 Result = DefaultLvalueConversion(Result.get()); 4989 if (Result.isInvalid()) { 4990 ErrorFound = true; 4991 continue; 4992 } 4993 Dim = Result.get(); 4994 } 4995 if (!Dim->isTypeDependent()) { 4996 ExprResult Result = 4997 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4998 if (Result.isInvalid()) { 4999 ErrorFound = true; 5000 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5001 << Dim->getSourceRange(); 5002 continue; 5003 } 5004 Dim = Result.get(); 5005 Expr::EvalResult EvResult; 5006 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5007 // OpenMP 5.0, [2.1.4 Array Shaping] 5008 // Each si is an integral type expression that must evaluate to a 5009 // positive integer. 5010 llvm::APSInt Value = EvResult.Val.getInt(); 5011 if (!Value.isStrictlyPositive()) { 5012 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5013 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5014 << Dim->getSourceRange(); 5015 ErrorFound = true; 5016 continue; 5017 } 5018 } 5019 } 5020 NewDims.push_back(Dim); 5021 } 5022 if (ErrorFound) 5023 return ExprError(); 5024 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5025 LParenLoc, RParenLoc, NewDims, Brackets); 5026 } 5027 5028 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5029 SourceLocation LLoc, SourceLocation RLoc, 5030 ArrayRef<OMPIteratorData> Data) { 5031 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5032 bool IsCorrect = true; 5033 for (const OMPIteratorData &D : Data) { 5034 TypeSourceInfo *TInfo = nullptr; 5035 SourceLocation StartLoc; 5036 QualType DeclTy; 5037 if (!D.Type.getAsOpaquePtr()) { 5038 // OpenMP 5.0, 2.1.6 Iterators 5039 // In an iterator-specifier, if the iterator-type is not specified then 5040 // the type of that iterator is of int type. 5041 DeclTy = Context.IntTy; 5042 StartLoc = D.DeclIdentLoc; 5043 } else { 5044 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5045 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5046 } 5047 5048 bool IsDeclTyDependent = DeclTy->isDependentType() || 5049 DeclTy->containsUnexpandedParameterPack() || 5050 DeclTy->isInstantiationDependentType(); 5051 if (!IsDeclTyDependent) { 5052 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5053 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5054 // The iterator-type must be an integral or pointer type. 5055 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5056 << DeclTy; 5057 IsCorrect = false; 5058 continue; 5059 } 5060 if (DeclTy.isConstant(Context)) { 5061 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5062 // The iterator-type must not be const qualified. 5063 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5064 << DeclTy; 5065 IsCorrect = false; 5066 continue; 5067 } 5068 } 5069 5070 // Iterator declaration. 5071 assert(D.DeclIdent && "Identifier expected."); 5072 // Always try to create iterator declarator to avoid extra error messages 5073 // about unknown declarations use. 5074 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5075 D.DeclIdent, DeclTy, TInfo, SC_None); 5076 VD->setImplicit(); 5077 if (S) { 5078 // Check for conflicting previous declaration. 5079 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5080 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5081 ForVisibleRedeclaration); 5082 Previous.suppressDiagnostics(); 5083 LookupName(Previous, S); 5084 5085 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5086 /*AllowInlineNamespace=*/false); 5087 if (!Previous.empty()) { 5088 NamedDecl *Old = Previous.getRepresentativeDecl(); 5089 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5090 Diag(Old->getLocation(), diag::note_previous_definition); 5091 } else { 5092 PushOnScopeChains(VD, S); 5093 } 5094 } else { 5095 CurContext->addDecl(VD); 5096 } 5097 Expr *Begin = D.Range.Begin; 5098 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5099 ExprResult BeginRes = 5100 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5101 Begin = BeginRes.get(); 5102 } 5103 Expr *End = D.Range.End; 5104 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5105 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5106 End = EndRes.get(); 5107 } 5108 Expr *Step = D.Range.Step; 5109 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5110 if (!Step->getType()->isIntegralType(Context)) { 5111 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5112 << Step << Step->getSourceRange(); 5113 IsCorrect = false; 5114 continue; 5115 } 5116 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5117 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5118 // If the step expression of a range-specification equals zero, the 5119 // behavior is unspecified. 5120 if (Result && Result->isNullValue()) { 5121 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5122 << Step << Step->getSourceRange(); 5123 IsCorrect = false; 5124 continue; 5125 } 5126 } 5127 if (!Begin || !End || !IsCorrect) { 5128 IsCorrect = false; 5129 continue; 5130 } 5131 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5132 IDElem.IteratorDecl = VD; 5133 IDElem.AssignmentLoc = D.AssignLoc; 5134 IDElem.Range.Begin = Begin; 5135 IDElem.Range.End = End; 5136 IDElem.Range.Step = Step; 5137 IDElem.ColonLoc = D.ColonLoc; 5138 IDElem.SecondColonLoc = D.SecColonLoc; 5139 } 5140 if (!IsCorrect) { 5141 // Invalidate all created iterator declarations if error is found. 5142 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5143 if (Decl *ID = D.IteratorDecl) 5144 ID->setInvalidDecl(); 5145 } 5146 return ExprError(); 5147 } 5148 SmallVector<OMPIteratorHelperData, 4> Helpers; 5149 if (!CurContext->isDependentContext()) { 5150 // Build number of ityeration for each iteration range. 5151 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5152 // ((Begini-Stepi-1-Endi) / -Stepi); 5153 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5154 // (Endi - Begini) 5155 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5156 D.Range.Begin); 5157 if(!Res.isUsable()) { 5158 IsCorrect = false; 5159 continue; 5160 } 5161 ExprResult St, St1; 5162 if (D.Range.Step) { 5163 St = D.Range.Step; 5164 // (Endi - Begini) + Stepi 5165 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5166 if (!Res.isUsable()) { 5167 IsCorrect = false; 5168 continue; 5169 } 5170 // (Endi - Begini) + Stepi - 1 5171 Res = 5172 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5173 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5174 if (!Res.isUsable()) { 5175 IsCorrect = false; 5176 continue; 5177 } 5178 // ((Endi - Begini) + Stepi - 1) / Stepi 5179 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5180 if (!Res.isUsable()) { 5181 IsCorrect = false; 5182 continue; 5183 } 5184 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5185 // (Begini - Endi) 5186 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5187 D.Range.Begin, D.Range.End); 5188 if (!Res1.isUsable()) { 5189 IsCorrect = false; 5190 continue; 5191 } 5192 // (Begini - Endi) - Stepi 5193 Res1 = 5194 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5195 if (!Res1.isUsable()) { 5196 IsCorrect = false; 5197 continue; 5198 } 5199 // (Begini - Endi) - Stepi - 1 5200 Res1 = 5201 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5202 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5203 if (!Res1.isUsable()) { 5204 IsCorrect = false; 5205 continue; 5206 } 5207 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5208 Res1 = 5209 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5210 if (!Res1.isUsable()) { 5211 IsCorrect = false; 5212 continue; 5213 } 5214 // Stepi > 0. 5215 ExprResult CmpRes = 5216 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5217 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5218 if (!CmpRes.isUsable()) { 5219 IsCorrect = false; 5220 continue; 5221 } 5222 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5223 Res.get(), Res1.get()); 5224 if (!Res.isUsable()) { 5225 IsCorrect = false; 5226 continue; 5227 } 5228 } 5229 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5230 if (!Res.isUsable()) { 5231 IsCorrect = false; 5232 continue; 5233 } 5234 5235 // Build counter update. 5236 // Build counter. 5237 auto *CounterVD = 5238 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5239 D.IteratorDecl->getBeginLoc(), nullptr, 5240 Res.get()->getType(), nullptr, SC_None); 5241 CounterVD->setImplicit(); 5242 ExprResult RefRes = 5243 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5244 D.IteratorDecl->getBeginLoc()); 5245 // Build counter update. 5246 // I = Begini + counter * Stepi; 5247 ExprResult UpdateRes; 5248 if (D.Range.Step) { 5249 UpdateRes = CreateBuiltinBinOp( 5250 D.AssignmentLoc, BO_Mul, 5251 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5252 } else { 5253 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5254 } 5255 if (!UpdateRes.isUsable()) { 5256 IsCorrect = false; 5257 continue; 5258 } 5259 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5260 UpdateRes.get()); 5261 if (!UpdateRes.isUsable()) { 5262 IsCorrect = false; 5263 continue; 5264 } 5265 ExprResult VDRes = 5266 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5267 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5268 D.IteratorDecl->getBeginLoc()); 5269 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5270 UpdateRes.get()); 5271 if (!UpdateRes.isUsable()) { 5272 IsCorrect = false; 5273 continue; 5274 } 5275 UpdateRes = 5276 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5277 if (!UpdateRes.isUsable()) { 5278 IsCorrect = false; 5279 continue; 5280 } 5281 ExprResult CounterUpdateRes = 5282 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5283 if (!CounterUpdateRes.isUsable()) { 5284 IsCorrect = false; 5285 continue; 5286 } 5287 CounterUpdateRes = 5288 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5289 if (!CounterUpdateRes.isUsable()) { 5290 IsCorrect = false; 5291 continue; 5292 } 5293 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5294 HD.CounterVD = CounterVD; 5295 HD.Upper = Res.get(); 5296 HD.Update = UpdateRes.get(); 5297 HD.CounterUpdate = CounterUpdateRes.get(); 5298 } 5299 } else { 5300 Helpers.assign(ID.size(), {}); 5301 } 5302 if (!IsCorrect) { 5303 // Invalidate all created iterator declarations if error is found. 5304 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5305 if (Decl *ID = D.IteratorDecl) 5306 ID->setInvalidDecl(); 5307 } 5308 return ExprError(); 5309 } 5310 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5311 LLoc, RLoc, ID, Helpers); 5312 } 5313 5314 ExprResult 5315 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5316 Expr *Idx, SourceLocation RLoc) { 5317 Expr *LHSExp = Base; 5318 Expr *RHSExp = Idx; 5319 5320 ExprValueKind VK = VK_LValue; 5321 ExprObjectKind OK = OK_Ordinary; 5322 5323 // Per C++ core issue 1213, the result is an xvalue if either operand is 5324 // a non-lvalue array, and an lvalue otherwise. 5325 if (getLangOpts().CPlusPlus11) { 5326 for (auto *Op : {LHSExp, RHSExp}) { 5327 Op = Op->IgnoreImplicit(); 5328 if (Op->getType()->isArrayType() && !Op->isLValue()) 5329 VK = VK_XValue; 5330 } 5331 } 5332 5333 // Perform default conversions. 5334 if (!LHSExp->getType()->getAs<VectorType>()) { 5335 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5336 if (Result.isInvalid()) 5337 return ExprError(); 5338 LHSExp = Result.get(); 5339 } 5340 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5341 if (Result.isInvalid()) 5342 return ExprError(); 5343 RHSExp = Result.get(); 5344 5345 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5346 5347 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5348 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5349 // in the subscript position. As a result, we need to derive the array base 5350 // and index from the expression types. 5351 Expr *BaseExpr, *IndexExpr; 5352 QualType ResultType; 5353 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5354 BaseExpr = LHSExp; 5355 IndexExpr = RHSExp; 5356 ResultType = Context.DependentTy; 5357 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5358 BaseExpr = LHSExp; 5359 IndexExpr = RHSExp; 5360 ResultType = PTy->getPointeeType(); 5361 } else if (const ObjCObjectPointerType *PTy = 5362 LHSTy->getAs<ObjCObjectPointerType>()) { 5363 BaseExpr = LHSExp; 5364 IndexExpr = RHSExp; 5365 5366 // Use custom logic if this should be the pseudo-object subscript 5367 // expression. 5368 if (!LangOpts.isSubscriptPointerArithmetic()) 5369 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5370 nullptr); 5371 5372 ResultType = PTy->getPointeeType(); 5373 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5374 // Handle the uncommon case of "123[Ptr]". 5375 BaseExpr = RHSExp; 5376 IndexExpr = LHSExp; 5377 ResultType = PTy->getPointeeType(); 5378 } else if (const ObjCObjectPointerType *PTy = 5379 RHSTy->getAs<ObjCObjectPointerType>()) { 5380 // Handle the uncommon case of "123[Ptr]". 5381 BaseExpr = RHSExp; 5382 IndexExpr = LHSExp; 5383 ResultType = PTy->getPointeeType(); 5384 if (!LangOpts.isSubscriptPointerArithmetic()) { 5385 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5386 << ResultType << BaseExpr->getSourceRange(); 5387 return ExprError(); 5388 } 5389 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5390 BaseExpr = LHSExp; // vectors: V[123] 5391 IndexExpr = RHSExp; 5392 // We apply C++ DR1213 to vector subscripting too. 5393 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5394 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5395 if (Materialized.isInvalid()) 5396 return ExprError(); 5397 LHSExp = Materialized.get(); 5398 } 5399 VK = LHSExp->getValueKind(); 5400 if (VK != VK_RValue) 5401 OK = OK_VectorComponent; 5402 5403 ResultType = VTy->getElementType(); 5404 QualType BaseType = BaseExpr->getType(); 5405 Qualifiers BaseQuals = BaseType.getQualifiers(); 5406 Qualifiers MemberQuals = ResultType.getQualifiers(); 5407 Qualifiers Combined = BaseQuals + MemberQuals; 5408 if (Combined != MemberQuals) 5409 ResultType = Context.getQualifiedType(ResultType, Combined); 5410 } else if (LHSTy->isArrayType()) { 5411 // If we see an array that wasn't promoted by 5412 // DefaultFunctionArrayLvalueConversion, it must be an array that 5413 // wasn't promoted because of the C90 rule that doesn't 5414 // allow promoting non-lvalue arrays. Warn, then 5415 // force the promotion here. 5416 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5417 << LHSExp->getSourceRange(); 5418 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5419 CK_ArrayToPointerDecay).get(); 5420 LHSTy = LHSExp->getType(); 5421 5422 BaseExpr = LHSExp; 5423 IndexExpr = RHSExp; 5424 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5425 } else if (RHSTy->isArrayType()) { 5426 // Same as previous, except for 123[f().a] case 5427 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5428 << RHSExp->getSourceRange(); 5429 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5430 CK_ArrayToPointerDecay).get(); 5431 RHSTy = RHSExp->getType(); 5432 5433 BaseExpr = RHSExp; 5434 IndexExpr = LHSExp; 5435 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5436 } else { 5437 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5438 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5439 } 5440 // C99 6.5.2.1p1 5441 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5442 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5443 << IndexExpr->getSourceRange()); 5444 5445 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5446 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5447 && !IndexExpr->isTypeDependent()) 5448 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5449 5450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5451 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5452 // type. Note that Functions are not objects, and that (in C99 parlance) 5453 // incomplete types are not object types. 5454 if (ResultType->isFunctionType()) { 5455 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5456 << ResultType << BaseExpr->getSourceRange(); 5457 return ExprError(); 5458 } 5459 5460 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5461 // GNU extension: subscripting on pointer to void 5462 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5463 << BaseExpr->getSourceRange(); 5464 5465 // C forbids expressions of unqualified void type from being l-values. 5466 // See IsCForbiddenLValueType. 5467 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5468 } else if (!ResultType->isDependentType() && 5469 RequireCompleteSizedType( 5470 LLoc, ResultType, 5471 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5472 return ExprError(); 5473 5474 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5475 !ResultType.isCForbiddenLValueType()); 5476 5477 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5478 FunctionScopes.size() > 1) { 5479 if (auto *TT = 5480 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5481 for (auto I = FunctionScopes.rbegin(), 5482 E = std::prev(FunctionScopes.rend()); 5483 I != E; ++I) { 5484 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5485 if (CSI == nullptr) 5486 break; 5487 DeclContext *DC = nullptr; 5488 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5489 DC = LSI->CallOperator; 5490 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5491 DC = CRSI->TheCapturedDecl; 5492 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5493 DC = BSI->TheDecl; 5494 if (DC) { 5495 if (DC->containsDecl(TT->getDecl())) 5496 break; 5497 captureVariablyModifiedType( 5498 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5499 } 5500 } 5501 } 5502 } 5503 5504 return new (Context) 5505 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5506 } 5507 5508 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5509 ParmVarDecl *Param) { 5510 if (Param->hasUnparsedDefaultArg()) { 5511 // If we've already cleared out the location for the default argument, 5512 // that means we're parsing it right now. 5513 if (!UnparsedDefaultArgLocs.count(Param)) { 5514 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5515 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5516 Param->setInvalidDecl(); 5517 return true; 5518 } 5519 5520 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5521 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5522 Diag(UnparsedDefaultArgLocs[Param], 5523 diag::note_default_argument_declared_here); 5524 return true; 5525 } 5526 5527 if (Param->hasUninstantiatedDefaultArg() && 5528 InstantiateDefaultArgument(CallLoc, FD, Param)) 5529 return true; 5530 5531 assert(Param->hasInit() && "default argument but no initializer?"); 5532 5533 // If the default expression creates temporaries, we need to 5534 // push them to the current stack of expression temporaries so they'll 5535 // be properly destroyed. 5536 // FIXME: We should really be rebuilding the default argument with new 5537 // bound temporaries; see the comment in PR5810. 5538 // We don't need to do that with block decls, though, because 5539 // blocks in default argument expression can never capture anything. 5540 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5541 // Set the "needs cleanups" bit regardless of whether there are 5542 // any explicit objects. 5543 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5544 5545 // Append all the objects to the cleanup list. Right now, this 5546 // should always be a no-op, because blocks in default argument 5547 // expressions should never be able to capture anything. 5548 assert(!Init->getNumObjects() && 5549 "default argument expression has capturing blocks?"); 5550 } 5551 5552 // We already type-checked the argument, so we know it works. 5553 // Just mark all of the declarations in this potentially-evaluated expression 5554 // as being "referenced". 5555 EnterExpressionEvaluationContext EvalContext( 5556 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5557 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5558 /*SkipLocalVariables=*/true); 5559 return false; 5560 } 5561 5562 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5563 FunctionDecl *FD, ParmVarDecl *Param) { 5564 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5565 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5566 return ExprError(); 5567 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5568 } 5569 5570 Sema::VariadicCallType 5571 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5572 Expr *Fn) { 5573 if (Proto && Proto->isVariadic()) { 5574 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5575 return VariadicConstructor; 5576 else if (Fn && Fn->getType()->isBlockPointerType()) 5577 return VariadicBlock; 5578 else if (FDecl) { 5579 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5580 if (Method->isInstance()) 5581 return VariadicMethod; 5582 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5583 return VariadicMethod; 5584 return VariadicFunction; 5585 } 5586 return VariadicDoesNotApply; 5587 } 5588 5589 namespace { 5590 class FunctionCallCCC final : public FunctionCallFilterCCC { 5591 public: 5592 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5593 unsigned NumArgs, MemberExpr *ME) 5594 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5595 FunctionName(FuncName) {} 5596 5597 bool ValidateCandidate(const TypoCorrection &candidate) override { 5598 if (!candidate.getCorrectionSpecifier() || 5599 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5600 return false; 5601 } 5602 5603 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5604 } 5605 5606 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5607 return std::make_unique<FunctionCallCCC>(*this); 5608 } 5609 5610 private: 5611 const IdentifierInfo *const FunctionName; 5612 }; 5613 } 5614 5615 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5616 FunctionDecl *FDecl, 5617 ArrayRef<Expr *> Args) { 5618 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5619 DeclarationName FuncName = FDecl->getDeclName(); 5620 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5621 5622 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5623 if (TypoCorrection Corrected = S.CorrectTypo( 5624 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5625 S.getScopeForContext(S.CurContext), nullptr, CCC, 5626 Sema::CTK_ErrorRecovery)) { 5627 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5628 if (Corrected.isOverloaded()) { 5629 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5630 OverloadCandidateSet::iterator Best; 5631 for (NamedDecl *CD : Corrected) { 5632 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5633 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5634 OCS); 5635 } 5636 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5637 case OR_Success: 5638 ND = Best->FoundDecl; 5639 Corrected.setCorrectionDecl(ND); 5640 break; 5641 default: 5642 break; 5643 } 5644 } 5645 ND = ND->getUnderlyingDecl(); 5646 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5647 return Corrected; 5648 } 5649 } 5650 return TypoCorrection(); 5651 } 5652 5653 /// ConvertArgumentsForCall - Converts the arguments specified in 5654 /// Args/NumArgs to the parameter types of the function FDecl with 5655 /// function prototype Proto. Call is the call expression itself, and 5656 /// Fn is the function expression. For a C++ member function, this 5657 /// routine does not attempt to convert the object argument. Returns 5658 /// true if the call is ill-formed. 5659 bool 5660 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5661 FunctionDecl *FDecl, 5662 const FunctionProtoType *Proto, 5663 ArrayRef<Expr *> Args, 5664 SourceLocation RParenLoc, 5665 bool IsExecConfig) { 5666 // Bail out early if calling a builtin with custom typechecking. 5667 if (FDecl) 5668 if (unsigned ID = FDecl->getBuiltinID()) 5669 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5670 return false; 5671 5672 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5673 // assignment, to the types of the corresponding parameter, ... 5674 unsigned NumParams = Proto->getNumParams(); 5675 bool Invalid = false; 5676 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5677 unsigned FnKind = Fn->getType()->isBlockPointerType() 5678 ? 1 /* block */ 5679 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5680 : 0 /* function */); 5681 5682 // If too few arguments are available (and we don't have default 5683 // arguments for the remaining parameters), don't make the call. 5684 if (Args.size() < NumParams) { 5685 if (Args.size() < MinArgs) { 5686 TypoCorrection TC; 5687 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5688 unsigned diag_id = 5689 MinArgs == NumParams && !Proto->isVariadic() 5690 ? diag::err_typecheck_call_too_few_args_suggest 5691 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5692 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5693 << static_cast<unsigned>(Args.size()) 5694 << TC.getCorrectionRange()); 5695 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5696 Diag(RParenLoc, 5697 MinArgs == NumParams && !Proto->isVariadic() 5698 ? diag::err_typecheck_call_too_few_args_one 5699 : diag::err_typecheck_call_too_few_args_at_least_one) 5700 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5701 else 5702 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5703 ? diag::err_typecheck_call_too_few_args 5704 : diag::err_typecheck_call_too_few_args_at_least) 5705 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5706 << Fn->getSourceRange(); 5707 5708 // Emit the location of the prototype. 5709 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5710 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5711 5712 return true; 5713 } 5714 // We reserve space for the default arguments when we create 5715 // the call expression, before calling ConvertArgumentsForCall. 5716 assert((Call->getNumArgs() == NumParams) && 5717 "We should have reserved space for the default arguments before!"); 5718 } 5719 5720 // If too many are passed and not variadic, error on the extras and drop 5721 // them. 5722 if (Args.size() > NumParams) { 5723 if (!Proto->isVariadic()) { 5724 TypoCorrection TC; 5725 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5726 unsigned diag_id = 5727 MinArgs == NumParams && !Proto->isVariadic() 5728 ? diag::err_typecheck_call_too_many_args_suggest 5729 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5730 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5731 << static_cast<unsigned>(Args.size()) 5732 << TC.getCorrectionRange()); 5733 } else if (NumParams == 1 && FDecl && 5734 FDecl->getParamDecl(0)->getDeclName()) 5735 Diag(Args[NumParams]->getBeginLoc(), 5736 MinArgs == NumParams 5737 ? diag::err_typecheck_call_too_many_args_one 5738 : diag::err_typecheck_call_too_many_args_at_most_one) 5739 << FnKind << FDecl->getParamDecl(0) 5740 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5741 << SourceRange(Args[NumParams]->getBeginLoc(), 5742 Args.back()->getEndLoc()); 5743 else 5744 Diag(Args[NumParams]->getBeginLoc(), 5745 MinArgs == NumParams 5746 ? diag::err_typecheck_call_too_many_args 5747 : diag::err_typecheck_call_too_many_args_at_most) 5748 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5749 << Fn->getSourceRange() 5750 << SourceRange(Args[NumParams]->getBeginLoc(), 5751 Args.back()->getEndLoc()); 5752 5753 // Emit the location of the prototype. 5754 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5755 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5756 5757 // This deletes the extra arguments. 5758 Call->shrinkNumArgs(NumParams); 5759 return true; 5760 } 5761 } 5762 SmallVector<Expr *, 8> AllArgs; 5763 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5764 5765 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5766 AllArgs, CallType); 5767 if (Invalid) 5768 return true; 5769 unsigned TotalNumArgs = AllArgs.size(); 5770 for (unsigned i = 0; i < TotalNumArgs; ++i) 5771 Call->setArg(i, AllArgs[i]); 5772 5773 return false; 5774 } 5775 5776 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5777 const FunctionProtoType *Proto, 5778 unsigned FirstParam, ArrayRef<Expr *> Args, 5779 SmallVectorImpl<Expr *> &AllArgs, 5780 VariadicCallType CallType, bool AllowExplicit, 5781 bool IsListInitialization) { 5782 unsigned NumParams = Proto->getNumParams(); 5783 bool Invalid = false; 5784 size_t ArgIx = 0; 5785 // Continue to check argument types (even if we have too few/many args). 5786 for (unsigned i = FirstParam; i < NumParams; i++) { 5787 QualType ProtoArgType = Proto->getParamType(i); 5788 5789 Expr *Arg; 5790 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5791 if (ArgIx < Args.size()) { 5792 Arg = Args[ArgIx++]; 5793 5794 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5795 diag::err_call_incomplete_argument, Arg)) 5796 return true; 5797 5798 // Strip the unbridged-cast placeholder expression off, if applicable. 5799 bool CFAudited = false; 5800 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5801 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5802 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5803 Arg = stripARCUnbridgedCast(Arg); 5804 else if (getLangOpts().ObjCAutoRefCount && 5805 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5806 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5807 CFAudited = true; 5808 5809 if (Proto->getExtParameterInfo(i).isNoEscape()) 5810 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5811 BE->getBlockDecl()->setDoesNotEscape(); 5812 5813 InitializedEntity Entity = 5814 Param ? InitializedEntity::InitializeParameter(Context, Param, 5815 ProtoArgType) 5816 : InitializedEntity::InitializeParameter( 5817 Context, ProtoArgType, Proto->isParamConsumed(i)); 5818 5819 // Remember that parameter belongs to a CF audited API. 5820 if (CFAudited) 5821 Entity.setParameterCFAudited(); 5822 5823 ExprResult ArgE = PerformCopyInitialization( 5824 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5825 if (ArgE.isInvalid()) 5826 return true; 5827 5828 Arg = ArgE.getAs<Expr>(); 5829 } else { 5830 assert(Param && "can't use default arguments without a known callee"); 5831 5832 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5833 if (ArgExpr.isInvalid()) 5834 return true; 5835 5836 Arg = ArgExpr.getAs<Expr>(); 5837 } 5838 5839 // Check for array bounds violations for each argument to the call. This 5840 // check only triggers warnings when the argument isn't a more complex Expr 5841 // with its own checking, such as a BinaryOperator. 5842 CheckArrayAccess(Arg); 5843 5844 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5845 CheckStaticArrayArgument(CallLoc, Param, Arg); 5846 5847 AllArgs.push_back(Arg); 5848 } 5849 5850 // If this is a variadic call, handle args passed through "...". 5851 if (CallType != VariadicDoesNotApply) { 5852 // Assume that extern "C" functions with variadic arguments that 5853 // return __unknown_anytype aren't *really* variadic. 5854 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5855 FDecl->isExternC()) { 5856 for (Expr *A : Args.slice(ArgIx)) { 5857 QualType paramType; // ignored 5858 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5859 Invalid |= arg.isInvalid(); 5860 AllArgs.push_back(arg.get()); 5861 } 5862 5863 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5864 } else { 5865 for (Expr *A : Args.slice(ArgIx)) { 5866 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5867 Invalid |= Arg.isInvalid(); 5868 AllArgs.push_back(Arg.get()); 5869 } 5870 } 5871 5872 // Check for array bounds violations. 5873 for (Expr *A : Args.slice(ArgIx)) 5874 CheckArrayAccess(A); 5875 } 5876 return Invalid; 5877 } 5878 5879 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5880 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5881 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5882 TL = DTL.getOriginalLoc(); 5883 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5884 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5885 << ATL.getLocalSourceRange(); 5886 } 5887 5888 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5889 /// array parameter, check that it is non-null, and that if it is formed by 5890 /// array-to-pointer decay, the underlying array is sufficiently large. 5891 /// 5892 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5893 /// array type derivation, then for each call to the function, the value of the 5894 /// corresponding actual argument shall provide access to the first element of 5895 /// an array with at least as many elements as specified by the size expression. 5896 void 5897 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5898 ParmVarDecl *Param, 5899 const Expr *ArgExpr) { 5900 // Static array parameters are not supported in C++. 5901 if (!Param || getLangOpts().CPlusPlus) 5902 return; 5903 5904 QualType OrigTy = Param->getOriginalType(); 5905 5906 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5907 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5908 return; 5909 5910 if (ArgExpr->isNullPointerConstant(Context, 5911 Expr::NPC_NeverValueDependent)) { 5912 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5913 DiagnoseCalleeStaticArrayParam(*this, Param); 5914 return; 5915 } 5916 5917 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5918 if (!CAT) 5919 return; 5920 5921 const ConstantArrayType *ArgCAT = 5922 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5923 if (!ArgCAT) 5924 return; 5925 5926 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5927 ArgCAT->getElementType())) { 5928 if (ArgCAT->getSize().ult(CAT->getSize())) { 5929 Diag(CallLoc, diag::warn_static_array_too_small) 5930 << ArgExpr->getSourceRange() 5931 << (unsigned)ArgCAT->getSize().getZExtValue() 5932 << (unsigned)CAT->getSize().getZExtValue() << 0; 5933 DiagnoseCalleeStaticArrayParam(*this, Param); 5934 } 5935 return; 5936 } 5937 5938 Optional<CharUnits> ArgSize = 5939 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5940 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5941 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5942 Diag(CallLoc, diag::warn_static_array_too_small) 5943 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5944 << (unsigned)ParmSize->getQuantity() << 1; 5945 DiagnoseCalleeStaticArrayParam(*this, Param); 5946 } 5947 } 5948 5949 /// Given a function expression of unknown-any type, try to rebuild it 5950 /// to have a function type. 5951 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5952 5953 /// Is the given type a placeholder that we need to lower out 5954 /// immediately during argument processing? 5955 static bool isPlaceholderToRemoveAsArg(QualType type) { 5956 // Placeholders are never sugared. 5957 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5958 if (!placeholder) return false; 5959 5960 switch (placeholder->getKind()) { 5961 // Ignore all the non-placeholder types. 5962 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5963 case BuiltinType::Id: 5964 #include "clang/Basic/OpenCLImageTypes.def" 5965 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5966 case BuiltinType::Id: 5967 #include "clang/Basic/OpenCLExtensionTypes.def" 5968 // In practice we'll never use this, since all SVE types are sugared 5969 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5970 #define SVE_TYPE(Name, Id, SingletonId) \ 5971 case BuiltinType::Id: 5972 #include "clang/Basic/AArch64SVEACLETypes.def" 5973 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5974 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5975 #include "clang/AST/BuiltinTypes.def" 5976 return false; 5977 5978 // We cannot lower out overload sets; they might validly be resolved 5979 // by the call machinery. 5980 case BuiltinType::Overload: 5981 return false; 5982 5983 // Unbridged casts in ARC can be handled in some call positions and 5984 // should be left in place. 5985 case BuiltinType::ARCUnbridgedCast: 5986 return false; 5987 5988 // Pseudo-objects should be converted as soon as possible. 5989 case BuiltinType::PseudoObject: 5990 return true; 5991 5992 // The debugger mode could theoretically but currently does not try 5993 // to resolve unknown-typed arguments based on known parameter types. 5994 case BuiltinType::UnknownAny: 5995 return true; 5996 5997 // These are always invalid as call arguments and should be reported. 5998 case BuiltinType::BoundMember: 5999 case BuiltinType::BuiltinFn: 6000 case BuiltinType::IncompleteMatrixIdx: 6001 case BuiltinType::OMPArraySection: 6002 case BuiltinType::OMPArrayShaping: 6003 case BuiltinType::OMPIterator: 6004 return true; 6005 6006 } 6007 llvm_unreachable("bad builtin type kind"); 6008 } 6009 6010 /// Check an argument list for placeholders that we won't try to 6011 /// handle later. 6012 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6013 // Apply this processing to all the arguments at once instead of 6014 // dying at the first failure. 6015 bool hasInvalid = false; 6016 for (size_t i = 0, e = args.size(); i != e; i++) { 6017 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6018 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6019 if (result.isInvalid()) hasInvalid = true; 6020 else args[i] = result.get(); 6021 } 6022 } 6023 return hasInvalid; 6024 } 6025 6026 /// If a builtin function has a pointer argument with no explicit address 6027 /// space, then it should be able to accept a pointer to any address 6028 /// space as input. In order to do this, we need to replace the 6029 /// standard builtin declaration with one that uses the same address space 6030 /// as the call. 6031 /// 6032 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6033 /// it does not contain any pointer arguments without 6034 /// an address space qualifer. Otherwise the rewritten 6035 /// FunctionDecl is returned. 6036 /// TODO: Handle pointer return types. 6037 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6038 FunctionDecl *FDecl, 6039 MultiExprArg ArgExprs) { 6040 6041 QualType DeclType = FDecl->getType(); 6042 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6043 6044 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6045 ArgExprs.size() < FT->getNumParams()) 6046 return nullptr; 6047 6048 bool NeedsNewDecl = false; 6049 unsigned i = 0; 6050 SmallVector<QualType, 8> OverloadParams; 6051 6052 for (QualType ParamType : FT->param_types()) { 6053 6054 // Convert array arguments to pointer to simplify type lookup. 6055 ExprResult ArgRes = 6056 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6057 if (ArgRes.isInvalid()) 6058 return nullptr; 6059 Expr *Arg = ArgRes.get(); 6060 QualType ArgType = Arg->getType(); 6061 if (!ParamType->isPointerType() || 6062 ParamType.hasAddressSpace() || 6063 !ArgType->isPointerType() || 6064 !ArgType->getPointeeType().hasAddressSpace()) { 6065 OverloadParams.push_back(ParamType); 6066 continue; 6067 } 6068 6069 QualType PointeeType = ParamType->getPointeeType(); 6070 if (PointeeType.hasAddressSpace()) 6071 continue; 6072 6073 NeedsNewDecl = true; 6074 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6075 6076 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6077 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6078 } 6079 6080 if (!NeedsNewDecl) 6081 return nullptr; 6082 6083 FunctionProtoType::ExtProtoInfo EPI; 6084 EPI.Variadic = FT->isVariadic(); 6085 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6086 OverloadParams, EPI); 6087 DeclContext *Parent = FDecl->getParent(); 6088 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6089 FDecl->getLocation(), 6090 FDecl->getLocation(), 6091 FDecl->getIdentifier(), 6092 OverloadTy, 6093 /*TInfo=*/nullptr, 6094 SC_Extern, false, 6095 /*hasPrototype=*/true); 6096 SmallVector<ParmVarDecl*, 16> Params; 6097 FT = cast<FunctionProtoType>(OverloadTy); 6098 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6099 QualType ParamType = FT->getParamType(i); 6100 ParmVarDecl *Parm = 6101 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6102 SourceLocation(), nullptr, ParamType, 6103 /*TInfo=*/nullptr, SC_None, nullptr); 6104 Parm->setScopeInfo(0, i); 6105 Params.push_back(Parm); 6106 } 6107 OverloadDecl->setParams(Params); 6108 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6109 return OverloadDecl; 6110 } 6111 6112 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6113 FunctionDecl *Callee, 6114 MultiExprArg ArgExprs) { 6115 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6116 // similar attributes) really don't like it when functions are called with an 6117 // invalid number of args. 6118 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6119 /*PartialOverloading=*/false) && 6120 !Callee->isVariadic()) 6121 return; 6122 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6123 return; 6124 6125 if (const EnableIfAttr *Attr = 6126 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6127 S.Diag(Fn->getBeginLoc(), 6128 isa<CXXMethodDecl>(Callee) 6129 ? diag::err_ovl_no_viable_member_function_in_call 6130 : diag::err_ovl_no_viable_function_in_call) 6131 << Callee << Callee->getSourceRange(); 6132 S.Diag(Callee->getLocation(), 6133 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6134 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6135 return; 6136 } 6137 } 6138 6139 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6140 const UnresolvedMemberExpr *const UME, Sema &S) { 6141 6142 const auto GetFunctionLevelDCIfCXXClass = 6143 [](Sema &S) -> const CXXRecordDecl * { 6144 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6145 if (!DC || !DC->getParent()) 6146 return nullptr; 6147 6148 // If the call to some member function was made from within a member 6149 // function body 'M' return return 'M's parent. 6150 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6151 return MD->getParent()->getCanonicalDecl(); 6152 // else the call was made from within a default member initializer of a 6153 // class, so return the class. 6154 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6155 return RD->getCanonicalDecl(); 6156 return nullptr; 6157 }; 6158 // If our DeclContext is neither a member function nor a class (in the 6159 // case of a lambda in a default member initializer), we can't have an 6160 // enclosing 'this'. 6161 6162 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6163 if (!CurParentClass) 6164 return false; 6165 6166 // The naming class for implicit member functions call is the class in which 6167 // name lookup starts. 6168 const CXXRecordDecl *const NamingClass = 6169 UME->getNamingClass()->getCanonicalDecl(); 6170 assert(NamingClass && "Must have naming class even for implicit access"); 6171 6172 // If the unresolved member functions were found in a 'naming class' that is 6173 // related (either the same or derived from) to the class that contains the 6174 // member function that itself contained the implicit member access. 6175 6176 return CurParentClass == NamingClass || 6177 CurParentClass->isDerivedFrom(NamingClass); 6178 } 6179 6180 static void 6181 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6182 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6183 6184 if (!UME) 6185 return; 6186 6187 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6188 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6189 // already been captured, or if this is an implicit member function call (if 6190 // it isn't, an attempt to capture 'this' should already have been made). 6191 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6192 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6193 return; 6194 6195 // Check if the naming class in which the unresolved members were found is 6196 // related (same as or is a base of) to the enclosing class. 6197 6198 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6199 return; 6200 6201 6202 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6203 // If the enclosing function is not dependent, then this lambda is 6204 // capture ready, so if we can capture this, do so. 6205 if (!EnclosingFunctionCtx->isDependentContext()) { 6206 // If the current lambda and all enclosing lambdas can capture 'this' - 6207 // then go ahead and capture 'this' (since our unresolved overload set 6208 // contains at least one non-static member function). 6209 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6210 S.CheckCXXThisCapture(CallLoc); 6211 } else if (S.CurContext->isDependentContext()) { 6212 // ... since this is an implicit member reference, that might potentially 6213 // involve a 'this' capture, mark 'this' for potential capture in 6214 // enclosing lambdas. 6215 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6216 CurLSI->addPotentialThisCapture(CallLoc); 6217 } 6218 } 6219 6220 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6221 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6222 Expr *ExecConfig) { 6223 ExprResult Call = 6224 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6225 if (Call.isInvalid()) 6226 return Call; 6227 6228 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6229 // language modes. 6230 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6231 if (ULE->hasExplicitTemplateArgs() && 6232 ULE->decls_begin() == ULE->decls_end()) { 6233 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6234 ? diag::warn_cxx17_compat_adl_only_template_id 6235 : diag::ext_adl_only_template_id) 6236 << ULE->getName(); 6237 } 6238 } 6239 6240 if (LangOpts.OpenMP) 6241 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6242 ExecConfig); 6243 6244 return Call; 6245 } 6246 6247 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6248 /// This provides the location of the left/right parens and a list of comma 6249 /// locations. 6250 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6251 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6252 Expr *ExecConfig, bool IsExecConfig) { 6253 // Since this might be a postfix expression, get rid of ParenListExprs. 6254 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6255 if (Result.isInvalid()) return ExprError(); 6256 Fn = Result.get(); 6257 6258 if (checkArgsForPlaceholders(*this, ArgExprs)) 6259 return ExprError(); 6260 6261 if (getLangOpts().CPlusPlus) { 6262 // If this is a pseudo-destructor expression, build the call immediately. 6263 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6264 if (!ArgExprs.empty()) { 6265 // Pseudo-destructor calls should not have any arguments. 6266 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6267 << FixItHint::CreateRemoval( 6268 SourceRange(ArgExprs.front()->getBeginLoc(), 6269 ArgExprs.back()->getEndLoc())); 6270 } 6271 6272 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6273 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6274 } 6275 if (Fn->getType() == Context.PseudoObjectTy) { 6276 ExprResult result = CheckPlaceholderExpr(Fn); 6277 if (result.isInvalid()) return ExprError(); 6278 Fn = result.get(); 6279 } 6280 6281 // Determine whether this is a dependent call inside a C++ template, 6282 // in which case we won't do any semantic analysis now. 6283 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6284 if (ExecConfig) { 6285 return CUDAKernelCallExpr::Create( 6286 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6287 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6288 } else { 6289 6290 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6291 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6292 Fn->getBeginLoc()); 6293 6294 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6295 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6296 } 6297 } 6298 6299 // Determine whether this is a call to an object (C++ [over.call.object]). 6300 if (Fn->getType()->isRecordType()) 6301 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6302 RParenLoc); 6303 6304 if (Fn->getType() == Context.UnknownAnyTy) { 6305 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6306 if (result.isInvalid()) return ExprError(); 6307 Fn = result.get(); 6308 } 6309 6310 if (Fn->getType() == Context.BoundMemberTy) { 6311 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6312 RParenLoc); 6313 } 6314 } 6315 6316 // Check for overloaded calls. This can happen even in C due to extensions. 6317 if (Fn->getType() == Context.OverloadTy) { 6318 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6319 6320 // We aren't supposed to apply this logic if there's an '&' involved. 6321 if (!find.HasFormOfMemberPointer) { 6322 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6323 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6324 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6325 OverloadExpr *ovl = find.Expression; 6326 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6327 return BuildOverloadedCallExpr( 6328 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6329 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6330 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6331 RParenLoc); 6332 } 6333 } 6334 6335 // If we're directly calling a function, get the appropriate declaration. 6336 if (Fn->getType() == Context.UnknownAnyTy) { 6337 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6338 if (result.isInvalid()) return ExprError(); 6339 Fn = result.get(); 6340 } 6341 6342 Expr *NakedFn = Fn->IgnoreParens(); 6343 6344 bool CallingNDeclIndirectly = false; 6345 NamedDecl *NDecl = nullptr; 6346 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6347 if (UnOp->getOpcode() == UO_AddrOf) { 6348 CallingNDeclIndirectly = true; 6349 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6350 } 6351 } 6352 6353 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6354 NDecl = DRE->getDecl(); 6355 6356 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6357 if (FDecl && FDecl->getBuiltinID()) { 6358 // Rewrite the function decl for this builtin by replacing parameters 6359 // with no explicit address space with the address space of the arguments 6360 // in ArgExprs. 6361 if ((FDecl = 6362 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6363 NDecl = FDecl; 6364 Fn = DeclRefExpr::Create( 6365 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6366 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6367 nullptr, DRE->isNonOdrUse()); 6368 } 6369 } 6370 } else if (isa<MemberExpr>(NakedFn)) 6371 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6372 6373 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6374 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6375 FD, /*Complain=*/true, Fn->getBeginLoc())) 6376 return ExprError(); 6377 6378 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6379 return ExprError(); 6380 6381 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6382 } 6383 6384 if (Context.isDependenceAllowed() && 6385 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6386 assert(!getLangOpts().CPlusPlus); 6387 assert((Fn->containsErrors() || 6388 llvm::any_of(ArgExprs, 6389 [](clang::Expr *E) { return E->containsErrors(); })) && 6390 "should only occur in error-recovery path."); 6391 QualType ReturnType = 6392 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6393 ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType() 6394 : Context.DependentTy; 6395 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6396 Expr::getValueKindForType(ReturnType), RParenLoc, 6397 CurFPFeatureOverrides()); 6398 } 6399 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6400 ExecConfig, IsExecConfig); 6401 } 6402 6403 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6404 /// 6405 /// __builtin_astype( value, dst type ) 6406 /// 6407 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6408 SourceLocation BuiltinLoc, 6409 SourceLocation RParenLoc) { 6410 ExprValueKind VK = VK_RValue; 6411 ExprObjectKind OK = OK_Ordinary; 6412 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6413 QualType SrcTy = E->getType(); 6414 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6415 return ExprError(Diag(BuiltinLoc, 6416 diag::err_invalid_astype_of_different_size) 6417 << DstTy 6418 << SrcTy 6419 << E->getSourceRange()); 6420 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6421 } 6422 6423 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6424 /// provided arguments. 6425 /// 6426 /// __builtin_convertvector( value, dst type ) 6427 /// 6428 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6429 SourceLocation BuiltinLoc, 6430 SourceLocation RParenLoc) { 6431 TypeSourceInfo *TInfo; 6432 GetTypeFromParser(ParsedDestTy, &TInfo); 6433 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6434 } 6435 6436 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6437 /// i.e. an expression not of \p OverloadTy. The expression should 6438 /// unary-convert to an expression of function-pointer or 6439 /// block-pointer type. 6440 /// 6441 /// \param NDecl the declaration being called, if available 6442 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6443 SourceLocation LParenLoc, 6444 ArrayRef<Expr *> Args, 6445 SourceLocation RParenLoc, Expr *Config, 6446 bool IsExecConfig, ADLCallKind UsesADL) { 6447 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6448 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6449 6450 // Functions with 'interrupt' attribute cannot be called directly. 6451 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6452 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6453 return ExprError(); 6454 } 6455 6456 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6457 // so there's some risk when calling out to non-interrupt handler functions 6458 // that the callee might not preserve them. This is easy to diagnose here, 6459 // but can be very challenging to debug. 6460 if (auto *Caller = getCurFunctionDecl()) 6461 if (Caller->hasAttr<ARMInterruptAttr>()) { 6462 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6463 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6464 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6465 } 6466 6467 // Promote the function operand. 6468 // We special-case function promotion here because we only allow promoting 6469 // builtin functions to function pointers in the callee of a call. 6470 ExprResult Result; 6471 QualType ResultTy; 6472 if (BuiltinID && 6473 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6474 // Extract the return type from the (builtin) function pointer type. 6475 // FIXME Several builtins still have setType in 6476 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6477 // Builtins.def to ensure they are correct before removing setType calls. 6478 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6479 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6480 ResultTy = FDecl->getCallResultType(); 6481 } else { 6482 Result = CallExprUnaryConversions(Fn); 6483 ResultTy = Context.BoolTy; 6484 } 6485 if (Result.isInvalid()) 6486 return ExprError(); 6487 Fn = Result.get(); 6488 6489 // Check for a valid function type, but only if it is not a builtin which 6490 // requires custom type checking. These will be handled by 6491 // CheckBuiltinFunctionCall below just after creation of the call expression. 6492 const FunctionType *FuncT = nullptr; 6493 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6494 retry: 6495 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6496 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6497 // have type pointer to function". 6498 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6499 if (!FuncT) 6500 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6501 << Fn->getType() << Fn->getSourceRange()); 6502 } else if (const BlockPointerType *BPT = 6503 Fn->getType()->getAs<BlockPointerType>()) { 6504 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6505 } else { 6506 // Handle calls to expressions of unknown-any type. 6507 if (Fn->getType() == Context.UnknownAnyTy) { 6508 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6509 if (rewrite.isInvalid()) 6510 return ExprError(); 6511 Fn = rewrite.get(); 6512 goto retry; 6513 } 6514 6515 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6516 << Fn->getType() << Fn->getSourceRange()); 6517 } 6518 } 6519 6520 // Get the number of parameters in the function prototype, if any. 6521 // We will allocate space for max(Args.size(), NumParams) arguments 6522 // in the call expression. 6523 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6524 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6525 6526 CallExpr *TheCall; 6527 if (Config) { 6528 assert(UsesADL == ADLCallKind::NotADL && 6529 "CUDAKernelCallExpr should not use ADL"); 6530 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6531 Args, ResultTy, VK_RValue, RParenLoc, 6532 CurFPFeatureOverrides(), NumParams); 6533 } else { 6534 TheCall = 6535 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6536 CurFPFeatureOverrides(), NumParams, UsesADL); 6537 } 6538 6539 if (!Context.isDependenceAllowed()) { 6540 // Forget about the nulled arguments since typo correction 6541 // do not handle them well. 6542 TheCall->shrinkNumArgs(Args.size()); 6543 // C cannot always handle TypoExpr nodes in builtin calls and direct 6544 // function calls as their argument checking don't necessarily handle 6545 // dependent types properly, so make sure any TypoExprs have been 6546 // dealt with. 6547 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6548 if (!Result.isUsable()) return ExprError(); 6549 CallExpr *TheOldCall = TheCall; 6550 TheCall = dyn_cast<CallExpr>(Result.get()); 6551 bool CorrectedTypos = TheCall != TheOldCall; 6552 if (!TheCall) return Result; 6553 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6554 6555 // A new call expression node was created if some typos were corrected. 6556 // However it may not have been constructed with enough storage. In this 6557 // case, rebuild the node with enough storage. The waste of space is 6558 // immaterial since this only happens when some typos were corrected. 6559 if (CorrectedTypos && Args.size() < NumParams) { 6560 if (Config) 6561 TheCall = CUDAKernelCallExpr::Create( 6562 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6563 RParenLoc, CurFPFeatureOverrides(), NumParams); 6564 else 6565 TheCall = 6566 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6567 CurFPFeatureOverrides(), NumParams, UsesADL); 6568 } 6569 // We can now handle the nulled arguments for the default arguments. 6570 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6571 } 6572 6573 // Bail out early if calling a builtin with custom type checking. 6574 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6575 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6576 6577 if (getLangOpts().CUDA) { 6578 if (Config) { 6579 // CUDA: Kernel calls must be to global functions 6580 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6581 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6582 << FDecl << Fn->getSourceRange()); 6583 6584 // CUDA: Kernel function must have 'void' return type 6585 if (!FuncT->getReturnType()->isVoidType() && 6586 !FuncT->getReturnType()->getAs<AutoType>() && 6587 !FuncT->getReturnType()->isInstantiationDependentType()) 6588 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6589 << Fn->getType() << Fn->getSourceRange()); 6590 } else { 6591 // CUDA: Calls to global functions must be configured 6592 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6593 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6594 << FDecl << Fn->getSourceRange()); 6595 } 6596 } 6597 6598 // Check for a valid return type 6599 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6600 FDecl)) 6601 return ExprError(); 6602 6603 // We know the result type of the call, set it. 6604 TheCall->setType(FuncT->getCallResultType(Context)); 6605 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6606 6607 if (Proto) { 6608 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6609 IsExecConfig)) 6610 return ExprError(); 6611 } else { 6612 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6613 6614 if (FDecl) { 6615 // Check if we have too few/too many template arguments, based 6616 // on our knowledge of the function definition. 6617 const FunctionDecl *Def = nullptr; 6618 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6619 Proto = Def->getType()->getAs<FunctionProtoType>(); 6620 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6621 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6622 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6623 } 6624 6625 // If the function we're calling isn't a function prototype, but we have 6626 // a function prototype from a prior declaratiom, use that prototype. 6627 if (!FDecl->hasPrototype()) 6628 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6629 } 6630 6631 // Promote the arguments (C99 6.5.2.2p6). 6632 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6633 Expr *Arg = Args[i]; 6634 6635 if (Proto && i < Proto->getNumParams()) { 6636 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6637 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6638 ExprResult ArgE = 6639 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6640 if (ArgE.isInvalid()) 6641 return true; 6642 6643 Arg = ArgE.getAs<Expr>(); 6644 6645 } else { 6646 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6647 6648 if (ArgE.isInvalid()) 6649 return true; 6650 6651 Arg = ArgE.getAs<Expr>(); 6652 } 6653 6654 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6655 diag::err_call_incomplete_argument, Arg)) 6656 return ExprError(); 6657 6658 TheCall->setArg(i, Arg); 6659 } 6660 } 6661 6662 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6663 if (!Method->isStatic()) 6664 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6665 << Fn->getSourceRange()); 6666 6667 // Check for sentinels 6668 if (NDecl) 6669 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6670 6671 // Warn for unions passing across security boundary (CMSE). 6672 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6673 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6674 if (const auto *RT = 6675 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6676 if (RT->getDecl()->isOrContainsUnion()) 6677 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6678 << 0 << i; 6679 } 6680 } 6681 } 6682 6683 // Do special checking on direct calls to functions. 6684 if (FDecl) { 6685 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6686 return ExprError(); 6687 6688 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6689 6690 if (BuiltinID) 6691 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6692 } else if (NDecl) { 6693 if (CheckPointerCall(NDecl, TheCall, Proto)) 6694 return ExprError(); 6695 } else { 6696 if (CheckOtherCall(TheCall, Proto)) 6697 return ExprError(); 6698 } 6699 6700 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6701 } 6702 6703 ExprResult 6704 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6705 SourceLocation RParenLoc, Expr *InitExpr) { 6706 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6707 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6708 6709 TypeSourceInfo *TInfo; 6710 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6711 if (!TInfo) 6712 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6713 6714 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6715 } 6716 6717 ExprResult 6718 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6719 SourceLocation RParenLoc, Expr *LiteralExpr) { 6720 QualType literalType = TInfo->getType(); 6721 6722 if (literalType->isArrayType()) { 6723 if (RequireCompleteSizedType( 6724 LParenLoc, Context.getBaseElementType(literalType), 6725 diag::err_array_incomplete_or_sizeless_type, 6726 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6727 return ExprError(); 6728 if (literalType->isVariableArrayType()) 6729 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6730 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6731 } else if (!literalType->isDependentType() && 6732 RequireCompleteType(LParenLoc, literalType, 6733 diag::err_typecheck_decl_incomplete_type, 6734 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6735 return ExprError(); 6736 6737 InitializedEntity Entity 6738 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6739 InitializationKind Kind 6740 = InitializationKind::CreateCStyleCast(LParenLoc, 6741 SourceRange(LParenLoc, RParenLoc), 6742 /*InitList=*/true); 6743 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6744 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6745 &literalType); 6746 if (Result.isInvalid()) 6747 return ExprError(); 6748 LiteralExpr = Result.get(); 6749 6750 bool isFileScope = !CurContext->isFunctionOrMethod(); 6751 6752 // In C, compound literals are l-values for some reason. 6753 // For GCC compatibility, in C++, file-scope array compound literals with 6754 // constant initializers are also l-values, and compound literals are 6755 // otherwise prvalues. 6756 // 6757 // (GCC also treats C++ list-initialized file-scope array prvalues with 6758 // constant initializers as l-values, but that's non-conforming, so we don't 6759 // follow it there.) 6760 // 6761 // FIXME: It would be better to handle the lvalue cases as materializing and 6762 // lifetime-extending a temporary object, but our materialized temporaries 6763 // representation only supports lifetime extension from a variable, not "out 6764 // of thin air". 6765 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6766 // is bound to the result of applying array-to-pointer decay to the compound 6767 // literal. 6768 // FIXME: GCC supports compound literals of reference type, which should 6769 // obviously have a value kind derived from the kind of reference involved. 6770 ExprValueKind VK = 6771 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6772 ? VK_RValue 6773 : VK_LValue; 6774 6775 if (isFileScope) 6776 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6777 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6778 Expr *Init = ILE->getInit(i); 6779 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6780 } 6781 6782 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6783 VK, LiteralExpr, isFileScope); 6784 if (isFileScope) { 6785 if (!LiteralExpr->isTypeDependent() && 6786 !LiteralExpr->isValueDependent() && 6787 !literalType->isDependentType()) // C99 6.5.2.5p3 6788 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6789 return ExprError(); 6790 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6791 literalType.getAddressSpace() != LangAS::Default) { 6792 // Embedded-C extensions to C99 6.5.2.5: 6793 // "If the compound literal occurs inside the body of a function, the 6794 // type name shall not be qualified by an address-space qualifier." 6795 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6796 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6797 return ExprError(); 6798 } 6799 6800 if (!isFileScope && !getLangOpts().CPlusPlus) { 6801 // Compound literals that have automatic storage duration are destroyed at 6802 // the end of the scope in C; in C++, they're just temporaries. 6803 6804 // Emit diagnostics if it is or contains a C union type that is non-trivial 6805 // to destruct. 6806 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6807 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6808 NTCUC_CompoundLiteral, NTCUK_Destruct); 6809 6810 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6811 if (literalType.isDestructedType()) { 6812 Cleanup.setExprNeedsCleanups(true); 6813 ExprCleanupObjects.push_back(E); 6814 getCurFunction()->setHasBranchProtectedScope(); 6815 } 6816 } 6817 6818 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6819 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6820 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6821 E->getInitializer()->getExprLoc()); 6822 6823 return MaybeBindToTemporary(E); 6824 } 6825 6826 ExprResult 6827 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6828 SourceLocation RBraceLoc) { 6829 // Only produce each kind of designated initialization diagnostic once. 6830 SourceLocation FirstDesignator; 6831 bool DiagnosedArrayDesignator = false; 6832 bool DiagnosedNestedDesignator = false; 6833 bool DiagnosedMixedDesignator = false; 6834 6835 // Check that any designated initializers are syntactically valid in the 6836 // current language mode. 6837 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6838 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6839 if (FirstDesignator.isInvalid()) 6840 FirstDesignator = DIE->getBeginLoc(); 6841 6842 if (!getLangOpts().CPlusPlus) 6843 break; 6844 6845 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6846 DiagnosedNestedDesignator = true; 6847 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6848 << DIE->getDesignatorsSourceRange(); 6849 } 6850 6851 for (auto &Desig : DIE->designators()) { 6852 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6853 DiagnosedArrayDesignator = true; 6854 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6855 << Desig.getSourceRange(); 6856 } 6857 } 6858 6859 if (!DiagnosedMixedDesignator && 6860 !isa<DesignatedInitExpr>(InitArgList[0])) { 6861 DiagnosedMixedDesignator = true; 6862 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6863 << DIE->getSourceRange(); 6864 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6865 << InitArgList[0]->getSourceRange(); 6866 } 6867 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6868 isa<DesignatedInitExpr>(InitArgList[0])) { 6869 DiagnosedMixedDesignator = true; 6870 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6871 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6872 << DIE->getSourceRange(); 6873 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6874 << InitArgList[I]->getSourceRange(); 6875 } 6876 } 6877 6878 if (FirstDesignator.isValid()) { 6879 // Only diagnose designated initiaization as a C++20 extension if we didn't 6880 // already diagnose use of (non-C++20) C99 designator syntax. 6881 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6882 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6883 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6884 ? diag::warn_cxx17_compat_designated_init 6885 : diag::ext_cxx_designated_init); 6886 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6887 Diag(FirstDesignator, diag::ext_designated_init); 6888 } 6889 } 6890 6891 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6892 } 6893 6894 ExprResult 6895 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6896 SourceLocation RBraceLoc) { 6897 // Semantic analysis for initializers is done by ActOnDeclarator() and 6898 // CheckInitializer() - it requires knowledge of the object being initialized. 6899 6900 // Immediately handle non-overload placeholders. Overloads can be 6901 // resolved contextually, but everything else here can't. 6902 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6903 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6904 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6905 6906 // Ignore failures; dropping the entire initializer list because 6907 // of one failure would be terrible for indexing/etc. 6908 if (result.isInvalid()) continue; 6909 6910 InitArgList[I] = result.get(); 6911 } 6912 } 6913 6914 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6915 RBraceLoc); 6916 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6917 return E; 6918 } 6919 6920 /// Do an explicit extend of the given block pointer if we're in ARC. 6921 void Sema::maybeExtendBlockObject(ExprResult &E) { 6922 assert(E.get()->getType()->isBlockPointerType()); 6923 assert(E.get()->isRValue()); 6924 6925 // Only do this in an r-value context. 6926 if (!getLangOpts().ObjCAutoRefCount) return; 6927 6928 E = ImplicitCastExpr::Create( 6929 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 6930 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 6931 Cleanup.setExprNeedsCleanups(true); 6932 } 6933 6934 /// Prepare a conversion of the given expression to an ObjC object 6935 /// pointer type. 6936 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6937 QualType type = E.get()->getType(); 6938 if (type->isObjCObjectPointerType()) { 6939 return CK_BitCast; 6940 } else if (type->isBlockPointerType()) { 6941 maybeExtendBlockObject(E); 6942 return CK_BlockPointerToObjCPointerCast; 6943 } else { 6944 assert(type->isPointerType()); 6945 return CK_CPointerToObjCPointerCast; 6946 } 6947 } 6948 6949 /// Prepares for a scalar cast, performing all the necessary stages 6950 /// except the final cast and returning the kind required. 6951 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6952 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6953 // Also, callers should have filtered out the invalid cases with 6954 // pointers. Everything else should be possible. 6955 6956 QualType SrcTy = Src.get()->getType(); 6957 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6958 return CK_NoOp; 6959 6960 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6961 case Type::STK_MemberPointer: 6962 llvm_unreachable("member pointer type in C"); 6963 6964 case Type::STK_CPointer: 6965 case Type::STK_BlockPointer: 6966 case Type::STK_ObjCObjectPointer: 6967 switch (DestTy->getScalarTypeKind()) { 6968 case Type::STK_CPointer: { 6969 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6970 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6971 if (SrcAS != DestAS) 6972 return CK_AddressSpaceConversion; 6973 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6974 return CK_NoOp; 6975 return CK_BitCast; 6976 } 6977 case Type::STK_BlockPointer: 6978 return (SrcKind == Type::STK_BlockPointer 6979 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6980 case Type::STK_ObjCObjectPointer: 6981 if (SrcKind == Type::STK_ObjCObjectPointer) 6982 return CK_BitCast; 6983 if (SrcKind == Type::STK_CPointer) 6984 return CK_CPointerToObjCPointerCast; 6985 maybeExtendBlockObject(Src); 6986 return CK_BlockPointerToObjCPointerCast; 6987 case Type::STK_Bool: 6988 return CK_PointerToBoolean; 6989 case Type::STK_Integral: 6990 return CK_PointerToIntegral; 6991 case Type::STK_Floating: 6992 case Type::STK_FloatingComplex: 6993 case Type::STK_IntegralComplex: 6994 case Type::STK_MemberPointer: 6995 case Type::STK_FixedPoint: 6996 llvm_unreachable("illegal cast from pointer"); 6997 } 6998 llvm_unreachable("Should have returned before this"); 6999 7000 case Type::STK_FixedPoint: 7001 switch (DestTy->getScalarTypeKind()) { 7002 case Type::STK_FixedPoint: 7003 return CK_FixedPointCast; 7004 case Type::STK_Bool: 7005 return CK_FixedPointToBoolean; 7006 case Type::STK_Integral: 7007 return CK_FixedPointToIntegral; 7008 case Type::STK_Floating: 7009 return CK_FixedPointToFloating; 7010 case Type::STK_IntegralComplex: 7011 case Type::STK_FloatingComplex: 7012 Diag(Src.get()->getExprLoc(), 7013 diag::err_unimplemented_conversion_with_fixed_point_type) 7014 << DestTy; 7015 return CK_IntegralCast; 7016 case Type::STK_CPointer: 7017 case Type::STK_ObjCObjectPointer: 7018 case Type::STK_BlockPointer: 7019 case Type::STK_MemberPointer: 7020 llvm_unreachable("illegal cast to pointer type"); 7021 } 7022 llvm_unreachable("Should have returned before this"); 7023 7024 case Type::STK_Bool: // casting from bool is like casting from an integer 7025 case Type::STK_Integral: 7026 switch (DestTy->getScalarTypeKind()) { 7027 case Type::STK_CPointer: 7028 case Type::STK_ObjCObjectPointer: 7029 case Type::STK_BlockPointer: 7030 if (Src.get()->isNullPointerConstant(Context, 7031 Expr::NPC_ValueDependentIsNull)) 7032 return CK_NullToPointer; 7033 return CK_IntegralToPointer; 7034 case Type::STK_Bool: 7035 return CK_IntegralToBoolean; 7036 case Type::STK_Integral: 7037 return CK_IntegralCast; 7038 case Type::STK_Floating: 7039 return CK_IntegralToFloating; 7040 case Type::STK_IntegralComplex: 7041 Src = ImpCastExprToType(Src.get(), 7042 DestTy->castAs<ComplexType>()->getElementType(), 7043 CK_IntegralCast); 7044 return CK_IntegralRealToComplex; 7045 case Type::STK_FloatingComplex: 7046 Src = ImpCastExprToType(Src.get(), 7047 DestTy->castAs<ComplexType>()->getElementType(), 7048 CK_IntegralToFloating); 7049 return CK_FloatingRealToComplex; 7050 case Type::STK_MemberPointer: 7051 llvm_unreachable("member pointer type in C"); 7052 case Type::STK_FixedPoint: 7053 return CK_IntegralToFixedPoint; 7054 } 7055 llvm_unreachable("Should have returned before this"); 7056 7057 case Type::STK_Floating: 7058 switch (DestTy->getScalarTypeKind()) { 7059 case Type::STK_Floating: 7060 return CK_FloatingCast; 7061 case Type::STK_Bool: 7062 return CK_FloatingToBoolean; 7063 case Type::STK_Integral: 7064 return CK_FloatingToIntegral; 7065 case Type::STK_FloatingComplex: 7066 Src = ImpCastExprToType(Src.get(), 7067 DestTy->castAs<ComplexType>()->getElementType(), 7068 CK_FloatingCast); 7069 return CK_FloatingRealToComplex; 7070 case Type::STK_IntegralComplex: 7071 Src = ImpCastExprToType(Src.get(), 7072 DestTy->castAs<ComplexType>()->getElementType(), 7073 CK_FloatingToIntegral); 7074 return CK_IntegralRealToComplex; 7075 case Type::STK_CPointer: 7076 case Type::STK_ObjCObjectPointer: 7077 case Type::STK_BlockPointer: 7078 llvm_unreachable("valid float->pointer cast?"); 7079 case Type::STK_MemberPointer: 7080 llvm_unreachable("member pointer type in C"); 7081 case Type::STK_FixedPoint: 7082 return CK_FloatingToFixedPoint; 7083 } 7084 llvm_unreachable("Should have returned before this"); 7085 7086 case Type::STK_FloatingComplex: 7087 switch (DestTy->getScalarTypeKind()) { 7088 case Type::STK_FloatingComplex: 7089 return CK_FloatingComplexCast; 7090 case Type::STK_IntegralComplex: 7091 return CK_FloatingComplexToIntegralComplex; 7092 case Type::STK_Floating: { 7093 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7094 if (Context.hasSameType(ET, DestTy)) 7095 return CK_FloatingComplexToReal; 7096 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7097 return CK_FloatingCast; 7098 } 7099 case Type::STK_Bool: 7100 return CK_FloatingComplexToBoolean; 7101 case Type::STK_Integral: 7102 Src = ImpCastExprToType(Src.get(), 7103 SrcTy->castAs<ComplexType>()->getElementType(), 7104 CK_FloatingComplexToReal); 7105 return CK_FloatingToIntegral; 7106 case Type::STK_CPointer: 7107 case Type::STK_ObjCObjectPointer: 7108 case Type::STK_BlockPointer: 7109 llvm_unreachable("valid complex float->pointer cast?"); 7110 case Type::STK_MemberPointer: 7111 llvm_unreachable("member pointer type in C"); 7112 case Type::STK_FixedPoint: 7113 Diag(Src.get()->getExprLoc(), 7114 diag::err_unimplemented_conversion_with_fixed_point_type) 7115 << SrcTy; 7116 return CK_IntegralCast; 7117 } 7118 llvm_unreachable("Should have returned before this"); 7119 7120 case Type::STK_IntegralComplex: 7121 switch (DestTy->getScalarTypeKind()) { 7122 case Type::STK_FloatingComplex: 7123 return CK_IntegralComplexToFloatingComplex; 7124 case Type::STK_IntegralComplex: 7125 return CK_IntegralComplexCast; 7126 case Type::STK_Integral: { 7127 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7128 if (Context.hasSameType(ET, DestTy)) 7129 return CK_IntegralComplexToReal; 7130 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7131 return CK_IntegralCast; 7132 } 7133 case Type::STK_Bool: 7134 return CK_IntegralComplexToBoolean; 7135 case Type::STK_Floating: 7136 Src = ImpCastExprToType(Src.get(), 7137 SrcTy->castAs<ComplexType>()->getElementType(), 7138 CK_IntegralComplexToReal); 7139 return CK_IntegralToFloating; 7140 case Type::STK_CPointer: 7141 case Type::STK_ObjCObjectPointer: 7142 case Type::STK_BlockPointer: 7143 llvm_unreachable("valid complex int->pointer cast?"); 7144 case Type::STK_MemberPointer: 7145 llvm_unreachable("member pointer type in C"); 7146 case Type::STK_FixedPoint: 7147 Diag(Src.get()->getExprLoc(), 7148 diag::err_unimplemented_conversion_with_fixed_point_type) 7149 << SrcTy; 7150 return CK_IntegralCast; 7151 } 7152 llvm_unreachable("Should have returned before this"); 7153 } 7154 7155 llvm_unreachable("Unhandled scalar cast"); 7156 } 7157 7158 static bool breakDownVectorType(QualType type, uint64_t &len, 7159 QualType &eltType) { 7160 // Vectors are simple. 7161 if (const VectorType *vecType = type->getAs<VectorType>()) { 7162 len = vecType->getNumElements(); 7163 eltType = vecType->getElementType(); 7164 assert(eltType->isScalarType()); 7165 return true; 7166 } 7167 7168 // We allow lax conversion to and from non-vector types, but only if 7169 // they're real types (i.e. non-complex, non-pointer scalar types). 7170 if (!type->isRealType()) return false; 7171 7172 len = 1; 7173 eltType = type; 7174 return true; 7175 } 7176 7177 /// Are the two types lax-compatible vector types? That is, given 7178 /// that one of them is a vector, do they have equal storage sizes, 7179 /// where the storage size is the number of elements times the element 7180 /// size? 7181 /// 7182 /// This will also return false if either of the types is neither a 7183 /// vector nor a real type. 7184 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7185 assert(destTy->isVectorType() || srcTy->isVectorType()); 7186 7187 // Disallow lax conversions between scalars and ExtVectors (these 7188 // conversions are allowed for other vector types because common headers 7189 // depend on them). Most scalar OP ExtVector cases are handled by the 7190 // splat path anyway, which does what we want (convert, not bitcast). 7191 // What this rules out for ExtVectors is crazy things like char4*float. 7192 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7193 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7194 7195 uint64_t srcLen, destLen; 7196 QualType srcEltTy, destEltTy; 7197 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7198 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7199 7200 // ASTContext::getTypeSize will return the size rounded up to a 7201 // power of 2, so instead of using that, we need to use the raw 7202 // element size multiplied by the element count. 7203 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7204 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7205 7206 return (srcLen * srcEltSize == destLen * destEltSize); 7207 } 7208 7209 /// Is this a legal conversion between two types, one of which is 7210 /// known to be a vector type? 7211 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7212 assert(destTy->isVectorType() || srcTy->isVectorType()); 7213 7214 switch (Context.getLangOpts().getLaxVectorConversions()) { 7215 case LangOptions::LaxVectorConversionKind::None: 7216 return false; 7217 7218 case LangOptions::LaxVectorConversionKind::Integer: 7219 if (!srcTy->isIntegralOrEnumerationType()) { 7220 auto *Vec = srcTy->getAs<VectorType>(); 7221 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7222 return false; 7223 } 7224 if (!destTy->isIntegralOrEnumerationType()) { 7225 auto *Vec = destTy->getAs<VectorType>(); 7226 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7227 return false; 7228 } 7229 // OK, integer (vector) -> integer (vector) bitcast. 7230 break; 7231 7232 case LangOptions::LaxVectorConversionKind::All: 7233 break; 7234 } 7235 7236 return areLaxCompatibleVectorTypes(srcTy, destTy); 7237 } 7238 7239 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7240 CastKind &Kind) { 7241 assert(VectorTy->isVectorType() && "Not a vector type!"); 7242 7243 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7244 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7245 return Diag(R.getBegin(), 7246 Ty->isVectorType() ? 7247 diag::err_invalid_conversion_between_vectors : 7248 diag::err_invalid_conversion_between_vector_and_integer) 7249 << VectorTy << Ty << R; 7250 } else 7251 return Diag(R.getBegin(), 7252 diag::err_invalid_conversion_between_vector_and_scalar) 7253 << VectorTy << Ty << R; 7254 7255 Kind = CK_BitCast; 7256 return false; 7257 } 7258 7259 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7260 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7261 7262 if (DestElemTy == SplattedExpr->getType()) 7263 return SplattedExpr; 7264 7265 assert(DestElemTy->isFloatingType() || 7266 DestElemTy->isIntegralOrEnumerationType()); 7267 7268 CastKind CK; 7269 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7270 // OpenCL requires that we convert `true` boolean expressions to -1, but 7271 // only when splatting vectors. 7272 if (DestElemTy->isFloatingType()) { 7273 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7274 // in two steps: boolean to signed integral, then to floating. 7275 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7276 CK_BooleanToSignedIntegral); 7277 SplattedExpr = CastExprRes.get(); 7278 CK = CK_IntegralToFloating; 7279 } else { 7280 CK = CK_BooleanToSignedIntegral; 7281 } 7282 } else { 7283 ExprResult CastExprRes = SplattedExpr; 7284 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7285 if (CastExprRes.isInvalid()) 7286 return ExprError(); 7287 SplattedExpr = CastExprRes.get(); 7288 } 7289 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7290 } 7291 7292 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7293 Expr *CastExpr, CastKind &Kind) { 7294 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7295 7296 QualType SrcTy = CastExpr->getType(); 7297 7298 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7299 // an ExtVectorType. 7300 // In OpenCL, casts between vectors of different types are not allowed. 7301 // (See OpenCL 6.2). 7302 if (SrcTy->isVectorType()) { 7303 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7304 (getLangOpts().OpenCL && 7305 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7306 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7307 << DestTy << SrcTy << R; 7308 return ExprError(); 7309 } 7310 Kind = CK_BitCast; 7311 return CastExpr; 7312 } 7313 7314 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7315 // conversion will take place first from scalar to elt type, and then 7316 // splat from elt type to vector. 7317 if (SrcTy->isPointerType()) 7318 return Diag(R.getBegin(), 7319 diag::err_invalid_conversion_between_vector_and_scalar) 7320 << DestTy << SrcTy << R; 7321 7322 Kind = CK_VectorSplat; 7323 return prepareVectorSplat(DestTy, CastExpr); 7324 } 7325 7326 ExprResult 7327 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7328 Declarator &D, ParsedType &Ty, 7329 SourceLocation RParenLoc, Expr *CastExpr) { 7330 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7331 "ActOnCastExpr(): missing type or expr"); 7332 7333 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7334 if (D.isInvalidType()) 7335 return ExprError(); 7336 7337 if (getLangOpts().CPlusPlus) { 7338 // Check that there are no default arguments (C++ only). 7339 CheckExtraCXXDefaultArguments(D); 7340 } else { 7341 // Make sure any TypoExprs have been dealt with. 7342 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7343 if (!Res.isUsable()) 7344 return ExprError(); 7345 CastExpr = Res.get(); 7346 } 7347 7348 checkUnusedDeclAttributes(D); 7349 7350 QualType castType = castTInfo->getType(); 7351 Ty = CreateParsedType(castType, castTInfo); 7352 7353 bool isVectorLiteral = false; 7354 7355 // Check for an altivec or OpenCL literal, 7356 // i.e. all the elements are integer constants. 7357 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7358 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7359 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7360 && castType->isVectorType() && (PE || PLE)) { 7361 if (PLE && PLE->getNumExprs() == 0) { 7362 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7363 return ExprError(); 7364 } 7365 if (PE || PLE->getNumExprs() == 1) { 7366 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7367 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7368 isVectorLiteral = true; 7369 } 7370 else 7371 isVectorLiteral = true; 7372 } 7373 7374 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7375 // then handle it as such. 7376 if (isVectorLiteral) 7377 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7378 7379 // If the Expr being casted is a ParenListExpr, handle it specially. 7380 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7381 // sequence of BinOp comma operators. 7382 if (isa<ParenListExpr>(CastExpr)) { 7383 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7384 if (Result.isInvalid()) return ExprError(); 7385 CastExpr = Result.get(); 7386 } 7387 7388 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7389 !getSourceManager().isInSystemMacro(LParenLoc)) 7390 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7391 7392 CheckTollFreeBridgeCast(castType, CastExpr); 7393 7394 CheckObjCBridgeRelatedCast(castType, CastExpr); 7395 7396 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7397 7398 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7399 } 7400 7401 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7402 SourceLocation RParenLoc, Expr *E, 7403 TypeSourceInfo *TInfo) { 7404 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7405 "Expected paren or paren list expression"); 7406 7407 Expr **exprs; 7408 unsigned numExprs; 7409 Expr *subExpr; 7410 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7411 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7412 LiteralLParenLoc = PE->getLParenLoc(); 7413 LiteralRParenLoc = PE->getRParenLoc(); 7414 exprs = PE->getExprs(); 7415 numExprs = PE->getNumExprs(); 7416 } else { // isa<ParenExpr> by assertion at function entrance 7417 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7418 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7419 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7420 exprs = &subExpr; 7421 numExprs = 1; 7422 } 7423 7424 QualType Ty = TInfo->getType(); 7425 assert(Ty->isVectorType() && "Expected vector type"); 7426 7427 SmallVector<Expr *, 8> initExprs; 7428 const VectorType *VTy = Ty->castAs<VectorType>(); 7429 unsigned numElems = VTy->getNumElements(); 7430 7431 // '(...)' form of vector initialization in AltiVec: the number of 7432 // initializers must be one or must match the size of the vector. 7433 // If a single value is specified in the initializer then it will be 7434 // replicated to all the components of the vector 7435 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7436 // The number of initializers must be one or must match the size of the 7437 // vector. If a single value is specified in the initializer then it will 7438 // be replicated to all the components of the vector 7439 if (numExprs == 1) { 7440 QualType ElemTy = VTy->getElementType(); 7441 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7442 if (Literal.isInvalid()) 7443 return ExprError(); 7444 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7445 PrepareScalarCast(Literal, ElemTy)); 7446 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7447 } 7448 else if (numExprs < numElems) { 7449 Diag(E->getExprLoc(), 7450 diag::err_incorrect_number_of_vector_initializers); 7451 return ExprError(); 7452 } 7453 else 7454 initExprs.append(exprs, exprs + numExprs); 7455 } 7456 else { 7457 // For OpenCL, when the number of initializers is a single value, 7458 // it will be replicated to all components of the vector. 7459 if (getLangOpts().OpenCL && 7460 VTy->getVectorKind() == VectorType::GenericVector && 7461 numExprs == 1) { 7462 QualType ElemTy = VTy->getElementType(); 7463 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7464 if (Literal.isInvalid()) 7465 return ExprError(); 7466 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7467 PrepareScalarCast(Literal, ElemTy)); 7468 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7469 } 7470 7471 initExprs.append(exprs, exprs + numExprs); 7472 } 7473 // FIXME: This means that pretty-printing the final AST will produce curly 7474 // braces instead of the original commas. 7475 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7476 initExprs, LiteralRParenLoc); 7477 initE->setType(Ty); 7478 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7479 } 7480 7481 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7482 /// the ParenListExpr into a sequence of comma binary operators. 7483 ExprResult 7484 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7485 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7486 if (!E) 7487 return OrigExpr; 7488 7489 ExprResult Result(E->getExpr(0)); 7490 7491 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7492 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7493 E->getExpr(i)); 7494 7495 if (Result.isInvalid()) return ExprError(); 7496 7497 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7498 } 7499 7500 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7501 SourceLocation R, 7502 MultiExprArg Val) { 7503 return ParenListExpr::Create(Context, L, Val, R); 7504 } 7505 7506 /// Emit a specialized diagnostic when one expression is a null pointer 7507 /// constant and the other is not a pointer. Returns true if a diagnostic is 7508 /// emitted. 7509 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7510 SourceLocation QuestionLoc) { 7511 Expr *NullExpr = LHSExpr; 7512 Expr *NonPointerExpr = RHSExpr; 7513 Expr::NullPointerConstantKind NullKind = 7514 NullExpr->isNullPointerConstant(Context, 7515 Expr::NPC_ValueDependentIsNotNull); 7516 7517 if (NullKind == Expr::NPCK_NotNull) { 7518 NullExpr = RHSExpr; 7519 NonPointerExpr = LHSExpr; 7520 NullKind = 7521 NullExpr->isNullPointerConstant(Context, 7522 Expr::NPC_ValueDependentIsNotNull); 7523 } 7524 7525 if (NullKind == Expr::NPCK_NotNull) 7526 return false; 7527 7528 if (NullKind == Expr::NPCK_ZeroExpression) 7529 return false; 7530 7531 if (NullKind == Expr::NPCK_ZeroLiteral) { 7532 // In this case, check to make sure that we got here from a "NULL" 7533 // string in the source code. 7534 NullExpr = NullExpr->IgnoreParenImpCasts(); 7535 SourceLocation loc = NullExpr->getExprLoc(); 7536 if (!findMacroSpelling(loc, "NULL")) 7537 return false; 7538 } 7539 7540 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7541 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7542 << NonPointerExpr->getType() << DiagType 7543 << NonPointerExpr->getSourceRange(); 7544 return true; 7545 } 7546 7547 /// Return false if the condition expression is valid, true otherwise. 7548 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7549 QualType CondTy = Cond->getType(); 7550 7551 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7552 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7553 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7554 << CondTy << Cond->getSourceRange(); 7555 return true; 7556 } 7557 7558 // C99 6.5.15p2 7559 if (CondTy->isScalarType()) return false; 7560 7561 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7562 << CondTy << Cond->getSourceRange(); 7563 return true; 7564 } 7565 7566 /// Handle when one or both operands are void type. 7567 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7568 ExprResult &RHS) { 7569 Expr *LHSExpr = LHS.get(); 7570 Expr *RHSExpr = RHS.get(); 7571 7572 if (!LHSExpr->getType()->isVoidType()) 7573 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7574 << RHSExpr->getSourceRange(); 7575 if (!RHSExpr->getType()->isVoidType()) 7576 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7577 << LHSExpr->getSourceRange(); 7578 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7579 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7580 return S.Context.VoidTy; 7581 } 7582 7583 /// Return false if the NullExpr can be promoted to PointerTy, 7584 /// true otherwise. 7585 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7586 QualType PointerTy) { 7587 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7588 !NullExpr.get()->isNullPointerConstant(S.Context, 7589 Expr::NPC_ValueDependentIsNull)) 7590 return true; 7591 7592 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7593 return false; 7594 } 7595 7596 /// Checks compatibility between two pointers and return the resulting 7597 /// type. 7598 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7599 ExprResult &RHS, 7600 SourceLocation Loc) { 7601 QualType LHSTy = LHS.get()->getType(); 7602 QualType RHSTy = RHS.get()->getType(); 7603 7604 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7605 // Two identical pointers types are always compatible. 7606 return LHSTy; 7607 } 7608 7609 QualType lhptee, rhptee; 7610 7611 // Get the pointee types. 7612 bool IsBlockPointer = false; 7613 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7614 lhptee = LHSBTy->getPointeeType(); 7615 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7616 IsBlockPointer = true; 7617 } else { 7618 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7619 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7620 } 7621 7622 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7623 // differently qualified versions of compatible types, the result type is 7624 // a pointer to an appropriately qualified version of the composite 7625 // type. 7626 7627 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7628 // clause doesn't make sense for our extensions. E.g. address space 2 should 7629 // be incompatible with address space 3: they may live on different devices or 7630 // anything. 7631 Qualifiers lhQual = lhptee.getQualifiers(); 7632 Qualifiers rhQual = rhptee.getQualifiers(); 7633 7634 LangAS ResultAddrSpace = LangAS::Default; 7635 LangAS LAddrSpace = lhQual.getAddressSpace(); 7636 LangAS RAddrSpace = rhQual.getAddressSpace(); 7637 7638 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7639 // spaces is disallowed. 7640 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7641 ResultAddrSpace = LAddrSpace; 7642 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7643 ResultAddrSpace = RAddrSpace; 7644 else { 7645 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7646 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7647 << RHS.get()->getSourceRange(); 7648 return QualType(); 7649 } 7650 7651 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7652 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7653 lhQual.removeCVRQualifiers(); 7654 rhQual.removeCVRQualifiers(); 7655 7656 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7657 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7658 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7659 // qual types are compatible iff 7660 // * corresponded types are compatible 7661 // * CVR qualifiers are equal 7662 // * address spaces are equal 7663 // Thus for conditional operator we merge CVR and address space unqualified 7664 // pointees and if there is a composite type we return a pointer to it with 7665 // merged qualifiers. 7666 LHSCastKind = 7667 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7668 RHSCastKind = 7669 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7670 lhQual.removeAddressSpace(); 7671 rhQual.removeAddressSpace(); 7672 7673 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7674 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7675 7676 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7677 7678 if (CompositeTy.isNull()) { 7679 // In this situation, we assume void* type. No especially good 7680 // reason, but this is what gcc does, and we do have to pick 7681 // to get a consistent AST. 7682 QualType incompatTy; 7683 incompatTy = S.Context.getPointerType( 7684 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7685 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7686 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7687 7688 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7689 // for casts between types with incompatible address space qualifiers. 7690 // For the following code the compiler produces casts between global and 7691 // local address spaces of the corresponded innermost pointees: 7692 // local int *global *a; 7693 // global int *global *b; 7694 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7695 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7696 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7697 << RHS.get()->getSourceRange(); 7698 7699 return incompatTy; 7700 } 7701 7702 // The pointer types are compatible. 7703 // In case of OpenCL ResultTy should have the address space qualifier 7704 // which is a superset of address spaces of both the 2nd and the 3rd 7705 // operands of the conditional operator. 7706 QualType ResultTy = [&, ResultAddrSpace]() { 7707 if (S.getLangOpts().OpenCL) { 7708 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7709 CompositeQuals.setAddressSpace(ResultAddrSpace); 7710 return S.Context 7711 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7712 .withCVRQualifiers(MergedCVRQual); 7713 } 7714 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7715 }(); 7716 if (IsBlockPointer) 7717 ResultTy = S.Context.getBlockPointerType(ResultTy); 7718 else 7719 ResultTy = S.Context.getPointerType(ResultTy); 7720 7721 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7722 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7723 return ResultTy; 7724 } 7725 7726 /// Return the resulting type when the operands are both block pointers. 7727 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7728 ExprResult &LHS, 7729 ExprResult &RHS, 7730 SourceLocation Loc) { 7731 QualType LHSTy = LHS.get()->getType(); 7732 QualType RHSTy = RHS.get()->getType(); 7733 7734 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7735 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7736 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7737 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7738 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7739 return destType; 7740 } 7741 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7742 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7743 << RHS.get()->getSourceRange(); 7744 return QualType(); 7745 } 7746 7747 // We have 2 block pointer types. 7748 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7749 } 7750 7751 /// Return the resulting type when the operands are both pointers. 7752 static QualType 7753 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7754 ExprResult &RHS, 7755 SourceLocation Loc) { 7756 // get the pointer types 7757 QualType LHSTy = LHS.get()->getType(); 7758 QualType RHSTy = RHS.get()->getType(); 7759 7760 // get the "pointed to" types 7761 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7762 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7763 7764 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7765 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7766 // Figure out necessary qualifiers (C99 6.5.15p6) 7767 QualType destPointee 7768 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7769 QualType destType = S.Context.getPointerType(destPointee); 7770 // Add qualifiers if necessary. 7771 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7772 // Promote to void*. 7773 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7774 return destType; 7775 } 7776 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7777 QualType destPointee 7778 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7779 QualType destType = S.Context.getPointerType(destPointee); 7780 // Add qualifiers if necessary. 7781 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7782 // Promote to void*. 7783 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7784 return destType; 7785 } 7786 7787 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7788 } 7789 7790 /// Return false if the first expression is not an integer and the second 7791 /// expression is not a pointer, true otherwise. 7792 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7793 Expr* PointerExpr, SourceLocation Loc, 7794 bool IsIntFirstExpr) { 7795 if (!PointerExpr->getType()->isPointerType() || 7796 !Int.get()->getType()->isIntegerType()) 7797 return false; 7798 7799 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7800 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7801 7802 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7803 << Expr1->getType() << Expr2->getType() 7804 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7805 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7806 CK_IntegralToPointer); 7807 return true; 7808 } 7809 7810 /// Simple conversion between integer and floating point types. 7811 /// 7812 /// Used when handling the OpenCL conditional operator where the 7813 /// condition is a vector while the other operands are scalar. 7814 /// 7815 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7816 /// types are either integer or floating type. Between the two 7817 /// operands, the type with the higher rank is defined as the "result 7818 /// type". The other operand needs to be promoted to the same type. No 7819 /// other type promotion is allowed. We cannot use 7820 /// UsualArithmeticConversions() for this purpose, since it always 7821 /// promotes promotable types. 7822 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7823 ExprResult &RHS, 7824 SourceLocation QuestionLoc) { 7825 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7826 if (LHS.isInvalid()) 7827 return QualType(); 7828 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7829 if (RHS.isInvalid()) 7830 return QualType(); 7831 7832 // For conversion purposes, we ignore any qualifiers. 7833 // For example, "const float" and "float" are equivalent. 7834 QualType LHSType = 7835 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7836 QualType RHSType = 7837 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7838 7839 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7840 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7841 << LHSType << LHS.get()->getSourceRange(); 7842 return QualType(); 7843 } 7844 7845 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7846 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7847 << RHSType << RHS.get()->getSourceRange(); 7848 return QualType(); 7849 } 7850 7851 // If both types are identical, no conversion is needed. 7852 if (LHSType == RHSType) 7853 return LHSType; 7854 7855 // Now handle "real" floating types (i.e. float, double, long double). 7856 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7857 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7858 /*IsCompAssign = */ false); 7859 7860 // Finally, we have two differing integer types. 7861 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7862 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7863 } 7864 7865 /// Convert scalar operands to a vector that matches the 7866 /// condition in length. 7867 /// 7868 /// Used when handling the OpenCL conditional operator where the 7869 /// condition is a vector while the other operands are scalar. 7870 /// 7871 /// We first compute the "result type" for the scalar operands 7872 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7873 /// into a vector of that type where the length matches the condition 7874 /// vector type. s6.11.6 requires that the element types of the result 7875 /// and the condition must have the same number of bits. 7876 static QualType 7877 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7878 QualType CondTy, SourceLocation QuestionLoc) { 7879 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7880 if (ResTy.isNull()) return QualType(); 7881 7882 const VectorType *CV = CondTy->getAs<VectorType>(); 7883 assert(CV); 7884 7885 // Determine the vector result type 7886 unsigned NumElements = CV->getNumElements(); 7887 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7888 7889 // Ensure that all types have the same number of bits 7890 if (S.Context.getTypeSize(CV->getElementType()) 7891 != S.Context.getTypeSize(ResTy)) { 7892 // Since VectorTy is created internally, it does not pretty print 7893 // with an OpenCL name. Instead, we just print a description. 7894 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7895 SmallString<64> Str; 7896 llvm::raw_svector_ostream OS(Str); 7897 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7898 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7899 << CondTy << OS.str(); 7900 return QualType(); 7901 } 7902 7903 // Convert operands to the vector result type 7904 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7905 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7906 7907 return VectorTy; 7908 } 7909 7910 /// Return false if this is a valid OpenCL condition vector 7911 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7912 SourceLocation QuestionLoc) { 7913 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7914 // integral type. 7915 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7916 assert(CondTy); 7917 QualType EleTy = CondTy->getElementType(); 7918 if (EleTy->isIntegerType()) return false; 7919 7920 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7921 << Cond->getType() << Cond->getSourceRange(); 7922 return true; 7923 } 7924 7925 /// Return false if the vector condition type and the vector 7926 /// result type are compatible. 7927 /// 7928 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7929 /// number of elements, and their element types have the same number 7930 /// of bits. 7931 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7932 SourceLocation QuestionLoc) { 7933 const VectorType *CV = CondTy->getAs<VectorType>(); 7934 const VectorType *RV = VecResTy->getAs<VectorType>(); 7935 assert(CV && RV); 7936 7937 if (CV->getNumElements() != RV->getNumElements()) { 7938 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7939 << CondTy << VecResTy; 7940 return true; 7941 } 7942 7943 QualType CVE = CV->getElementType(); 7944 QualType RVE = RV->getElementType(); 7945 7946 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7947 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7948 << CondTy << VecResTy; 7949 return true; 7950 } 7951 7952 return false; 7953 } 7954 7955 /// Return the resulting type for the conditional operator in 7956 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7957 /// s6.3.i) when the condition is a vector type. 7958 static QualType 7959 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7960 ExprResult &LHS, ExprResult &RHS, 7961 SourceLocation QuestionLoc) { 7962 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7963 if (Cond.isInvalid()) 7964 return QualType(); 7965 QualType CondTy = Cond.get()->getType(); 7966 7967 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7968 return QualType(); 7969 7970 // If either operand is a vector then find the vector type of the 7971 // result as specified in OpenCL v1.1 s6.3.i. 7972 if (LHS.get()->getType()->isVectorType() || 7973 RHS.get()->getType()->isVectorType()) { 7974 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7975 /*isCompAssign*/false, 7976 /*AllowBothBool*/true, 7977 /*AllowBoolConversions*/false); 7978 if (VecResTy.isNull()) return QualType(); 7979 // The result type must match the condition type as specified in 7980 // OpenCL v1.1 s6.11.6. 7981 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7982 return QualType(); 7983 return VecResTy; 7984 } 7985 7986 // Both operands are scalar. 7987 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7988 } 7989 7990 /// Return true if the Expr is block type 7991 static bool checkBlockType(Sema &S, const Expr *E) { 7992 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7993 QualType Ty = CE->getCallee()->getType(); 7994 if (Ty->isBlockPointerType()) { 7995 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7996 return true; 7997 } 7998 } 7999 return false; 8000 } 8001 8002 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8003 /// In that case, LHS = cond. 8004 /// C99 6.5.15 8005 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8006 ExprResult &RHS, ExprValueKind &VK, 8007 ExprObjectKind &OK, 8008 SourceLocation QuestionLoc) { 8009 8010 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8011 if (!LHSResult.isUsable()) return QualType(); 8012 LHS = LHSResult; 8013 8014 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8015 if (!RHSResult.isUsable()) return QualType(); 8016 RHS = RHSResult; 8017 8018 // C++ is sufficiently different to merit its own checker. 8019 if (getLangOpts().CPlusPlus) 8020 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8021 8022 VK = VK_RValue; 8023 OK = OK_Ordinary; 8024 8025 if (Context.isDependenceAllowed() && 8026 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8027 RHS.get()->isTypeDependent())) { 8028 assert(!getLangOpts().CPlusPlus); 8029 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8030 RHS.get()->containsErrors()) && 8031 "should only occur in error-recovery path."); 8032 return Context.DependentTy; 8033 } 8034 8035 // The OpenCL operator with a vector condition is sufficiently 8036 // different to merit its own checker. 8037 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8038 Cond.get()->getType()->isExtVectorType()) 8039 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8040 8041 // First, check the condition. 8042 Cond = UsualUnaryConversions(Cond.get()); 8043 if (Cond.isInvalid()) 8044 return QualType(); 8045 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8046 return QualType(); 8047 8048 // Now check the two expressions. 8049 if (LHS.get()->getType()->isVectorType() || 8050 RHS.get()->getType()->isVectorType()) 8051 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8052 /*AllowBothBool*/true, 8053 /*AllowBoolConversions*/false); 8054 8055 QualType ResTy = 8056 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8057 if (LHS.isInvalid() || RHS.isInvalid()) 8058 return QualType(); 8059 8060 QualType LHSTy = LHS.get()->getType(); 8061 QualType RHSTy = RHS.get()->getType(); 8062 8063 // Diagnose attempts to convert between __float128 and long double where 8064 // such conversions currently can't be handled. 8065 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8066 Diag(QuestionLoc, 8067 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8068 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8069 return QualType(); 8070 } 8071 8072 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8073 // selection operator (?:). 8074 if (getLangOpts().OpenCL && 8075 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8076 return QualType(); 8077 } 8078 8079 // If both operands have arithmetic type, do the usual arithmetic conversions 8080 // to find a common type: C99 6.5.15p3,5. 8081 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8082 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8083 // different sizes, or between ExtInts and other types. 8084 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8085 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8086 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8087 << RHS.get()->getSourceRange(); 8088 return QualType(); 8089 } 8090 8091 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8092 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8093 8094 return ResTy; 8095 } 8096 8097 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8098 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8099 return LHSTy; 8100 } 8101 8102 // If both operands are the same structure or union type, the result is that 8103 // type. 8104 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8105 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8106 if (LHSRT->getDecl() == RHSRT->getDecl()) 8107 // "If both the operands have structure or union type, the result has 8108 // that type." This implies that CV qualifiers are dropped. 8109 return LHSTy.getUnqualifiedType(); 8110 // FIXME: Type of conditional expression must be complete in C mode. 8111 } 8112 8113 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8114 // The following || allows only one side to be void (a GCC-ism). 8115 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8116 return checkConditionalVoidType(*this, LHS, RHS); 8117 } 8118 8119 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8120 // the type of the other operand." 8121 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8122 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8123 8124 // All objective-c pointer type analysis is done here. 8125 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8126 QuestionLoc); 8127 if (LHS.isInvalid() || RHS.isInvalid()) 8128 return QualType(); 8129 if (!compositeType.isNull()) 8130 return compositeType; 8131 8132 8133 // Handle block pointer types. 8134 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8135 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8136 QuestionLoc); 8137 8138 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8139 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8140 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8141 QuestionLoc); 8142 8143 // GCC compatibility: soften pointer/integer mismatch. Note that 8144 // null pointers have been filtered out by this point. 8145 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8146 /*IsIntFirstExpr=*/true)) 8147 return RHSTy; 8148 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8149 /*IsIntFirstExpr=*/false)) 8150 return LHSTy; 8151 8152 // Allow ?: operations in which both operands have the same 8153 // built-in sizeless type. 8154 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8155 return LHSTy; 8156 8157 // Emit a better diagnostic if one of the expressions is a null pointer 8158 // constant and the other is not a pointer type. In this case, the user most 8159 // likely forgot to take the address of the other expression. 8160 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8161 return QualType(); 8162 8163 // Otherwise, the operands are not compatible. 8164 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8165 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8166 << RHS.get()->getSourceRange(); 8167 return QualType(); 8168 } 8169 8170 /// FindCompositeObjCPointerType - Helper method to find composite type of 8171 /// two objective-c pointer types of the two input expressions. 8172 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8173 SourceLocation QuestionLoc) { 8174 QualType LHSTy = LHS.get()->getType(); 8175 QualType RHSTy = RHS.get()->getType(); 8176 8177 // Handle things like Class and struct objc_class*. Here we case the result 8178 // to the pseudo-builtin, because that will be implicitly cast back to the 8179 // redefinition type if an attempt is made to access its fields. 8180 if (LHSTy->isObjCClassType() && 8181 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8182 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8183 return LHSTy; 8184 } 8185 if (RHSTy->isObjCClassType() && 8186 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8187 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8188 return RHSTy; 8189 } 8190 // And the same for struct objc_object* / id 8191 if (LHSTy->isObjCIdType() && 8192 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8193 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8194 return LHSTy; 8195 } 8196 if (RHSTy->isObjCIdType() && 8197 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8198 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8199 return RHSTy; 8200 } 8201 // And the same for struct objc_selector* / SEL 8202 if (Context.isObjCSelType(LHSTy) && 8203 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8204 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8205 return LHSTy; 8206 } 8207 if (Context.isObjCSelType(RHSTy) && 8208 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8209 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8210 return RHSTy; 8211 } 8212 // Check constraints for Objective-C object pointers types. 8213 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8214 8215 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8216 // Two identical object pointer types are always compatible. 8217 return LHSTy; 8218 } 8219 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8220 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8221 QualType compositeType = LHSTy; 8222 8223 // If both operands are interfaces and either operand can be 8224 // assigned to the other, use that type as the composite 8225 // type. This allows 8226 // xxx ? (A*) a : (B*) b 8227 // where B is a subclass of A. 8228 // 8229 // Additionally, as for assignment, if either type is 'id' 8230 // allow silent coercion. Finally, if the types are 8231 // incompatible then make sure to use 'id' as the composite 8232 // type so the result is acceptable for sending messages to. 8233 8234 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8235 // It could return the composite type. 8236 if (!(compositeType = 8237 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8238 // Nothing more to do. 8239 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8240 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8241 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8242 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8243 } else if ((LHSOPT->isObjCQualifiedIdType() || 8244 RHSOPT->isObjCQualifiedIdType()) && 8245 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8246 true)) { 8247 // Need to handle "id<xx>" explicitly. 8248 // GCC allows qualified id and any Objective-C type to devolve to 8249 // id. Currently localizing to here until clear this should be 8250 // part of ObjCQualifiedIdTypesAreCompatible. 8251 compositeType = Context.getObjCIdType(); 8252 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8253 compositeType = Context.getObjCIdType(); 8254 } else { 8255 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8256 << LHSTy << RHSTy 8257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8258 QualType incompatTy = Context.getObjCIdType(); 8259 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8260 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8261 return incompatTy; 8262 } 8263 // The object pointer types are compatible. 8264 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8265 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8266 return compositeType; 8267 } 8268 // Check Objective-C object pointer types and 'void *' 8269 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8270 if (getLangOpts().ObjCAutoRefCount) { 8271 // ARC forbids the implicit conversion of object pointers to 'void *', 8272 // so these types are not compatible. 8273 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8274 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8275 LHS = RHS = true; 8276 return QualType(); 8277 } 8278 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8279 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8280 QualType destPointee 8281 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8282 QualType destType = Context.getPointerType(destPointee); 8283 // Add qualifiers if necessary. 8284 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8285 // Promote to void*. 8286 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8287 return destType; 8288 } 8289 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8290 if (getLangOpts().ObjCAutoRefCount) { 8291 // ARC forbids the implicit conversion of object pointers to 'void *', 8292 // so these types are not compatible. 8293 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8295 LHS = RHS = true; 8296 return QualType(); 8297 } 8298 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8299 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8300 QualType destPointee 8301 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8302 QualType destType = Context.getPointerType(destPointee); 8303 // Add qualifiers if necessary. 8304 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8305 // Promote to void*. 8306 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8307 return destType; 8308 } 8309 return QualType(); 8310 } 8311 8312 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8313 /// ParenRange in parentheses. 8314 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8315 const PartialDiagnostic &Note, 8316 SourceRange ParenRange) { 8317 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8318 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8319 EndLoc.isValid()) { 8320 Self.Diag(Loc, Note) 8321 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8322 << FixItHint::CreateInsertion(EndLoc, ")"); 8323 } else { 8324 // We can't display the parentheses, so just show the bare note. 8325 Self.Diag(Loc, Note) << ParenRange; 8326 } 8327 } 8328 8329 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8330 return BinaryOperator::isAdditiveOp(Opc) || 8331 BinaryOperator::isMultiplicativeOp(Opc) || 8332 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8333 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8334 // not any of the logical operators. Bitwise-xor is commonly used as a 8335 // logical-xor because there is no logical-xor operator. The logical 8336 // operators, including uses of xor, have a high false positive rate for 8337 // precedence warnings. 8338 } 8339 8340 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8341 /// expression, either using a built-in or overloaded operator, 8342 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8343 /// expression. 8344 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8345 Expr **RHSExprs) { 8346 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8347 E = E->IgnoreImpCasts(); 8348 E = E->IgnoreConversionOperatorSingleStep(); 8349 E = E->IgnoreImpCasts(); 8350 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8351 E = MTE->getSubExpr(); 8352 E = E->IgnoreImpCasts(); 8353 } 8354 8355 // Built-in binary operator. 8356 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8357 if (IsArithmeticOp(OP->getOpcode())) { 8358 *Opcode = OP->getOpcode(); 8359 *RHSExprs = OP->getRHS(); 8360 return true; 8361 } 8362 } 8363 8364 // Overloaded operator. 8365 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8366 if (Call->getNumArgs() != 2) 8367 return false; 8368 8369 // Make sure this is really a binary operator that is safe to pass into 8370 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8371 OverloadedOperatorKind OO = Call->getOperator(); 8372 if (OO < OO_Plus || OO > OO_Arrow || 8373 OO == OO_PlusPlus || OO == OO_MinusMinus) 8374 return false; 8375 8376 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8377 if (IsArithmeticOp(OpKind)) { 8378 *Opcode = OpKind; 8379 *RHSExprs = Call->getArg(1); 8380 return true; 8381 } 8382 } 8383 8384 return false; 8385 } 8386 8387 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8388 /// or is a logical expression such as (x==y) which has int type, but is 8389 /// commonly interpreted as boolean. 8390 static bool ExprLooksBoolean(Expr *E) { 8391 E = E->IgnoreParenImpCasts(); 8392 8393 if (E->getType()->isBooleanType()) 8394 return true; 8395 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8396 return OP->isComparisonOp() || OP->isLogicalOp(); 8397 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8398 return OP->getOpcode() == UO_LNot; 8399 if (E->getType()->isPointerType()) 8400 return true; 8401 // FIXME: What about overloaded operator calls returning "unspecified boolean 8402 // type"s (commonly pointer-to-members)? 8403 8404 return false; 8405 } 8406 8407 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8408 /// and binary operator are mixed in a way that suggests the programmer assumed 8409 /// the conditional operator has higher precedence, for example: 8410 /// "int x = a + someBinaryCondition ? 1 : 2". 8411 static void DiagnoseConditionalPrecedence(Sema &Self, 8412 SourceLocation OpLoc, 8413 Expr *Condition, 8414 Expr *LHSExpr, 8415 Expr *RHSExpr) { 8416 BinaryOperatorKind CondOpcode; 8417 Expr *CondRHS; 8418 8419 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8420 return; 8421 if (!ExprLooksBoolean(CondRHS)) 8422 return; 8423 8424 // The condition is an arithmetic binary expression, with a right- 8425 // hand side that looks boolean, so warn. 8426 8427 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8428 ? diag::warn_precedence_bitwise_conditional 8429 : diag::warn_precedence_conditional; 8430 8431 Self.Diag(OpLoc, DiagID) 8432 << Condition->getSourceRange() 8433 << BinaryOperator::getOpcodeStr(CondOpcode); 8434 8435 SuggestParentheses( 8436 Self, OpLoc, 8437 Self.PDiag(diag::note_precedence_silence) 8438 << BinaryOperator::getOpcodeStr(CondOpcode), 8439 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8440 8441 SuggestParentheses(Self, OpLoc, 8442 Self.PDiag(diag::note_precedence_conditional_first), 8443 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8444 } 8445 8446 /// Compute the nullability of a conditional expression. 8447 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8448 QualType LHSTy, QualType RHSTy, 8449 ASTContext &Ctx) { 8450 if (!ResTy->isAnyPointerType()) 8451 return ResTy; 8452 8453 auto GetNullability = [&Ctx](QualType Ty) { 8454 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8455 if (Kind) 8456 return *Kind; 8457 return NullabilityKind::Unspecified; 8458 }; 8459 8460 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8461 NullabilityKind MergedKind; 8462 8463 // Compute nullability of a binary conditional expression. 8464 if (IsBin) { 8465 if (LHSKind == NullabilityKind::NonNull) 8466 MergedKind = NullabilityKind::NonNull; 8467 else 8468 MergedKind = RHSKind; 8469 // Compute nullability of a normal conditional expression. 8470 } else { 8471 if (LHSKind == NullabilityKind::Nullable || 8472 RHSKind == NullabilityKind::Nullable) 8473 MergedKind = NullabilityKind::Nullable; 8474 else if (LHSKind == NullabilityKind::NonNull) 8475 MergedKind = RHSKind; 8476 else if (RHSKind == NullabilityKind::NonNull) 8477 MergedKind = LHSKind; 8478 else 8479 MergedKind = NullabilityKind::Unspecified; 8480 } 8481 8482 // Return if ResTy already has the correct nullability. 8483 if (GetNullability(ResTy) == MergedKind) 8484 return ResTy; 8485 8486 // Strip all nullability from ResTy. 8487 while (ResTy->getNullability(Ctx)) 8488 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8489 8490 // Create a new AttributedType with the new nullability kind. 8491 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8492 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8493 } 8494 8495 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8496 /// in the case of a the GNU conditional expr extension. 8497 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8498 SourceLocation ColonLoc, 8499 Expr *CondExpr, Expr *LHSExpr, 8500 Expr *RHSExpr) { 8501 if (!Context.isDependenceAllowed()) { 8502 // C cannot handle TypoExpr nodes in the condition because it 8503 // doesn't handle dependent types properly, so make sure any TypoExprs have 8504 // been dealt with before checking the operands. 8505 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8506 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8507 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8508 8509 if (!CondResult.isUsable()) 8510 return ExprError(); 8511 8512 if (LHSExpr) { 8513 if (!LHSResult.isUsable()) 8514 return ExprError(); 8515 } 8516 8517 if (!RHSResult.isUsable()) 8518 return ExprError(); 8519 8520 CondExpr = CondResult.get(); 8521 LHSExpr = LHSResult.get(); 8522 RHSExpr = RHSResult.get(); 8523 } 8524 8525 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8526 // was the condition. 8527 OpaqueValueExpr *opaqueValue = nullptr; 8528 Expr *commonExpr = nullptr; 8529 if (!LHSExpr) { 8530 commonExpr = CondExpr; 8531 // Lower out placeholder types first. This is important so that we don't 8532 // try to capture a placeholder. This happens in few cases in C++; such 8533 // as Objective-C++'s dictionary subscripting syntax. 8534 if (commonExpr->hasPlaceholderType()) { 8535 ExprResult result = CheckPlaceholderExpr(commonExpr); 8536 if (!result.isUsable()) return ExprError(); 8537 commonExpr = result.get(); 8538 } 8539 // We usually want to apply unary conversions *before* saving, except 8540 // in the special case of a C++ l-value conditional. 8541 if (!(getLangOpts().CPlusPlus 8542 && !commonExpr->isTypeDependent() 8543 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8544 && commonExpr->isGLValue() 8545 && commonExpr->isOrdinaryOrBitFieldObject() 8546 && RHSExpr->isOrdinaryOrBitFieldObject() 8547 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8548 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8549 if (commonRes.isInvalid()) 8550 return ExprError(); 8551 commonExpr = commonRes.get(); 8552 } 8553 8554 // If the common expression is a class or array prvalue, materialize it 8555 // so that we can safely refer to it multiple times. 8556 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8557 commonExpr->getType()->isArrayType())) { 8558 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8559 if (MatExpr.isInvalid()) 8560 return ExprError(); 8561 commonExpr = MatExpr.get(); 8562 } 8563 8564 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8565 commonExpr->getType(), 8566 commonExpr->getValueKind(), 8567 commonExpr->getObjectKind(), 8568 commonExpr); 8569 LHSExpr = CondExpr = opaqueValue; 8570 } 8571 8572 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8573 ExprValueKind VK = VK_RValue; 8574 ExprObjectKind OK = OK_Ordinary; 8575 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8576 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8577 VK, OK, QuestionLoc); 8578 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8579 RHS.isInvalid()) 8580 return ExprError(); 8581 8582 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8583 RHS.get()); 8584 8585 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8586 8587 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8588 Context); 8589 8590 if (!commonExpr) 8591 return new (Context) 8592 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8593 RHS.get(), result, VK, OK); 8594 8595 return new (Context) BinaryConditionalOperator( 8596 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8597 ColonLoc, result, VK, OK); 8598 } 8599 8600 // Check if we have a conversion between incompatible cmse function pointer 8601 // types, that is, a conversion between a function pointer with the 8602 // cmse_nonsecure_call attribute and one without. 8603 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8604 QualType ToType) { 8605 if (const auto *ToFn = 8606 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8607 if (const auto *FromFn = 8608 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8609 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8610 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8611 8612 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8613 } 8614 } 8615 return false; 8616 } 8617 8618 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8619 // being closely modeled after the C99 spec:-). The odd characteristic of this 8620 // routine is it effectively iqnores the qualifiers on the top level pointee. 8621 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8622 // FIXME: add a couple examples in this comment. 8623 static Sema::AssignConvertType 8624 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8625 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8626 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8627 8628 // get the "pointed to" type (ignoring qualifiers at the top level) 8629 const Type *lhptee, *rhptee; 8630 Qualifiers lhq, rhq; 8631 std::tie(lhptee, lhq) = 8632 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8633 std::tie(rhptee, rhq) = 8634 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8635 8636 Sema::AssignConvertType ConvTy = Sema::Compatible; 8637 8638 // C99 6.5.16.1p1: This following citation is common to constraints 8639 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8640 // qualifiers of the type *pointed to* by the right; 8641 8642 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8643 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8644 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8645 // Ignore lifetime for further calculation. 8646 lhq.removeObjCLifetime(); 8647 rhq.removeObjCLifetime(); 8648 } 8649 8650 if (!lhq.compatiblyIncludes(rhq)) { 8651 // Treat address-space mismatches as fatal. 8652 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8653 return Sema::IncompatiblePointerDiscardsQualifiers; 8654 8655 // It's okay to add or remove GC or lifetime qualifiers when converting to 8656 // and from void*. 8657 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8658 .compatiblyIncludes( 8659 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8660 && (lhptee->isVoidType() || rhptee->isVoidType())) 8661 ; // keep old 8662 8663 // Treat lifetime mismatches as fatal. 8664 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8665 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8666 8667 // For GCC/MS compatibility, other qualifier mismatches are treated 8668 // as still compatible in C. 8669 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8670 } 8671 8672 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8673 // incomplete type and the other is a pointer to a qualified or unqualified 8674 // version of void... 8675 if (lhptee->isVoidType()) { 8676 if (rhptee->isIncompleteOrObjectType()) 8677 return ConvTy; 8678 8679 // As an extension, we allow cast to/from void* to function pointer. 8680 assert(rhptee->isFunctionType()); 8681 return Sema::FunctionVoidPointer; 8682 } 8683 8684 if (rhptee->isVoidType()) { 8685 if (lhptee->isIncompleteOrObjectType()) 8686 return ConvTy; 8687 8688 // As an extension, we allow cast to/from void* to function pointer. 8689 assert(lhptee->isFunctionType()); 8690 return Sema::FunctionVoidPointer; 8691 } 8692 8693 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8694 // unqualified versions of compatible types, ... 8695 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8696 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8697 // Check if the pointee types are compatible ignoring the sign. 8698 // We explicitly check for char so that we catch "char" vs 8699 // "unsigned char" on systems where "char" is unsigned. 8700 if (lhptee->isCharType()) 8701 ltrans = S.Context.UnsignedCharTy; 8702 else if (lhptee->hasSignedIntegerRepresentation()) 8703 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8704 8705 if (rhptee->isCharType()) 8706 rtrans = S.Context.UnsignedCharTy; 8707 else if (rhptee->hasSignedIntegerRepresentation()) 8708 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8709 8710 if (ltrans == rtrans) { 8711 // Types are compatible ignoring the sign. Qualifier incompatibility 8712 // takes priority over sign incompatibility because the sign 8713 // warning can be disabled. 8714 if (ConvTy != Sema::Compatible) 8715 return ConvTy; 8716 8717 return Sema::IncompatiblePointerSign; 8718 } 8719 8720 // If we are a multi-level pointer, it's possible that our issue is simply 8721 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8722 // the eventual target type is the same and the pointers have the same 8723 // level of indirection, this must be the issue. 8724 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8725 do { 8726 std::tie(lhptee, lhq) = 8727 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8728 std::tie(rhptee, rhq) = 8729 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8730 8731 // Inconsistent address spaces at this point is invalid, even if the 8732 // address spaces would be compatible. 8733 // FIXME: This doesn't catch address space mismatches for pointers of 8734 // different nesting levels, like: 8735 // __local int *** a; 8736 // int ** b = a; 8737 // It's not clear how to actually determine when such pointers are 8738 // invalidly incompatible. 8739 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8740 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8741 8742 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8743 8744 if (lhptee == rhptee) 8745 return Sema::IncompatibleNestedPointerQualifiers; 8746 } 8747 8748 // General pointer incompatibility takes priority over qualifiers. 8749 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8750 return Sema::IncompatibleFunctionPointer; 8751 return Sema::IncompatiblePointer; 8752 } 8753 if (!S.getLangOpts().CPlusPlus && 8754 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8755 return Sema::IncompatibleFunctionPointer; 8756 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8757 return Sema::IncompatibleFunctionPointer; 8758 return ConvTy; 8759 } 8760 8761 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8762 /// block pointer types are compatible or whether a block and normal pointer 8763 /// are compatible. It is more restrict than comparing two function pointer 8764 // types. 8765 static Sema::AssignConvertType 8766 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8767 QualType RHSType) { 8768 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8769 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8770 8771 QualType lhptee, rhptee; 8772 8773 // get the "pointed to" type (ignoring qualifiers at the top level) 8774 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8775 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8776 8777 // In C++, the types have to match exactly. 8778 if (S.getLangOpts().CPlusPlus) 8779 return Sema::IncompatibleBlockPointer; 8780 8781 Sema::AssignConvertType ConvTy = Sema::Compatible; 8782 8783 // For blocks we enforce that qualifiers are identical. 8784 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8785 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8786 if (S.getLangOpts().OpenCL) { 8787 LQuals.removeAddressSpace(); 8788 RQuals.removeAddressSpace(); 8789 } 8790 if (LQuals != RQuals) 8791 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8792 8793 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8794 // assignment. 8795 // The current behavior is similar to C++ lambdas. A block might be 8796 // assigned to a variable iff its return type and parameters are compatible 8797 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8798 // an assignment. Presumably it should behave in way that a function pointer 8799 // assignment does in C, so for each parameter and return type: 8800 // * CVR and address space of LHS should be a superset of CVR and address 8801 // space of RHS. 8802 // * unqualified types should be compatible. 8803 if (S.getLangOpts().OpenCL) { 8804 if (!S.Context.typesAreBlockPointerCompatible( 8805 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8806 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8807 return Sema::IncompatibleBlockPointer; 8808 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8809 return Sema::IncompatibleBlockPointer; 8810 8811 return ConvTy; 8812 } 8813 8814 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8815 /// for assignment compatibility. 8816 static Sema::AssignConvertType 8817 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8818 QualType RHSType) { 8819 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8820 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8821 8822 if (LHSType->isObjCBuiltinType()) { 8823 // Class is not compatible with ObjC object pointers. 8824 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8825 !RHSType->isObjCQualifiedClassType()) 8826 return Sema::IncompatiblePointer; 8827 return Sema::Compatible; 8828 } 8829 if (RHSType->isObjCBuiltinType()) { 8830 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8831 !LHSType->isObjCQualifiedClassType()) 8832 return Sema::IncompatiblePointer; 8833 return Sema::Compatible; 8834 } 8835 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8836 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8837 8838 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8839 // make an exception for id<P> 8840 !LHSType->isObjCQualifiedIdType()) 8841 return Sema::CompatiblePointerDiscardsQualifiers; 8842 8843 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8844 return Sema::Compatible; 8845 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8846 return Sema::IncompatibleObjCQualifiedId; 8847 return Sema::IncompatiblePointer; 8848 } 8849 8850 Sema::AssignConvertType 8851 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8852 QualType LHSType, QualType RHSType) { 8853 // Fake up an opaque expression. We don't actually care about what 8854 // cast operations are required, so if CheckAssignmentConstraints 8855 // adds casts to this they'll be wasted, but fortunately that doesn't 8856 // usually happen on valid code. 8857 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8858 ExprResult RHSPtr = &RHSExpr; 8859 CastKind K; 8860 8861 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8862 } 8863 8864 /// This helper function returns true if QT is a vector type that has element 8865 /// type ElementType. 8866 static bool isVector(QualType QT, QualType ElementType) { 8867 if (const VectorType *VT = QT->getAs<VectorType>()) 8868 return VT->getElementType().getCanonicalType() == ElementType; 8869 return false; 8870 } 8871 8872 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8873 /// has code to accommodate several GCC extensions when type checking 8874 /// pointers. Here are some objectionable examples that GCC considers warnings: 8875 /// 8876 /// int a, *pint; 8877 /// short *pshort; 8878 /// struct foo *pfoo; 8879 /// 8880 /// pint = pshort; // warning: assignment from incompatible pointer type 8881 /// a = pint; // warning: assignment makes integer from pointer without a cast 8882 /// pint = a; // warning: assignment makes pointer from integer without a cast 8883 /// pint = pfoo; // warning: assignment from incompatible pointer type 8884 /// 8885 /// As a result, the code for dealing with pointers is more complex than the 8886 /// C99 spec dictates. 8887 /// 8888 /// Sets 'Kind' for any result kind except Incompatible. 8889 Sema::AssignConvertType 8890 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8891 CastKind &Kind, bool ConvertRHS) { 8892 QualType RHSType = RHS.get()->getType(); 8893 QualType OrigLHSType = LHSType; 8894 8895 // Get canonical types. We're not formatting these types, just comparing 8896 // them. 8897 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8898 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8899 8900 // Common case: no conversion required. 8901 if (LHSType == RHSType) { 8902 Kind = CK_NoOp; 8903 return Compatible; 8904 } 8905 8906 // If we have an atomic type, try a non-atomic assignment, then just add an 8907 // atomic qualification step. 8908 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8909 Sema::AssignConvertType result = 8910 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8911 if (result != Compatible) 8912 return result; 8913 if (Kind != CK_NoOp && ConvertRHS) 8914 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8915 Kind = CK_NonAtomicToAtomic; 8916 return Compatible; 8917 } 8918 8919 // If the left-hand side is a reference type, then we are in a 8920 // (rare!) case where we've allowed the use of references in C, 8921 // e.g., as a parameter type in a built-in function. In this case, 8922 // just make sure that the type referenced is compatible with the 8923 // right-hand side type. The caller is responsible for adjusting 8924 // LHSType so that the resulting expression does not have reference 8925 // type. 8926 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8927 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8928 Kind = CK_LValueBitCast; 8929 return Compatible; 8930 } 8931 return Incompatible; 8932 } 8933 8934 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8935 // to the same ExtVector type. 8936 if (LHSType->isExtVectorType()) { 8937 if (RHSType->isExtVectorType()) 8938 return Incompatible; 8939 if (RHSType->isArithmeticType()) { 8940 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8941 if (ConvertRHS) 8942 RHS = prepareVectorSplat(LHSType, RHS.get()); 8943 Kind = CK_VectorSplat; 8944 return Compatible; 8945 } 8946 } 8947 8948 // Conversions to or from vector type. 8949 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8950 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8951 // Allow assignments of an AltiVec vector type to an equivalent GCC 8952 // vector type and vice versa 8953 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8954 Kind = CK_BitCast; 8955 return Compatible; 8956 } 8957 8958 // If we are allowing lax vector conversions, and LHS and RHS are both 8959 // vectors, the total size only needs to be the same. This is a bitcast; 8960 // no bits are changed but the result type is different. 8961 if (isLaxVectorConversion(RHSType, LHSType)) { 8962 Kind = CK_BitCast; 8963 return IncompatibleVectors; 8964 } 8965 } 8966 8967 // When the RHS comes from another lax conversion (e.g. binops between 8968 // scalars and vectors) the result is canonicalized as a vector. When the 8969 // LHS is also a vector, the lax is allowed by the condition above. Handle 8970 // the case where LHS is a scalar. 8971 if (LHSType->isScalarType()) { 8972 const VectorType *VecType = RHSType->getAs<VectorType>(); 8973 if (VecType && VecType->getNumElements() == 1 && 8974 isLaxVectorConversion(RHSType, LHSType)) { 8975 ExprResult *VecExpr = &RHS; 8976 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8977 Kind = CK_BitCast; 8978 return Compatible; 8979 } 8980 } 8981 8982 // Allow assignments between fixed-length and sizeless SVE vectors. 8983 if (((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 8984 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) && 8985 Context.areCompatibleSveTypes(LHSType, RHSType)) { 8986 Kind = CK_BitCast; 8987 return Compatible; 8988 } 8989 8990 return Incompatible; 8991 } 8992 8993 // Diagnose attempts to convert between __float128 and long double where 8994 // such conversions currently can't be handled. 8995 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8996 return Incompatible; 8997 8998 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8999 // discards the imaginary part. 9000 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9001 !LHSType->getAs<ComplexType>()) 9002 return Incompatible; 9003 9004 // Arithmetic conversions. 9005 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9006 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9007 if (ConvertRHS) 9008 Kind = PrepareScalarCast(RHS, LHSType); 9009 return Compatible; 9010 } 9011 9012 // Conversions to normal pointers. 9013 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9014 // U* -> T* 9015 if (isa<PointerType>(RHSType)) { 9016 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9017 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9018 if (AddrSpaceL != AddrSpaceR) 9019 Kind = CK_AddressSpaceConversion; 9020 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9021 Kind = CK_NoOp; 9022 else 9023 Kind = CK_BitCast; 9024 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9025 } 9026 9027 // int -> T* 9028 if (RHSType->isIntegerType()) { 9029 Kind = CK_IntegralToPointer; // FIXME: null? 9030 return IntToPointer; 9031 } 9032 9033 // C pointers are not compatible with ObjC object pointers, 9034 // with two exceptions: 9035 if (isa<ObjCObjectPointerType>(RHSType)) { 9036 // - conversions to void* 9037 if (LHSPointer->getPointeeType()->isVoidType()) { 9038 Kind = CK_BitCast; 9039 return Compatible; 9040 } 9041 9042 // - conversions from 'Class' to the redefinition type 9043 if (RHSType->isObjCClassType() && 9044 Context.hasSameType(LHSType, 9045 Context.getObjCClassRedefinitionType())) { 9046 Kind = CK_BitCast; 9047 return Compatible; 9048 } 9049 9050 Kind = CK_BitCast; 9051 return IncompatiblePointer; 9052 } 9053 9054 // U^ -> void* 9055 if (RHSType->getAs<BlockPointerType>()) { 9056 if (LHSPointer->getPointeeType()->isVoidType()) { 9057 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9058 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9059 ->getPointeeType() 9060 .getAddressSpace(); 9061 Kind = 9062 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9063 return Compatible; 9064 } 9065 } 9066 9067 return Incompatible; 9068 } 9069 9070 // Conversions to block pointers. 9071 if (isa<BlockPointerType>(LHSType)) { 9072 // U^ -> T^ 9073 if (RHSType->isBlockPointerType()) { 9074 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9075 ->getPointeeType() 9076 .getAddressSpace(); 9077 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9078 ->getPointeeType() 9079 .getAddressSpace(); 9080 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9081 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9082 } 9083 9084 // int or null -> T^ 9085 if (RHSType->isIntegerType()) { 9086 Kind = CK_IntegralToPointer; // FIXME: null 9087 return IntToBlockPointer; 9088 } 9089 9090 // id -> T^ 9091 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9092 Kind = CK_AnyPointerToBlockPointerCast; 9093 return Compatible; 9094 } 9095 9096 // void* -> T^ 9097 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9098 if (RHSPT->getPointeeType()->isVoidType()) { 9099 Kind = CK_AnyPointerToBlockPointerCast; 9100 return Compatible; 9101 } 9102 9103 return Incompatible; 9104 } 9105 9106 // Conversions to Objective-C pointers. 9107 if (isa<ObjCObjectPointerType>(LHSType)) { 9108 // A* -> B* 9109 if (RHSType->isObjCObjectPointerType()) { 9110 Kind = CK_BitCast; 9111 Sema::AssignConvertType result = 9112 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9113 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9114 result == Compatible && 9115 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9116 result = IncompatibleObjCWeakRef; 9117 return result; 9118 } 9119 9120 // int or null -> A* 9121 if (RHSType->isIntegerType()) { 9122 Kind = CK_IntegralToPointer; // FIXME: null 9123 return IntToPointer; 9124 } 9125 9126 // In general, C pointers are not compatible with ObjC object pointers, 9127 // with two exceptions: 9128 if (isa<PointerType>(RHSType)) { 9129 Kind = CK_CPointerToObjCPointerCast; 9130 9131 // - conversions from 'void*' 9132 if (RHSType->isVoidPointerType()) { 9133 return Compatible; 9134 } 9135 9136 // - conversions to 'Class' from its redefinition type 9137 if (LHSType->isObjCClassType() && 9138 Context.hasSameType(RHSType, 9139 Context.getObjCClassRedefinitionType())) { 9140 return Compatible; 9141 } 9142 9143 return IncompatiblePointer; 9144 } 9145 9146 // Only under strict condition T^ is compatible with an Objective-C pointer. 9147 if (RHSType->isBlockPointerType() && 9148 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9149 if (ConvertRHS) 9150 maybeExtendBlockObject(RHS); 9151 Kind = CK_BlockPointerToObjCPointerCast; 9152 return Compatible; 9153 } 9154 9155 return Incompatible; 9156 } 9157 9158 // Conversions from pointers that are not covered by the above. 9159 if (isa<PointerType>(RHSType)) { 9160 // T* -> _Bool 9161 if (LHSType == Context.BoolTy) { 9162 Kind = CK_PointerToBoolean; 9163 return Compatible; 9164 } 9165 9166 // T* -> int 9167 if (LHSType->isIntegerType()) { 9168 Kind = CK_PointerToIntegral; 9169 return PointerToInt; 9170 } 9171 9172 return Incompatible; 9173 } 9174 9175 // Conversions from Objective-C pointers that are not covered by the above. 9176 if (isa<ObjCObjectPointerType>(RHSType)) { 9177 // T* -> _Bool 9178 if (LHSType == Context.BoolTy) { 9179 Kind = CK_PointerToBoolean; 9180 return Compatible; 9181 } 9182 9183 // T* -> int 9184 if (LHSType->isIntegerType()) { 9185 Kind = CK_PointerToIntegral; 9186 return PointerToInt; 9187 } 9188 9189 return Incompatible; 9190 } 9191 9192 // struct A -> struct B 9193 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9194 if (Context.typesAreCompatible(LHSType, RHSType)) { 9195 Kind = CK_NoOp; 9196 return Compatible; 9197 } 9198 } 9199 9200 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9201 Kind = CK_IntToOCLSampler; 9202 return Compatible; 9203 } 9204 9205 return Incompatible; 9206 } 9207 9208 /// Constructs a transparent union from an expression that is 9209 /// used to initialize the transparent union. 9210 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9211 ExprResult &EResult, QualType UnionType, 9212 FieldDecl *Field) { 9213 // Build an initializer list that designates the appropriate member 9214 // of the transparent union. 9215 Expr *E = EResult.get(); 9216 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9217 E, SourceLocation()); 9218 Initializer->setType(UnionType); 9219 Initializer->setInitializedFieldInUnion(Field); 9220 9221 // Build a compound literal constructing a value of the transparent 9222 // union type from this initializer list. 9223 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9224 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9225 VK_RValue, Initializer, false); 9226 } 9227 9228 Sema::AssignConvertType 9229 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9230 ExprResult &RHS) { 9231 QualType RHSType = RHS.get()->getType(); 9232 9233 // If the ArgType is a Union type, we want to handle a potential 9234 // transparent_union GCC extension. 9235 const RecordType *UT = ArgType->getAsUnionType(); 9236 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9237 return Incompatible; 9238 9239 // The field to initialize within the transparent union. 9240 RecordDecl *UD = UT->getDecl(); 9241 FieldDecl *InitField = nullptr; 9242 // It's compatible if the expression matches any of the fields. 9243 for (auto *it : UD->fields()) { 9244 if (it->getType()->isPointerType()) { 9245 // If the transparent union contains a pointer type, we allow: 9246 // 1) void pointer 9247 // 2) null pointer constant 9248 if (RHSType->isPointerType()) 9249 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9250 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9251 InitField = it; 9252 break; 9253 } 9254 9255 if (RHS.get()->isNullPointerConstant(Context, 9256 Expr::NPC_ValueDependentIsNull)) { 9257 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9258 CK_NullToPointer); 9259 InitField = it; 9260 break; 9261 } 9262 } 9263 9264 CastKind Kind; 9265 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9266 == Compatible) { 9267 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9268 InitField = it; 9269 break; 9270 } 9271 } 9272 9273 if (!InitField) 9274 return Incompatible; 9275 9276 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9277 return Compatible; 9278 } 9279 9280 Sema::AssignConvertType 9281 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9282 bool Diagnose, 9283 bool DiagnoseCFAudited, 9284 bool ConvertRHS) { 9285 // We need to be able to tell the caller whether we diagnosed a problem, if 9286 // they ask us to issue diagnostics. 9287 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9288 9289 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9290 // we can't avoid *all* modifications at the moment, so we need some somewhere 9291 // to put the updated value. 9292 ExprResult LocalRHS = CallerRHS; 9293 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9294 9295 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9296 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9297 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9298 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9299 Diag(RHS.get()->getExprLoc(), 9300 diag::warn_noderef_to_dereferenceable_pointer) 9301 << RHS.get()->getSourceRange(); 9302 } 9303 } 9304 } 9305 9306 if (getLangOpts().CPlusPlus) { 9307 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9308 // C++ 5.17p3: If the left operand is not of class type, the 9309 // expression is implicitly converted (C++ 4) to the 9310 // cv-unqualified type of the left operand. 9311 QualType RHSType = RHS.get()->getType(); 9312 if (Diagnose) { 9313 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9314 AA_Assigning); 9315 } else { 9316 ImplicitConversionSequence ICS = 9317 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9318 /*SuppressUserConversions=*/false, 9319 AllowedExplicit::None, 9320 /*InOverloadResolution=*/false, 9321 /*CStyle=*/false, 9322 /*AllowObjCWritebackConversion=*/false); 9323 if (ICS.isFailure()) 9324 return Incompatible; 9325 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9326 ICS, AA_Assigning); 9327 } 9328 if (RHS.isInvalid()) 9329 return Incompatible; 9330 Sema::AssignConvertType result = Compatible; 9331 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9332 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9333 result = IncompatibleObjCWeakRef; 9334 return result; 9335 } 9336 9337 // FIXME: Currently, we fall through and treat C++ classes like C 9338 // structures. 9339 // FIXME: We also fall through for atomics; not sure what should 9340 // happen there, though. 9341 } else if (RHS.get()->getType() == Context.OverloadTy) { 9342 // As a set of extensions to C, we support overloading on functions. These 9343 // functions need to be resolved here. 9344 DeclAccessPair DAP; 9345 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9346 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9347 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9348 else 9349 return Incompatible; 9350 } 9351 9352 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9353 // a null pointer constant. 9354 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9355 LHSType->isBlockPointerType()) && 9356 RHS.get()->isNullPointerConstant(Context, 9357 Expr::NPC_ValueDependentIsNull)) { 9358 if (Diagnose || ConvertRHS) { 9359 CastKind Kind; 9360 CXXCastPath Path; 9361 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9362 /*IgnoreBaseAccess=*/false, Diagnose); 9363 if (ConvertRHS) 9364 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9365 } 9366 return Compatible; 9367 } 9368 9369 // OpenCL queue_t type assignment. 9370 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9371 Context, Expr::NPC_ValueDependentIsNull)) { 9372 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9373 return Compatible; 9374 } 9375 9376 // This check seems unnatural, however it is necessary to ensure the proper 9377 // conversion of functions/arrays. If the conversion were done for all 9378 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9379 // expressions that suppress this implicit conversion (&, sizeof). 9380 // 9381 // Suppress this for references: C++ 8.5.3p5. 9382 if (!LHSType->isReferenceType()) { 9383 // FIXME: We potentially allocate here even if ConvertRHS is false. 9384 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9385 if (RHS.isInvalid()) 9386 return Incompatible; 9387 } 9388 CastKind Kind; 9389 Sema::AssignConvertType result = 9390 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9391 9392 // C99 6.5.16.1p2: The value of the right operand is converted to the 9393 // type of the assignment expression. 9394 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9395 // so that we can use references in built-in functions even in C. 9396 // The getNonReferenceType() call makes sure that the resulting expression 9397 // does not have reference type. 9398 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9399 QualType Ty = LHSType.getNonLValueExprType(Context); 9400 Expr *E = RHS.get(); 9401 9402 // Check for various Objective-C errors. If we are not reporting 9403 // diagnostics and just checking for errors, e.g., during overload 9404 // resolution, return Incompatible to indicate the failure. 9405 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9406 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9407 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9408 if (!Diagnose) 9409 return Incompatible; 9410 } 9411 if (getLangOpts().ObjC && 9412 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9413 E->getType(), E, Diagnose) || 9414 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9415 if (!Diagnose) 9416 return Incompatible; 9417 // Replace the expression with a corrected version and continue so we 9418 // can find further errors. 9419 RHS = E; 9420 return Compatible; 9421 } 9422 9423 if (ConvertRHS) 9424 RHS = ImpCastExprToType(E, Ty, Kind); 9425 } 9426 9427 return result; 9428 } 9429 9430 namespace { 9431 /// The original operand to an operator, prior to the application of the usual 9432 /// arithmetic conversions and converting the arguments of a builtin operator 9433 /// candidate. 9434 struct OriginalOperand { 9435 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9436 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9437 Op = MTE->getSubExpr(); 9438 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9439 Op = BTE->getSubExpr(); 9440 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9441 Orig = ICE->getSubExprAsWritten(); 9442 Conversion = ICE->getConversionFunction(); 9443 } 9444 } 9445 9446 QualType getType() const { return Orig->getType(); } 9447 9448 Expr *Orig; 9449 NamedDecl *Conversion; 9450 }; 9451 } 9452 9453 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9454 ExprResult &RHS) { 9455 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9456 9457 Diag(Loc, diag::err_typecheck_invalid_operands) 9458 << OrigLHS.getType() << OrigRHS.getType() 9459 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9460 9461 // If a user-defined conversion was applied to either of the operands prior 9462 // to applying the built-in operator rules, tell the user about it. 9463 if (OrigLHS.Conversion) { 9464 Diag(OrigLHS.Conversion->getLocation(), 9465 diag::note_typecheck_invalid_operands_converted) 9466 << 0 << LHS.get()->getType(); 9467 } 9468 if (OrigRHS.Conversion) { 9469 Diag(OrigRHS.Conversion->getLocation(), 9470 diag::note_typecheck_invalid_operands_converted) 9471 << 1 << RHS.get()->getType(); 9472 } 9473 9474 return QualType(); 9475 } 9476 9477 // Diagnose cases where a scalar was implicitly converted to a vector and 9478 // diagnose the underlying types. Otherwise, diagnose the error 9479 // as invalid vector logical operands for non-C++ cases. 9480 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9481 ExprResult &RHS) { 9482 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9483 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9484 9485 bool LHSNatVec = LHSType->isVectorType(); 9486 bool RHSNatVec = RHSType->isVectorType(); 9487 9488 if (!(LHSNatVec && RHSNatVec)) { 9489 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9490 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9491 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9492 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9493 << Vector->getSourceRange(); 9494 return QualType(); 9495 } 9496 9497 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9498 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9499 << RHS.get()->getSourceRange(); 9500 9501 return QualType(); 9502 } 9503 9504 /// Try to convert a value of non-vector type to a vector type by converting 9505 /// the type to the element type of the vector and then performing a splat. 9506 /// If the language is OpenCL, we only use conversions that promote scalar 9507 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9508 /// for float->int. 9509 /// 9510 /// OpenCL V2.0 6.2.6.p2: 9511 /// An error shall occur if any scalar operand type has greater rank 9512 /// than the type of the vector element. 9513 /// 9514 /// \param scalar - if non-null, actually perform the conversions 9515 /// \return true if the operation fails (but without diagnosing the failure) 9516 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9517 QualType scalarTy, 9518 QualType vectorEltTy, 9519 QualType vectorTy, 9520 unsigned &DiagID) { 9521 // The conversion to apply to the scalar before splatting it, 9522 // if necessary. 9523 CastKind scalarCast = CK_NoOp; 9524 9525 if (vectorEltTy->isIntegralType(S.Context)) { 9526 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9527 (scalarTy->isIntegerType() && 9528 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9529 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9530 return true; 9531 } 9532 if (!scalarTy->isIntegralType(S.Context)) 9533 return true; 9534 scalarCast = CK_IntegralCast; 9535 } else if (vectorEltTy->isRealFloatingType()) { 9536 if (scalarTy->isRealFloatingType()) { 9537 if (S.getLangOpts().OpenCL && 9538 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9539 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9540 return true; 9541 } 9542 scalarCast = CK_FloatingCast; 9543 } 9544 else if (scalarTy->isIntegralType(S.Context)) 9545 scalarCast = CK_IntegralToFloating; 9546 else 9547 return true; 9548 } else { 9549 return true; 9550 } 9551 9552 // Adjust scalar if desired. 9553 if (scalar) { 9554 if (scalarCast != CK_NoOp) 9555 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9556 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9557 } 9558 return false; 9559 } 9560 9561 /// Convert vector E to a vector with the same number of elements but different 9562 /// element type. 9563 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9564 const auto *VecTy = E->getType()->getAs<VectorType>(); 9565 assert(VecTy && "Expression E must be a vector"); 9566 QualType NewVecTy = S.Context.getVectorType(ElementType, 9567 VecTy->getNumElements(), 9568 VecTy->getVectorKind()); 9569 9570 // Look through the implicit cast. Return the subexpression if its type is 9571 // NewVecTy. 9572 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9573 if (ICE->getSubExpr()->getType() == NewVecTy) 9574 return ICE->getSubExpr(); 9575 9576 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9577 return S.ImpCastExprToType(E, NewVecTy, Cast); 9578 } 9579 9580 /// Test if a (constant) integer Int can be casted to another integer type 9581 /// IntTy without losing precision. 9582 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9583 QualType OtherIntTy) { 9584 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9585 9586 // Reject cases where the value of the Int is unknown as that would 9587 // possibly cause truncation, but accept cases where the scalar can be 9588 // demoted without loss of precision. 9589 Expr::EvalResult EVResult; 9590 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9591 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9592 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9593 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9594 9595 if (CstInt) { 9596 // If the scalar is constant and is of a higher order and has more active 9597 // bits that the vector element type, reject it. 9598 llvm::APSInt Result = EVResult.Val.getInt(); 9599 unsigned NumBits = IntSigned 9600 ? (Result.isNegative() ? Result.getMinSignedBits() 9601 : Result.getActiveBits()) 9602 : Result.getActiveBits(); 9603 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9604 return true; 9605 9606 // If the signedness of the scalar type and the vector element type 9607 // differs and the number of bits is greater than that of the vector 9608 // element reject it. 9609 return (IntSigned != OtherIntSigned && 9610 NumBits > S.Context.getIntWidth(OtherIntTy)); 9611 } 9612 9613 // Reject cases where the value of the scalar is not constant and it's 9614 // order is greater than that of the vector element type. 9615 return (Order < 0); 9616 } 9617 9618 /// Test if a (constant) integer Int can be casted to floating point type 9619 /// FloatTy without losing precision. 9620 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9621 QualType FloatTy) { 9622 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9623 9624 // Determine if the integer constant can be expressed as a floating point 9625 // number of the appropriate type. 9626 Expr::EvalResult EVResult; 9627 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9628 9629 uint64_t Bits = 0; 9630 if (CstInt) { 9631 // Reject constants that would be truncated if they were converted to 9632 // the floating point type. Test by simple to/from conversion. 9633 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9634 // could be avoided if there was a convertFromAPInt method 9635 // which could signal back if implicit truncation occurred. 9636 llvm::APSInt Result = EVResult.Val.getInt(); 9637 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9638 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9639 llvm::APFloat::rmTowardZero); 9640 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9641 !IntTy->hasSignedIntegerRepresentation()); 9642 bool Ignored = false; 9643 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9644 &Ignored); 9645 if (Result != ConvertBack) 9646 return true; 9647 } else { 9648 // Reject types that cannot be fully encoded into the mantissa of 9649 // the float. 9650 Bits = S.Context.getTypeSize(IntTy); 9651 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9652 S.Context.getFloatTypeSemantics(FloatTy)); 9653 if (Bits > FloatPrec) 9654 return true; 9655 } 9656 9657 return false; 9658 } 9659 9660 /// Attempt to convert and splat Scalar into a vector whose types matches 9661 /// Vector following GCC conversion rules. The rule is that implicit 9662 /// conversion can occur when Scalar can be casted to match Vector's element 9663 /// type without causing truncation of Scalar. 9664 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9665 ExprResult *Vector) { 9666 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9667 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9668 const VectorType *VT = VectorTy->getAs<VectorType>(); 9669 9670 assert(!isa<ExtVectorType>(VT) && 9671 "ExtVectorTypes should not be handled here!"); 9672 9673 QualType VectorEltTy = VT->getElementType(); 9674 9675 // Reject cases where the vector element type or the scalar element type are 9676 // not integral or floating point types. 9677 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9678 return true; 9679 9680 // The conversion to apply to the scalar before splatting it, 9681 // if necessary. 9682 CastKind ScalarCast = CK_NoOp; 9683 9684 // Accept cases where the vector elements are integers and the scalar is 9685 // an integer. 9686 // FIXME: Notionally if the scalar was a floating point value with a precise 9687 // integral representation, we could cast it to an appropriate integer 9688 // type and then perform the rest of the checks here. GCC will perform 9689 // this conversion in some cases as determined by the input language. 9690 // We should accept it on a language independent basis. 9691 if (VectorEltTy->isIntegralType(S.Context) && 9692 ScalarTy->isIntegralType(S.Context) && 9693 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9694 9695 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9696 return true; 9697 9698 ScalarCast = CK_IntegralCast; 9699 } else if (VectorEltTy->isIntegralType(S.Context) && 9700 ScalarTy->isRealFloatingType()) { 9701 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9702 ScalarCast = CK_FloatingToIntegral; 9703 else 9704 return true; 9705 } else if (VectorEltTy->isRealFloatingType()) { 9706 if (ScalarTy->isRealFloatingType()) { 9707 9708 // Reject cases where the scalar type is not a constant and has a higher 9709 // Order than the vector element type. 9710 llvm::APFloat Result(0.0); 9711 9712 // Determine whether this is a constant scalar. In the event that the 9713 // value is dependent (and thus cannot be evaluated by the constant 9714 // evaluator), skip the evaluation. This will then diagnose once the 9715 // expression is instantiated. 9716 bool CstScalar = Scalar->get()->isValueDependent() || 9717 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9718 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9719 if (!CstScalar && Order < 0) 9720 return true; 9721 9722 // If the scalar cannot be safely casted to the vector element type, 9723 // reject it. 9724 if (CstScalar) { 9725 bool Truncated = false; 9726 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9727 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9728 if (Truncated) 9729 return true; 9730 } 9731 9732 ScalarCast = CK_FloatingCast; 9733 } else if (ScalarTy->isIntegralType(S.Context)) { 9734 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9735 return true; 9736 9737 ScalarCast = CK_IntegralToFloating; 9738 } else 9739 return true; 9740 } else if (ScalarTy->isEnumeralType()) 9741 return true; 9742 9743 // Adjust scalar if desired. 9744 if (Scalar) { 9745 if (ScalarCast != CK_NoOp) 9746 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9747 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9748 } 9749 return false; 9750 } 9751 9752 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9753 SourceLocation Loc, bool IsCompAssign, 9754 bool AllowBothBool, 9755 bool AllowBoolConversions) { 9756 if (!IsCompAssign) { 9757 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9758 if (LHS.isInvalid()) 9759 return QualType(); 9760 } 9761 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9762 if (RHS.isInvalid()) 9763 return QualType(); 9764 9765 // For conversion purposes, we ignore any qualifiers. 9766 // For example, "const float" and "float" are equivalent. 9767 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9768 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9769 9770 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9771 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9772 assert(LHSVecType || RHSVecType); 9773 9774 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9775 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9776 return InvalidOperands(Loc, LHS, RHS); 9777 9778 // AltiVec-style "vector bool op vector bool" combinations are allowed 9779 // for some operators but not others. 9780 if (!AllowBothBool && 9781 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9782 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9783 return InvalidOperands(Loc, LHS, RHS); 9784 9785 // If the vector types are identical, return. 9786 if (Context.hasSameType(LHSType, RHSType)) 9787 return LHSType; 9788 9789 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9790 if (LHSVecType && RHSVecType && 9791 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9792 if (isa<ExtVectorType>(LHSVecType)) { 9793 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9794 return LHSType; 9795 } 9796 9797 if (!IsCompAssign) 9798 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9799 return RHSType; 9800 } 9801 9802 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9803 // can be mixed, with the result being the non-bool type. The non-bool 9804 // operand must have integer element type. 9805 if (AllowBoolConversions && LHSVecType && RHSVecType && 9806 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9807 (Context.getTypeSize(LHSVecType->getElementType()) == 9808 Context.getTypeSize(RHSVecType->getElementType()))) { 9809 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9810 LHSVecType->getElementType()->isIntegerType() && 9811 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9812 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9813 return LHSType; 9814 } 9815 if (!IsCompAssign && 9816 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9817 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9818 RHSVecType->getElementType()->isIntegerType()) { 9819 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9820 return RHSType; 9821 } 9822 } 9823 9824 // If there's a vector type and a scalar, try to convert the scalar to 9825 // the vector element type and splat. 9826 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9827 if (!RHSVecType) { 9828 if (isa<ExtVectorType>(LHSVecType)) { 9829 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9830 LHSVecType->getElementType(), LHSType, 9831 DiagID)) 9832 return LHSType; 9833 } else { 9834 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9835 return LHSType; 9836 } 9837 } 9838 if (!LHSVecType) { 9839 if (isa<ExtVectorType>(RHSVecType)) { 9840 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9841 LHSType, RHSVecType->getElementType(), 9842 RHSType, DiagID)) 9843 return RHSType; 9844 } else { 9845 if (LHS.get()->getValueKind() == VK_LValue || 9846 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9847 return RHSType; 9848 } 9849 } 9850 9851 // FIXME: The code below also handles conversion between vectors and 9852 // non-scalars, we should break this down into fine grained specific checks 9853 // and emit proper diagnostics. 9854 QualType VecType = LHSVecType ? LHSType : RHSType; 9855 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9856 QualType OtherType = LHSVecType ? RHSType : LHSType; 9857 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9858 if (isLaxVectorConversion(OtherType, VecType)) { 9859 // If we're allowing lax vector conversions, only the total (data) size 9860 // needs to be the same. For non compound assignment, if one of the types is 9861 // scalar, the result is always the vector type. 9862 if (!IsCompAssign) { 9863 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9864 return VecType; 9865 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9866 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9867 // type. Note that this is already done by non-compound assignments in 9868 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9869 // <1 x T> -> T. The result is also a vector type. 9870 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9871 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9872 ExprResult *RHSExpr = &RHS; 9873 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9874 return VecType; 9875 } 9876 } 9877 9878 // Okay, the expression is invalid. 9879 9880 // Returns true if the operands are SVE VLA and VLS types. 9881 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9882 const VectorType *VecType = SecondType->getAs<VectorType>(); 9883 return FirstType->isSizelessBuiltinType() && VecType && 9884 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9885 VecType->getVectorKind() == 9886 VectorType::SveFixedLengthPredicateVector); 9887 }; 9888 9889 // If there's a sizeless and fixed-length operand, diagnose that. 9890 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9891 Diag(Loc, diag::err_typecheck_vector_not_convertable_sizeless) 9892 << LHSType << RHSType; 9893 return QualType(); 9894 } 9895 9896 // If there's a non-vector, non-real operand, diagnose that. 9897 if ((!RHSVecType && !RHSType->isRealType()) || 9898 (!LHSVecType && !LHSType->isRealType())) { 9899 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9900 << LHSType << RHSType 9901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9902 return QualType(); 9903 } 9904 9905 // OpenCL V1.1 6.2.6.p1: 9906 // If the operands are of more than one vector type, then an error shall 9907 // occur. Implicit conversions between vector types are not permitted, per 9908 // section 6.2.1. 9909 if (getLangOpts().OpenCL && 9910 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9911 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9912 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9913 << RHSType; 9914 return QualType(); 9915 } 9916 9917 9918 // If there is a vector type that is not a ExtVector and a scalar, we reach 9919 // this point if scalar could not be converted to the vector's element type 9920 // without truncation. 9921 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9922 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9923 QualType Scalar = LHSVecType ? RHSType : LHSType; 9924 QualType Vector = LHSVecType ? LHSType : RHSType; 9925 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9926 Diag(Loc, 9927 diag::err_typecheck_vector_not_convertable_implict_truncation) 9928 << ScalarOrVector << Scalar << Vector; 9929 9930 return QualType(); 9931 } 9932 9933 // Otherwise, use the generic diagnostic. 9934 Diag(Loc, DiagID) 9935 << LHSType << RHSType 9936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9937 return QualType(); 9938 } 9939 9940 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9941 // expression. These are mainly cases where the null pointer is used as an 9942 // integer instead of a pointer. 9943 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9944 SourceLocation Loc, bool IsCompare) { 9945 // The canonical way to check for a GNU null is with isNullPointerConstant, 9946 // but we use a bit of a hack here for speed; this is a relatively 9947 // hot path, and isNullPointerConstant is slow. 9948 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9949 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9950 9951 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9952 9953 // Avoid analyzing cases where the result will either be invalid (and 9954 // diagnosed as such) or entirely valid and not something to warn about. 9955 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9956 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9957 return; 9958 9959 // Comparison operations would not make sense with a null pointer no matter 9960 // what the other expression is. 9961 if (!IsCompare) { 9962 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9963 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9964 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9965 return; 9966 } 9967 9968 // The rest of the operations only make sense with a null pointer 9969 // if the other expression is a pointer. 9970 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9971 NonNullType->canDecayToPointerType()) 9972 return; 9973 9974 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9975 << LHSNull /* LHS is NULL */ << NonNullType 9976 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9977 } 9978 9979 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9980 SourceLocation Loc) { 9981 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9982 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9983 if (!LUE || !RUE) 9984 return; 9985 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9986 RUE->getKind() != UETT_SizeOf) 9987 return; 9988 9989 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9990 QualType LHSTy = LHSArg->getType(); 9991 QualType RHSTy; 9992 9993 if (RUE->isArgumentType()) 9994 RHSTy = RUE->getArgumentType().getNonReferenceType(); 9995 else 9996 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9997 9998 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9999 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10000 return; 10001 10002 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10003 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10004 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10005 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10006 << LHSArgDecl; 10007 } 10008 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10009 QualType ArrayElemTy = ArrayTy->getElementType(); 10010 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10011 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10012 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10013 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10014 return; 10015 S.Diag(Loc, diag::warn_division_sizeof_array) 10016 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10017 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10018 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10019 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10020 << LHSArgDecl; 10021 } 10022 10023 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10024 } 10025 } 10026 10027 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10028 ExprResult &RHS, 10029 SourceLocation Loc, bool IsDiv) { 10030 // Check for division/remainder by zero. 10031 Expr::EvalResult RHSValue; 10032 if (!RHS.get()->isValueDependent() && 10033 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10034 RHSValue.Val.getInt() == 0) 10035 S.DiagRuntimeBehavior(Loc, RHS.get(), 10036 S.PDiag(diag::warn_remainder_division_by_zero) 10037 << IsDiv << RHS.get()->getSourceRange()); 10038 } 10039 10040 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10041 SourceLocation Loc, 10042 bool IsCompAssign, bool IsDiv) { 10043 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10044 10045 if (LHS.get()->getType()->isVectorType() || 10046 RHS.get()->getType()->isVectorType()) 10047 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10048 /*AllowBothBool*/getLangOpts().AltiVec, 10049 /*AllowBoolConversions*/false); 10050 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10051 RHS.get()->getType()->isConstantMatrixType())) 10052 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10053 10054 QualType compType = UsualArithmeticConversions( 10055 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10056 if (LHS.isInvalid() || RHS.isInvalid()) 10057 return QualType(); 10058 10059 10060 if (compType.isNull() || !compType->isArithmeticType()) 10061 return InvalidOperands(Loc, LHS, RHS); 10062 if (IsDiv) { 10063 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10064 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10065 } 10066 return compType; 10067 } 10068 10069 QualType Sema::CheckRemainderOperands( 10070 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10071 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10072 10073 if (LHS.get()->getType()->isVectorType() || 10074 RHS.get()->getType()->isVectorType()) { 10075 if (LHS.get()->getType()->hasIntegerRepresentation() && 10076 RHS.get()->getType()->hasIntegerRepresentation()) 10077 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10078 /*AllowBothBool*/getLangOpts().AltiVec, 10079 /*AllowBoolConversions*/false); 10080 return InvalidOperands(Loc, LHS, RHS); 10081 } 10082 10083 QualType compType = UsualArithmeticConversions( 10084 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10085 if (LHS.isInvalid() || RHS.isInvalid()) 10086 return QualType(); 10087 10088 if (compType.isNull() || !compType->isIntegerType()) 10089 return InvalidOperands(Loc, LHS, RHS); 10090 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10091 return compType; 10092 } 10093 10094 /// Diagnose invalid arithmetic on two void pointers. 10095 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10096 Expr *LHSExpr, Expr *RHSExpr) { 10097 S.Diag(Loc, S.getLangOpts().CPlusPlus 10098 ? diag::err_typecheck_pointer_arith_void_type 10099 : diag::ext_gnu_void_ptr) 10100 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10101 << RHSExpr->getSourceRange(); 10102 } 10103 10104 /// Diagnose invalid arithmetic on a void pointer. 10105 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10106 Expr *Pointer) { 10107 S.Diag(Loc, S.getLangOpts().CPlusPlus 10108 ? diag::err_typecheck_pointer_arith_void_type 10109 : diag::ext_gnu_void_ptr) 10110 << 0 /* one pointer */ << Pointer->getSourceRange(); 10111 } 10112 10113 /// Diagnose invalid arithmetic on a null pointer. 10114 /// 10115 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10116 /// idiom, which we recognize as a GNU extension. 10117 /// 10118 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10119 Expr *Pointer, bool IsGNUIdiom) { 10120 if (IsGNUIdiom) 10121 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10122 << Pointer->getSourceRange(); 10123 else 10124 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10125 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10126 } 10127 10128 /// Diagnose invalid arithmetic on two function pointers. 10129 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10130 Expr *LHS, Expr *RHS) { 10131 assert(LHS->getType()->isAnyPointerType()); 10132 assert(RHS->getType()->isAnyPointerType()); 10133 S.Diag(Loc, S.getLangOpts().CPlusPlus 10134 ? diag::err_typecheck_pointer_arith_function_type 10135 : diag::ext_gnu_ptr_func_arith) 10136 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10137 // We only show the second type if it differs from the first. 10138 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10139 RHS->getType()) 10140 << RHS->getType()->getPointeeType() 10141 << LHS->getSourceRange() << RHS->getSourceRange(); 10142 } 10143 10144 /// Diagnose invalid arithmetic on a function pointer. 10145 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10146 Expr *Pointer) { 10147 assert(Pointer->getType()->isAnyPointerType()); 10148 S.Diag(Loc, S.getLangOpts().CPlusPlus 10149 ? diag::err_typecheck_pointer_arith_function_type 10150 : diag::ext_gnu_ptr_func_arith) 10151 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10152 << 0 /* one pointer, so only one type */ 10153 << Pointer->getSourceRange(); 10154 } 10155 10156 /// Emit error if Operand is incomplete pointer type 10157 /// 10158 /// \returns True if pointer has incomplete type 10159 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10160 Expr *Operand) { 10161 QualType ResType = Operand->getType(); 10162 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10163 ResType = ResAtomicType->getValueType(); 10164 10165 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10166 QualType PointeeTy = ResType->getPointeeType(); 10167 return S.RequireCompleteSizedType( 10168 Loc, PointeeTy, 10169 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10170 Operand->getSourceRange()); 10171 } 10172 10173 /// Check the validity of an arithmetic pointer operand. 10174 /// 10175 /// If the operand has pointer type, this code will check for pointer types 10176 /// which are invalid in arithmetic operations. These will be diagnosed 10177 /// appropriately, including whether or not the use is supported as an 10178 /// extension. 10179 /// 10180 /// \returns True when the operand is valid to use (even if as an extension). 10181 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10182 Expr *Operand) { 10183 QualType ResType = Operand->getType(); 10184 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10185 ResType = ResAtomicType->getValueType(); 10186 10187 if (!ResType->isAnyPointerType()) return true; 10188 10189 QualType PointeeTy = ResType->getPointeeType(); 10190 if (PointeeTy->isVoidType()) { 10191 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10192 return !S.getLangOpts().CPlusPlus; 10193 } 10194 if (PointeeTy->isFunctionType()) { 10195 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10196 return !S.getLangOpts().CPlusPlus; 10197 } 10198 10199 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10200 10201 return true; 10202 } 10203 10204 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10205 /// operands. 10206 /// 10207 /// This routine will diagnose any invalid arithmetic on pointer operands much 10208 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10209 /// for emitting a single diagnostic even for operations where both LHS and RHS 10210 /// are (potentially problematic) pointers. 10211 /// 10212 /// \returns True when the operand is valid to use (even if as an extension). 10213 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10214 Expr *LHSExpr, Expr *RHSExpr) { 10215 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10216 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10217 if (!isLHSPointer && !isRHSPointer) return true; 10218 10219 QualType LHSPointeeTy, RHSPointeeTy; 10220 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10221 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10222 10223 // if both are pointers check if operation is valid wrt address spaces 10224 if (isLHSPointer && isRHSPointer) { 10225 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10226 S.Diag(Loc, 10227 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10228 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10229 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10230 return false; 10231 } 10232 } 10233 10234 // Check for arithmetic on pointers to incomplete types. 10235 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10236 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10237 if (isLHSVoidPtr || isRHSVoidPtr) { 10238 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10239 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10240 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10241 10242 return !S.getLangOpts().CPlusPlus; 10243 } 10244 10245 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10246 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10247 if (isLHSFuncPtr || isRHSFuncPtr) { 10248 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10249 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10250 RHSExpr); 10251 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10252 10253 return !S.getLangOpts().CPlusPlus; 10254 } 10255 10256 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10257 return false; 10258 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10259 return false; 10260 10261 return true; 10262 } 10263 10264 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10265 /// literal. 10266 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10267 Expr *LHSExpr, Expr *RHSExpr) { 10268 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10269 Expr* IndexExpr = RHSExpr; 10270 if (!StrExpr) { 10271 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10272 IndexExpr = LHSExpr; 10273 } 10274 10275 bool IsStringPlusInt = StrExpr && 10276 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10277 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10278 return; 10279 10280 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10281 Self.Diag(OpLoc, diag::warn_string_plus_int) 10282 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10283 10284 // Only print a fixit for "str" + int, not for int + "str". 10285 if (IndexExpr == RHSExpr) { 10286 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10287 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10288 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10289 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10290 << FixItHint::CreateInsertion(EndLoc, "]"); 10291 } else 10292 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10293 } 10294 10295 /// Emit a warning when adding a char literal to a string. 10296 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10297 Expr *LHSExpr, Expr *RHSExpr) { 10298 const Expr *StringRefExpr = LHSExpr; 10299 const CharacterLiteral *CharExpr = 10300 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10301 10302 if (!CharExpr) { 10303 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10304 StringRefExpr = RHSExpr; 10305 } 10306 10307 if (!CharExpr || !StringRefExpr) 10308 return; 10309 10310 const QualType StringType = StringRefExpr->getType(); 10311 10312 // Return if not a PointerType. 10313 if (!StringType->isAnyPointerType()) 10314 return; 10315 10316 // Return if not a CharacterType. 10317 if (!StringType->getPointeeType()->isAnyCharacterType()) 10318 return; 10319 10320 ASTContext &Ctx = Self.getASTContext(); 10321 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10322 10323 const QualType CharType = CharExpr->getType(); 10324 if (!CharType->isAnyCharacterType() && 10325 CharType->isIntegerType() && 10326 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10327 Self.Diag(OpLoc, diag::warn_string_plus_char) 10328 << DiagRange << Ctx.CharTy; 10329 } else { 10330 Self.Diag(OpLoc, diag::warn_string_plus_char) 10331 << DiagRange << CharExpr->getType(); 10332 } 10333 10334 // Only print a fixit for str + char, not for char + str. 10335 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10336 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10337 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10338 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10339 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10340 << FixItHint::CreateInsertion(EndLoc, "]"); 10341 } else { 10342 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10343 } 10344 } 10345 10346 /// Emit error when two pointers are incompatible. 10347 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10348 Expr *LHSExpr, Expr *RHSExpr) { 10349 assert(LHSExpr->getType()->isAnyPointerType()); 10350 assert(RHSExpr->getType()->isAnyPointerType()); 10351 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10352 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10353 << RHSExpr->getSourceRange(); 10354 } 10355 10356 // C99 6.5.6 10357 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10358 SourceLocation Loc, BinaryOperatorKind Opc, 10359 QualType* CompLHSTy) { 10360 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10361 10362 if (LHS.get()->getType()->isVectorType() || 10363 RHS.get()->getType()->isVectorType()) { 10364 QualType compType = CheckVectorOperands( 10365 LHS, RHS, Loc, CompLHSTy, 10366 /*AllowBothBool*/getLangOpts().AltiVec, 10367 /*AllowBoolConversions*/getLangOpts().ZVector); 10368 if (CompLHSTy) *CompLHSTy = compType; 10369 return compType; 10370 } 10371 10372 if (LHS.get()->getType()->isConstantMatrixType() || 10373 RHS.get()->getType()->isConstantMatrixType()) { 10374 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10375 } 10376 10377 QualType compType = UsualArithmeticConversions( 10378 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10379 if (LHS.isInvalid() || RHS.isInvalid()) 10380 return QualType(); 10381 10382 // Diagnose "string literal" '+' int and string '+' "char literal". 10383 if (Opc == BO_Add) { 10384 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10385 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10386 } 10387 10388 // handle the common case first (both operands are arithmetic). 10389 if (!compType.isNull() && compType->isArithmeticType()) { 10390 if (CompLHSTy) *CompLHSTy = compType; 10391 return compType; 10392 } 10393 10394 // Type-checking. Ultimately the pointer's going to be in PExp; 10395 // note that we bias towards the LHS being the pointer. 10396 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10397 10398 bool isObjCPointer; 10399 if (PExp->getType()->isPointerType()) { 10400 isObjCPointer = false; 10401 } else if (PExp->getType()->isObjCObjectPointerType()) { 10402 isObjCPointer = true; 10403 } else { 10404 std::swap(PExp, IExp); 10405 if (PExp->getType()->isPointerType()) { 10406 isObjCPointer = false; 10407 } else if (PExp->getType()->isObjCObjectPointerType()) { 10408 isObjCPointer = true; 10409 } else { 10410 return InvalidOperands(Loc, LHS, RHS); 10411 } 10412 } 10413 assert(PExp->getType()->isAnyPointerType()); 10414 10415 if (!IExp->getType()->isIntegerType()) 10416 return InvalidOperands(Loc, LHS, RHS); 10417 10418 // Adding to a null pointer results in undefined behavior. 10419 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10420 Context, Expr::NPC_ValueDependentIsNotNull)) { 10421 // In C++ adding zero to a null pointer is defined. 10422 Expr::EvalResult KnownVal; 10423 if (!getLangOpts().CPlusPlus || 10424 (!IExp->isValueDependent() && 10425 (!IExp->EvaluateAsInt(KnownVal, Context) || 10426 KnownVal.Val.getInt() != 0))) { 10427 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10428 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10429 Context, BO_Add, PExp, IExp); 10430 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10431 } 10432 } 10433 10434 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10435 return QualType(); 10436 10437 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10438 return QualType(); 10439 10440 // Check array bounds for pointer arithemtic 10441 CheckArrayAccess(PExp, IExp); 10442 10443 if (CompLHSTy) { 10444 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10445 if (LHSTy.isNull()) { 10446 LHSTy = LHS.get()->getType(); 10447 if (LHSTy->isPromotableIntegerType()) 10448 LHSTy = Context.getPromotedIntegerType(LHSTy); 10449 } 10450 *CompLHSTy = LHSTy; 10451 } 10452 10453 return PExp->getType(); 10454 } 10455 10456 // C99 6.5.6 10457 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10458 SourceLocation Loc, 10459 QualType* CompLHSTy) { 10460 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10461 10462 if (LHS.get()->getType()->isVectorType() || 10463 RHS.get()->getType()->isVectorType()) { 10464 QualType compType = CheckVectorOperands( 10465 LHS, RHS, Loc, CompLHSTy, 10466 /*AllowBothBool*/getLangOpts().AltiVec, 10467 /*AllowBoolConversions*/getLangOpts().ZVector); 10468 if (CompLHSTy) *CompLHSTy = compType; 10469 return compType; 10470 } 10471 10472 if (LHS.get()->getType()->isConstantMatrixType() || 10473 RHS.get()->getType()->isConstantMatrixType()) { 10474 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10475 } 10476 10477 QualType compType = UsualArithmeticConversions( 10478 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10479 if (LHS.isInvalid() || RHS.isInvalid()) 10480 return QualType(); 10481 10482 // Enforce type constraints: C99 6.5.6p3. 10483 10484 // Handle the common case first (both operands are arithmetic). 10485 if (!compType.isNull() && compType->isArithmeticType()) { 10486 if (CompLHSTy) *CompLHSTy = compType; 10487 return compType; 10488 } 10489 10490 // Either ptr - int or ptr - ptr. 10491 if (LHS.get()->getType()->isAnyPointerType()) { 10492 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10493 10494 // Diagnose bad cases where we step over interface counts. 10495 if (LHS.get()->getType()->isObjCObjectPointerType() && 10496 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10497 return QualType(); 10498 10499 // The result type of a pointer-int computation is the pointer type. 10500 if (RHS.get()->getType()->isIntegerType()) { 10501 // Subtracting from a null pointer should produce a warning. 10502 // The last argument to the diagnose call says this doesn't match the 10503 // GNU int-to-pointer idiom. 10504 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10505 Expr::NPC_ValueDependentIsNotNull)) { 10506 // In C++ adding zero to a null pointer is defined. 10507 Expr::EvalResult KnownVal; 10508 if (!getLangOpts().CPlusPlus || 10509 (!RHS.get()->isValueDependent() && 10510 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10511 KnownVal.Val.getInt() != 0))) { 10512 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10513 } 10514 } 10515 10516 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10517 return QualType(); 10518 10519 // Check array bounds for pointer arithemtic 10520 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10521 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10522 10523 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10524 return LHS.get()->getType(); 10525 } 10526 10527 // Handle pointer-pointer subtractions. 10528 if (const PointerType *RHSPTy 10529 = RHS.get()->getType()->getAs<PointerType>()) { 10530 QualType rpointee = RHSPTy->getPointeeType(); 10531 10532 if (getLangOpts().CPlusPlus) { 10533 // Pointee types must be the same: C++ [expr.add] 10534 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10535 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10536 } 10537 } else { 10538 // Pointee types must be compatible C99 6.5.6p3 10539 if (!Context.typesAreCompatible( 10540 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10541 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10542 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10543 return QualType(); 10544 } 10545 } 10546 10547 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10548 LHS.get(), RHS.get())) 10549 return QualType(); 10550 10551 // FIXME: Add warnings for nullptr - ptr. 10552 10553 // The pointee type may have zero size. As an extension, a structure or 10554 // union may have zero size or an array may have zero length. In this 10555 // case subtraction does not make sense. 10556 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10557 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10558 if (ElementSize.isZero()) { 10559 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10560 << rpointee.getUnqualifiedType() 10561 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10562 } 10563 } 10564 10565 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10566 return Context.getPointerDiffType(); 10567 } 10568 } 10569 10570 return InvalidOperands(Loc, LHS, RHS); 10571 } 10572 10573 static bool isScopedEnumerationType(QualType T) { 10574 if (const EnumType *ET = T->getAs<EnumType>()) 10575 return ET->getDecl()->isScoped(); 10576 return false; 10577 } 10578 10579 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10580 SourceLocation Loc, BinaryOperatorKind Opc, 10581 QualType LHSType) { 10582 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10583 // so skip remaining warnings as we don't want to modify values within Sema. 10584 if (S.getLangOpts().OpenCL) 10585 return; 10586 10587 // Check right/shifter operand 10588 Expr::EvalResult RHSResult; 10589 if (RHS.get()->isValueDependent() || 10590 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10591 return; 10592 llvm::APSInt Right = RHSResult.Val.getInt(); 10593 10594 if (Right.isNegative()) { 10595 S.DiagRuntimeBehavior(Loc, RHS.get(), 10596 S.PDiag(diag::warn_shift_negative) 10597 << RHS.get()->getSourceRange()); 10598 return; 10599 } 10600 10601 QualType LHSExprType = LHS.get()->getType(); 10602 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10603 if (LHSExprType->isExtIntType()) 10604 LeftSize = S.Context.getIntWidth(LHSExprType); 10605 else if (LHSExprType->isFixedPointType()) { 10606 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10607 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10608 } 10609 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10610 if (Right.uge(LeftBits)) { 10611 S.DiagRuntimeBehavior(Loc, RHS.get(), 10612 S.PDiag(diag::warn_shift_gt_typewidth) 10613 << RHS.get()->getSourceRange()); 10614 return; 10615 } 10616 10617 // FIXME: We probably need to handle fixed point types specially here. 10618 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10619 return; 10620 10621 // When left shifting an ICE which is signed, we can check for overflow which 10622 // according to C++ standards prior to C++2a has undefined behavior 10623 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10624 // more than the maximum value representable in the result type, so never 10625 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10626 // expression is still probably a bug.) 10627 Expr::EvalResult LHSResult; 10628 if (LHS.get()->isValueDependent() || 10629 LHSType->hasUnsignedIntegerRepresentation() || 10630 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10631 return; 10632 llvm::APSInt Left = LHSResult.Val.getInt(); 10633 10634 // If LHS does not have a signed type and non-negative value 10635 // then, the behavior is undefined before C++2a. Warn about it. 10636 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10637 !S.getLangOpts().CPlusPlus20) { 10638 S.DiagRuntimeBehavior(Loc, LHS.get(), 10639 S.PDiag(diag::warn_shift_lhs_negative) 10640 << LHS.get()->getSourceRange()); 10641 return; 10642 } 10643 10644 llvm::APInt ResultBits = 10645 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10646 if (LeftBits.uge(ResultBits)) 10647 return; 10648 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10649 Result = Result.shl(Right); 10650 10651 // Print the bit representation of the signed integer as an unsigned 10652 // hexadecimal number. 10653 SmallString<40> HexResult; 10654 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10655 10656 // If we are only missing a sign bit, this is less likely to result in actual 10657 // bugs -- if the result is cast back to an unsigned type, it will have the 10658 // expected value. Thus we place this behind a different warning that can be 10659 // turned off separately if needed. 10660 if (LeftBits == ResultBits - 1) { 10661 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10662 << HexResult << LHSType 10663 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10664 return; 10665 } 10666 10667 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10668 << HexResult.str() << Result.getMinSignedBits() << LHSType 10669 << Left.getBitWidth() << LHS.get()->getSourceRange() 10670 << RHS.get()->getSourceRange(); 10671 } 10672 10673 /// Return the resulting type when a vector is shifted 10674 /// by a scalar or vector shift amount. 10675 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10676 SourceLocation Loc, bool IsCompAssign) { 10677 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10678 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10679 !LHS.get()->getType()->isVectorType()) { 10680 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10681 << RHS.get()->getType() << LHS.get()->getType() 10682 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10683 return QualType(); 10684 } 10685 10686 if (!IsCompAssign) { 10687 LHS = S.UsualUnaryConversions(LHS.get()); 10688 if (LHS.isInvalid()) return QualType(); 10689 } 10690 10691 RHS = S.UsualUnaryConversions(RHS.get()); 10692 if (RHS.isInvalid()) return QualType(); 10693 10694 QualType LHSType = LHS.get()->getType(); 10695 // Note that LHS might be a scalar because the routine calls not only in 10696 // OpenCL case. 10697 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10698 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10699 10700 // Note that RHS might not be a vector. 10701 QualType RHSType = RHS.get()->getType(); 10702 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10703 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10704 10705 // The operands need to be integers. 10706 if (!LHSEleType->isIntegerType()) { 10707 S.Diag(Loc, diag::err_typecheck_expect_int) 10708 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10709 return QualType(); 10710 } 10711 10712 if (!RHSEleType->isIntegerType()) { 10713 S.Diag(Loc, diag::err_typecheck_expect_int) 10714 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10715 return QualType(); 10716 } 10717 10718 if (!LHSVecTy) { 10719 assert(RHSVecTy); 10720 if (IsCompAssign) 10721 return RHSType; 10722 if (LHSEleType != RHSEleType) { 10723 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10724 LHSEleType = RHSEleType; 10725 } 10726 QualType VecTy = 10727 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10728 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10729 LHSType = VecTy; 10730 } else if (RHSVecTy) { 10731 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10732 // are applied component-wise. So if RHS is a vector, then ensure 10733 // that the number of elements is the same as LHS... 10734 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10735 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10736 << LHS.get()->getType() << RHS.get()->getType() 10737 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10738 return QualType(); 10739 } 10740 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10741 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10742 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10743 if (LHSBT != RHSBT && 10744 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10745 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10746 << LHS.get()->getType() << RHS.get()->getType() 10747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10748 } 10749 } 10750 } else { 10751 // ...else expand RHS to match the number of elements in LHS. 10752 QualType VecTy = 10753 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10754 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10755 } 10756 10757 return LHSType; 10758 } 10759 10760 // C99 6.5.7 10761 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10762 SourceLocation Loc, BinaryOperatorKind Opc, 10763 bool IsCompAssign) { 10764 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10765 10766 // Vector shifts promote their scalar inputs to vector type. 10767 if (LHS.get()->getType()->isVectorType() || 10768 RHS.get()->getType()->isVectorType()) { 10769 if (LangOpts.ZVector) { 10770 // The shift operators for the z vector extensions work basically 10771 // like general shifts, except that neither the LHS nor the RHS is 10772 // allowed to be a "vector bool". 10773 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10774 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10775 return InvalidOperands(Loc, LHS, RHS); 10776 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10777 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10778 return InvalidOperands(Loc, LHS, RHS); 10779 } 10780 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10781 } 10782 10783 // Shifts don't perform usual arithmetic conversions, they just do integer 10784 // promotions on each operand. C99 6.5.7p3 10785 10786 // For the LHS, do usual unary conversions, but then reset them away 10787 // if this is a compound assignment. 10788 ExprResult OldLHS = LHS; 10789 LHS = UsualUnaryConversions(LHS.get()); 10790 if (LHS.isInvalid()) 10791 return QualType(); 10792 QualType LHSType = LHS.get()->getType(); 10793 if (IsCompAssign) LHS = OldLHS; 10794 10795 // The RHS is simpler. 10796 RHS = UsualUnaryConversions(RHS.get()); 10797 if (RHS.isInvalid()) 10798 return QualType(); 10799 QualType RHSType = RHS.get()->getType(); 10800 10801 // C99 6.5.7p2: Each of the operands shall have integer type. 10802 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10803 if ((!LHSType->isFixedPointOrIntegerType() && 10804 !LHSType->hasIntegerRepresentation()) || 10805 !RHSType->hasIntegerRepresentation()) 10806 return InvalidOperands(Loc, LHS, RHS); 10807 10808 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10809 // hasIntegerRepresentation() above instead of this. 10810 if (isScopedEnumerationType(LHSType) || 10811 isScopedEnumerationType(RHSType)) { 10812 return InvalidOperands(Loc, LHS, RHS); 10813 } 10814 // Sanity-check shift operands 10815 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10816 10817 // "The type of the result is that of the promoted left operand." 10818 return LHSType; 10819 } 10820 10821 /// Diagnose bad pointer comparisons. 10822 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10823 ExprResult &LHS, ExprResult &RHS, 10824 bool IsError) { 10825 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10826 : diag::ext_typecheck_comparison_of_distinct_pointers) 10827 << LHS.get()->getType() << RHS.get()->getType() 10828 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10829 } 10830 10831 /// Returns false if the pointers are converted to a composite type, 10832 /// true otherwise. 10833 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10834 ExprResult &LHS, ExprResult &RHS) { 10835 // C++ [expr.rel]p2: 10836 // [...] Pointer conversions (4.10) and qualification 10837 // conversions (4.4) are performed on pointer operands (or on 10838 // a pointer operand and a null pointer constant) to bring 10839 // them to their composite pointer type. [...] 10840 // 10841 // C++ [expr.eq]p1 uses the same notion for (in)equality 10842 // comparisons of pointers. 10843 10844 QualType LHSType = LHS.get()->getType(); 10845 QualType RHSType = RHS.get()->getType(); 10846 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10847 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10848 10849 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10850 if (T.isNull()) { 10851 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10852 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10853 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10854 else 10855 S.InvalidOperands(Loc, LHS, RHS); 10856 return true; 10857 } 10858 10859 return false; 10860 } 10861 10862 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10863 ExprResult &LHS, 10864 ExprResult &RHS, 10865 bool IsError) { 10866 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10867 : diag::ext_typecheck_comparison_of_fptr_to_void) 10868 << LHS.get()->getType() << RHS.get()->getType() 10869 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10870 } 10871 10872 static bool isObjCObjectLiteral(ExprResult &E) { 10873 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10874 case Stmt::ObjCArrayLiteralClass: 10875 case Stmt::ObjCDictionaryLiteralClass: 10876 case Stmt::ObjCStringLiteralClass: 10877 case Stmt::ObjCBoxedExprClass: 10878 return true; 10879 default: 10880 // Note that ObjCBoolLiteral is NOT an object literal! 10881 return false; 10882 } 10883 } 10884 10885 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10886 const ObjCObjectPointerType *Type = 10887 LHS->getType()->getAs<ObjCObjectPointerType>(); 10888 10889 // If this is not actually an Objective-C object, bail out. 10890 if (!Type) 10891 return false; 10892 10893 // Get the LHS object's interface type. 10894 QualType InterfaceType = Type->getPointeeType(); 10895 10896 // If the RHS isn't an Objective-C object, bail out. 10897 if (!RHS->getType()->isObjCObjectPointerType()) 10898 return false; 10899 10900 // Try to find the -isEqual: method. 10901 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10902 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10903 InterfaceType, 10904 /*IsInstance=*/true); 10905 if (!Method) { 10906 if (Type->isObjCIdType()) { 10907 // For 'id', just check the global pool. 10908 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10909 /*receiverId=*/true); 10910 } else { 10911 // Check protocols. 10912 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10913 /*IsInstance=*/true); 10914 } 10915 } 10916 10917 if (!Method) 10918 return false; 10919 10920 QualType T = Method->parameters()[0]->getType(); 10921 if (!T->isObjCObjectPointerType()) 10922 return false; 10923 10924 QualType R = Method->getReturnType(); 10925 if (!R->isScalarType()) 10926 return false; 10927 10928 return true; 10929 } 10930 10931 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10932 FromE = FromE->IgnoreParenImpCasts(); 10933 switch (FromE->getStmtClass()) { 10934 default: 10935 break; 10936 case Stmt::ObjCStringLiteralClass: 10937 // "string literal" 10938 return LK_String; 10939 case Stmt::ObjCArrayLiteralClass: 10940 // "array literal" 10941 return LK_Array; 10942 case Stmt::ObjCDictionaryLiteralClass: 10943 // "dictionary literal" 10944 return LK_Dictionary; 10945 case Stmt::BlockExprClass: 10946 return LK_Block; 10947 case Stmt::ObjCBoxedExprClass: { 10948 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10949 switch (Inner->getStmtClass()) { 10950 case Stmt::IntegerLiteralClass: 10951 case Stmt::FloatingLiteralClass: 10952 case Stmt::CharacterLiteralClass: 10953 case Stmt::ObjCBoolLiteralExprClass: 10954 case Stmt::CXXBoolLiteralExprClass: 10955 // "numeric literal" 10956 return LK_Numeric; 10957 case Stmt::ImplicitCastExprClass: { 10958 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10959 // Boolean literals can be represented by implicit casts. 10960 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10961 return LK_Numeric; 10962 break; 10963 } 10964 default: 10965 break; 10966 } 10967 return LK_Boxed; 10968 } 10969 } 10970 return LK_None; 10971 } 10972 10973 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10974 ExprResult &LHS, ExprResult &RHS, 10975 BinaryOperator::Opcode Opc){ 10976 Expr *Literal; 10977 Expr *Other; 10978 if (isObjCObjectLiteral(LHS)) { 10979 Literal = LHS.get(); 10980 Other = RHS.get(); 10981 } else { 10982 Literal = RHS.get(); 10983 Other = LHS.get(); 10984 } 10985 10986 // Don't warn on comparisons against nil. 10987 Other = Other->IgnoreParenCasts(); 10988 if (Other->isNullPointerConstant(S.getASTContext(), 10989 Expr::NPC_ValueDependentIsNotNull)) 10990 return; 10991 10992 // This should be kept in sync with warn_objc_literal_comparison. 10993 // LK_String should always be after the other literals, since it has its own 10994 // warning flag. 10995 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10996 assert(LiteralKind != Sema::LK_Block); 10997 if (LiteralKind == Sema::LK_None) { 10998 llvm_unreachable("Unknown Objective-C object literal kind"); 10999 } 11000 11001 if (LiteralKind == Sema::LK_String) 11002 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11003 << Literal->getSourceRange(); 11004 else 11005 S.Diag(Loc, diag::warn_objc_literal_comparison) 11006 << LiteralKind << Literal->getSourceRange(); 11007 11008 if (BinaryOperator::isEqualityOp(Opc) && 11009 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11010 SourceLocation Start = LHS.get()->getBeginLoc(); 11011 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11012 CharSourceRange OpRange = 11013 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11014 11015 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11016 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11017 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11018 << FixItHint::CreateInsertion(End, "]"); 11019 } 11020 } 11021 11022 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11023 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11024 ExprResult &RHS, SourceLocation Loc, 11025 BinaryOperatorKind Opc) { 11026 // Check that left hand side is !something. 11027 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11028 if (!UO || UO->getOpcode() != UO_LNot) return; 11029 11030 // Only check if the right hand side is non-bool arithmetic type. 11031 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11032 11033 // Make sure that the something in !something is not bool. 11034 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11035 if (SubExpr->isKnownToHaveBooleanValue()) return; 11036 11037 // Emit warning. 11038 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11039 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11040 << Loc << IsBitwiseOp; 11041 11042 // First note suggest !(x < y) 11043 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11044 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11045 FirstClose = S.getLocForEndOfToken(FirstClose); 11046 if (FirstClose.isInvalid()) 11047 FirstOpen = SourceLocation(); 11048 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11049 << IsBitwiseOp 11050 << FixItHint::CreateInsertion(FirstOpen, "(") 11051 << FixItHint::CreateInsertion(FirstClose, ")"); 11052 11053 // Second note suggests (!x) < y 11054 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11055 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11056 SecondClose = S.getLocForEndOfToken(SecondClose); 11057 if (SecondClose.isInvalid()) 11058 SecondOpen = SourceLocation(); 11059 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11060 << FixItHint::CreateInsertion(SecondOpen, "(") 11061 << FixItHint::CreateInsertion(SecondClose, ")"); 11062 } 11063 11064 // Returns true if E refers to a non-weak array. 11065 static bool checkForArray(const Expr *E) { 11066 const ValueDecl *D = nullptr; 11067 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11068 D = DR->getDecl(); 11069 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11070 if (Mem->isImplicitAccess()) 11071 D = Mem->getMemberDecl(); 11072 } 11073 if (!D) 11074 return false; 11075 return D->getType()->isArrayType() && !D->isWeak(); 11076 } 11077 11078 /// Diagnose some forms of syntactically-obvious tautological comparison. 11079 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11080 Expr *LHS, Expr *RHS, 11081 BinaryOperatorKind Opc) { 11082 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11083 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11084 11085 QualType LHSType = LHS->getType(); 11086 QualType RHSType = RHS->getType(); 11087 if (LHSType->hasFloatingRepresentation() || 11088 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11089 S.inTemplateInstantiation()) 11090 return; 11091 11092 // Comparisons between two array types are ill-formed for operator<=>, so 11093 // we shouldn't emit any additional warnings about it. 11094 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11095 return; 11096 11097 // For non-floating point types, check for self-comparisons of the form 11098 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11099 // often indicate logic errors in the program. 11100 // 11101 // NOTE: Don't warn about comparison expressions resulting from macro 11102 // expansion. Also don't warn about comparisons which are only self 11103 // comparisons within a template instantiation. The warnings should catch 11104 // obvious cases in the definition of the template anyways. The idea is to 11105 // warn when the typed comparison operator will always evaluate to the same 11106 // result. 11107 11108 // Used for indexing into %select in warn_comparison_always 11109 enum { 11110 AlwaysConstant, 11111 AlwaysTrue, 11112 AlwaysFalse, 11113 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11114 }; 11115 11116 // C++2a [depr.array.comp]: 11117 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11118 // operands of array type are deprecated. 11119 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11120 RHSStripped->getType()->isArrayType()) { 11121 S.Diag(Loc, diag::warn_depr_array_comparison) 11122 << LHS->getSourceRange() << RHS->getSourceRange() 11123 << LHSStripped->getType() << RHSStripped->getType(); 11124 // Carry on to produce the tautological comparison warning, if this 11125 // expression is potentially-evaluated, we can resolve the array to a 11126 // non-weak declaration, and so on. 11127 } 11128 11129 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11130 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11131 unsigned Result; 11132 switch (Opc) { 11133 case BO_EQ: 11134 case BO_LE: 11135 case BO_GE: 11136 Result = AlwaysTrue; 11137 break; 11138 case BO_NE: 11139 case BO_LT: 11140 case BO_GT: 11141 Result = AlwaysFalse; 11142 break; 11143 case BO_Cmp: 11144 Result = AlwaysEqual; 11145 break; 11146 default: 11147 Result = AlwaysConstant; 11148 break; 11149 } 11150 S.DiagRuntimeBehavior(Loc, nullptr, 11151 S.PDiag(diag::warn_comparison_always) 11152 << 0 /*self-comparison*/ 11153 << Result); 11154 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11155 // What is it always going to evaluate to? 11156 unsigned Result; 11157 switch (Opc) { 11158 case BO_EQ: // e.g. array1 == array2 11159 Result = AlwaysFalse; 11160 break; 11161 case BO_NE: // e.g. array1 != array2 11162 Result = AlwaysTrue; 11163 break; 11164 default: // e.g. array1 <= array2 11165 // The best we can say is 'a constant' 11166 Result = AlwaysConstant; 11167 break; 11168 } 11169 S.DiagRuntimeBehavior(Loc, nullptr, 11170 S.PDiag(diag::warn_comparison_always) 11171 << 1 /*array comparison*/ 11172 << Result); 11173 } 11174 } 11175 11176 if (isa<CastExpr>(LHSStripped)) 11177 LHSStripped = LHSStripped->IgnoreParenCasts(); 11178 if (isa<CastExpr>(RHSStripped)) 11179 RHSStripped = RHSStripped->IgnoreParenCasts(); 11180 11181 // Warn about comparisons against a string constant (unless the other 11182 // operand is null); the user probably wants string comparison function. 11183 Expr *LiteralString = nullptr; 11184 Expr *LiteralStringStripped = nullptr; 11185 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11186 !RHSStripped->isNullPointerConstant(S.Context, 11187 Expr::NPC_ValueDependentIsNull)) { 11188 LiteralString = LHS; 11189 LiteralStringStripped = LHSStripped; 11190 } else if ((isa<StringLiteral>(RHSStripped) || 11191 isa<ObjCEncodeExpr>(RHSStripped)) && 11192 !LHSStripped->isNullPointerConstant(S.Context, 11193 Expr::NPC_ValueDependentIsNull)) { 11194 LiteralString = RHS; 11195 LiteralStringStripped = RHSStripped; 11196 } 11197 11198 if (LiteralString) { 11199 S.DiagRuntimeBehavior(Loc, nullptr, 11200 S.PDiag(diag::warn_stringcompare) 11201 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11202 << LiteralString->getSourceRange()); 11203 } 11204 } 11205 11206 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11207 switch (CK) { 11208 default: { 11209 #ifndef NDEBUG 11210 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11211 << "\n"; 11212 #endif 11213 llvm_unreachable("unhandled cast kind"); 11214 } 11215 case CK_UserDefinedConversion: 11216 return ICK_Identity; 11217 case CK_LValueToRValue: 11218 return ICK_Lvalue_To_Rvalue; 11219 case CK_ArrayToPointerDecay: 11220 return ICK_Array_To_Pointer; 11221 case CK_FunctionToPointerDecay: 11222 return ICK_Function_To_Pointer; 11223 case CK_IntegralCast: 11224 return ICK_Integral_Conversion; 11225 case CK_FloatingCast: 11226 return ICK_Floating_Conversion; 11227 case CK_IntegralToFloating: 11228 case CK_FloatingToIntegral: 11229 return ICK_Floating_Integral; 11230 case CK_IntegralComplexCast: 11231 case CK_FloatingComplexCast: 11232 case CK_FloatingComplexToIntegralComplex: 11233 case CK_IntegralComplexToFloatingComplex: 11234 return ICK_Complex_Conversion; 11235 case CK_FloatingComplexToReal: 11236 case CK_FloatingRealToComplex: 11237 case CK_IntegralComplexToReal: 11238 case CK_IntegralRealToComplex: 11239 return ICK_Complex_Real; 11240 } 11241 } 11242 11243 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11244 QualType FromType, 11245 SourceLocation Loc) { 11246 // Check for a narrowing implicit conversion. 11247 StandardConversionSequence SCS; 11248 SCS.setAsIdentityConversion(); 11249 SCS.setToType(0, FromType); 11250 SCS.setToType(1, ToType); 11251 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11252 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11253 11254 APValue PreNarrowingValue; 11255 QualType PreNarrowingType; 11256 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11257 PreNarrowingType, 11258 /*IgnoreFloatToIntegralConversion*/ true)) { 11259 case NK_Dependent_Narrowing: 11260 // Implicit conversion to a narrower type, but the expression is 11261 // value-dependent so we can't tell whether it's actually narrowing. 11262 case NK_Not_Narrowing: 11263 return false; 11264 11265 case NK_Constant_Narrowing: 11266 // Implicit conversion to a narrower type, and the value is not a constant 11267 // expression. 11268 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11269 << /*Constant*/ 1 11270 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11271 return true; 11272 11273 case NK_Variable_Narrowing: 11274 // Implicit conversion to a narrower type, and the value is not a constant 11275 // expression. 11276 case NK_Type_Narrowing: 11277 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11278 << /*Constant*/ 0 << FromType << ToType; 11279 // TODO: It's not a constant expression, but what if the user intended it 11280 // to be? Can we produce notes to help them figure out why it isn't? 11281 return true; 11282 } 11283 llvm_unreachable("unhandled case in switch"); 11284 } 11285 11286 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11287 ExprResult &LHS, 11288 ExprResult &RHS, 11289 SourceLocation Loc) { 11290 QualType LHSType = LHS.get()->getType(); 11291 QualType RHSType = RHS.get()->getType(); 11292 // Dig out the original argument type and expression before implicit casts 11293 // were applied. These are the types/expressions we need to check the 11294 // [expr.spaceship] requirements against. 11295 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11296 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11297 QualType LHSStrippedType = LHSStripped.get()->getType(); 11298 QualType RHSStrippedType = RHSStripped.get()->getType(); 11299 11300 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11301 // other is not, the program is ill-formed. 11302 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11303 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11304 return QualType(); 11305 } 11306 11307 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11308 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11309 RHSStrippedType->isEnumeralType(); 11310 if (NumEnumArgs == 1) { 11311 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11312 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11313 if (OtherTy->hasFloatingRepresentation()) { 11314 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11315 return QualType(); 11316 } 11317 } 11318 if (NumEnumArgs == 2) { 11319 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11320 // type E, the operator yields the result of converting the operands 11321 // to the underlying type of E and applying <=> to the converted operands. 11322 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11323 S.InvalidOperands(Loc, LHS, RHS); 11324 return QualType(); 11325 } 11326 QualType IntType = 11327 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11328 assert(IntType->isArithmeticType()); 11329 11330 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11331 // promote the boolean type, and all other promotable integer types, to 11332 // avoid this. 11333 if (IntType->isPromotableIntegerType()) 11334 IntType = S.Context.getPromotedIntegerType(IntType); 11335 11336 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11337 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11338 LHSType = RHSType = IntType; 11339 } 11340 11341 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11342 // usual arithmetic conversions are applied to the operands. 11343 QualType Type = 11344 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11345 if (LHS.isInvalid() || RHS.isInvalid()) 11346 return QualType(); 11347 if (Type.isNull()) 11348 return S.InvalidOperands(Loc, LHS, RHS); 11349 11350 Optional<ComparisonCategoryType> CCT = 11351 getComparisonCategoryForBuiltinCmp(Type); 11352 if (!CCT) 11353 return S.InvalidOperands(Loc, LHS, RHS); 11354 11355 bool HasNarrowing = checkThreeWayNarrowingConversion( 11356 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11357 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11358 RHS.get()->getBeginLoc()); 11359 if (HasNarrowing) 11360 return QualType(); 11361 11362 assert(!Type.isNull() && "composite type for <=> has not been set"); 11363 11364 return S.CheckComparisonCategoryType( 11365 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11366 } 11367 11368 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11369 ExprResult &RHS, 11370 SourceLocation Loc, 11371 BinaryOperatorKind Opc) { 11372 if (Opc == BO_Cmp) 11373 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11374 11375 // C99 6.5.8p3 / C99 6.5.9p4 11376 QualType Type = 11377 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11378 if (LHS.isInvalid() || RHS.isInvalid()) 11379 return QualType(); 11380 if (Type.isNull()) 11381 return S.InvalidOperands(Loc, LHS, RHS); 11382 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11383 11384 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11385 return S.InvalidOperands(Loc, LHS, RHS); 11386 11387 // Check for comparisons of floating point operands using != and ==. 11388 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11389 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11390 11391 // The result of comparisons is 'bool' in C++, 'int' in C. 11392 return S.Context.getLogicalOperationType(); 11393 } 11394 11395 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11396 if (!NullE.get()->getType()->isAnyPointerType()) 11397 return; 11398 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11399 if (!E.get()->getType()->isAnyPointerType() && 11400 E.get()->isNullPointerConstant(Context, 11401 Expr::NPC_ValueDependentIsNotNull) == 11402 Expr::NPCK_ZeroExpression) { 11403 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11404 if (CL->getValue() == 0) 11405 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11406 << NullValue 11407 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11408 NullValue ? "NULL" : "(void *)0"); 11409 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11410 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11411 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11412 if (T == Context.CharTy) 11413 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11414 << NullValue 11415 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11416 NullValue ? "NULL" : "(void *)0"); 11417 } 11418 } 11419 } 11420 11421 // C99 6.5.8, C++ [expr.rel] 11422 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11423 SourceLocation Loc, 11424 BinaryOperatorKind Opc) { 11425 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11426 bool IsThreeWay = Opc == BO_Cmp; 11427 bool IsOrdered = IsRelational || IsThreeWay; 11428 auto IsAnyPointerType = [](ExprResult E) { 11429 QualType Ty = E.get()->getType(); 11430 return Ty->isPointerType() || Ty->isMemberPointerType(); 11431 }; 11432 11433 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11434 // type, array-to-pointer, ..., conversions are performed on both operands to 11435 // bring them to their composite type. 11436 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11437 // any type-related checks. 11438 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11439 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11440 if (LHS.isInvalid()) 11441 return QualType(); 11442 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11443 if (RHS.isInvalid()) 11444 return QualType(); 11445 } else { 11446 LHS = DefaultLvalueConversion(LHS.get()); 11447 if (LHS.isInvalid()) 11448 return QualType(); 11449 RHS = DefaultLvalueConversion(RHS.get()); 11450 if (RHS.isInvalid()) 11451 return QualType(); 11452 } 11453 11454 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11455 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11456 CheckPtrComparisonWithNullChar(LHS, RHS); 11457 CheckPtrComparisonWithNullChar(RHS, LHS); 11458 } 11459 11460 // Handle vector comparisons separately. 11461 if (LHS.get()->getType()->isVectorType() || 11462 RHS.get()->getType()->isVectorType()) 11463 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11464 11465 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11466 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11467 11468 QualType LHSType = LHS.get()->getType(); 11469 QualType RHSType = RHS.get()->getType(); 11470 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11471 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11472 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11473 11474 const Expr::NullPointerConstantKind LHSNullKind = 11475 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11476 const Expr::NullPointerConstantKind RHSNullKind = 11477 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11478 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11479 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11480 11481 auto computeResultTy = [&]() { 11482 if (Opc != BO_Cmp) 11483 return Context.getLogicalOperationType(); 11484 assert(getLangOpts().CPlusPlus); 11485 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11486 11487 QualType CompositeTy = LHS.get()->getType(); 11488 assert(!CompositeTy->isReferenceType()); 11489 11490 Optional<ComparisonCategoryType> CCT = 11491 getComparisonCategoryForBuiltinCmp(CompositeTy); 11492 if (!CCT) 11493 return InvalidOperands(Loc, LHS, RHS); 11494 11495 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11496 // P0946R0: Comparisons between a null pointer constant and an object 11497 // pointer result in std::strong_equality, which is ill-formed under 11498 // P1959R0. 11499 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11500 << (LHSIsNull ? LHS.get()->getSourceRange() 11501 : RHS.get()->getSourceRange()); 11502 return QualType(); 11503 } 11504 11505 return CheckComparisonCategoryType( 11506 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11507 }; 11508 11509 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11510 bool IsEquality = Opc == BO_EQ; 11511 if (RHSIsNull) 11512 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11513 RHS.get()->getSourceRange()); 11514 else 11515 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11516 LHS.get()->getSourceRange()); 11517 } 11518 11519 if ((LHSType->isIntegerType() && !LHSIsNull) || 11520 (RHSType->isIntegerType() && !RHSIsNull)) { 11521 // Skip normal pointer conversion checks in this case; we have better 11522 // diagnostics for this below. 11523 } else if (getLangOpts().CPlusPlus) { 11524 // Equality comparison of a function pointer to a void pointer is invalid, 11525 // but we allow it as an extension. 11526 // FIXME: If we really want to allow this, should it be part of composite 11527 // pointer type computation so it works in conditionals too? 11528 if (!IsOrdered && 11529 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11530 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11531 // This is a gcc extension compatibility comparison. 11532 // In a SFINAE context, we treat this as a hard error to maintain 11533 // conformance with the C++ standard. 11534 diagnoseFunctionPointerToVoidComparison( 11535 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11536 11537 if (isSFINAEContext()) 11538 return QualType(); 11539 11540 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11541 return computeResultTy(); 11542 } 11543 11544 // C++ [expr.eq]p2: 11545 // If at least one operand is a pointer [...] bring them to their 11546 // composite pointer type. 11547 // C++ [expr.spaceship]p6 11548 // If at least one of the operands is of pointer type, [...] bring them 11549 // to their composite pointer type. 11550 // C++ [expr.rel]p2: 11551 // If both operands are pointers, [...] bring them to their composite 11552 // pointer type. 11553 // For <=>, the only valid non-pointer types are arrays and functions, and 11554 // we already decayed those, so this is really the same as the relational 11555 // comparison rule. 11556 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11557 (IsOrdered ? 2 : 1) && 11558 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11559 RHSType->isObjCObjectPointerType()))) { 11560 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11561 return QualType(); 11562 return computeResultTy(); 11563 } 11564 } else if (LHSType->isPointerType() && 11565 RHSType->isPointerType()) { // C99 6.5.8p2 11566 // All of the following pointer-related warnings are GCC extensions, except 11567 // when handling null pointer constants. 11568 QualType LCanPointeeTy = 11569 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11570 QualType RCanPointeeTy = 11571 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11572 11573 // C99 6.5.9p2 and C99 6.5.8p2 11574 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11575 RCanPointeeTy.getUnqualifiedType())) { 11576 if (IsRelational) { 11577 // Pointers both need to point to complete or incomplete types 11578 if ((LCanPointeeTy->isIncompleteType() != 11579 RCanPointeeTy->isIncompleteType()) && 11580 !getLangOpts().C11) { 11581 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11582 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11583 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11584 << RCanPointeeTy->isIncompleteType(); 11585 } 11586 if (LCanPointeeTy->isFunctionType()) { 11587 // Valid unless a relational comparison of function pointers 11588 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11589 << LHSType << RHSType << LHS.get()->getSourceRange() 11590 << RHS.get()->getSourceRange(); 11591 } 11592 } 11593 } else if (!IsRelational && 11594 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11595 // Valid unless comparison between non-null pointer and function pointer 11596 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11597 && !LHSIsNull && !RHSIsNull) 11598 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11599 /*isError*/false); 11600 } else { 11601 // Invalid 11602 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11603 } 11604 if (LCanPointeeTy != RCanPointeeTy) { 11605 // Treat NULL constant as a special case in OpenCL. 11606 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11607 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11608 Diag(Loc, 11609 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11610 << LHSType << RHSType << 0 /* comparison */ 11611 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11612 } 11613 } 11614 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11615 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11616 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11617 : CK_BitCast; 11618 if (LHSIsNull && !RHSIsNull) 11619 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11620 else 11621 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11622 } 11623 return computeResultTy(); 11624 } 11625 11626 if (getLangOpts().CPlusPlus) { 11627 // C++ [expr.eq]p4: 11628 // Two operands of type std::nullptr_t or one operand of type 11629 // std::nullptr_t and the other a null pointer constant compare equal. 11630 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11631 if (LHSType->isNullPtrType()) { 11632 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11633 return computeResultTy(); 11634 } 11635 if (RHSType->isNullPtrType()) { 11636 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11637 return computeResultTy(); 11638 } 11639 } 11640 11641 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11642 // These aren't covered by the composite pointer type rules. 11643 if (!IsOrdered && RHSType->isNullPtrType() && 11644 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11645 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11646 return computeResultTy(); 11647 } 11648 if (!IsOrdered && LHSType->isNullPtrType() && 11649 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11650 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11651 return computeResultTy(); 11652 } 11653 11654 if (IsRelational && 11655 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11656 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11657 // HACK: Relational comparison of nullptr_t against a pointer type is 11658 // invalid per DR583, but we allow it within std::less<> and friends, 11659 // since otherwise common uses of it break. 11660 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11661 // friends to have std::nullptr_t overload candidates. 11662 DeclContext *DC = CurContext; 11663 if (isa<FunctionDecl>(DC)) 11664 DC = DC->getParent(); 11665 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11666 if (CTSD->isInStdNamespace() && 11667 llvm::StringSwitch<bool>(CTSD->getName()) 11668 .Cases("less", "less_equal", "greater", "greater_equal", true) 11669 .Default(false)) { 11670 if (RHSType->isNullPtrType()) 11671 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11672 else 11673 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11674 return computeResultTy(); 11675 } 11676 } 11677 } 11678 11679 // C++ [expr.eq]p2: 11680 // If at least one operand is a pointer to member, [...] bring them to 11681 // their composite pointer type. 11682 if (!IsOrdered && 11683 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11684 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11685 return QualType(); 11686 else 11687 return computeResultTy(); 11688 } 11689 } 11690 11691 // Handle block pointer types. 11692 if (!IsOrdered && LHSType->isBlockPointerType() && 11693 RHSType->isBlockPointerType()) { 11694 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11695 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11696 11697 if (!LHSIsNull && !RHSIsNull && 11698 !Context.typesAreCompatible(lpointee, rpointee)) { 11699 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11700 << LHSType << RHSType << LHS.get()->getSourceRange() 11701 << RHS.get()->getSourceRange(); 11702 } 11703 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11704 return computeResultTy(); 11705 } 11706 11707 // Allow block pointers to be compared with null pointer constants. 11708 if (!IsOrdered 11709 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11710 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11711 if (!LHSIsNull && !RHSIsNull) { 11712 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11713 ->getPointeeType()->isVoidType()) 11714 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11715 ->getPointeeType()->isVoidType()))) 11716 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11717 << LHSType << RHSType << LHS.get()->getSourceRange() 11718 << RHS.get()->getSourceRange(); 11719 } 11720 if (LHSIsNull && !RHSIsNull) 11721 LHS = ImpCastExprToType(LHS.get(), RHSType, 11722 RHSType->isPointerType() ? CK_BitCast 11723 : CK_AnyPointerToBlockPointerCast); 11724 else 11725 RHS = ImpCastExprToType(RHS.get(), LHSType, 11726 LHSType->isPointerType() ? CK_BitCast 11727 : CK_AnyPointerToBlockPointerCast); 11728 return computeResultTy(); 11729 } 11730 11731 if (LHSType->isObjCObjectPointerType() || 11732 RHSType->isObjCObjectPointerType()) { 11733 const PointerType *LPT = LHSType->getAs<PointerType>(); 11734 const PointerType *RPT = RHSType->getAs<PointerType>(); 11735 if (LPT || RPT) { 11736 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11737 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11738 11739 if (!LPtrToVoid && !RPtrToVoid && 11740 !Context.typesAreCompatible(LHSType, RHSType)) { 11741 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11742 /*isError*/false); 11743 } 11744 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11745 // the RHS, but we have test coverage for this behavior. 11746 // FIXME: Consider using convertPointersToCompositeType in C++. 11747 if (LHSIsNull && !RHSIsNull) { 11748 Expr *E = LHS.get(); 11749 if (getLangOpts().ObjCAutoRefCount) 11750 CheckObjCConversion(SourceRange(), RHSType, E, 11751 CCK_ImplicitConversion); 11752 LHS = ImpCastExprToType(E, RHSType, 11753 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11754 } 11755 else { 11756 Expr *E = RHS.get(); 11757 if (getLangOpts().ObjCAutoRefCount) 11758 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11759 /*Diagnose=*/true, 11760 /*DiagnoseCFAudited=*/false, Opc); 11761 RHS = ImpCastExprToType(E, LHSType, 11762 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11763 } 11764 return computeResultTy(); 11765 } 11766 if (LHSType->isObjCObjectPointerType() && 11767 RHSType->isObjCObjectPointerType()) { 11768 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11769 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11770 /*isError*/false); 11771 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11772 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11773 11774 if (LHSIsNull && !RHSIsNull) 11775 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11776 else 11777 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11778 return computeResultTy(); 11779 } 11780 11781 if (!IsOrdered && LHSType->isBlockPointerType() && 11782 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11783 LHS = ImpCastExprToType(LHS.get(), RHSType, 11784 CK_BlockPointerToObjCPointerCast); 11785 return computeResultTy(); 11786 } else if (!IsOrdered && 11787 LHSType->isBlockCompatibleObjCPointerType(Context) && 11788 RHSType->isBlockPointerType()) { 11789 RHS = ImpCastExprToType(RHS.get(), LHSType, 11790 CK_BlockPointerToObjCPointerCast); 11791 return computeResultTy(); 11792 } 11793 } 11794 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11795 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11796 unsigned DiagID = 0; 11797 bool isError = false; 11798 if (LangOpts.DebuggerSupport) { 11799 // Under a debugger, allow the comparison of pointers to integers, 11800 // since users tend to want to compare addresses. 11801 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11802 (RHSIsNull && RHSType->isIntegerType())) { 11803 if (IsOrdered) { 11804 isError = getLangOpts().CPlusPlus; 11805 DiagID = 11806 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11807 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11808 } 11809 } else if (getLangOpts().CPlusPlus) { 11810 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11811 isError = true; 11812 } else if (IsOrdered) 11813 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11814 else 11815 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11816 11817 if (DiagID) { 11818 Diag(Loc, DiagID) 11819 << LHSType << RHSType << LHS.get()->getSourceRange() 11820 << RHS.get()->getSourceRange(); 11821 if (isError) 11822 return QualType(); 11823 } 11824 11825 if (LHSType->isIntegerType()) 11826 LHS = ImpCastExprToType(LHS.get(), RHSType, 11827 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11828 else 11829 RHS = ImpCastExprToType(RHS.get(), LHSType, 11830 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11831 return computeResultTy(); 11832 } 11833 11834 // Handle block pointers. 11835 if (!IsOrdered && RHSIsNull 11836 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11837 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11838 return computeResultTy(); 11839 } 11840 if (!IsOrdered && LHSIsNull 11841 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11842 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11843 return computeResultTy(); 11844 } 11845 11846 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11847 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11848 return computeResultTy(); 11849 } 11850 11851 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11852 return computeResultTy(); 11853 } 11854 11855 if (LHSIsNull && RHSType->isQueueT()) { 11856 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11857 return computeResultTy(); 11858 } 11859 11860 if (LHSType->isQueueT() && RHSIsNull) { 11861 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11862 return computeResultTy(); 11863 } 11864 } 11865 11866 return InvalidOperands(Loc, LHS, RHS); 11867 } 11868 11869 // Return a signed ext_vector_type that is of identical size and number of 11870 // elements. For floating point vectors, return an integer type of identical 11871 // size and number of elements. In the non ext_vector_type case, search from 11872 // the largest type to the smallest type to avoid cases where long long == long, 11873 // where long gets picked over long long. 11874 QualType Sema::GetSignedVectorType(QualType V) { 11875 const VectorType *VTy = V->castAs<VectorType>(); 11876 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11877 11878 if (isa<ExtVectorType>(VTy)) { 11879 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11880 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11881 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11882 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11883 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11884 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11885 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11886 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11887 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11888 "Unhandled vector element size in vector compare"); 11889 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11890 } 11891 11892 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11893 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11894 VectorType::GenericVector); 11895 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11896 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11897 VectorType::GenericVector); 11898 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11899 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11900 VectorType::GenericVector); 11901 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11902 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11903 VectorType::GenericVector); 11904 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11905 "Unhandled vector element size in vector compare"); 11906 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11907 VectorType::GenericVector); 11908 } 11909 11910 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11911 /// operates on extended vector types. Instead of producing an IntTy result, 11912 /// like a scalar comparison, a vector comparison produces a vector of integer 11913 /// types. 11914 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11915 SourceLocation Loc, 11916 BinaryOperatorKind Opc) { 11917 if (Opc == BO_Cmp) { 11918 Diag(Loc, diag::err_three_way_vector_comparison); 11919 return QualType(); 11920 } 11921 11922 // Check to make sure we're operating on vectors of the same type and width, 11923 // Allowing one side to be a scalar of element type. 11924 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11925 /*AllowBothBool*/true, 11926 /*AllowBoolConversions*/getLangOpts().ZVector); 11927 if (vType.isNull()) 11928 return vType; 11929 11930 QualType LHSType = LHS.get()->getType(); 11931 11932 // If AltiVec, the comparison results in a numeric type, i.e. 11933 // bool for C++, int for C 11934 if (getLangOpts().AltiVec && 11935 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11936 return Context.getLogicalOperationType(); 11937 11938 // For non-floating point types, check for self-comparisons of the form 11939 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11940 // often indicate logic errors in the program. 11941 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11942 11943 // Check for comparisons of floating point operands using != and ==. 11944 if (BinaryOperator::isEqualityOp(Opc) && 11945 LHSType->hasFloatingRepresentation()) { 11946 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11947 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11948 } 11949 11950 // Return a signed type for the vector. 11951 return GetSignedVectorType(vType); 11952 } 11953 11954 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11955 const ExprResult &XorRHS, 11956 const SourceLocation Loc) { 11957 // Do not diagnose macros. 11958 if (Loc.isMacroID()) 11959 return; 11960 11961 bool Negative = false; 11962 bool ExplicitPlus = false; 11963 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11964 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11965 11966 if (!LHSInt) 11967 return; 11968 if (!RHSInt) { 11969 // Check negative literals. 11970 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11971 UnaryOperatorKind Opc = UO->getOpcode(); 11972 if (Opc != UO_Minus && Opc != UO_Plus) 11973 return; 11974 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11975 if (!RHSInt) 11976 return; 11977 Negative = (Opc == UO_Minus); 11978 ExplicitPlus = !Negative; 11979 } else { 11980 return; 11981 } 11982 } 11983 11984 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11985 llvm::APInt RightSideValue = RHSInt->getValue(); 11986 if (LeftSideValue != 2 && LeftSideValue != 10) 11987 return; 11988 11989 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11990 return; 11991 11992 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11993 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11994 llvm::StringRef ExprStr = 11995 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11996 11997 CharSourceRange XorRange = 11998 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11999 llvm::StringRef XorStr = 12000 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12001 // Do not diagnose if xor keyword/macro is used. 12002 if (XorStr == "xor") 12003 return; 12004 12005 std::string LHSStr = std::string(Lexer::getSourceText( 12006 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12007 S.getSourceManager(), S.getLangOpts())); 12008 std::string RHSStr = std::string(Lexer::getSourceText( 12009 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12010 S.getSourceManager(), S.getLangOpts())); 12011 12012 if (Negative) { 12013 RightSideValue = -RightSideValue; 12014 RHSStr = "-" + RHSStr; 12015 } else if (ExplicitPlus) { 12016 RHSStr = "+" + RHSStr; 12017 } 12018 12019 StringRef LHSStrRef = LHSStr; 12020 StringRef RHSStrRef = RHSStr; 12021 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12022 // literals. 12023 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12024 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12025 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12026 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12027 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12028 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12029 LHSStrRef.find('\'') != StringRef::npos || 12030 RHSStrRef.find('\'') != StringRef::npos) 12031 return; 12032 12033 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12034 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12035 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12036 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12037 std::string SuggestedExpr = "1 << " + RHSStr; 12038 bool Overflow = false; 12039 llvm::APInt One = (LeftSideValue - 1); 12040 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12041 if (Overflow) { 12042 if (RightSideIntValue < 64) 12043 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12044 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12045 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12046 else if (RightSideIntValue == 64) 12047 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12048 else 12049 return; 12050 } else { 12051 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12052 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12053 << PowValue.toString(10, true) 12054 << FixItHint::CreateReplacement( 12055 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12056 } 12057 12058 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12059 } else if (LeftSideValue == 10) { 12060 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12061 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12062 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12063 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12064 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12065 } 12066 } 12067 12068 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12069 SourceLocation Loc) { 12070 // Ensure that either both operands are of the same vector type, or 12071 // one operand is of a vector type and the other is of its element type. 12072 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12073 /*AllowBothBool*/true, 12074 /*AllowBoolConversions*/false); 12075 if (vType.isNull()) 12076 return InvalidOperands(Loc, LHS, RHS); 12077 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12078 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12079 return InvalidOperands(Loc, LHS, RHS); 12080 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12081 // usage of the logical operators && and || with vectors in C. This 12082 // check could be notionally dropped. 12083 if (!getLangOpts().CPlusPlus && 12084 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12085 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12086 12087 return GetSignedVectorType(LHS.get()->getType()); 12088 } 12089 12090 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12091 SourceLocation Loc, 12092 bool IsCompAssign) { 12093 if (!IsCompAssign) { 12094 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12095 if (LHS.isInvalid()) 12096 return QualType(); 12097 } 12098 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12099 if (RHS.isInvalid()) 12100 return QualType(); 12101 12102 // For conversion purposes, we ignore any qualifiers. 12103 // For example, "const float" and "float" are equivalent. 12104 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12105 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12106 12107 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12108 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12109 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12110 12111 if (Context.hasSameType(LHSType, RHSType)) 12112 return LHSType; 12113 12114 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12115 // case we have to return InvalidOperands. 12116 ExprResult OriginalLHS = LHS; 12117 ExprResult OriginalRHS = RHS; 12118 if (LHSMatType && !RHSMatType) { 12119 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12120 if (!RHS.isInvalid()) 12121 return LHSType; 12122 12123 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12124 } 12125 12126 if (!LHSMatType && RHSMatType) { 12127 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12128 if (!LHS.isInvalid()) 12129 return RHSType; 12130 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12131 } 12132 12133 return InvalidOperands(Loc, LHS, RHS); 12134 } 12135 12136 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12137 SourceLocation Loc, 12138 bool IsCompAssign) { 12139 if (!IsCompAssign) { 12140 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12141 if (LHS.isInvalid()) 12142 return QualType(); 12143 } 12144 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12145 if (RHS.isInvalid()) 12146 return QualType(); 12147 12148 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12149 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12150 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12151 12152 if (LHSMatType && RHSMatType) { 12153 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12154 return InvalidOperands(Loc, LHS, RHS); 12155 12156 if (!Context.hasSameType(LHSMatType->getElementType(), 12157 RHSMatType->getElementType())) 12158 return InvalidOperands(Loc, LHS, RHS); 12159 12160 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12161 LHSMatType->getNumRows(), 12162 RHSMatType->getNumColumns()); 12163 } 12164 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12165 } 12166 12167 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12168 SourceLocation Loc, 12169 BinaryOperatorKind Opc) { 12170 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12171 12172 bool IsCompAssign = 12173 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12174 12175 if (LHS.get()->getType()->isVectorType() || 12176 RHS.get()->getType()->isVectorType()) { 12177 if (LHS.get()->getType()->hasIntegerRepresentation() && 12178 RHS.get()->getType()->hasIntegerRepresentation()) 12179 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12180 /*AllowBothBool*/true, 12181 /*AllowBoolConversions*/getLangOpts().ZVector); 12182 return InvalidOperands(Loc, LHS, RHS); 12183 } 12184 12185 if (Opc == BO_And) 12186 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12187 12188 if (LHS.get()->getType()->hasFloatingRepresentation() || 12189 RHS.get()->getType()->hasFloatingRepresentation()) 12190 return InvalidOperands(Loc, LHS, RHS); 12191 12192 ExprResult LHSResult = LHS, RHSResult = RHS; 12193 QualType compType = UsualArithmeticConversions( 12194 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12195 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12196 return QualType(); 12197 LHS = LHSResult.get(); 12198 RHS = RHSResult.get(); 12199 12200 if (Opc == BO_Xor) 12201 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12202 12203 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12204 return compType; 12205 return InvalidOperands(Loc, LHS, RHS); 12206 } 12207 12208 // C99 6.5.[13,14] 12209 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12210 SourceLocation Loc, 12211 BinaryOperatorKind Opc) { 12212 // Check vector operands differently. 12213 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12214 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12215 12216 bool EnumConstantInBoolContext = false; 12217 for (const ExprResult &HS : {LHS, RHS}) { 12218 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12219 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12220 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12221 EnumConstantInBoolContext = true; 12222 } 12223 } 12224 12225 if (EnumConstantInBoolContext) 12226 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12227 12228 // Diagnose cases where the user write a logical and/or but probably meant a 12229 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12230 // is a constant. 12231 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12232 !LHS.get()->getType()->isBooleanType() && 12233 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12234 // Don't warn in macros or template instantiations. 12235 !Loc.isMacroID() && !inTemplateInstantiation()) { 12236 // If the RHS can be constant folded, and if it constant folds to something 12237 // that isn't 0 or 1 (which indicate a potential logical operation that 12238 // happened to fold to true/false) then warn. 12239 // Parens on the RHS are ignored. 12240 Expr::EvalResult EVResult; 12241 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12242 llvm::APSInt Result = EVResult.Val.getInt(); 12243 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12244 !RHS.get()->getExprLoc().isMacroID()) || 12245 (Result != 0 && Result != 1)) { 12246 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12247 << RHS.get()->getSourceRange() 12248 << (Opc == BO_LAnd ? "&&" : "||"); 12249 // Suggest replacing the logical operator with the bitwise version 12250 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12251 << (Opc == BO_LAnd ? "&" : "|") 12252 << FixItHint::CreateReplacement(SourceRange( 12253 Loc, getLocForEndOfToken(Loc)), 12254 Opc == BO_LAnd ? "&" : "|"); 12255 if (Opc == BO_LAnd) 12256 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12257 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12258 << FixItHint::CreateRemoval( 12259 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12260 RHS.get()->getEndLoc())); 12261 } 12262 } 12263 } 12264 12265 if (!Context.getLangOpts().CPlusPlus) { 12266 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12267 // not operate on the built-in scalar and vector float types. 12268 if (Context.getLangOpts().OpenCL && 12269 Context.getLangOpts().OpenCLVersion < 120) { 12270 if (LHS.get()->getType()->isFloatingType() || 12271 RHS.get()->getType()->isFloatingType()) 12272 return InvalidOperands(Loc, LHS, RHS); 12273 } 12274 12275 LHS = UsualUnaryConversions(LHS.get()); 12276 if (LHS.isInvalid()) 12277 return QualType(); 12278 12279 RHS = UsualUnaryConversions(RHS.get()); 12280 if (RHS.isInvalid()) 12281 return QualType(); 12282 12283 if (!LHS.get()->getType()->isScalarType() || 12284 !RHS.get()->getType()->isScalarType()) 12285 return InvalidOperands(Loc, LHS, RHS); 12286 12287 return Context.IntTy; 12288 } 12289 12290 // The following is safe because we only use this method for 12291 // non-overloadable operands. 12292 12293 // C++ [expr.log.and]p1 12294 // C++ [expr.log.or]p1 12295 // The operands are both contextually converted to type bool. 12296 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12297 if (LHSRes.isInvalid()) 12298 return InvalidOperands(Loc, LHS, RHS); 12299 LHS = LHSRes; 12300 12301 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12302 if (RHSRes.isInvalid()) 12303 return InvalidOperands(Loc, LHS, RHS); 12304 RHS = RHSRes; 12305 12306 // C++ [expr.log.and]p2 12307 // C++ [expr.log.or]p2 12308 // The result is a bool. 12309 return Context.BoolTy; 12310 } 12311 12312 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12313 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12314 if (!ME) return false; 12315 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12316 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12317 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12318 if (!Base) return false; 12319 return Base->getMethodDecl() != nullptr; 12320 } 12321 12322 /// Is the given expression (which must be 'const') a reference to a 12323 /// variable which was originally non-const, but which has become 12324 /// 'const' due to being captured within a block? 12325 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12326 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12327 assert(E->isLValue() && E->getType().isConstQualified()); 12328 E = E->IgnoreParens(); 12329 12330 // Must be a reference to a declaration from an enclosing scope. 12331 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12332 if (!DRE) return NCCK_None; 12333 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12334 12335 // The declaration must be a variable which is not declared 'const'. 12336 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12337 if (!var) return NCCK_None; 12338 if (var->getType().isConstQualified()) return NCCK_None; 12339 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12340 12341 // Decide whether the first capture was for a block or a lambda. 12342 DeclContext *DC = S.CurContext, *Prev = nullptr; 12343 // Decide whether the first capture was for a block or a lambda. 12344 while (DC) { 12345 // For init-capture, it is possible that the variable belongs to the 12346 // template pattern of the current context. 12347 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12348 if (var->isInitCapture() && 12349 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12350 break; 12351 if (DC == var->getDeclContext()) 12352 break; 12353 Prev = DC; 12354 DC = DC->getParent(); 12355 } 12356 // Unless we have an init-capture, we've gone one step too far. 12357 if (!var->isInitCapture()) 12358 DC = Prev; 12359 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12360 } 12361 12362 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12363 Ty = Ty.getNonReferenceType(); 12364 if (IsDereference && Ty->isPointerType()) 12365 Ty = Ty->getPointeeType(); 12366 return !Ty.isConstQualified(); 12367 } 12368 12369 // Update err_typecheck_assign_const and note_typecheck_assign_const 12370 // when this enum is changed. 12371 enum { 12372 ConstFunction, 12373 ConstVariable, 12374 ConstMember, 12375 ConstMethod, 12376 NestedConstMember, 12377 ConstUnknown, // Keep as last element 12378 }; 12379 12380 /// Emit the "read-only variable not assignable" error and print notes to give 12381 /// more information about why the variable is not assignable, such as pointing 12382 /// to the declaration of a const variable, showing that a method is const, or 12383 /// that the function is returning a const reference. 12384 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12385 SourceLocation Loc) { 12386 SourceRange ExprRange = E->getSourceRange(); 12387 12388 // Only emit one error on the first const found. All other consts will emit 12389 // a note to the error. 12390 bool DiagnosticEmitted = false; 12391 12392 // Track if the current expression is the result of a dereference, and if the 12393 // next checked expression is the result of a dereference. 12394 bool IsDereference = false; 12395 bool NextIsDereference = false; 12396 12397 // Loop to process MemberExpr chains. 12398 while (true) { 12399 IsDereference = NextIsDereference; 12400 12401 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12402 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12403 NextIsDereference = ME->isArrow(); 12404 const ValueDecl *VD = ME->getMemberDecl(); 12405 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12406 // Mutable fields can be modified even if the class is const. 12407 if (Field->isMutable()) { 12408 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12409 break; 12410 } 12411 12412 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12413 if (!DiagnosticEmitted) { 12414 S.Diag(Loc, diag::err_typecheck_assign_const) 12415 << ExprRange << ConstMember << false /*static*/ << Field 12416 << Field->getType(); 12417 DiagnosticEmitted = true; 12418 } 12419 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12420 << ConstMember << false /*static*/ << Field << Field->getType() 12421 << Field->getSourceRange(); 12422 } 12423 E = ME->getBase(); 12424 continue; 12425 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12426 if (VDecl->getType().isConstQualified()) { 12427 if (!DiagnosticEmitted) { 12428 S.Diag(Loc, diag::err_typecheck_assign_const) 12429 << ExprRange << ConstMember << true /*static*/ << VDecl 12430 << VDecl->getType(); 12431 DiagnosticEmitted = true; 12432 } 12433 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12434 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12435 << VDecl->getSourceRange(); 12436 } 12437 // Static fields do not inherit constness from parents. 12438 break; 12439 } 12440 break; // End MemberExpr 12441 } else if (const ArraySubscriptExpr *ASE = 12442 dyn_cast<ArraySubscriptExpr>(E)) { 12443 E = ASE->getBase()->IgnoreParenImpCasts(); 12444 continue; 12445 } else if (const ExtVectorElementExpr *EVE = 12446 dyn_cast<ExtVectorElementExpr>(E)) { 12447 E = EVE->getBase()->IgnoreParenImpCasts(); 12448 continue; 12449 } 12450 break; 12451 } 12452 12453 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12454 // Function calls 12455 const FunctionDecl *FD = CE->getDirectCallee(); 12456 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12457 if (!DiagnosticEmitted) { 12458 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12459 << ConstFunction << FD; 12460 DiagnosticEmitted = true; 12461 } 12462 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12463 diag::note_typecheck_assign_const) 12464 << ConstFunction << FD << FD->getReturnType() 12465 << FD->getReturnTypeSourceRange(); 12466 } 12467 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12468 // Point to variable declaration. 12469 if (const ValueDecl *VD = DRE->getDecl()) { 12470 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12471 if (!DiagnosticEmitted) { 12472 S.Diag(Loc, diag::err_typecheck_assign_const) 12473 << ExprRange << ConstVariable << VD << VD->getType(); 12474 DiagnosticEmitted = true; 12475 } 12476 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12477 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12478 } 12479 } 12480 } else if (isa<CXXThisExpr>(E)) { 12481 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12482 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12483 if (MD->isConst()) { 12484 if (!DiagnosticEmitted) { 12485 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12486 << ConstMethod << MD; 12487 DiagnosticEmitted = true; 12488 } 12489 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12490 << ConstMethod << MD << MD->getSourceRange(); 12491 } 12492 } 12493 } 12494 } 12495 12496 if (DiagnosticEmitted) 12497 return; 12498 12499 // Can't determine a more specific message, so display the generic error. 12500 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12501 } 12502 12503 enum OriginalExprKind { 12504 OEK_Variable, 12505 OEK_Member, 12506 OEK_LValue 12507 }; 12508 12509 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12510 const RecordType *Ty, 12511 SourceLocation Loc, SourceRange Range, 12512 OriginalExprKind OEK, 12513 bool &DiagnosticEmitted) { 12514 std::vector<const RecordType *> RecordTypeList; 12515 RecordTypeList.push_back(Ty); 12516 unsigned NextToCheckIndex = 0; 12517 // We walk the record hierarchy breadth-first to ensure that we print 12518 // diagnostics in field nesting order. 12519 while (RecordTypeList.size() > NextToCheckIndex) { 12520 bool IsNested = NextToCheckIndex > 0; 12521 for (const FieldDecl *Field : 12522 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12523 // First, check every field for constness. 12524 QualType FieldTy = Field->getType(); 12525 if (FieldTy.isConstQualified()) { 12526 if (!DiagnosticEmitted) { 12527 S.Diag(Loc, diag::err_typecheck_assign_const) 12528 << Range << NestedConstMember << OEK << VD 12529 << IsNested << Field; 12530 DiagnosticEmitted = true; 12531 } 12532 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12533 << NestedConstMember << IsNested << Field 12534 << FieldTy << Field->getSourceRange(); 12535 } 12536 12537 // Then we append it to the list to check next in order. 12538 FieldTy = FieldTy.getCanonicalType(); 12539 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12540 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12541 RecordTypeList.push_back(FieldRecTy); 12542 } 12543 } 12544 ++NextToCheckIndex; 12545 } 12546 } 12547 12548 /// Emit an error for the case where a record we are trying to assign to has a 12549 /// const-qualified field somewhere in its hierarchy. 12550 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12551 SourceLocation Loc) { 12552 QualType Ty = E->getType(); 12553 assert(Ty->isRecordType() && "lvalue was not record?"); 12554 SourceRange Range = E->getSourceRange(); 12555 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12556 bool DiagEmitted = false; 12557 12558 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12559 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12560 Range, OEK_Member, DiagEmitted); 12561 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12562 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12563 Range, OEK_Variable, DiagEmitted); 12564 else 12565 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12566 Range, OEK_LValue, DiagEmitted); 12567 if (!DiagEmitted) 12568 DiagnoseConstAssignment(S, E, Loc); 12569 } 12570 12571 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12572 /// emit an error and return true. If so, return false. 12573 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12574 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12575 12576 S.CheckShadowingDeclModification(E, Loc); 12577 12578 SourceLocation OrigLoc = Loc; 12579 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12580 &Loc); 12581 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12582 IsLV = Expr::MLV_InvalidMessageExpression; 12583 if (IsLV == Expr::MLV_Valid) 12584 return false; 12585 12586 unsigned DiagID = 0; 12587 bool NeedType = false; 12588 switch (IsLV) { // C99 6.5.16p2 12589 case Expr::MLV_ConstQualified: 12590 // Use a specialized diagnostic when we're assigning to an object 12591 // from an enclosing function or block. 12592 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12593 if (NCCK == NCCK_Block) 12594 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12595 else 12596 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12597 break; 12598 } 12599 12600 // In ARC, use some specialized diagnostics for occasions where we 12601 // infer 'const'. These are always pseudo-strong variables. 12602 if (S.getLangOpts().ObjCAutoRefCount) { 12603 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12604 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12605 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12606 12607 // Use the normal diagnostic if it's pseudo-__strong but the 12608 // user actually wrote 'const'. 12609 if (var->isARCPseudoStrong() && 12610 (!var->getTypeSourceInfo() || 12611 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12612 // There are three pseudo-strong cases: 12613 // - self 12614 ObjCMethodDecl *method = S.getCurMethodDecl(); 12615 if (method && var == method->getSelfDecl()) { 12616 DiagID = method->isClassMethod() 12617 ? diag::err_typecheck_arc_assign_self_class_method 12618 : diag::err_typecheck_arc_assign_self; 12619 12620 // - Objective-C externally_retained attribute. 12621 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12622 isa<ParmVarDecl>(var)) { 12623 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12624 12625 // - fast enumeration variables 12626 } else { 12627 DiagID = diag::err_typecheck_arr_assign_enumeration; 12628 } 12629 12630 SourceRange Assign; 12631 if (Loc != OrigLoc) 12632 Assign = SourceRange(OrigLoc, OrigLoc); 12633 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12634 // We need to preserve the AST regardless, so migration tool 12635 // can do its job. 12636 return false; 12637 } 12638 } 12639 } 12640 12641 // If none of the special cases above are triggered, then this is a 12642 // simple const assignment. 12643 if (DiagID == 0) { 12644 DiagnoseConstAssignment(S, E, Loc); 12645 return true; 12646 } 12647 12648 break; 12649 case Expr::MLV_ConstAddrSpace: 12650 DiagnoseConstAssignment(S, E, Loc); 12651 return true; 12652 case Expr::MLV_ConstQualifiedField: 12653 DiagnoseRecursiveConstFields(S, E, Loc); 12654 return true; 12655 case Expr::MLV_ArrayType: 12656 case Expr::MLV_ArrayTemporary: 12657 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12658 NeedType = true; 12659 break; 12660 case Expr::MLV_NotObjectType: 12661 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12662 NeedType = true; 12663 break; 12664 case Expr::MLV_LValueCast: 12665 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12666 break; 12667 case Expr::MLV_Valid: 12668 llvm_unreachable("did not take early return for MLV_Valid"); 12669 case Expr::MLV_InvalidExpression: 12670 case Expr::MLV_MemberFunction: 12671 case Expr::MLV_ClassTemporary: 12672 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12673 break; 12674 case Expr::MLV_IncompleteType: 12675 case Expr::MLV_IncompleteVoidType: 12676 return S.RequireCompleteType(Loc, E->getType(), 12677 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12678 case Expr::MLV_DuplicateVectorComponents: 12679 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12680 break; 12681 case Expr::MLV_NoSetterProperty: 12682 llvm_unreachable("readonly properties should be processed differently"); 12683 case Expr::MLV_InvalidMessageExpression: 12684 DiagID = diag::err_readonly_message_assignment; 12685 break; 12686 case Expr::MLV_SubObjCPropertySetting: 12687 DiagID = diag::err_no_subobject_property_setting; 12688 break; 12689 } 12690 12691 SourceRange Assign; 12692 if (Loc != OrigLoc) 12693 Assign = SourceRange(OrigLoc, OrigLoc); 12694 if (NeedType) 12695 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12696 else 12697 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12698 return true; 12699 } 12700 12701 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12702 SourceLocation Loc, 12703 Sema &Sema) { 12704 if (Sema.inTemplateInstantiation()) 12705 return; 12706 if (Sema.isUnevaluatedContext()) 12707 return; 12708 if (Loc.isInvalid() || Loc.isMacroID()) 12709 return; 12710 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12711 return; 12712 12713 // C / C++ fields 12714 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12715 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12716 if (ML && MR) { 12717 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12718 return; 12719 const ValueDecl *LHSDecl = 12720 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12721 const ValueDecl *RHSDecl = 12722 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12723 if (LHSDecl != RHSDecl) 12724 return; 12725 if (LHSDecl->getType().isVolatileQualified()) 12726 return; 12727 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12728 if (RefTy->getPointeeType().isVolatileQualified()) 12729 return; 12730 12731 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12732 } 12733 12734 // Objective-C instance variables 12735 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12736 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12737 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12738 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12739 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12740 if (RL && RR && RL->getDecl() == RR->getDecl()) 12741 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12742 } 12743 } 12744 12745 // C99 6.5.16.1 12746 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12747 SourceLocation Loc, 12748 QualType CompoundType) { 12749 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12750 12751 // Verify that LHS is a modifiable lvalue, and emit error if not. 12752 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12753 return QualType(); 12754 12755 QualType LHSType = LHSExpr->getType(); 12756 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12757 CompoundType; 12758 // OpenCL v1.2 s6.1.1.1 p2: 12759 // The half data type can only be used to declare a pointer to a buffer that 12760 // contains half values 12761 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12762 LHSType->isHalfType()) { 12763 Diag(Loc, diag::err_opencl_half_load_store) << 1 12764 << LHSType.getUnqualifiedType(); 12765 return QualType(); 12766 } 12767 12768 AssignConvertType ConvTy; 12769 if (CompoundType.isNull()) { 12770 Expr *RHSCheck = RHS.get(); 12771 12772 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12773 12774 QualType LHSTy(LHSType); 12775 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12776 if (RHS.isInvalid()) 12777 return QualType(); 12778 // Special case of NSObject attributes on c-style pointer types. 12779 if (ConvTy == IncompatiblePointer && 12780 ((Context.isObjCNSObjectType(LHSType) && 12781 RHSType->isObjCObjectPointerType()) || 12782 (Context.isObjCNSObjectType(RHSType) && 12783 LHSType->isObjCObjectPointerType()))) 12784 ConvTy = Compatible; 12785 12786 if (ConvTy == Compatible && 12787 LHSType->isObjCObjectType()) 12788 Diag(Loc, diag::err_objc_object_assignment) 12789 << LHSType; 12790 12791 // If the RHS is a unary plus or minus, check to see if they = and + are 12792 // right next to each other. If so, the user may have typo'd "x =+ 4" 12793 // instead of "x += 4". 12794 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12795 RHSCheck = ICE->getSubExpr(); 12796 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12797 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12798 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12799 // Only if the two operators are exactly adjacent. 12800 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12801 // And there is a space or other character before the subexpr of the 12802 // unary +/-. We don't want to warn on "x=-1". 12803 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12804 UO->getSubExpr()->getBeginLoc().isFileID()) { 12805 Diag(Loc, diag::warn_not_compound_assign) 12806 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12807 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12808 } 12809 } 12810 12811 if (ConvTy == Compatible) { 12812 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12813 // Warn about retain cycles where a block captures the LHS, but 12814 // not if the LHS is a simple variable into which the block is 12815 // being stored...unless that variable can be captured by reference! 12816 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12817 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12818 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12819 checkRetainCycles(LHSExpr, RHS.get()); 12820 } 12821 12822 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12823 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12824 // It is safe to assign a weak reference into a strong variable. 12825 // Although this code can still have problems: 12826 // id x = self.weakProp; 12827 // id y = self.weakProp; 12828 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12829 // paths through the function. This should be revisited if 12830 // -Wrepeated-use-of-weak is made flow-sensitive. 12831 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12832 // variable, which will be valid for the current autorelease scope. 12833 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12834 RHS.get()->getBeginLoc())) 12835 getCurFunction()->markSafeWeakUse(RHS.get()); 12836 12837 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12838 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12839 } 12840 } 12841 } else { 12842 // Compound assignment "x += y" 12843 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12844 } 12845 12846 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12847 RHS.get(), AA_Assigning)) 12848 return QualType(); 12849 12850 CheckForNullPointerDereference(*this, LHSExpr); 12851 12852 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12853 if (CompoundType.isNull()) { 12854 // C++2a [expr.ass]p5: 12855 // A simple-assignment whose left operand is of a volatile-qualified 12856 // type is deprecated unless the assignment is either a discarded-value 12857 // expression or an unevaluated operand 12858 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12859 } else { 12860 // C++2a [expr.ass]p6: 12861 // [Compound-assignment] expressions are deprecated if E1 has 12862 // volatile-qualified type 12863 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12864 } 12865 } 12866 12867 // C99 6.5.16p3: The type of an assignment expression is the type of the 12868 // left operand unless the left operand has qualified type, in which case 12869 // it is the unqualified version of the type of the left operand. 12870 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12871 // is converted to the type of the assignment expression (above). 12872 // C++ 5.17p1: the type of the assignment expression is that of its left 12873 // operand. 12874 return (getLangOpts().CPlusPlus 12875 ? LHSType : LHSType.getUnqualifiedType()); 12876 } 12877 12878 // Only ignore explicit casts to void. 12879 static bool IgnoreCommaOperand(const Expr *E) { 12880 E = E->IgnoreParens(); 12881 12882 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12883 if (CE->getCastKind() == CK_ToVoid) { 12884 return true; 12885 } 12886 12887 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12888 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12889 CE->getSubExpr()->getType()->isDependentType()) { 12890 return true; 12891 } 12892 } 12893 12894 return false; 12895 } 12896 12897 // Look for instances where it is likely the comma operator is confused with 12898 // another operator. There is an explicit list of acceptable expressions for 12899 // the left hand side of the comma operator, otherwise emit a warning. 12900 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12901 // No warnings in macros 12902 if (Loc.isMacroID()) 12903 return; 12904 12905 // Don't warn in template instantiations. 12906 if (inTemplateInstantiation()) 12907 return; 12908 12909 // Scope isn't fine-grained enough to explicitly list the specific cases, so 12910 // instead, skip more than needed, then call back into here with the 12911 // CommaVisitor in SemaStmt.cpp. 12912 // The listed locations are the initialization and increment portions 12913 // of a for loop. The additional checks are on the condition of 12914 // if statements, do/while loops, and for loops. 12915 // Differences in scope flags for C89 mode requires the extra logic. 12916 const unsigned ForIncrementFlags = 12917 getLangOpts().C99 || getLangOpts().CPlusPlus 12918 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12919 : Scope::ContinueScope | Scope::BreakScope; 12920 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12921 const unsigned ScopeFlags = getCurScope()->getFlags(); 12922 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12923 (ScopeFlags & ForInitFlags) == ForInitFlags) 12924 return; 12925 12926 // If there are multiple comma operators used together, get the RHS of the 12927 // of the comma operator as the LHS. 12928 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12929 if (BO->getOpcode() != BO_Comma) 12930 break; 12931 LHS = BO->getRHS(); 12932 } 12933 12934 // Only allow some expressions on LHS to not warn. 12935 if (IgnoreCommaOperand(LHS)) 12936 return; 12937 12938 Diag(Loc, diag::warn_comma_operator); 12939 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12940 << LHS->getSourceRange() 12941 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12942 LangOpts.CPlusPlus ? "static_cast<void>(" 12943 : "(void)(") 12944 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12945 ")"); 12946 } 12947 12948 // C99 6.5.17 12949 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12950 SourceLocation Loc) { 12951 LHS = S.CheckPlaceholderExpr(LHS.get()); 12952 RHS = S.CheckPlaceholderExpr(RHS.get()); 12953 if (LHS.isInvalid() || RHS.isInvalid()) 12954 return QualType(); 12955 12956 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12957 // operands, but not unary promotions. 12958 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12959 12960 // So we treat the LHS as a ignored value, and in C++ we allow the 12961 // containing site to determine what should be done with the RHS. 12962 LHS = S.IgnoredValueConversions(LHS.get()); 12963 if (LHS.isInvalid()) 12964 return QualType(); 12965 12966 S.DiagnoseUnusedExprResult(LHS.get()); 12967 12968 if (!S.getLangOpts().CPlusPlus) { 12969 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12970 if (RHS.isInvalid()) 12971 return QualType(); 12972 if (!RHS.get()->getType()->isVoidType()) 12973 S.RequireCompleteType(Loc, RHS.get()->getType(), 12974 diag::err_incomplete_type); 12975 } 12976 12977 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12978 S.DiagnoseCommaOperator(LHS.get(), Loc); 12979 12980 return RHS.get()->getType(); 12981 } 12982 12983 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12984 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12985 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12986 ExprValueKind &VK, 12987 ExprObjectKind &OK, 12988 SourceLocation OpLoc, 12989 bool IsInc, bool IsPrefix) { 12990 if (Op->isTypeDependent()) 12991 return S.Context.DependentTy; 12992 12993 QualType ResType = Op->getType(); 12994 // Atomic types can be used for increment / decrement where the non-atomic 12995 // versions can, so ignore the _Atomic() specifier for the purpose of 12996 // checking. 12997 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12998 ResType = ResAtomicType->getValueType(); 12999 13000 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13001 13002 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13003 // Decrement of bool is not allowed. 13004 if (!IsInc) { 13005 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13006 return QualType(); 13007 } 13008 // Increment of bool sets it to true, but is deprecated. 13009 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13010 : diag::warn_increment_bool) 13011 << Op->getSourceRange(); 13012 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13013 // Error on enum increments and decrements in C++ mode 13014 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13015 return QualType(); 13016 } else if (ResType->isRealType()) { 13017 // OK! 13018 } else if (ResType->isPointerType()) { 13019 // C99 6.5.2.4p2, 6.5.6p2 13020 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13021 return QualType(); 13022 } else if (ResType->isObjCObjectPointerType()) { 13023 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13024 // Otherwise, we just need a complete type. 13025 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13026 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13027 return QualType(); 13028 } else if (ResType->isAnyComplexType()) { 13029 // C99 does not support ++/-- on complex types, we allow as an extension. 13030 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13031 << ResType << Op->getSourceRange(); 13032 } else if (ResType->isPlaceholderType()) { 13033 ExprResult PR = S.CheckPlaceholderExpr(Op); 13034 if (PR.isInvalid()) return QualType(); 13035 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13036 IsInc, IsPrefix); 13037 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13038 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13039 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13040 (ResType->castAs<VectorType>()->getVectorKind() != 13041 VectorType::AltiVecBool)) { 13042 // The z vector extensions allow ++ and -- for non-bool vectors. 13043 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13044 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13045 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13046 } else { 13047 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13048 << ResType << int(IsInc) << Op->getSourceRange(); 13049 return QualType(); 13050 } 13051 // At this point, we know we have a real, complex or pointer type. 13052 // Now make sure the operand is a modifiable lvalue. 13053 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13054 return QualType(); 13055 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13056 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13057 // An operand with volatile-qualified type is deprecated 13058 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13059 << IsInc << ResType; 13060 } 13061 // In C++, a prefix increment is the same type as the operand. Otherwise 13062 // (in C or with postfix), the increment is the unqualified type of the 13063 // operand. 13064 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13065 VK = VK_LValue; 13066 OK = Op->getObjectKind(); 13067 return ResType; 13068 } else { 13069 VK = VK_RValue; 13070 return ResType.getUnqualifiedType(); 13071 } 13072 } 13073 13074 13075 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13076 /// This routine allows us to typecheck complex/recursive expressions 13077 /// where the declaration is needed for type checking. We only need to 13078 /// handle cases when the expression references a function designator 13079 /// or is an lvalue. Here are some examples: 13080 /// - &(x) => x 13081 /// - &*****f => f for f a function designator. 13082 /// - &s.xx => s 13083 /// - &s.zz[1].yy -> s, if zz is an array 13084 /// - *(x + 1) -> x, if x is an array 13085 /// - &"123"[2] -> 0 13086 /// - & __real__ x -> x 13087 /// 13088 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13089 /// members. 13090 static ValueDecl *getPrimaryDecl(Expr *E) { 13091 switch (E->getStmtClass()) { 13092 case Stmt::DeclRefExprClass: 13093 return cast<DeclRefExpr>(E)->getDecl(); 13094 case Stmt::MemberExprClass: 13095 // If this is an arrow operator, the address is an offset from 13096 // the base's value, so the object the base refers to is 13097 // irrelevant. 13098 if (cast<MemberExpr>(E)->isArrow()) 13099 return nullptr; 13100 // Otherwise, the expression refers to a part of the base 13101 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13102 case Stmt::ArraySubscriptExprClass: { 13103 // FIXME: This code shouldn't be necessary! We should catch the implicit 13104 // promotion of register arrays earlier. 13105 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13106 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13107 if (ICE->getSubExpr()->getType()->isArrayType()) 13108 return getPrimaryDecl(ICE->getSubExpr()); 13109 } 13110 return nullptr; 13111 } 13112 case Stmt::UnaryOperatorClass: { 13113 UnaryOperator *UO = cast<UnaryOperator>(E); 13114 13115 switch(UO->getOpcode()) { 13116 case UO_Real: 13117 case UO_Imag: 13118 case UO_Extension: 13119 return getPrimaryDecl(UO->getSubExpr()); 13120 default: 13121 return nullptr; 13122 } 13123 } 13124 case Stmt::ParenExprClass: 13125 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13126 case Stmt::ImplicitCastExprClass: 13127 // If the result of an implicit cast is an l-value, we care about 13128 // the sub-expression; otherwise, the result here doesn't matter. 13129 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13130 case Stmt::CXXUuidofExprClass: 13131 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13132 default: 13133 return nullptr; 13134 } 13135 } 13136 13137 namespace { 13138 enum { 13139 AO_Bit_Field = 0, 13140 AO_Vector_Element = 1, 13141 AO_Property_Expansion = 2, 13142 AO_Register_Variable = 3, 13143 AO_Matrix_Element = 4, 13144 AO_No_Error = 5 13145 }; 13146 } 13147 /// Diagnose invalid operand for address of operations. 13148 /// 13149 /// \param Type The type of operand which cannot have its address taken. 13150 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13151 Expr *E, unsigned Type) { 13152 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13153 } 13154 13155 /// CheckAddressOfOperand - The operand of & must be either a function 13156 /// designator or an lvalue designating an object. If it is an lvalue, the 13157 /// object cannot be declared with storage class register or be a bit field. 13158 /// Note: The usual conversions are *not* applied to the operand of the & 13159 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13160 /// In C++, the operand might be an overloaded function name, in which case 13161 /// we allow the '&' but retain the overloaded-function type. 13162 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13163 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13164 if (PTy->getKind() == BuiltinType::Overload) { 13165 Expr *E = OrigOp.get()->IgnoreParens(); 13166 if (!isa<OverloadExpr>(E)) { 13167 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13168 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13169 << OrigOp.get()->getSourceRange(); 13170 return QualType(); 13171 } 13172 13173 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13174 if (isa<UnresolvedMemberExpr>(Ovl)) 13175 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13176 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13177 << OrigOp.get()->getSourceRange(); 13178 return QualType(); 13179 } 13180 13181 return Context.OverloadTy; 13182 } 13183 13184 if (PTy->getKind() == BuiltinType::UnknownAny) 13185 return Context.UnknownAnyTy; 13186 13187 if (PTy->getKind() == BuiltinType::BoundMember) { 13188 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13189 << OrigOp.get()->getSourceRange(); 13190 return QualType(); 13191 } 13192 13193 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13194 if (OrigOp.isInvalid()) return QualType(); 13195 } 13196 13197 if (OrigOp.get()->isTypeDependent()) 13198 return Context.DependentTy; 13199 13200 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13201 13202 // Make sure to ignore parentheses in subsequent checks 13203 Expr *op = OrigOp.get()->IgnoreParens(); 13204 13205 // In OpenCL captures for blocks called as lambda functions 13206 // are located in the private address space. Blocks used in 13207 // enqueue_kernel can be located in a different address space 13208 // depending on a vendor implementation. Thus preventing 13209 // taking an address of the capture to avoid invalid AS casts. 13210 if (LangOpts.OpenCL) { 13211 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13212 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13213 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13214 return QualType(); 13215 } 13216 } 13217 13218 if (getLangOpts().C99) { 13219 // Implement C99-only parts of addressof rules. 13220 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13221 if (uOp->getOpcode() == UO_Deref) 13222 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13223 // (assuming the deref expression is valid). 13224 return uOp->getSubExpr()->getType(); 13225 } 13226 // Technically, there should be a check for array subscript 13227 // expressions here, but the result of one is always an lvalue anyway. 13228 } 13229 ValueDecl *dcl = getPrimaryDecl(op); 13230 13231 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13232 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13233 op->getBeginLoc())) 13234 return QualType(); 13235 13236 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13237 unsigned AddressOfError = AO_No_Error; 13238 13239 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13240 bool sfinae = (bool)isSFINAEContext(); 13241 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13242 : diag::ext_typecheck_addrof_temporary) 13243 << op->getType() << op->getSourceRange(); 13244 if (sfinae) 13245 return QualType(); 13246 // Materialize the temporary as an lvalue so that we can take its address. 13247 OrigOp = op = 13248 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13249 } else if (isa<ObjCSelectorExpr>(op)) { 13250 return Context.getPointerType(op->getType()); 13251 } else if (lval == Expr::LV_MemberFunction) { 13252 // If it's an instance method, make a member pointer. 13253 // The expression must have exactly the form &A::foo. 13254 13255 // If the underlying expression isn't a decl ref, give up. 13256 if (!isa<DeclRefExpr>(op)) { 13257 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13258 << OrigOp.get()->getSourceRange(); 13259 return QualType(); 13260 } 13261 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13262 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13263 13264 // The id-expression was parenthesized. 13265 if (OrigOp.get() != DRE) { 13266 Diag(OpLoc, diag::err_parens_pointer_member_function) 13267 << OrigOp.get()->getSourceRange(); 13268 13269 // The method was named without a qualifier. 13270 } else if (!DRE->getQualifier()) { 13271 if (MD->getParent()->getName().empty()) 13272 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13273 << op->getSourceRange(); 13274 else { 13275 SmallString<32> Str; 13276 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13277 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13278 << op->getSourceRange() 13279 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13280 } 13281 } 13282 13283 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13284 if (isa<CXXDestructorDecl>(MD)) 13285 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13286 13287 QualType MPTy = Context.getMemberPointerType( 13288 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13289 // Under the MS ABI, lock down the inheritance model now. 13290 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13291 (void)isCompleteType(OpLoc, MPTy); 13292 return MPTy; 13293 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13294 // C99 6.5.3.2p1 13295 // The operand must be either an l-value or a function designator 13296 if (!op->getType()->isFunctionType()) { 13297 // Use a special diagnostic for loads from property references. 13298 if (isa<PseudoObjectExpr>(op)) { 13299 AddressOfError = AO_Property_Expansion; 13300 } else { 13301 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13302 << op->getType() << op->getSourceRange(); 13303 return QualType(); 13304 } 13305 } 13306 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13307 // The operand cannot be a bit-field 13308 AddressOfError = AO_Bit_Field; 13309 } else if (op->getObjectKind() == OK_VectorComponent) { 13310 // The operand cannot be an element of a vector 13311 AddressOfError = AO_Vector_Element; 13312 } else if (op->getObjectKind() == OK_MatrixComponent) { 13313 // The operand cannot be an element of a matrix. 13314 AddressOfError = AO_Matrix_Element; 13315 } else if (dcl) { // C99 6.5.3.2p1 13316 // We have an lvalue with a decl. Make sure the decl is not declared 13317 // with the register storage-class specifier. 13318 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13319 // in C++ it is not error to take address of a register 13320 // variable (c++03 7.1.1P3) 13321 if (vd->getStorageClass() == SC_Register && 13322 !getLangOpts().CPlusPlus) { 13323 AddressOfError = AO_Register_Variable; 13324 } 13325 } else if (isa<MSPropertyDecl>(dcl)) { 13326 AddressOfError = AO_Property_Expansion; 13327 } else if (isa<FunctionTemplateDecl>(dcl)) { 13328 return Context.OverloadTy; 13329 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13330 // Okay: we can take the address of a field. 13331 // Could be a pointer to member, though, if there is an explicit 13332 // scope qualifier for the class. 13333 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13334 DeclContext *Ctx = dcl->getDeclContext(); 13335 if (Ctx && Ctx->isRecord()) { 13336 if (dcl->getType()->isReferenceType()) { 13337 Diag(OpLoc, 13338 diag::err_cannot_form_pointer_to_member_of_reference_type) 13339 << dcl->getDeclName() << dcl->getType(); 13340 return QualType(); 13341 } 13342 13343 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13344 Ctx = Ctx->getParent(); 13345 13346 QualType MPTy = Context.getMemberPointerType( 13347 op->getType(), 13348 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13349 // Under the MS ABI, lock down the inheritance model now. 13350 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13351 (void)isCompleteType(OpLoc, MPTy); 13352 return MPTy; 13353 } 13354 } 13355 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13356 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13357 llvm_unreachable("Unknown/unexpected decl type"); 13358 } 13359 13360 if (AddressOfError != AO_No_Error) { 13361 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13362 return QualType(); 13363 } 13364 13365 if (lval == Expr::LV_IncompleteVoidType) { 13366 // Taking the address of a void variable is technically illegal, but we 13367 // allow it in cases which are otherwise valid. 13368 // Example: "extern void x; void* y = &x;". 13369 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13370 } 13371 13372 // If the operand has type "type", the result has type "pointer to type". 13373 if (op->getType()->isObjCObjectType()) 13374 return Context.getObjCObjectPointerType(op->getType()); 13375 13376 CheckAddressOfPackedMember(op); 13377 13378 return Context.getPointerType(op->getType()); 13379 } 13380 13381 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13382 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13383 if (!DRE) 13384 return; 13385 const Decl *D = DRE->getDecl(); 13386 if (!D) 13387 return; 13388 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13389 if (!Param) 13390 return; 13391 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13392 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13393 return; 13394 if (FunctionScopeInfo *FD = S.getCurFunction()) 13395 if (!FD->ModifiedNonNullParams.count(Param)) 13396 FD->ModifiedNonNullParams.insert(Param); 13397 } 13398 13399 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13400 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13401 SourceLocation OpLoc) { 13402 if (Op->isTypeDependent()) 13403 return S.Context.DependentTy; 13404 13405 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13406 if (ConvResult.isInvalid()) 13407 return QualType(); 13408 Op = ConvResult.get(); 13409 QualType OpTy = Op->getType(); 13410 QualType Result; 13411 13412 if (isa<CXXReinterpretCastExpr>(Op)) { 13413 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13414 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13415 Op->getSourceRange()); 13416 } 13417 13418 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13419 { 13420 Result = PT->getPointeeType(); 13421 } 13422 else if (const ObjCObjectPointerType *OPT = 13423 OpTy->getAs<ObjCObjectPointerType>()) 13424 Result = OPT->getPointeeType(); 13425 else { 13426 ExprResult PR = S.CheckPlaceholderExpr(Op); 13427 if (PR.isInvalid()) return QualType(); 13428 if (PR.get() != Op) 13429 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13430 } 13431 13432 if (Result.isNull()) { 13433 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13434 << OpTy << Op->getSourceRange(); 13435 return QualType(); 13436 } 13437 13438 // Note that per both C89 and C99, indirection is always legal, even if Result 13439 // is an incomplete type or void. It would be possible to warn about 13440 // dereferencing a void pointer, but it's completely well-defined, and such a 13441 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13442 // for pointers to 'void' but is fine for any other pointer type: 13443 // 13444 // C++ [expr.unary.op]p1: 13445 // [...] the expression to which [the unary * operator] is applied shall 13446 // be a pointer to an object type, or a pointer to a function type 13447 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13448 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13449 << OpTy << Op->getSourceRange(); 13450 13451 // Dereferences are usually l-values... 13452 VK = VK_LValue; 13453 13454 // ...except that certain expressions are never l-values in C. 13455 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13456 VK = VK_RValue; 13457 13458 return Result; 13459 } 13460 13461 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13462 BinaryOperatorKind Opc; 13463 switch (Kind) { 13464 default: llvm_unreachable("Unknown binop!"); 13465 case tok::periodstar: Opc = BO_PtrMemD; break; 13466 case tok::arrowstar: Opc = BO_PtrMemI; break; 13467 case tok::star: Opc = BO_Mul; break; 13468 case tok::slash: Opc = BO_Div; break; 13469 case tok::percent: Opc = BO_Rem; break; 13470 case tok::plus: Opc = BO_Add; break; 13471 case tok::minus: Opc = BO_Sub; break; 13472 case tok::lessless: Opc = BO_Shl; break; 13473 case tok::greatergreater: Opc = BO_Shr; break; 13474 case tok::lessequal: Opc = BO_LE; break; 13475 case tok::less: Opc = BO_LT; break; 13476 case tok::greaterequal: Opc = BO_GE; break; 13477 case tok::greater: Opc = BO_GT; break; 13478 case tok::exclaimequal: Opc = BO_NE; break; 13479 case tok::equalequal: Opc = BO_EQ; break; 13480 case tok::spaceship: Opc = BO_Cmp; break; 13481 case tok::amp: Opc = BO_And; break; 13482 case tok::caret: Opc = BO_Xor; break; 13483 case tok::pipe: Opc = BO_Or; break; 13484 case tok::ampamp: Opc = BO_LAnd; break; 13485 case tok::pipepipe: Opc = BO_LOr; break; 13486 case tok::equal: Opc = BO_Assign; break; 13487 case tok::starequal: Opc = BO_MulAssign; break; 13488 case tok::slashequal: Opc = BO_DivAssign; break; 13489 case tok::percentequal: Opc = BO_RemAssign; break; 13490 case tok::plusequal: Opc = BO_AddAssign; break; 13491 case tok::minusequal: Opc = BO_SubAssign; break; 13492 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13493 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13494 case tok::ampequal: Opc = BO_AndAssign; break; 13495 case tok::caretequal: Opc = BO_XorAssign; break; 13496 case tok::pipeequal: Opc = BO_OrAssign; break; 13497 case tok::comma: Opc = BO_Comma; break; 13498 } 13499 return Opc; 13500 } 13501 13502 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13503 tok::TokenKind Kind) { 13504 UnaryOperatorKind Opc; 13505 switch (Kind) { 13506 default: llvm_unreachable("Unknown unary op!"); 13507 case tok::plusplus: Opc = UO_PreInc; break; 13508 case tok::minusminus: Opc = UO_PreDec; break; 13509 case tok::amp: Opc = UO_AddrOf; break; 13510 case tok::star: Opc = UO_Deref; break; 13511 case tok::plus: Opc = UO_Plus; break; 13512 case tok::minus: Opc = UO_Minus; break; 13513 case tok::tilde: Opc = UO_Not; break; 13514 case tok::exclaim: Opc = UO_LNot; break; 13515 case tok::kw___real: Opc = UO_Real; break; 13516 case tok::kw___imag: Opc = UO_Imag; break; 13517 case tok::kw___extension__: Opc = UO_Extension; break; 13518 } 13519 return Opc; 13520 } 13521 13522 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13523 /// This warning suppressed in the event of macro expansions. 13524 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13525 SourceLocation OpLoc, bool IsBuiltin) { 13526 if (S.inTemplateInstantiation()) 13527 return; 13528 if (S.isUnevaluatedContext()) 13529 return; 13530 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13531 return; 13532 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13533 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13534 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13535 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13536 if (!LHSDeclRef || !RHSDeclRef || 13537 LHSDeclRef->getLocation().isMacroID() || 13538 RHSDeclRef->getLocation().isMacroID()) 13539 return; 13540 const ValueDecl *LHSDecl = 13541 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13542 const ValueDecl *RHSDecl = 13543 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13544 if (LHSDecl != RHSDecl) 13545 return; 13546 if (LHSDecl->getType().isVolatileQualified()) 13547 return; 13548 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13549 if (RefTy->getPointeeType().isVolatileQualified()) 13550 return; 13551 13552 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13553 : diag::warn_self_assignment_overloaded) 13554 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13555 << RHSExpr->getSourceRange(); 13556 } 13557 13558 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13559 /// is usually indicative of introspection within the Objective-C pointer. 13560 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13561 SourceLocation OpLoc) { 13562 if (!S.getLangOpts().ObjC) 13563 return; 13564 13565 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13566 const Expr *LHS = L.get(); 13567 const Expr *RHS = R.get(); 13568 13569 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13570 ObjCPointerExpr = LHS; 13571 OtherExpr = RHS; 13572 } 13573 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13574 ObjCPointerExpr = RHS; 13575 OtherExpr = LHS; 13576 } 13577 13578 // This warning is deliberately made very specific to reduce false 13579 // positives with logic that uses '&' for hashing. This logic mainly 13580 // looks for code trying to introspect into tagged pointers, which 13581 // code should generally never do. 13582 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13583 unsigned Diag = diag::warn_objc_pointer_masking; 13584 // Determine if we are introspecting the result of performSelectorXXX. 13585 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13586 // Special case messages to -performSelector and friends, which 13587 // can return non-pointer values boxed in a pointer value. 13588 // Some clients may wish to silence warnings in this subcase. 13589 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13590 Selector S = ME->getSelector(); 13591 StringRef SelArg0 = S.getNameForSlot(0); 13592 if (SelArg0.startswith("performSelector")) 13593 Diag = diag::warn_objc_pointer_masking_performSelector; 13594 } 13595 13596 S.Diag(OpLoc, Diag) 13597 << ObjCPointerExpr->getSourceRange(); 13598 } 13599 } 13600 13601 static NamedDecl *getDeclFromExpr(Expr *E) { 13602 if (!E) 13603 return nullptr; 13604 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13605 return DRE->getDecl(); 13606 if (auto *ME = dyn_cast<MemberExpr>(E)) 13607 return ME->getMemberDecl(); 13608 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13609 return IRE->getDecl(); 13610 return nullptr; 13611 } 13612 13613 // This helper function promotes a binary operator's operands (which are of a 13614 // half vector type) to a vector of floats and then truncates the result to 13615 // a vector of either half or short. 13616 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13617 BinaryOperatorKind Opc, QualType ResultTy, 13618 ExprValueKind VK, ExprObjectKind OK, 13619 bool IsCompAssign, SourceLocation OpLoc, 13620 FPOptionsOverride FPFeatures) { 13621 auto &Context = S.getASTContext(); 13622 assert((isVector(ResultTy, Context.HalfTy) || 13623 isVector(ResultTy, Context.ShortTy)) && 13624 "Result must be a vector of half or short"); 13625 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13626 isVector(RHS.get()->getType(), Context.HalfTy) && 13627 "both operands expected to be a half vector"); 13628 13629 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13630 QualType BinOpResTy = RHS.get()->getType(); 13631 13632 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13633 // change BinOpResTy to a vector of ints. 13634 if (isVector(ResultTy, Context.ShortTy)) 13635 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13636 13637 if (IsCompAssign) 13638 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13639 ResultTy, VK, OK, OpLoc, FPFeatures, 13640 BinOpResTy, BinOpResTy); 13641 13642 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13643 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13644 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13645 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13646 } 13647 13648 static std::pair<ExprResult, ExprResult> 13649 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13650 Expr *RHSExpr) { 13651 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13652 if (!S.Context.isDependenceAllowed()) { 13653 // C cannot handle TypoExpr nodes on either side of a binop because it 13654 // doesn't handle dependent types properly, so make sure any TypoExprs have 13655 // been dealt with before checking the operands. 13656 LHS = S.CorrectDelayedTyposInExpr(LHS); 13657 RHS = S.CorrectDelayedTyposInExpr( 13658 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13659 [Opc, LHS](Expr *E) { 13660 if (Opc != BO_Assign) 13661 return ExprResult(E); 13662 // Avoid correcting the RHS to the same Expr as the LHS. 13663 Decl *D = getDeclFromExpr(E); 13664 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13665 }); 13666 } 13667 return std::make_pair(LHS, RHS); 13668 } 13669 13670 /// Returns true if conversion between vectors of halfs and vectors of floats 13671 /// is needed. 13672 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13673 Expr *E0, Expr *E1 = nullptr) { 13674 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13675 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13676 return false; 13677 13678 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13679 QualType Ty = E->IgnoreImplicit()->getType(); 13680 13681 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13682 // to vectors of floats. Although the element type of the vectors is __fp16, 13683 // the vectors shouldn't be treated as storage-only types. See the 13684 // discussion here: https://reviews.llvm.org/rG825235c140e7 13685 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13686 if (VT->getVectorKind() == VectorType::NeonVector) 13687 return false; 13688 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13689 } 13690 return false; 13691 }; 13692 13693 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13694 } 13695 13696 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13697 /// operator @p Opc at location @c TokLoc. This routine only supports 13698 /// built-in operations; ActOnBinOp handles overloaded operators. 13699 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13700 BinaryOperatorKind Opc, 13701 Expr *LHSExpr, Expr *RHSExpr) { 13702 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13703 // The syntax only allows initializer lists on the RHS of assignment, 13704 // so we don't need to worry about accepting invalid code for 13705 // non-assignment operators. 13706 // C++11 5.17p9: 13707 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13708 // of x = {} is x = T(). 13709 InitializationKind Kind = InitializationKind::CreateDirectList( 13710 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13711 InitializedEntity Entity = 13712 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13713 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13714 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13715 if (Init.isInvalid()) 13716 return Init; 13717 RHSExpr = Init.get(); 13718 } 13719 13720 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13721 QualType ResultTy; // Result type of the binary operator. 13722 // The following two variables are used for compound assignment operators 13723 QualType CompLHSTy; // Type of LHS after promotions for computation 13724 QualType CompResultTy; // Type of computation result 13725 ExprValueKind VK = VK_RValue; 13726 ExprObjectKind OK = OK_Ordinary; 13727 bool ConvertHalfVec = false; 13728 13729 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13730 if (!LHS.isUsable() || !RHS.isUsable()) 13731 return ExprError(); 13732 13733 if (getLangOpts().OpenCL) { 13734 QualType LHSTy = LHSExpr->getType(); 13735 QualType RHSTy = RHSExpr->getType(); 13736 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13737 // the ATOMIC_VAR_INIT macro. 13738 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13739 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13740 if (BO_Assign == Opc) 13741 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13742 else 13743 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13744 return ExprError(); 13745 } 13746 13747 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13748 // only with a builtin functions and therefore should be disallowed here. 13749 if (LHSTy->isImageType() || RHSTy->isImageType() || 13750 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13751 LHSTy->isPipeType() || RHSTy->isPipeType() || 13752 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13753 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13754 return ExprError(); 13755 } 13756 } 13757 13758 switch (Opc) { 13759 case BO_Assign: 13760 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13761 if (getLangOpts().CPlusPlus && 13762 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13763 VK = LHS.get()->getValueKind(); 13764 OK = LHS.get()->getObjectKind(); 13765 } 13766 if (!ResultTy.isNull()) { 13767 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13768 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13769 13770 // Avoid copying a block to the heap if the block is assigned to a local 13771 // auto variable that is declared in the same scope as the block. This 13772 // optimization is unsafe if the local variable is declared in an outer 13773 // scope. For example: 13774 // 13775 // BlockTy b; 13776 // { 13777 // b = ^{...}; 13778 // } 13779 // // It is unsafe to invoke the block here if it wasn't copied to the 13780 // // heap. 13781 // b(); 13782 13783 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13784 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13785 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13786 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13787 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13788 13789 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13790 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13791 NTCUC_Assignment, NTCUK_Copy); 13792 } 13793 RecordModifiableNonNullParam(*this, LHS.get()); 13794 break; 13795 case BO_PtrMemD: 13796 case BO_PtrMemI: 13797 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13798 Opc == BO_PtrMemI); 13799 break; 13800 case BO_Mul: 13801 case BO_Div: 13802 ConvertHalfVec = true; 13803 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13804 Opc == BO_Div); 13805 break; 13806 case BO_Rem: 13807 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13808 break; 13809 case BO_Add: 13810 ConvertHalfVec = true; 13811 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13812 break; 13813 case BO_Sub: 13814 ConvertHalfVec = true; 13815 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13816 break; 13817 case BO_Shl: 13818 case BO_Shr: 13819 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13820 break; 13821 case BO_LE: 13822 case BO_LT: 13823 case BO_GE: 13824 case BO_GT: 13825 ConvertHalfVec = true; 13826 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13827 break; 13828 case BO_EQ: 13829 case BO_NE: 13830 ConvertHalfVec = true; 13831 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13832 break; 13833 case BO_Cmp: 13834 ConvertHalfVec = true; 13835 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13836 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13837 break; 13838 case BO_And: 13839 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13840 LLVM_FALLTHROUGH; 13841 case BO_Xor: 13842 case BO_Or: 13843 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13844 break; 13845 case BO_LAnd: 13846 case BO_LOr: 13847 ConvertHalfVec = true; 13848 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13849 break; 13850 case BO_MulAssign: 13851 case BO_DivAssign: 13852 ConvertHalfVec = true; 13853 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13854 Opc == BO_DivAssign); 13855 CompLHSTy = CompResultTy; 13856 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13857 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13858 break; 13859 case BO_RemAssign: 13860 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13861 CompLHSTy = CompResultTy; 13862 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13863 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13864 break; 13865 case BO_AddAssign: 13866 ConvertHalfVec = true; 13867 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13868 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13869 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13870 break; 13871 case BO_SubAssign: 13872 ConvertHalfVec = true; 13873 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13874 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13875 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13876 break; 13877 case BO_ShlAssign: 13878 case BO_ShrAssign: 13879 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13880 CompLHSTy = CompResultTy; 13881 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13882 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13883 break; 13884 case BO_AndAssign: 13885 case BO_OrAssign: // fallthrough 13886 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13887 LLVM_FALLTHROUGH; 13888 case BO_XorAssign: 13889 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13890 CompLHSTy = CompResultTy; 13891 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13892 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13893 break; 13894 case BO_Comma: 13895 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13896 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13897 VK = RHS.get()->getValueKind(); 13898 OK = RHS.get()->getObjectKind(); 13899 } 13900 break; 13901 } 13902 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13903 return ExprError(); 13904 13905 // Some of the binary operations require promoting operands of half vector to 13906 // float vectors and truncating the result back to half vector. For now, we do 13907 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13908 // arm64). 13909 assert( 13910 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 13911 isVector(LHS.get()->getType(), Context.HalfTy)) && 13912 "both sides are half vectors or neither sides are"); 13913 ConvertHalfVec = 13914 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13915 13916 // Check for array bounds violations for both sides of the BinaryOperator 13917 CheckArrayAccess(LHS.get()); 13918 CheckArrayAccess(RHS.get()); 13919 13920 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13921 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13922 &Context.Idents.get("object_setClass"), 13923 SourceLocation(), LookupOrdinaryName); 13924 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13925 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13926 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13927 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13928 "object_setClass(") 13929 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13930 ",") 13931 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13932 } 13933 else 13934 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13935 } 13936 else if (const ObjCIvarRefExpr *OIRE = 13937 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13938 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13939 13940 // Opc is not a compound assignment if CompResultTy is null. 13941 if (CompResultTy.isNull()) { 13942 if (ConvertHalfVec) 13943 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13944 OpLoc, CurFPFeatureOverrides()); 13945 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13946 VK, OK, OpLoc, CurFPFeatureOverrides()); 13947 } 13948 13949 // Handle compound assignments. 13950 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13951 OK_ObjCProperty) { 13952 VK = VK_LValue; 13953 OK = LHS.get()->getObjectKind(); 13954 } 13955 13956 // The LHS is not converted to the result type for fixed-point compound 13957 // assignment as the common type is computed on demand. Reset the CompLHSTy 13958 // to the LHS type we would have gotten after unary conversions. 13959 if (CompResultTy->isFixedPointType()) 13960 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13961 13962 if (ConvertHalfVec) 13963 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13964 OpLoc, CurFPFeatureOverrides()); 13965 13966 return CompoundAssignOperator::Create( 13967 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 13968 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 13969 } 13970 13971 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13972 /// operators are mixed in a way that suggests that the programmer forgot that 13973 /// comparison operators have higher precedence. The most typical example of 13974 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13975 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13976 SourceLocation OpLoc, Expr *LHSExpr, 13977 Expr *RHSExpr) { 13978 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13979 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13980 13981 // Check that one of the sides is a comparison operator and the other isn't. 13982 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13983 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13984 if (isLeftComp == isRightComp) 13985 return; 13986 13987 // Bitwise operations are sometimes used as eager logical ops. 13988 // Don't diagnose this. 13989 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13990 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13991 if (isLeftBitwise || isRightBitwise) 13992 return; 13993 13994 SourceRange DiagRange = isLeftComp 13995 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13996 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13997 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13998 SourceRange ParensRange = 13999 isLeftComp 14000 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14001 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14002 14003 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14004 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14005 SuggestParentheses(Self, OpLoc, 14006 Self.PDiag(diag::note_precedence_silence) << OpStr, 14007 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14008 SuggestParentheses(Self, OpLoc, 14009 Self.PDiag(diag::note_precedence_bitwise_first) 14010 << BinaryOperator::getOpcodeStr(Opc), 14011 ParensRange); 14012 } 14013 14014 /// It accepts a '&&' expr that is inside a '||' one. 14015 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14016 /// in parentheses. 14017 static void 14018 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14019 BinaryOperator *Bop) { 14020 assert(Bop->getOpcode() == BO_LAnd); 14021 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14022 << Bop->getSourceRange() << OpLoc; 14023 SuggestParentheses(Self, Bop->getOperatorLoc(), 14024 Self.PDiag(diag::note_precedence_silence) 14025 << Bop->getOpcodeStr(), 14026 Bop->getSourceRange()); 14027 } 14028 14029 /// Returns true if the given expression can be evaluated as a constant 14030 /// 'true'. 14031 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14032 bool Res; 14033 return !E->isValueDependent() && 14034 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14035 } 14036 14037 /// Returns true if the given expression can be evaluated as a constant 14038 /// 'false'. 14039 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14040 bool Res; 14041 return !E->isValueDependent() && 14042 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14043 } 14044 14045 /// Look for '&&' in the left hand of a '||' expr. 14046 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14047 Expr *LHSExpr, Expr *RHSExpr) { 14048 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14049 if (Bop->getOpcode() == BO_LAnd) { 14050 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14051 if (EvaluatesAsFalse(S, RHSExpr)) 14052 return; 14053 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14054 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14055 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14056 } else if (Bop->getOpcode() == BO_LOr) { 14057 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14058 // If it's "a || b && 1 || c" we didn't warn earlier for 14059 // "a || b && 1", but warn now. 14060 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14061 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14062 } 14063 } 14064 } 14065 } 14066 14067 /// Look for '&&' in the right hand of a '||' expr. 14068 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14069 Expr *LHSExpr, Expr *RHSExpr) { 14070 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14071 if (Bop->getOpcode() == BO_LAnd) { 14072 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14073 if (EvaluatesAsFalse(S, LHSExpr)) 14074 return; 14075 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14076 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14077 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14078 } 14079 } 14080 } 14081 14082 /// Look for bitwise op in the left or right hand of a bitwise op with 14083 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14084 /// the '&' expression in parentheses. 14085 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14086 SourceLocation OpLoc, Expr *SubExpr) { 14087 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14088 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14089 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14090 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14091 << Bop->getSourceRange() << OpLoc; 14092 SuggestParentheses(S, Bop->getOperatorLoc(), 14093 S.PDiag(diag::note_precedence_silence) 14094 << Bop->getOpcodeStr(), 14095 Bop->getSourceRange()); 14096 } 14097 } 14098 } 14099 14100 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14101 Expr *SubExpr, StringRef Shift) { 14102 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14103 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14104 StringRef Op = Bop->getOpcodeStr(); 14105 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14106 << Bop->getSourceRange() << OpLoc << Shift << Op; 14107 SuggestParentheses(S, Bop->getOperatorLoc(), 14108 S.PDiag(diag::note_precedence_silence) << Op, 14109 Bop->getSourceRange()); 14110 } 14111 } 14112 } 14113 14114 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14115 Expr *LHSExpr, Expr *RHSExpr) { 14116 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14117 if (!OCE) 14118 return; 14119 14120 FunctionDecl *FD = OCE->getDirectCallee(); 14121 if (!FD || !FD->isOverloadedOperator()) 14122 return; 14123 14124 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14125 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14126 return; 14127 14128 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14129 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14130 << (Kind == OO_LessLess); 14131 SuggestParentheses(S, OCE->getOperatorLoc(), 14132 S.PDiag(diag::note_precedence_silence) 14133 << (Kind == OO_LessLess ? "<<" : ">>"), 14134 OCE->getSourceRange()); 14135 SuggestParentheses( 14136 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14137 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14138 } 14139 14140 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14141 /// precedence. 14142 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14143 SourceLocation OpLoc, Expr *LHSExpr, 14144 Expr *RHSExpr){ 14145 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14146 if (BinaryOperator::isBitwiseOp(Opc)) 14147 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14148 14149 // Diagnose "arg1 & arg2 | arg3" 14150 if ((Opc == BO_Or || Opc == BO_Xor) && 14151 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14152 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14153 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14154 } 14155 14156 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14157 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14158 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14159 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14160 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14161 } 14162 14163 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14164 || Opc == BO_Shr) { 14165 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14166 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14167 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14168 } 14169 14170 // Warn on overloaded shift operators and comparisons, such as: 14171 // cout << 5 == 4; 14172 if (BinaryOperator::isComparisonOp(Opc)) 14173 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14174 } 14175 14176 // Binary Operators. 'Tok' is the token for the operator. 14177 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14178 tok::TokenKind Kind, 14179 Expr *LHSExpr, Expr *RHSExpr) { 14180 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14181 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14182 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14183 14184 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14185 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14186 14187 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14188 } 14189 14190 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14191 UnresolvedSetImpl &Functions) { 14192 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14193 if (OverOp != OO_None && OverOp != OO_Equal) 14194 LookupOverloadedOperatorName(OverOp, S, Functions); 14195 14196 // In C++20 onwards, we may have a second operator to look up. 14197 if (getLangOpts().CPlusPlus20) { 14198 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14199 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14200 } 14201 } 14202 14203 /// Build an overloaded binary operator expression in the given scope. 14204 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14205 BinaryOperatorKind Opc, 14206 Expr *LHS, Expr *RHS) { 14207 switch (Opc) { 14208 case BO_Assign: 14209 case BO_DivAssign: 14210 case BO_RemAssign: 14211 case BO_SubAssign: 14212 case BO_AndAssign: 14213 case BO_OrAssign: 14214 case BO_XorAssign: 14215 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14216 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14217 break; 14218 default: 14219 break; 14220 } 14221 14222 // Find all of the overloaded operators visible from this point. 14223 UnresolvedSet<16> Functions; 14224 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14225 14226 // Build the (potentially-overloaded, potentially-dependent) 14227 // binary operation. 14228 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14229 } 14230 14231 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14232 BinaryOperatorKind Opc, 14233 Expr *LHSExpr, Expr *RHSExpr) { 14234 ExprResult LHS, RHS; 14235 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14236 if (!LHS.isUsable() || !RHS.isUsable()) 14237 return ExprError(); 14238 LHSExpr = LHS.get(); 14239 RHSExpr = RHS.get(); 14240 14241 // We want to end up calling one of checkPseudoObjectAssignment 14242 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14243 // both expressions are overloadable or either is type-dependent), 14244 // or CreateBuiltinBinOp (in any other case). We also want to get 14245 // any placeholder types out of the way. 14246 14247 // Handle pseudo-objects in the LHS. 14248 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14249 // Assignments with a pseudo-object l-value need special analysis. 14250 if (pty->getKind() == BuiltinType::PseudoObject && 14251 BinaryOperator::isAssignmentOp(Opc)) 14252 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14253 14254 // Don't resolve overloads if the other type is overloadable. 14255 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14256 // We can't actually test that if we still have a placeholder, 14257 // though. Fortunately, none of the exceptions we see in that 14258 // code below are valid when the LHS is an overload set. Note 14259 // that an overload set can be dependently-typed, but it never 14260 // instantiates to having an overloadable type. 14261 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14262 if (resolvedRHS.isInvalid()) return ExprError(); 14263 RHSExpr = resolvedRHS.get(); 14264 14265 if (RHSExpr->isTypeDependent() || 14266 RHSExpr->getType()->isOverloadableType()) 14267 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14268 } 14269 14270 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14271 // template, diagnose the missing 'template' keyword instead of diagnosing 14272 // an invalid use of a bound member function. 14273 // 14274 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14275 // to C++1z [over.over]/1.4, but we already checked for that case above. 14276 if (Opc == BO_LT && inTemplateInstantiation() && 14277 (pty->getKind() == BuiltinType::BoundMember || 14278 pty->getKind() == BuiltinType::Overload)) { 14279 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14280 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14281 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14282 return isa<FunctionTemplateDecl>(ND); 14283 })) { 14284 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14285 : OE->getNameLoc(), 14286 diag::err_template_kw_missing) 14287 << OE->getName().getAsString() << ""; 14288 return ExprError(); 14289 } 14290 } 14291 14292 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14293 if (LHS.isInvalid()) return ExprError(); 14294 LHSExpr = LHS.get(); 14295 } 14296 14297 // Handle pseudo-objects in the RHS. 14298 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14299 // An overload in the RHS can potentially be resolved by the type 14300 // being assigned to. 14301 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14302 if (getLangOpts().CPlusPlus && 14303 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14304 LHSExpr->getType()->isOverloadableType())) 14305 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14306 14307 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14308 } 14309 14310 // Don't resolve overloads if the other type is overloadable. 14311 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14312 LHSExpr->getType()->isOverloadableType()) 14313 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14314 14315 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14316 if (!resolvedRHS.isUsable()) return ExprError(); 14317 RHSExpr = resolvedRHS.get(); 14318 } 14319 14320 if (getLangOpts().CPlusPlus) { 14321 // If either expression is type-dependent, always build an 14322 // overloaded op. 14323 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14324 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14325 14326 // Otherwise, build an overloaded op if either expression has an 14327 // overloadable type. 14328 if (LHSExpr->getType()->isOverloadableType() || 14329 RHSExpr->getType()->isOverloadableType()) 14330 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14331 } 14332 14333 if (getLangOpts().RecoveryAST && 14334 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14335 assert(!getLangOpts().CPlusPlus); 14336 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14337 "Should only occur in error-recovery path."); 14338 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14339 // C [6.15.16] p3: 14340 // An assignment expression has the value of the left operand after the 14341 // assignment, but is not an lvalue. 14342 return CompoundAssignOperator::Create( 14343 Context, LHSExpr, RHSExpr, Opc, 14344 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14345 OpLoc, CurFPFeatureOverrides()); 14346 QualType ResultType; 14347 switch (Opc) { 14348 case BO_Assign: 14349 ResultType = LHSExpr->getType().getUnqualifiedType(); 14350 break; 14351 case BO_LT: 14352 case BO_GT: 14353 case BO_LE: 14354 case BO_GE: 14355 case BO_EQ: 14356 case BO_NE: 14357 case BO_LAnd: 14358 case BO_LOr: 14359 // These operators have a fixed result type regardless of operands. 14360 ResultType = Context.IntTy; 14361 break; 14362 case BO_Comma: 14363 ResultType = RHSExpr->getType(); 14364 break; 14365 default: 14366 ResultType = Context.DependentTy; 14367 break; 14368 } 14369 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14370 VK_RValue, OK_Ordinary, OpLoc, 14371 CurFPFeatureOverrides()); 14372 } 14373 14374 // Build a built-in binary operation. 14375 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14376 } 14377 14378 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14379 if (T.isNull() || T->isDependentType()) 14380 return false; 14381 14382 if (!T->isPromotableIntegerType()) 14383 return true; 14384 14385 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14386 } 14387 14388 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14389 UnaryOperatorKind Opc, 14390 Expr *InputExpr) { 14391 ExprResult Input = InputExpr; 14392 ExprValueKind VK = VK_RValue; 14393 ExprObjectKind OK = OK_Ordinary; 14394 QualType resultType; 14395 bool CanOverflow = false; 14396 14397 bool ConvertHalfVec = false; 14398 if (getLangOpts().OpenCL) { 14399 QualType Ty = InputExpr->getType(); 14400 // The only legal unary operation for atomics is '&'. 14401 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14402 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14403 // only with a builtin functions and therefore should be disallowed here. 14404 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14405 || Ty->isBlockPointerType())) { 14406 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14407 << InputExpr->getType() 14408 << Input.get()->getSourceRange()); 14409 } 14410 } 14411 14412 switch (Opc) { 14413 case UO_PreInc: 14414 case UO_PreDec: 14415 case UO_PostInc: 14416 case UO_PostDec: 14417 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14418 OpLoc, 14419 Opc == UO_PreInc || 14420 Opc == UO_PostInc, 14421 Opc == UO_PreInc || 14422 Opc == UO_PreDec); 14423 CanOverflow = isOverflowingIntegerType(Context, resultType); 14424 break; 14425 case UO_AddrOf: 14426 resultType = CheckAddressOfOperand(Input, OpLoc); 14427 CheckAddressOfNoDeref(InputExpr); 14428 RecordModifiableNonNullParam(*this, InputExpr); 14429 break; 14430 case UO_Deref: { 14431 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14432 if (Input.isInvalid()) return ExprError(); 14433 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14434 break; 14435 } 14436 case UO_Plus: 14437 case UO_Minus: 14438 CanOverflow = Opc == UO_Minus && 14439 isOverflowingIntegerType(Context, Input.get()->getType()); 14440 Input = UsualUnaryConversions(Input.get()); 14441 if (Input.isInvalid()) return ExprError(); 14442 // Unary plus and minus require promoting an operand of half vector to a 14443 // float vector and truncating the result back to a half vector. For now, we 14444 // do this only when HalfArgsAndReturns is set (that is, when the target is 14445 // arm or arm64). 14446 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14447 14448 // If the operand is a half vector, promote it to a float vector. 14449 if (ConvertHalfVec) 14450 Input = convertVector(Input.get(), Context.FloatTy, *this); 14451 resultType = Input.get()->getType(); 14452 if (resultType->isDependentType()) 14453 break; 14454 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14455 break; 14456 else if (resultType->isVectorType() && 14457 // The z vector extensions don't allow + or - with bool vectors. 14458 (!Context.getLangOpts().ZVector || 14459 resultType->castAs<VectorType>()->getVectorKind() != 14460 VectorType::AltiVecBool)) 14461 break; 14462 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14463 Opc == UO_Plus && 14464 resultType->isPointerType()) 14465 break; 14466 14467 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14468 << resultType << Input.get()->getSourceRange()); 14469 14470 case UO_Not: // bitwise complement 14471 Input = UsualUnaryConversions(Input.get()); 14472 if (Input.isInvalid()) 14473 return ExprError(); 14474 resultType = Input.get()->getType(); 14475 if (resultType->isDependentType()) 14476 break; 14477 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14478 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14479 // C99 does not support '~' for complex conjugation. 14480 Diag(OpLoc, diag::ext_integer_complement_complex) 14481 << resultType << Input.get()->getSourceRange(); 14482 else if (resultType->hasIntegerRepresentation()) 14483 break; 14484 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14485 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14486 // on vector float types. 14487 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14488 if (!T->isIntegerType()) 14489 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14490 << resultType << Input.get()->getSourceRange()); 14491 } else { 14492 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14493 << resultType << Input.get()->getSourceRange()); 14494 } 14495 break; 14496 14497 case UO_LNot: // logical negation 14498 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14499 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14500 if (Input.isInvalid()) return ExprError(); 14501 resultType = Input.get()->getType(); 14502 14503 // Though we still have to promote half FP to float... 14504 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14505 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14506 resultType = Context.FloatTy; 14507 } 14508 14509 if (resultType->isDependentType()) 14510 break; 14511 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14512 // C99 6.5.3.3p1: ok, fallthrough; 14513 if (Context.getLangOpts().CPlusPlus) { 14514 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14515 // operand contextually converted to bool. 14516 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14517 ScalarTypeToBooleanCastKind(resultType)); 14518 } else if (Context.getLangOpts().OpenCL && 14519 Context.getLangOpts().OpenCLVersion < 120) { 14520 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14521 // operate on scalar float types. 14522 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14523 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14524 << resultType << Input.get()->getSourceRange()); 14525 } 14526 } else if (resultType->isExtVectorType()) { 14527 if (Context.getLangOpts().OpenCL && 14528 Context.getLangOpts().OpenCLVersion < 120 && 14529 !Context.getLangOpts().OpenCLCPlusPlus) { 14530 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14531 // operate on vector float types. 14532 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14533 if (!T->isIntegerType()) 14534 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14535 << resultType << Input.get()->getSourceRange()); 14536 } 14537 // Vector logical not returns the signed variant of the operand type. 14538 resultType = GetSignedVectorType(resultType); 14539 break; 14540 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14541 const VectorType *VTy = resultType->castAs<VectorType>(); 14542 if (VTy->getVectorKind() != VectorType::GenericVector) 14543 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14544 << resultType << Input.get()->getSourceRange()); 14545 14546 // Vector logical not returns the signed variant of the operand type. 14547 resultType = GetSignedVectorType(resultType); 14548 break; 14549 } else { 14550 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14551 << resultType << Input.get()->getSourceRange()); 14552 } 14553 14554 // LNot always has type int. C99 6.5.3.3p5. 14555 // In C++, it's bool. C++ 5.3.1p8 14556 resultType = Context.getLogicalOperationType(); 14557 break; 14558 case UO_Real: 14559 case UO_Imag: 14560 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14561 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14562 // complex l-values to ordinary l-values and all other values to r-values. 14563 if (Input.isInvalid()) return ExprError(); 14564 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14565 if (Input.get()->getValueKind() != VK_RValue && 14566 Input.get()->getObjectKind() == OK_Ordinary) 14567 VK = Input.get()->getValueKind(); 14568 } else if (!getLangOpts().CPlusPlus) { 14569 // In C, a volatile scalar is read by __imag. In C++, it is not. 14570 Input = DefaultLvalueConversion(Input.get()); 14571 } 14572 break; 14573 case UO_Extension: 14574 resultType = Input.get()->getType(); 14575 VK = Input.get()->getValueKind(); 14576 OK = Input.get()->getObjectKind(); 14577 break; 14578 case UO_Coawait: 14579 // It's unnecessary to represent the pass-through operator co_await in the 14580 // AST; just return the input expression instead. 14581 assert(!Input.get()->getType()->isDependentType() && 14582 "the co_await expression must be non-dependant before " 14583 "building operator co_await"); 14584 return Input; 14585 } 14586 if (resultType.isNull() || Input.isInvalid()) 14587 return ExprError(); 14588 14589 // Check for array bounds violations in the operand of the UnaryOperator, 14590 // except for the '*' and '&' operators that have to be handled specially 14591 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14592 // that are explicitly defined as valid by the standard). 14593 if (Opc != UO_AddrOf && Opc != UO_Deref) 14594 CheckArrayAccess(Input.get()); 14595 14596 auto *UO = 14597 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14598 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14599 14600 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14601 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14602 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14603 14604 // Convert the result back to a half vector. 14605 if (ConvertHalfVec) 14606 return convertVector(UO, Context.HalfTy, *this); 14607 return UO; 14608 } 14609 14610 /// Determine whether the given expression is a qualified member 14611 /// access expression, of a form that could be turned into a pointer to member 14612 /// with the address-of operator. 14613 bool Sema::isQualifiedMemberAccess(Expr *E) { 14614 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14615 if (!DRE->getQualifier()) 14616 return false; 14617 14618 ValueDecl *VD = DRE->getDecl(); 14619 if (!VD->isCXXClassMember()) 14620 return false; 14621 14622 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14623 return true; 14624 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14625 return Method->isInstance(); 14626 14627 return false; 14628 } 14629 14630 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14631 if (!ULE->getQualifier()) 14632 return false; 14633 14634 for (NamedDecl *D : ULE->decls()) { 14635 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14636 if (Method->isInstance()) 14637 return true; 14638 } else { 14639 // Overload set does not contain methods. 14640 break; 14641 } 14642 } 14643 14644 return false; 14645 } 14646 14647 return false; 14648 } 14649 14650 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14651 UnaryOperatorKind Opc, Expr *Input) { 14652 // First things first: handle placeholders so that the 14653 // overloaded-operator check considers the right type. 14654 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14655 // Increment and decrement of pseudo-object references. 14656 if (pty->getKind() == BuiltinType::PseudoObject && 14657 UnaryOperator::isIncrementDecrementOp(Opc)) 14658 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14659 14660 // extension is always a builtin operator. 14661 if (Opc == UO_Extension) 14662 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14663 14664 // & gets special logic for several kinds of placeholder. 14665 // The builtin code knows what to do. 14666 if (Opc == UO_AddrOf && 14667 (pty->getKind() == BuiltinType::Overload || 14668 pty->getKind() == BuiltinType::UnknownAny || 14669 pty->getKind() == BuiltinType::BoundMember)) 14670 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14671 14672 // Anything else needs to be handled now. 14673 ExprResult Result = CheckPlaceholderExpr(Input); 14674 if (Result.isInvalid()) return ExprError(); 14675 Input = Result.get(); 14676 } 14677 14678 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14679 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14680 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14681 // Find all of the overloaded operators visible from this point. 14682 UnresolvedSet<16> Functions; 14683 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14684 if (S && OverOp != OO_None) 14685 LookupOverloadedOperatorName(OverOp, S, Functions); 14686 14687 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14688 } 14689 14690 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14691 } 14692 14693 // Unary Operators. 'Tok' is the token for the operator. 14694 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14695 tok::TokenKind Op, Expr *Input) { 14696 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14697 } 14698 14699 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14700 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14701 LabelDecl *TheDecl) { 14702 TheDecl->markUsed(Context); 14703 // Create the AST node. The address of a label always has type 'void*'. 14704 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14705 Context.getPointerType(Context.VoidTy)); 14706 } 14707 14708 void Sema::ActOnStartStmtExpr() { 14709 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14710 } 14711 14712 void Sema::ActOnStmtExprError() { 14713 // Note that function is also called by TreeTransform when leaving a 14714 // StmtExpr scope without rebuilding anything. 14715 14716 DiscardCleanupsInEvaluationContext(); 14717 PopExpressionEvaluationContext(); 14718 } 14719 14720 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14721 SourceLocation RPLoc) { 14722 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14723 } 14724 14725 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14726 SourceLocation RPLoc, unsigned TemplateDepth) { 14727 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14728 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14729 14730 if (hasAnyUnrecoverableErrorsInThisFunction()) 14731 DiscardCleanupsInEvaluationContext(); 14732 assert(!Cleanup.exprNeedsCleanups() && 14733 "cleanups within StmtExpr not correctly bound!"); 14734 PopExpressionEvaluationContext(); 14735 14736 // FIXME: there are a variety of strange constraints to enforce here, for 14737 // example, it is not possible to goto into a stmt expression apparently. 14738 // More semantic analysis is needed. 14739 14740 // If there are sub-stmts in the compound stmt, take the type of the last one 14741 // as the type of the stmtexpr. 14742 QualType Ty = Context.VoidTy; 14743 bool StmtExprMayBindToTemp = false; 14744 if (!Compound->body_empty()) { 14745 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14746 if (const auto *LastStmt = 14747 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14748 if (const Expr *Value = LastStmt->getExprStmt()) { 14749 StmtExprMayBindToTemp = true; 14750 Ty = Value->getType(); 14751 } 14752 } 14753 } 14754 14755 // FIXME: Check that expression type is complete/non-abstract; statement 14756 // expressions are not lvalues. 14757 Expr *ResStmtExpr = 14758 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14759 if (StmtExprMayBindToTemp) 14760 return MaybeBindToTemporary(ResStmtExpr); 14761 return ResStmtExpr; 14762 } 14763 14764 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14765 if (ER.isInvalid()) 14766 return ExprError(); 14767 14768 // Do function/array conversion on the last expression, but not 14769 // lvalue-to-rvalue. However, initialize an unqualified type. 14770 ER = DefaultFunctionArrayConversion(ER.get()); 14771 if (ER.isInvalid()) 14772 return ExprError(); 14773 Expr *E = ER.get(); 14774 14775 if (E->isTypeDependent()) 14776 return E; 14777 14778 // In ARC, if the final expression ends in a consume, splice 14779 // the consume out and bind it later. In the alternate case 14780 // (when dealing with a retainable type), the result 14781 // initialization will create a produce. In both cases the 14782 // result will be +1, and we'll need to balance that out with 14783 // a bind. 14784 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14785 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14786 return Cast->getSubExpr(); 14787 14788 // FIXME: Provide a better location for the initialization. 14789 return PerformCopyInitialization( 14790 InitializedEntity::InitializeStmtExprResult( 14791 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14792 SourceLocation(), E); 14793 } 14794 14795 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14796 TypeSourceInfo *TInfo, 14797 ArrayRef<OffsetOfComponent> Components, 14798 SourceLocation RParenLoc) { 14799 QualType ArgTy = TInfo->getType(); 14800 bool Dependent = ArgTy->isDependentType(); 14801 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14802 14803 // We must have at least one component that refers to the type, and the first 14804 // one is known to be a field designator. Verify that the ArgTy represents 14805 // a struct/union/class. 14806 if (!Dependent && !ArgTy->isRecordType()) 14807 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14808 << ArgTy << TypeRange); 14809 14810 // Type must be complete per C99 7.17p3 because a declaring a variable 14811 // with an incomplete type would be ill-formed. 14812 if (!Dependent 14813 && RequireCompleteType(BuiltinLoc, ArgTy, 14814 diag::err_offsetof_incomplete_type, TypeRange)) 14815 return ExprError(); 14816 14817 bool DidWarnAboutNonPOD = false; 14818 QualType CurrentType = ArgTy; 14819 SmallVector<OffsetOfNode, 4> Comps; 14820 SmallVector<Expr*, 4> Exprs; 14821 for (const OffsetOfComponent &OC : Components) { 14822 if (OC.isBrackets) { 14823 // Offset of an array sub-field. TODO: Should we allow vector elements? 14824 if (!CurrentType->isDependentType()) { 14825 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14826 if(!AT) 14827 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14828 << CurrentType); 14829 CurrentType = AT->getElementType(); 14830 } else 14831 CurrentType = Context.DependentTy; 14832 14833 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14834 if (IdxRval.isInvalid()) 14835 return ExprError(); 14836 Expr *Idx = IdxRval.get(); 14837 14838 // The expression must be an integral expression. 14839 // FIXME: An integral constant expression? 14840 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14841 !Idx->getType()->isIntegerType()) 14842 return ExprError( 14843 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14844 << Idx->getSourceRange()); 14845 14846 // Record this array index. 14847 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14848 Exprs.push_back(Idx); 14849 continue; 14850 } 14851 14852 // Offset of a field. 14853 if (CurrentType->isDependentType()) { 14854 // We have the offset of a field, but we can't look into the dependent 14855 // type. Just record the identifier of the field. 14856 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14857 CurrentType = Context.DependentTy; 14858 continue; 14859 } 14860 14861 // We need to have a complete type to look into. 14862 if (RequireCompleteType(OC.LocStart, CurrentType, 14863 diag::err_offsetof_incomplete_type)) 14864 return ExprError(); 14865 14866 // Look for the designated field. 14867 const RecordType *RC = CurrentType->getAs<RecordType>(); 14868 if (!RC) 14869 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14870 << CurrentType); 14871 RecordDecl *RD = RC->getDecl(); 14872 14873 // C++ [lib.support.types]p5: 14874 // The macro offsetof accepts a restricted set of type arguments in this 14875 // International Standard. type shall be a POD structure or a POD union 14876 // (clause 9). 14877 // C++11 [support.types]p4: 14878 // If type is not a standard-layout class (Clause 9), the results are 14879 // undefined. 14880 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14881 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14882 unsigned DiagID = 14883 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14884 : diag::ext_offsetof_non_pod_type; 14885 14886 if (!IsSafe && !DidWarnAboutNonPOD && 14887 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14888 PDiag(DiagID) 14889 << SourceRange(Components[0].LocStart, OC.LocEnd) 14890 << CurrentType)) 14891 DidWarnAboutNonPOD = true; 14892 } 14893 14894 // Look for the field. 14895 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14896 LookupQualifiedName(R, RD); 14897 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14898 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14899 if (!MemberDecl) { 14900 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14901 MemberDecl = IndirectMemberDecl->getAnonField(); 14902 } 14903 14904 if (!MemberDecl) 14905 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14906 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14907 OC.LocEnd)); 14908 14909 // C99 7.17p3: 14910 // (If the specified member is a bit-field, the behavior is undefined.) 14911 // 14912 // We diagnose this as an error. 14913 if (MemberDecl->isBitField()) { 14914 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14915 << MemberDecl->getDeclName() 14916 << SourceRange(BuiltinLoc, RParenLoc); 14917 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14918 return ExprError(); 14919 } 14920 14921 RecordDecl *Parent = MemberDecl->getParent(); 14922 if (IndirectMemberDecl) 14923 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14924 14925 // If the member was found in a base class, introduce OffsetOfNodes for 14926 // the base class indirections. 14927 CXXBasePaths Paths; 14928 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14929 Paths)) { 14930 if (Paths.getDetectedVirtual()) { 14931 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14932 << MemberDecl->getDeclName() 14933 << SourceRange(BuiltinLoc, RParenLoc); 14934 return ExprError(); 14935 } 14936 14937 CXXBasePath &Path = Paths.front(); 14938 for (const CXXBasePathElement &B : Path) 14939 Comps.push_back(OffsetOfNode(B.Base)); 14940 } 14941 14942 if (IndirectMemberDecl) { 14943 for (auto *FI : IndirectMemberDecl->chain()) { 14944 assert(isa<FieldDecl>(FI)); 14945 Comps.push_back(OffsetOfNode(OC.LocStart, 14946 cast<FieldDecl>(FI), OC.LocEnd)); 14947 } 14948 } else 14949 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14950 14951 CurrentType = MemberDecl->getType().getNonReferenceType(); 14952 } 14953 14954 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14955 Comps, Exprs, RParenLoc); 14956 } 14957 14958 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14959 SourceLocation BuiltinLoc, 14960 SourceLocation TypeLoc, 14961 ParsedType ParsedArgTy, 14962 ArrayRef<OffsetOfComponent> Components, 14963 SourceLocation RParenLoc) { 14964 14965 TypeSourceInfo *ArgTInfo; 14966 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14967 if (ArgTy.isNull()) 14968 return ExprError(); 14969 14970 if (!ArgTInfo) 14971 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14972 14973 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14974 } 14975 14976 14977 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14978 Expr *CondExpr, 14979 Expr *LHSExpr, Expr *RHSExpr, 14980 SourceLocation RPLoc) { 14981 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14982 14983 ExprValueKind VK = VK_RValue; 14984 ExprObjectKind OK = OK_Ordinary; 14985 QualType resType; 14986 bool CondIsTrue = false; 14987 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14988 resType = Context.DependentTy; 14989 } else { 14990 // The conditional expression is required to be a constant expression. 14991 llvm::APSInt condEval(32); 14992 ExprResult CondICE = VerifyIntegerConstantExpression( 14993 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 14994 if (CondICE.isInvalid()) 14995 return ExprError(); 14996 CondExpr = CondICE.get(); 14997 CondIsTrue = condEval.getZExtValue(); 14998 14999 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15000 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15001 15002 resType = ActiveExpr->getType(); 15003 VK = ActiveExpr->getValueKind(); 15004 OK = ActiveExpr->getObjectKind(); 15005 } 15006 15007 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15008 resType, VK, OK, RPLoc, CondIsTrue); 15009 } 15010 15011 //===----------------------------------------------------------------------===// 15012 // Clang Extensions. 15013 //===----------------------------------------------------------------------===// 15014 15015 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15016 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15017 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15018 15019 if (LangOpts.CPlusPlus) { 15020 MangleNumberingContext *MCtx; 15021 Decl *ManglingContextDecl; 15022 std::tie(MCtx, ManglingContextDecl) = 15023 getCurrentMangleNumberContext(Block->getDeclContext()); 15024 if (MCtx) { 15025 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15026 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15027 } 15028 } 15029 15030 PushBlockScope(CurScope, Block); 15031 CurContext->addDecl(Block); 15032 if (CurScope) 15033 PushDeclContext(CurScope, Block); 15034 else 15035 CurContext = Block; 15036 15037 getCurBlock()->HasImplicitReturnType = true; 15038 15039 // Enter a new evaluation context to insulate the block from any 15040 // cleanups from the enclosing full-expression. 15041 PushExpressionEvaluationContext( 15042 ExpressionEvaluationContext::PotentiallyEvaluated); 15043 } 15044 15045 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15046 Scope *CurScope) { 15047 assert(ParamInfo.getIdentifier() == nullptr && 15048 "block-id should have no identifier!"); 15049 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 15050 BlockScopeInfo *CurBlock = getCurBlock(); 15051 15052 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15053 QualType T = Sig->getType(); 15054 15055 // FIXME: We should allow unexpanded parameter packs here, but that would, 15056 // in turn, make the block expression contain unexpanded parameter packs. 15057 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15058 // Drop the parameters. 15059 FunctionProtoType::ExtProtoInfo EPI; 15060 EPI.HasTrailingReturn = false; 15061 EPI.TypeQuals.addConst(); 15062 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15063 Sig = Context.getTrivialTypeSourceInfo(T); 15064 } 15065 15066 // GetTypeForDeclarator always produces a function type for a block 15067 // literal signature. Furthermore, it is always a FunctionProtoType 15068 // unless the function was written with a typedef. 15069 assert(T->isFunctionType() && 15070 "GetTypeForDeclarator made a non-function block signature"); 15071 15072 // Look for an explicit signature in that function type. 15073 FunctionProtoTypeLoc ExplicitSignature; 15074 15075 if ((ExplicitSignature = Sig->getTypeLoc() 15076 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15077 15078 // Check whether that explicit signature was synthesized by 15079 // GetTypeForDeclarator. If so, don't save that as part of the 15080 // written signature. 15081 if (ExplicitSignature.getLocalRangeBegin() == 15082 ExplicitSignature.getLocalRangeEnd()) { 15083 // This would be much cheaper if we stored TypeLocs instead of 15084 // TypeSourceInfos. 15085 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15086 unsigned Size = Result.getFullDataSize(); 15087 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15088 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15089 15090 ExplicitSignature = FunctionProtoTypeLoc(); 15091 } 15092 } 15093 15094 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15095 CurBlock->FunctionType = T; 15096 15097 const FunctionType *Fn = T->getAs<FunctionType>(); 15098 QualType RetTy = Fn->getReturnType(); 15099 bool isVariadic = 15100 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15101 15102 CurBlock->TheDecl->setIsVariadic(isVariadic); 15103 15104 // Context.DependentTy is used as a placeholder for a missing block 15105 // return type. TODO: what should we do with declarators like: 15106 // ^ * { ... } 15107 // If the answer is "apply template argument deduction".... 15108 if (RetTy != Context.DependentTy) { 15109 CurBlock->ReturnType = RetTy; 15110 CurBlock->TheDecl->setBlockMissingReturnType(false); 15111 CurBlock->HasImplicitReturnType = false; 15112 } 15113 15114 // Push block parameters from the declarator if we had them. 15115 SmallVector<ParmVarDecl*, 8> Params; 15116 if (ExplicitSignature) { 15117 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15118 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15119 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15120 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15121 // Diagnose this as an extension in C17 and earlier. 15122 if (!getLangOpts().C2x) 15123 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15124 } 15125 Params.push_back(Param); 15126 } 15127 15128 // Fake up parameter variables if we have a typedef, like 15129 // ^ fntype { ... } 15130 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15131 for (const auto &I : Fn->param_types()) { 15132 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15133 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15134 Params.push_back(Param); 15135 } 15136 } 15137 15138 // Set the parameters on the block decl. 15139 if (!Params.empty()) { 15140 CurBlock->TheDecl->setParams(Params); 15141 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15142 /*CheckParameterNames=*/false); 15143 } 15144 15145 // Finally we can process decl attributes. 15146 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15147 15148 // Put the parameter variables in scope. 15149 for (auto AI : CurBlock->TheDecl->parameters()) { 15150 AI->setOwningFunction(CurBlock->TheDecl); 15151 15152 // If this has an identifier, add it to the scope stack. 15153 if (AI->getIdentifier()) { 15154 CheckShadow(CurBlock->TheScope, AI); 15155 15156 PushOnScopeChains(AI, CurBlock->TheScope); 15157 } 15158 } 15159 } 15160 15161 /// ActOnBlockError - If there is an error parsing a block, this callback 15162 /// is invoked to pop the information about the block from the action impl. 15163 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15164 // Leave the expression-evaluation context. 15165 DiscardCleanupsInEvaluationContext(); 15166 PopExpressionEvaluationContext(); 15167 15168 // Pop off CurBlock, handle nested blocks. 15169 PopDeclContext(); 15170 PopFunctionScopeInfo(); 15171 } 15172 15173 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15174 /// literal was successfully completed. ^(int x){...} 15175 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15176 Stmt *Body, Scope *CurScope) { 15177 // If blocks are disabled, emit an error. 15178 if (!LangOpts.Blocks) 15179 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15180 15181 // Leave the expression-evaluation context. 15182 if (hasAnyUnrecoverableErrorsInThisFunction()) 15183 DiscardCleanupsInEvaluationContext(); 15184 assert(!Cleanup.exprNeedsCleanups() && 15185 "cleanups within block not correctly bound!"); 15186 PopExpressionEvaluationContext(); 15187 15188 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15189 BlockDecl *BD = BSI->TheDecl; 15190 15191 if (BSI->HasImplicitReturnType) 15192 deduceClosureReturnType(*BSI); 15193 15194 QualType RetTy = Context.VoidTy; 15195 if (!BSI->ReturnType.isNull()) 15196 RetTy = BSI->ReturnType; 15197 15198 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15199 QualType BlockTy; 15200 15201 // If the user wrote a function type in some form, try to use that. 15202 if (!BSI->FunctionType.isNull()) { 15203 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15204 15205 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15206 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15207 15208 // Turn protoless block types into nullary block types. 15209 if (isa<FunctionNoProtoType>(FTy)) { 15210 FunctionProtoType::ExtProtoInfo EPI; 15211 EPI.ExtInfo = Ext; 15212 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15213 15214 // Otherwise, if we don't need to change anything about the function type, 15215 // preserve its sugar structure. 15216 } else if (FTy->getReturnType() == RetTy && 15217 (!NoReturn || FTy->getNoReturnAttr())) { 15218 BlockTy = BSI->FunctionType; 15219 15220 // Otherwise, make the minimal modifications to the function type. 15221 } else { 15222 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15223 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15224 EPI.TypeQuals = Qualifiers(); 15225 EPI.ExtInfo = Ext; 15226 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15227 } 15228 15229 // If we don't have a function type, just build one from nothing. 15230 } else { 15231 FunctionProtoType::ExtProtoInfo EPI; 15232 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15233 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15234 } 15235 15236 DiagnoseUnusedParameters(BD->parameters()); 15237 BlockTy = Context.getBlockPointerType(BlockTy); 15238 15239 // If needed, diagnose invalid gotos and switches in the block. 15240 if (getCurFunction()->NeedsScopeChecking() && 15241 !PP.isCodeCompletionEnabled()) 15242 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15243 15244 BD->setBody(cast<CompoundStmt>(Body)); 15245 15246 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15247 DiagnoseUnguardedAvailabilityViolations(BD); 15248 15249 // Try to apply the named return value optimization. We have to check again 15250 // if we can do this, though, because blocks keep return statements around 15251 // to deduce an implicit return type. 15252 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15253 !BD->isDependentContext()) 15254 computeNRVO(Body, BSI); 15255 15256 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15257 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15258 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15259 NTCUK_Destruct|NTCUK_Copy); 15260 15261 PopDeclContext(); 15262 15263 // Pop the block scope now but keep it alive to the end of this function. 15264 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15265 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15266 15267 // Set the captured variables on the block. 15268 SmallVector<BlockDecl::Capture, 4> Captures; 15269 for (Capture &Cap : BSI->Captures) { 15270 if (Cap.isInvalid() || Cap.isThisCapture()) 15271 continue; 15272 15273 VarDecl *Var = Cap.getVariable(); 15274 Expr *CopyExpr = nullptr; 15275 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15276 if (const RecordType *Record = 15277 Cap.getCaptureType()->getAs<RecordType>()) { 15278 // The capture logic needs the destructor, so make sure we mark it. 15279 // Usually this is unnecessary because most local variables have 15280 // their destructors marked at declaration time, but parameters are 15281 // an exception because it's technically only the call site that 15282 // actually requires the destructor. 15283 if (isa<ParmVarDecl>(Var)) 15284 FinalizeVarWithDestructor(Var, Record); 15285 15286 // Enter a separate potentially-evaluated context while building block 15287 // initializers to isolate their cleanups from those of the block 15288 // itself. 15289 // FIXME: Is this appropriate even when the block itself occurs in an 15290 // unevaluated operand? 15291 EnterExpressionEvaluationContext EvalContext( 15292 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15293 15294 SourceLocation Loc = Cap.getLocation(); 15295 15296 ExprResult Result = BuildDeclarationNameExpr( 15297 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15298 15299 // According to the blocks spec, the capture of a variable from 15300 // the stack requires a const copy constructor. This is not true 15301 // of the copy/move done to move a __block variable to the heap. 15302 if (!Result.isInvalid() && 15303 !Result.get()->getType().isConstQualified()) { 15304 Result = ImpCastExprToType(Result.get(), 15305 Result.get()->getType().withConst(), 15306 CK_NoOp, VK_LValue); 15307 } 15308 15309 if (!Result.isInvalid()) { 15310 Result = PerformCopyInitialization( 15311 InitializedEntity::InitializeBlock(Var->getLocation(), 15312 Cap.getCaptureType(), false), 15313 Loc, Result.get()); 15314 } 15315 15316 // Build a full-expression copy expression if initialization 15317 // succeeded and used a non-trivial constructor. Recover from 15318 // errors by pretending that the copy isn't necessary. 15319 if (!Result.isInvalid() && 15320 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15321 ->isTrivial()) { 15322 Result = MaybeCreateExprWithCleanups(Result); 15323 CopyExpr = Result.get(); 15324 } 15325 } 15326 } 15327 15328 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15329 CopyExpr); 15330 Captures.push_back(NewCap); 15331 } 15332 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15333 15334 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15335 15336 // If the block isn't obviously global, i.e. it captures anything at 15337 // all, then we need to do a few things in the surrounding context: 15338 if (Result->getBlockDecl()->hasCaptures()) { 15339 // First, this expression has a new cleanup object. 15340 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15341 Cleanup.setExprNeedsCleanups(true); 15342 15343 // It also gets a branch-protected scope if any of the captured 15344 // variables needs destruction. 15345 for (const auto &CI : Result->getBlockDecl()->captures()) { 15346 const VarDecl *var = CI.getVariable(); 15347 if (var->getType().isDestructedType() != QualType::DK_none) { 15348 setFunctionHasBranchProtectedScope(); 15349 break; 15350 } 15351 } 15352 } 15353 15354 if (getCurFunction()) 15355 getCurFunction()->addBlock(BD); 15356 15357 return Result; 15358 } 15359 15360 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15361 SourceLocation RPLoc) { 15362 TypeSourceInfo *TInfo; 15363 GetTypeFromParser(Ty, &TInfo); 15364 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15365 } 15366 15367 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15368 Expr *E, TypeSourceInfo *TInfo, 15369 SourceLocation RPLoc) { 15370 Expr *OrigExpr = E; 15371 bool IsMS = false; 15372 15373 // CUDA device code does not support varargs. 15374 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15375 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15376 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15377 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15378 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15379 } 15380 } 15381 15382 // NVPTX does not support va_arg expression. 15383 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15384 Context.getTargetInfo().getTriple().isNVPTX()) 15385 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15386 15387 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15388 // as Microsoft ABI on an actual Microsoft platform, where 15389 // __builtin_ms_va_list and __builtin_va_list are the same.) 15390 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15391 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15392 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15393 if (Context.hasSameType(MSVaListType, E->getType())) { 15394 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15395 return ExprError(); 15396 IsMS = true; 15397 } 15398 } 15399 15400 // Get the va_list type 15401 QualType VaListType = Context.getBuiltinVaListType(); 15402 if (!IsMS) { 15403 if (VaListType->isArrayType()) { 15404 // Deal with implicit array decay; for example, on x86-64, 15405 // va_list is an array, but it's supposed to decay to 15406 // a pointer for va_arg. 15407 VaListType = Context.getArrayDecayedType(VaListType); 15408 // Make sure the input expression also decays appropriately. 15409 ExprResult Result = UsualUnaryConversions(E); 15410 if (Result.isInvalid()) 15411 return ExprError(); 15412 E = Result.get(); 15413 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15414 // If va_list is a record type and we are compiling in C++ mode, 15415 // check the argument using reference binding. 15416 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15417 Context, Context.getLValueReferenceType(VaListType), false); 15418 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15419 if (Init.isInvalid()) 15420 return ExprError(); 15421 E = Init.getAs<Expr>(); 15422 } else { 15423 // Otherwise, the va_list argument must be an l-value because 15424 // it is modified by va_arg. 15425 if (!E->isTypeDependent() && 15426 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15427 return ExprError(); 15428 } 15429 } 15430 15431 if (!IsMS && !E->isTypeDependent() && 15432 !Context.hasSameType(VaListType, E->getType())) 15433 return ExprError( 15434 Diag(E->getBeginLoc(), 15435 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15436 << OrigExpr->getType() << E->getSourceRange()); 15437 15438 if (!TInfo->getType()->isDependentType()) { 15439 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15440 diag::err_second_parameter_to_va_arg_incomplete, 15441 TInfo->getTypeLoc())) 15442 return ExprError(); 15443 15444 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15445 TInfo->getType(), 15446 diag::err_second_parameter_to_va_arg_abstract, 15447 TInfo->getTypeLoc())) 15448 return ExprError(); 15449 15450 if (!TInfo->getType().isPODType(Context)) { 15451 Diag(TInfo->getTypeLoc().getBeginLoc(), 15452 TInfo->getType()->isObjCLifetimeType() 15453 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15454 : diag::warn_second_parameter_to_va_arg_not_pod) 15455 << TInfo->getType() 15456 << TInfo->getTypeLoc().getSourceRange(); 15457 } 15458 15459 // Check for va_arg where arguments of the given type will be promoted 15460 // (i.e. this va_arg is guaranteed to have undefined behavior). 15461 QualType PromoteType; 15462 if (TInfo->getType()->isPromotableIntegerType()) { 15463 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15464 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15465 PromoteType = QualType(); 15466 } 15467 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15468 PromoteType = Context.DoubleTy; 15469 if (!PromoteType.isNull()) 15470 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15471 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15472 << TInfo->getType() 15473 << PromoteType 15474 << TInfo->getTypeLoc().getSourceRange()); 15475 } 15476 15477 QualType T = TInfo->getType().getNonLValueExprType(Context); 15478 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15479 } 15480 15481 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15482 // The type of __null will be int or long, depending on the size of 15483 // pointers on the target. 15484 QualType Ty; 15485 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15486 if (pw == Context.getTargetInfo().getIntWidth()) 15487 Ty = Context.IntTy; 15488 else if (pw == Context.getTargetInfo().getLongWidth()) 15489 Ty = Context.LongTy; 15490 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15491 Ty = Context.LongLongTy; 15492 else { 15493 llvm_unreachable("I don't know size of pointer!"); 15494 } 15495 15496 return new (Context) GNUNullExpr(Ty, TokenLoc); 15497 } 15498 15499 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15500 SourceLocation BuiltinLoc, 15501 SourceLocation RPLoc) { 15502 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15503 } 15504 15505 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15506 SourceLocation BuiltinLoc, 15507 SourceLocation RPLoc, 15508 DeclContext *ParentContext) { 15509 return new (Context) 15510 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15511 } 15512 15513 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15514 bool Diagnose) { 15515 if (!getLangOpts().ObjC) 15516 return false; 15517 15518 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15519 if (!PT) 15520 return false; 15521 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15522 15523 // Ignore any parens, implicit casts (should only be 15524 // array-to-pointer decays), and not-so-opaque values. The last is 15525 // important for making this trigger for property assignments. 15526 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15527 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15528 if (OV->getSourceExpr()) 15529 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15530 15531 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15532 if (!PT->isObjCIdType() && 15533 !(ID && ID->getIdentifier()->isStr("NSString"))) 15534 return false; 15535 if (!SL->isAscii()) 15536 return false; 15537 15538 if (Diagnose) { 15539 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15540 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15541 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15542 } 15543 return true; 15544 } 15545 15546 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15547 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15548 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15549 !SrcExpr->isNullPointerConstant( 15550 getASTContext(), Expr::NPC_NeverValueDependent)) { 15551 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15552 return false; 15553 if (Diagnose) { 15554 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15555 << /*number*/1 15556 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15557 Expr *NumLit = 15558 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15559 if (NumLit) 15560 Exp = NumLit; 15561 } 15562 return true; 15563 } 15564 15565 return false; 15566 } 15567 15568 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15569 const Expr *SrcExpr) { 15570 if (!DstType->isFunctionPointerType() || 15571 !SrcExpr->getType()->isFunctionType()) 15572 return false; 15573 15574 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15575 if (!DRE) 15576 return false; 15577 15578 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15579 if (!FD) 15580 return false; 15581 15582 return !S.checkAddressOfFunctionIsAvailable(FD, 15583 /*Complain=*/true, 15584 SrcExpr->getBeginLoc()); 15585 } 15586 15587 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15588 SourceLocation Loc, 15589 QualType DstType, QualType SrcType, 15590 Expr *SrcExpr, AssignmentAction Action, 15591 bool *Complained) { 15592 if (Complained) 15593 *Complained = false; 15594 15595 // Decode the result (notice that AST's are still created for extensions). 15596 bool CheckInferredResultType = false; 15597 bool isInvalid = false; 15598 unsigned DiagKind = 0; 15599 ConversionFixItGenerator ConvHints; 15600 bool MayHaveConvFixit = false; 15601 bool MayHaveFunctionDiff = false; 15602 const ObjCInterfaceDecl *IFace = nullptr; 15603 const ObjCProtocolDecl *PDecl = nullptr; 15604 15605 switch (ConvTy) { 15606 case Compatible: 15607 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15608 return false; 15609 15610 case PointerToInt: 15611 if (getLangOpts().CPlusPlus) { 15612 DiagKind = diag::err_typecheck_convert_pointer_int; 15613 isInvalid = true; 15614 } else { 15615 DiagKind = diag::ext_typecheck_convert_pointer_int; 15616 } 15617 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15618 MayHaveConvFixit = true; 15619 break; 15620 case IntToPointer: 15621 if (getLangOpts().CPlusPlus) { 15622 DiagKind = diag::err_typecheck_convert_int_pointer; 15623 isInvalid = true; 15624 } else { 15625 DiagKind = diag::ext_typecheck_convert_int_pointer; 15626 } 15627 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15628 MayHaveConvFixit = true; 15629 break; 15630 case IncompatibleFunctionPointer: 15631 if (getLangOpts().CPlusPlus) { 15632 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15633 isInvalid = true; 15634 } else { 15635 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15636 } 15637 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15638 MayHaveConvFixit = true; 15639 break; 15640 case IncompatiblePointer: 15641 if (Action == AA_Passing_CFAudited) { 15642 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15643 } else if (getLangOpts().CPlusPlus) { 15644 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15645 isInvalid = true; 15646 } else { 15647 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15648 } 15649 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15650 SrcType->isObjCObjectPointerType(); 15651 if (!CheckInferredResultType) { 15652 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15653 } else if (CheckInferredResultType) { 15654 SrcType = SrcType.getUnqualifiedType(); 15655 DstType = DstType.getUnqualifiedType(); 15656 } 15657 MayHaveConvFixit = true; 15658 break; 15659 case IncompatiblePointerSign: 15660 if (getLangOpts().CPlusPlus) { 15661 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15662 isInvalid = true; 15663 } else { 15664 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15665 } 15666 break; 15667 case FunctionVoidPointer: 15668 if (getLangOpts().CPlusPlus) { 15669 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15670 isInvalid = true; 15671 } else { 15672 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15673 } 15674 break; 15675 case IncompatiblePointerDiscardsQualifiers: { 15676 // Perform array-to-pointer decay if necessary. 15677 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15678 15679 isInvalid = true; 15680 15681 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15682 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15683 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15684 DiagKind = diag::err_typecheck_incompatible_address_space; 15685 break; 15686 15687 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15688 DiagKind = diag::err_typecheck_incompatible_ownership; 15689 break; 15690 } 15691 15692 llvm_unreachable("unknown error case for discarding qualifiers!"); 15693 // fallthrough 15694 } 15695 case CompatiblePointerDiscardsQualifiers: 15696 // If the qualifiers lost were because we were applying the 15697 // (deprecated) C++ conversion from a string literal to a char* 15698 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15699 // Ideally, this check would be performed in 15700 // checkPointerTypesForAssignment. However, that would require a 15701 // bit of refactoring (so that the second argument is an 15702 // expression, rather than a type), which should be done as part 15703 // of a larger effort to fix checkPointerTypesForAssignment for 15704 // C++ semantics. 15705 if (getLangOpts().CPlusPlus && 15706 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15707 return false; 15708 if (getLangOpts().CPlusPlus) { 15709 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15710 isInvalid = true; 15711 } else { 15712 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15713 } 15714 15715 break; 15716 case IncompatibleNestedPointerQualifiers: 15717 if (getLangOpts().CPlusPlus) { 15718 isInvalid = true; 15719 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15720 } else { 15721 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15722 } 15723 break; 15724 case IncompatibleNestedPointerAddressSpaceMismatch: 15725 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15726 isInvalid = true; 15727 break; 15728 case IntToBlockPointer: 15729 DiagKind = diag::err_int_to_block_pointer; 15730 isInvalid = true; 15731 break; 15732 case IncompatibleBlockPointer: 15733 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15734 isInvalid = true; 15735 break; 15736 case IncompatibleObjCQualifiedId: { 15737 if (SrcType->isObjCQualifiedIdType()) { 15738 const ObjCObjectPointerType *srcOPT = 15739 SrcType->castAs<ObjCObjectPointerType>(); 15740 for (auto *srcProto : srcOPT->quals()) { 15741 PDecl = srcProto; 15742 break; 15743 } 15744 if (const ObjCInterfaceType *IFaceT = 15745 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15746 IFace = IFaceT->getDecl(); 15747 } 15748 else if (DstType->isObjCQualifiedIdType()) { 15749 const ObjCObjectPointerType *dstOPT = 15750 DstType->castAs<ObjCObjectPointerType>(); 15751 for (auto *dstProto : dstOPT->quals()) { 15752 PDecl = dstProto; 15753 break; 15754 } 15755 if (const ObjCInterfaceType *IFaceT = 15756 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15757 IFace = IFaceT->getDecl(); 15758 } 15759 if (getLangOpts().CPlusPlus) { 15760 DiagKind = diag::err_incompatible_qualified_id; 15761 isInvalid = true; 15762 } else { 15763 DiagKind = diag::warn_incompatible_qualified_id; 15764 } 15765 break; 15766 } 15767 case IncompatibleVectors: 15768 if (getLangOpts().CPlusPlus) { 15769 DiagKind = diag::err_incompatible_vectors; 15770 isInvalid = true; 15771 } else { 15772 DiagKind = diag::warn_incompatible_vectors; 15773 } 15774 break; 15775 case IncompatibleObjCWeakRef: 15776 DiagKind = diag::err_arc_weak_unavailable_assign; 15777 isInvalid = true; 15778 break; 15779 case Incompatible: 15780 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15781 if (Complained) 15782 *Complained = true; 15783 return true; 15784 } 15785 15786 DiagKind = diag::err_typecheck_convert_incompatible; 15787 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15788 MayHaveConvFixit = true; 15789 isInvalid = true; 15790 MayHaveFunctionDiff = true; 15791 break; 15792 } 15793 15794 QualType FirstType, SecondType; 15795 switch (Action) { 15796 case AA_Assigning: 15797 case AA_Initializing: 15798 // The destination type comes first. 15799 FirstType = DstType; 15800 SecondType = SrcType; 15801 break; 15802 15803 case AA_Returning: 15804 case AA_Passing: 15805 case AA_Passing_CFAudited: 15806 case AA_Converting: 15807 case AA_Sending: 15808 case AA_Casting: 15809 // The source type comes first. 15810 FirstType = SrcType; 15811 SecondType = DstType; 15812 break; 15813 } 15814 15815 PartialDiagnostic FDiag = PDiag(DiagKind); 15816 if (Action == AA_Passing_CFAudited) 15817 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15818 else 15819 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15820 15821 // If we can fix the conversion, suggest the FixIts. 15822 if (!ConvHints.isNull()) { 15823 for (FixItHint &H : ConvHints.Hints) 15824 FDiag << H; 15825 } 15826 15827 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15828 15829 if (MayHaveFunctionDiff) 15830 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15831 15832 Diag(Loc, FDiag); 15833 if ((DiagKind == diag::warn_incompatible_qualified_id || 15834 DiagKind == diag::err_incompatible_qualified_id) && 15835 PDecl && IFace && !IFace->hasDefinition()) 15836 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15837 << IFace << PDecl; 15838 15839 if (SecondType == Context.OverloadTy) 15840 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15841 FirstType, /*TakingAddress=*/true); 15842 15843 if (CheckInferredResultType) 15844 EmitRelatedResultTypeNote(SrcExpr); 15845 15846 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15847 EmitRelatedResultTypeNoteForReturn(DstType); 15848 15849 if (Complained) 15850 *Complained = true; 15851 return isInvalid; 15852 } 15853 15854 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15855 llvm::APSInt *Result, 15856 AllowFoldKind CanFold) { 15857 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15858 public: 15859 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 15860 QualType T) override { 15861 return S.Diag(Loc, diag::err_ice_not_integral) 15862 << T << S.LangOpts.CPlusPlus; 15863 } 15864 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15865 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 15866 } 15867 } Diagnoser; 15868 15869 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 15870 } 15871 15872 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15873 llvm::APSInt *Result, 15874 unsigned DiagID, 15875 AllowFoldKind CanFold) { 15876 class IDDiagnoser : public VerifyICEDiagnoser { 15877 unsigned DiagID; 15878 15879 public: 15880 IDDiagnoser(unsigned DiagID) 15881 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15882 15883 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15884 return S.Diag(Loc, DiagID); 15885 } 15886 } Diagnoser(DiagID); 15887 15888 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 15889 } 15890 15891 Sema::SemaDiagnosticBuilder 15892 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 15893 QualType T) { 15894 return diagnoseNotICE(S, Loc); 15895 } 15896 15897 Sema::SemaDiagnosticBuilder 15898 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 15899 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 15900 } 15901 15902 ExprResult 15903 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15904 VerifyICEDiagnoser &Diagnoser, 15905 AllowFoldKind CanFold) { 15906 SourceLocation DiagLoc = E->getBeginLoc(); 15907 15908 if (getLangOpts().CPlusPlus11) { 15909 // C++11 [expr.const]p5: 15910 // If an expression of literal class type is used in a context where an 15911 // integral constant expression is required, then that class type shall 15912 // have a single non-explicit conversion function to an integral or 15913 // unscoped enumeration type 15914 ExprResult Converted; 15915 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15916 VerifyICEDiagnoser &BaseDiagnoser; 15917 public: 15918 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 15919 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 15920 BaseDiagnoser.Suppress, true), 15921 BaseDiagnoser(BaseDiagnoser) {} 15922 15923 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15924 QualType T) override { 15925 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 15926 } 15927 15928 SemaDiagnosticBuilder diagnoseIncomplete( 15929 Sema &S, SourceLocation Loc, QualType T) override { 15930 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15931 } 15932 15933 SemaDiagnosticBuilder diagnoseExplicitConv( 15934 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15935 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15936 } 15937 15938 SemaDiagnosticBuilder noteExplicitConv( 15939 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15940 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15941 << ConvTy->isEnumeralType() << ConvTy; 15942 } 15943 15944 SemaDiagnosticBuilder diagnoseAmbiguous( 15945 Sema &S, SourceLocation Loc, QualType T) override { 15946 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15947 } 15948 15949 SemaDiagnosticBuilder noteAmbiguous( 15950 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15951 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15952 << ConvTy->isEnumeralType() << ConvTy; 15953 } 15954 15955 SemaDiagnosticBuilder diagnoseConversion( 15956 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15957 llvm_unreachable("conversion functions are permitted"); 15958 } 15959 } ConvertDiagnoser(Diagnoser); 15960 15961 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15962 ConvertDiagnoser); 15963 if (Converted.isInvalid()) 15964 return Converted; 15965 E = Converted.get(); 15966 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15967 return ExprError(); 15968 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15969 // An ICE must be of integral or unscoped enumeration type. 15970 if (!Diagnoser.Suppress) 15971 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 15972 << E->getSourceRange(); 15973 return ExprError(); 15974 } 15975 15976 ExprResult RValueExpr = DefaultLvalueConversion(E); 15977 if (RValueExpr.isInvalid()) 15978 return ExprError(); 15979 15980 E = RValueExpr.get(); 15981 15982 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15983 // in the non-ICE case. 15984 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15985 if (Result) 15986 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15987 if (!isa<ConstantExpr>(E)) 15988 E = ConstantExpr::Create(Context, E); 15989 return E; 15990 } 15991 15992 Expr::EvalResult EvalResult; 15993 SmallVector<PartialDiagnosticAt, 8> Notes; 15994 EvalResult.Diag = &Notes; 15995 15996 // Try to evaluate the expression, and produce diagnostics explaining why it's 15997 // not a constant expression as a side-effect. 15998 bool Folded = 15999 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16000 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16001 16002 if (!isa<ConstantExpr>(E)) 16003 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16004 16005 // In C++11, we can rely on diagnostics being produced for any expression 16006 // which is not a constant expression. If no diagnostics were produced, then 16007 // this is a constant expression. 16008 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16009 if (Result) 16010 *Result = EvalResult.Val.getInt(); 16011 return E; 16012 } 16013 16014 // If our only note is the usual "invalid subexpression" note, just point 16015 // the caret at its location rather than producing an essentially 16016 // redundant note. 16017 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16018 diag::note_invalid_subexpr_in_const_expr) { 16019 DiagLoc = Notes[0].first; 16020 Notes.clear(); 16021 } 16022 16023 if (!Folded || !CanFold) { 16024 if (!Diagnoser.Suppress) { 16025 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16026 for (const PartialDiagnosticAt &Note : Notes) 16027 Diag(Note.first, Note.second); 16028 } 16029 16030 return ExprError(); 16031 } 16032 16033 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16034 for (const PartialDiagnosticAt &Note : Notes) 16035 Diag(Note.first, Note.second); 16036 16037 if (Result) 16038 *Result = EvalResult.Val.getInt(); 16039 return E; 16040 } 16041 16042 namespace { 16043 // Handle the case where we conclude a expression which we speculatively 16044 // considered to be unevaluated is actually evaluated. 16045 class TransformToPE : public TreeTransform<TransformToPE> { 16046 typedef TreeTransform<TransformToPE> BaseTransform; 16047 16048 public: 16049 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16050 16051 // Make sure we redo semantic analysis 16052 bool AlwaysRebuild() { return true; } 16053 bool ReplacingOriginal() { return true; } 16054 16055 // We need to special-case DeclRefExprs referring to FieldDecls which 16056 // are not part of a member pointer formation; normal TreeTransforming 16057 // doesn't catch this case because of the way we represent them in the AST. 16058 // FIXME: This is a bit ugly; is it really the best way to handle this 16059 // case? 16060 // 16061 // Error on DeclRefExprs referring to FieldDecls. 16062 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16063 if (isa<FieldDecl>(E->getDecl()) && 16064 !SemaRef.isUnevaluatedContext()) 16065 return SemaRef.Diag(E->getLocation(), 16066 diag::err_invalid_non_static_member_use) 16067 << E->getDecl() << E->getSourceRange(); 16068 16069 return BaseTransform::TransformDeclRefExpr(E); 16070 } 16071 16072 // Exception: filter out member pointer formation 16073 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16074 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16075 return E; 16076 16077 return BaseTransform::TransformUnaryOperator(E); 16078 } 16079 16080 // The body of a lambda-expression is in a separate expression evaluation 16081 // context so never needs to be transformed. 16082 // FIXME: Ideally we wouldn't transform the closure type either, and would 16083 // just recreate the capture expressions and lambda expression. 16084 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16085 return SkipLambdaBody(E, Body); 16086 } 16087 }; 16088 } 16089 16090 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16091 assert(isUnevaluatedContext() && 16092 "Should only transform unevaluated expressions"); 16093 ExprEvalContexts.back().Context = 16094 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16095 if (isUnevaluatedContext()) 16096 return E; 16097 return TransformToPE(*this).TransformExpr(E); 16098 } 16099 16100 void 16101 Sema::PushExpressionEvaluationContext( 16102 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16103 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16104 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16105 LambdaContextDecl, ExprContext); 16106 Cleanup.reset(); 16107 if (!MaybeODRUseExprs.empty()) 16108 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16109 } 16110 16111 void 16112 Sema::PushExpressionEvaluationContext( 16113 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16114 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16115 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16116 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16117 } 16118 16119 namespace { 16120 16121 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16122 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16123 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16124 if (E->getOpcode() == UO_Deref) 16125 return CheckPossibleDeref(S, E->getSubExpr()); 16126 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16127 return CheckPossibleDeref(S, E->getBase()); 16128 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16129 return CheckPossibleDeref(S, E->getBase()); 16130 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16131 QualType Inner; 16132 QualType Ty = E->getType(); 16133 if (const auto *Ptr = Ty->getAs<PointerType>()) 16134 Inner = Ptr->getPointeeType(); 16135 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16136 Inner = Arr->getElementType(); 16137 else 16138 return nullptr; 16139 16140 if (Inner->hasAttr(attr::NoDeref)) 16141 return E; 16142 } 16143 return nullptr; 16144 } 16145 16146 } // namespace 16147 16148 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16149 for (const Expr *E : Rec.PossibleDerefs) { 16150 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16151 if (DeclRef) { 16152 const ValueDecl *Decl = DeclRef->getDecl(); 16153 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16154 << Decl->getName() << E->getSourceRange(); 16155 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16156 } else { 16157 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16158 << E->getSourceRange(); 16159 } 16160 } 16161 Rec.PossibleDerefs.clear(); 16162 } 16163 16164 /// Check whether E, which is either a discarded-value expression or an 16165 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16166 /// and if so, remove it from the list of volatile-qualified assignments that 16167 /// we are going to warn are deprecated. 16168 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16169 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16170 return; 16171 16172 // Note: ignoring parens here is not justified by the standard rules, but 16173 // ignoring parentheses seems like a more reasonable approach, and this only 16174 // drives a deprecation warning so doesn't affect conformance. 16175 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16176 if (BO->getOpcode() == BO_Assign) { 16177 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16178 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16179 LHSs.end()); 16180 } 16181 } 16182 } 16183 16184 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16185 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16186 RebuildingImmediateInvocation) 16187 return E; 16188 16189 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16190 /// It's OK if this fails; we'll also remove this in 16191 /// HandleImmediateInvocations, but catching it here allows us to avoid 16192 /// walking the AST looking for it in simple cases. 16193 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16194 if (auto *DeclRef = 16195 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16196 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16197 16198 E = MaybeCreateExprWithCleanups(E); 16199 16200 ConstantExpr *Res = ConstantExpr::Create( 16201 getASTContext(), E.get(), 16202 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16203 getASTContext()), 16204 /*IsImmediateInvocation*/ true); 16205 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16206 return Res; 16207 } 16208 16209 static void EvaluateAndDiagnoseImmediateInvocation( 16210 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16211 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16212 Expr::EvalResult Eval; 16213 Eval.Diag = &Notes; 16214 ConstantExpr *CE = Candidate.getPointer(); 16215 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16216 SemaRef.getASTContext(), true); 16217 if (!Result || !Notes.empty()) { 16218 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16219 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16220 InnerExpr = FunctionalCast->getSubExpr(); 16221 FunctionDecl *FD = nullptr; 16222 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16223 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16224 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16225 FD = Call->getConstructor(); 16226 else 16227 llvm_unreachable("unhandled decl kind"); 16228 assert(FD->isConsteval()); 16229 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16230 for (auto &Note : Notes) 16231 SemaRef.Diag(Note.first, Note.second); 16232 return; 16233 } 16234 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16235 } 16236 16237 static void RemoveNestedImmediateInvocation( 16238 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16239 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16240 struct ComplexRemove : TreeTransform<ComplexRemove> { 16241 using Base = TreeTransform<ComplexRemove>; 16242 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16243 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16244 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16245 CurrentII; 16246 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16247 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16248 SmallVector<Sema::ImmediateInvocationCandidate, 16249 4>::reverse_iterator Current) 16250 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16251 void RemoveImmediateInvocation(ConstantExpr* E) { 16252 auto It = std::find_if(CurrentII, IISet.rend(), 16253 [E](Sema::ImmediateInvocationCandidate Elem) { 16254 return Elem.getPointer() == E; 16255 }); 16256 assert(It != IISet.rend() && 16257 "ConstantExpr marked IsImmediateInvocation should " 16258 "be present"); 16259 It->setInt(1); // Mark as deleted 16260 } 16261 ExprResult TransformConstantExpr(ConstantExpr *E) { 16262 if (!E->isImmediateInvocation()) 16263 return Base::TransformConstantExpr(E); 16264 RemoveImmediateInvocation(E); 16265 return Base::TransformExpr(E->getSubExpr()); 16266 } 16267 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16268 /// we need to remove its DeclRefExpr from the DRSet. 16269 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16270 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16271 return Base::TransformCXXOperatorCallExpr(E); 16272 } 16273 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16274 /// here. 16275 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16276 if (!Init) 16277 return Init; 16278 /// ConstantExpr are the first layer of implicit node to be removed so if 16279 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16280 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16281 if (CE->isImmediateInvocation()) 16282 RemoveImmediateInvocation(CE); 16283 return Base::TransformInitializer(Init, NotCopyInit); 16284 } 16285 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16286 DRSet.erase(E); 16287 return E; 16288 } 16289 bool AlwaysRebuild() { return false; } 16290 bool ReplacingOriginal() { return true; } 16291 bool AllowSkippingCXXConstructExpr() { 16292 bool Res = AllowSkippingFirstCXXConstructExpr; 16293 AllowSkippingFirstCXXConstructExpr = true; 16294 return Res; 16295 } 16296 bool AllowSkippingFirstCXXConstructExpr = true; 16297 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16298 Rec.ImmediateInvocationCandidates, It); 16299 16300 /// CXXConstructExpr with a single argument are getting skipped by 16301 /// TreeTransform in some situtation because they could be implicit. This 16302 /// can only occur for the top-level CXXConstructExpr because it is used 16303 /// nowhere in the expression being transformed therefore will not be rebuilt. 16304 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16305 /// skipping the first CXXConstructExpr. 16306 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16307 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16308 16309 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16310 assert(Res.isUsable()); 16311 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16312 It->getPointer()->setSubExpr(Res.get()); 16313 } 16314 16315 static void 16316 HandleImmediateInvocations(Sema &SemaRef, 16317 Sema::ExpressionEvaluationContextRecord &Rec) { 16318 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16319 Rec.ReferenceToConsteval.size() == 0) || 16320 SemaRef.RebuildingImmediateInvocation) 16321 return; 16322 16323 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16324 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16325 /// need to remove ReferenceToConsteval in the immediate invocation. 16326 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16327 16328 /// Prevent sema calls during the tree transform from adding pointers that 16329 /// are already in the sets. 16330 llvm::SaveAndRestore<bool> DisableIITracking( 16331 SemaRef.RebuildingImmediateInvocation, true); 16332 16333 /// Prevent diagnostic during tree transfrom as they are duplicates 16334 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16335 16336 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16337 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16338 if (!It->getInt()) 16339 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16340 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16341 Rec.ReferenceToConsteval.size()) { 16342 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16343 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16344 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16345 bool VisitDeclRefExpr(DeclRefExpr *E) { 16346 DRSet.erase(E); 16347 return DRSet.size(); 16348 } 16349 } Visitor(Rec.ReferenceToConsteval); 16350 Visitor.TraverseStmt( 16351 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16352 } 16353 for (auto CE : Rec.ImmediateInvocationCandidates) 16354 if (!CE.getInt()) 16355 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16356 for (auto DR : Rec.ReferenceToConsteval) { 16357 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16358 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16359 << FD; 16360 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16361 } 16362 } 16363 16364 void Sema::PopExpressionEvaluationContext() { 16365 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16366 unsigned NumTypos = Rec.NumTypos; 16367 16368 if (!Rec.Lambdas.empty()) { 16369 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16370 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16371 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16372 unsigned D; 16373 if (Rec.isUnevaluated()) { 16374 // C++11 [expr.prim.lambda]p2: 16375 // A lambda-expression shall not appear in an unevaluated operand 16376 // (Clause 5). 16377 D = diag::err_lambda_unevaluated_operand; 16378 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16379 // C++1y [expr.const]p2: 16380 // A conditional-expression e is a core constant expression unless the 16381 // evaluation of e, following the rules of the abstract machine, would 16382 // evaluate [...] a lambda-expression. 16383 D = diag::err_lambda_in_constant_expression; 16384 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16385 // C++17 [expr.prim.lamda]p2: 16386 // A lambda-expression shall not appear [...] in a template-argument. 16387 D = diag::err_lambda_in_invalid_context; 16388 } else 16389 llvm_unreachable("Couldn't infer lambda error message."); 16390 16391 for (const auto *L : Rec.Lambdas) 16392 Diag(L->getBeginLoc(), D); 16393 } 16394 } 16395 16396 WarnOnPendingNoDerefs(Rec); 16397 HandleImmediateInvocations(*this, Rec); 16398 16399 // Warn on any volatile-qualified simple-assignments that are not discarded- 16400 // value expressions nor unevaluated operands (those cases get removed from 16401 // this list by CheckUnusedVolatileAssignment). 16402 for (auto *BO : Rec.VolatileAssignmentLHSs) 16403 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16404 << BO->getType(); 16405 16406 // When are coming out of an unevaluated context, clear out any 16407 // temporaries that we may have created as part of the evaluation of 16408 // the expression in that context: they aren't relevant because they 16409 // will never be constructed. 16410 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16411 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16412 ExprCleanupObjects.end()); 16413 Cleanup = Rec.ParentCleanup; 16414 CleanupVarDeclMarking(); 16415 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16416 // Otherwise, merge the contexts together. 16417 } else { 16418 Cleanup.mergeFrom(Rec.ParentCleanup); 16419 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16420 Rec.SavedMaybeODRUseExprs.end()); 16421 } 16422 16423 // Pop the current expression evaluation context off the stack. 16424 ExprEvalContexts.pop_back(); 16425 16426 // The global expression evaluation context record is never popped. 16427 ExprEvalContexts.back().NumTypos += NumTypos; 16428 } 16429 16430 void Sema::DiscardCleanupsInEvaluationContext() { 16431 ExprCleanupObjects.erase( 16432 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16433 ExprCleanupObjects.end()); 16434 Cleanup.reset(); 16435 MaybeODRUseExprs.clear(); 16436 } 16437 16438 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16439 ExprResult Result = CheckPlaceholderExpr(E); 16440 if (Result.isInvalid()) 16441 return ExprError(); 16442 E = Result.get(); 16443 if (!E->getType()->isVariablyModifiedType()) 16444 return E; 16445 return TransformToPotentiallyEvaluated(E); 16446 } 16447 16448 /// Are we in a context that is potentially constant evaluated per C++20 16449 /// [expr.const]p12? 16450 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16451 /// C++2a [expr.const]p12: 16452 // An expression or conversion is potentially constant evaluated if it is 16453 switch (SemaRef.ExprEvalContexts.back().Context) { 16454 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16455 // -- a manifestly constant-evaluated expression, 16456 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16457 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16458 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16459 // -- a potentially-evaluated expression, 16460 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16461 // -- an immediate subexpression of a braced-init-list, 16462 16463 // -- [FIXME] an expression of the form & cast-expression that occurs 16464 // within a templated entity 16465 // -- a subexpression of one of the above that is not a subexpression of 16466 // a nested unevaluated operand. 16467 return true; 16468 16469 case Sema::ExpressionEvaluationContext::Unevaluated: 16470 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16471 // Expressions in this context are never evaluated. 16472 return false; 16473 } 16474 llvm_unreachable("Invalid context"); 16475 } 16476 16477 /// Return true if this function has a calling convention that requires mangling 16478 /// in the size of the parameter pack. 16479 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16480 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16481 // we don't need parameter type sizes. 16482 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16483 if (!TT.isOSWindows() || !TT.isX86()) 16484 return false; 16485 16486 // If this is C++ and this isn't an extern "C" function, parameters do not 16487 // need to be complete. In this case, C++ mangling will apply, which doesn't 16488 // use the size of the parameters. 16489 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16490 return false; 16491 16492 // Stdcall, fastcall, and vectorcall need this special treatment. 16493 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16494 switch (CC) { 16495 case CC_X86StdCall: 16496 case CC_X86FastCall: 16497 case CC_X86VectorCall: 16498 return true; 16499 default: 16500 break; 16501 } 16502 return false; 16503 } 16504 16505 /// Require that all of the parameter types of function be complete. Normally, 16506 /// parameter types are only required to be complete when a function is called 16507 /// or defined, but to mangle functions with certain calling conventions, the 16508 /// mangler needs to know the size of the parameter list. In this situation, 16509 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16510 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16511 /// result in a linker error. Clang doesn't implement this behavior, and instead 16512 /// attempts to error at compile time. 16513 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16514 SourceLocation Loc) { 16515 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16516 FunctionDecl *FD; 16517 ParmVarDecl *Param; 16518 16519 public: 16520 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16521 : FD(FD), Param(Param) {} 16522 16523 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16524 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16525 StringRef CCName; 16526 switch (CC) { 16527 case CC_X86StdCall: 16528 CCName = "stdcall"; 16529 break; 16530 case CC_X86FastCall: 16531 CCName = "fastcall"; 16532 break; 16533 case CC_X86VectorCall: 16534 CCName = "vectorcall"; 16535 break; 16536 default: 16537 llvm_unreachable("CC does not need mangling"); 16538 } 16539 16540 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16541 << Param->getDeclName() << FD->getDeclName() << CCName; 16542 } 16543 }; 16544 16545 for (ParmVarDecl *Param : FD->parameters()) { 16546 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16547 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16548 } 16549 } 16550 16551 namespace { 16552 enum class OdrUseContext { 16553 /// Declarations in this context are not odr-used. 16554 None, 16555 /// Declarations in this context are formally odr-used, but this is a 16556 /// dependent context. 16557 Dependent, 16558 /// Declarations in this context are odr-used but not actually used (yet). 16559 FormallyOdrUsed, 16560 /// Declarations in this context are used. 16561 Used 16562 }; 16563 } 16564 16565 /// Are we within a context in which references to resolved functions or to 16566 /// variables result in odr-use? 16567 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16568 OdrUseContext Result; 16569 16570 switch (SemaRef.ExprEvalContexts.back().Context) { 16571 case Sema::ExpressionEvaluationContext::Unevaluated: 16572 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16573 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16574 return OdrUseContext::None; 16575 16576 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16577 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16578 Result = OdrUseContext::Used; 16579 break; 16580 16581 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16582 Result = OdrUseContext::FormallyOdrUsed; 16583 break; 16584 16585 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16586 // A default argument formally results in odr-use, but doesn't actually 16587 // result in a use in any real sense until it itself is used. 16588 Result = OdrUseContext::FormallyOdrUsed; 16589 break; 16590 } 16591 16592 if (SemaRef.CurContext->isDependentContext()) 16593 return OdrUseContext::Dependent; 16594 16595 return Result; 16596 } 16597 16598 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16599 if (!Func->isConstexpr()) 16600 return false; 16601 16602 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16603 return true; 16604 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16605 return CCD && CCD->getInheritedConstructor(); 16606 } 16607 16608 /// Mark a function referenced, and check whether it is odr-used 16609 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16610 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16611 bool MightBeOdrUse) { 16612 assert(Func && "No function?"); 16613 16614 Func->setReferenced(); 16615 16616 // Recursive functions aren't really used until they're used from some other 16617 // context. 16618 bool IsRecursiveCall = CurContext == Func; 16619 16620 // C++11 [basic.def.odr]p3: 16621 // A function whose name appears as a potentially-evaluated expression is 16622 // odr-used if it is the unique lookup result or the selected member of a 16623 // set of overloaded functions [...]. 16624 // 16625 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16626 // can just check that here. 16627 OdrUseContext OdrUse = 16628 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16629 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16630 OdrUse = OdrUseContext::FormallyOdrUsed; 16631 16632 // Trivial default constructors and destructors are never actually used. 16633 // FIXME: What about other special members? 16634 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16635 OdrUse == OdrUseContext::Used) { 16636 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16637 if (Constructor->isDefaultConstructor()) 16638 OdrUse = OdrUseContext::FormallyOdrUsed; 16639 if (isa<CXXDestructorDecl>(Func)) 16640 OdrUse = OdrUseContext::FormallyOdrUsed; 16641 } 16642 16643 // C++20 [expr.const]p12: 16644 // A function [...] is needed for constant evaluation if it is [...] a 16645 // constexpr function that is named by an expression that is potentially 16646 // constant evaluated 16647 bool NeededForConstantEvaluation = 16648 isPotentiallyConstantEvaluatedContext(*this) && 16649 isImplicitlyDefinableConstexprFunction(Func); 16650 16651 // Determine whether we require a function definition to exist, per 16652 // C++11 [temp.inst]p3: 16653 // Unless a function template specialization has been explicitly 16654 // instantiated or explicitly specialized, the function template 16655 // specialization is implicitly instantiated when the specialization is 16656 // referenced in a context that requires a function definition to exist. 16657 // C++20 [temp.inst]p7: 16658 // The existence of a definition of a [...] function is considered to 16659 // affect the semantics of the program if the [...] function is needed for 16660 // constant evaluation by an expression 16661 // C++20 [basic.def.odr]p10: 16662 // Every program shall contain exactly one definition of every non-inline 16663 // function or variable that is odr-used in that program outside of a 16664 // discarded statement 16665 // C++20 [special]p1: 16666 // The implementation will implicitly define [defaulted special members] 16667 // if they are odr-used or needed for constant evaluation. 16668 // 16669 // Note that we skip the implicit instantiation of templates that are only 16670 // used in unused default arguments or by recursive calls to themselves. 16671 // This is formally non-conforming, but seems reasonable in practice. 16672 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16673 NeededForConstantEvaluation); 16674 16675 // C++14 [temp.expl.spec]p6: 16676 // If a template [...] is explicitly specialized then that specialization 16677 // shall be declared before the first use of that specialization that would 16678 // cause an implicit instantiation to take place, in every translation unit 16679 // in which such a use occurs 16680 if (NeedDefinition && 16681 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16682 Func->getMemberSpecializationInfo())) 16683 checkSpecializationVisibility(Loc, Func); 16684 16685 if (getLangOpts().CUDA) 16686 CheckCUDACall(Loc, Func); 16687 16688 if (getLangOpts().SYCLIsDevice) 16689 checkSYCLDeviceFunction(Loc, Func); 16690 16691 // If we need a definition, try to create one. 16692 if (NeedDefinition && !Func->getBody()) { 16693 runWithSufficientStackSpace(Loc, [&] { 16694 if (CXXConstructorDecl *Constructor = 16695 dyn_cast<CXXConstructorDecl>(Func)) { 16696 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16697 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16698 if (Constructor->isDefaultConstructor()) { 16699 if (Constructor->isTrivial() && 16700 !Constructor->hasAttr<DLLExportAttr>()) 16701 return; 16702 DefineImplicitDefaultConstructor(Loc, Constructor); 16703 } else if (Constructor->isCopyConstructor()) { 16704 DefineImplicitCopyConstructor(Loc, Constructor); 16705 } else if (Constructor->isMoveConstructor()) { 16706 DefineImplicitMoveConstructor(Loc, Constructor); 16707 } 16708 } else if (Constructor->getInheritedConstructor()) { 16709 DefineInheritingConstructor(Loc, Constructor); 16710 } 16711 } else if (CXXDestructorDecl *Destructor = 16712 dyn_cast<CXXDestructorDecl>(Func)) { 16713 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16714 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16715 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16716 return; 16717 DefineImplicitDestructor(Loc, Destructor); 16718 } 16719 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16720 MarkVTableUsed(Loc, Destructor->getParent()); 16721 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16722 if (MethodDecl->isOverloadedOperator() && 16723 MethodDecl->getOverloadedOperator() == OO_Equal) { 16724 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16725 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16726 if (MethodDecl->isCopyAssignmentOperator()) 16727 DefineImplicitCopyAssignment(Loc, MethodDecl); 16728 else if (MethodDecl->isMoveAssignmentOperator()) 16729 DefineImplicitMoveAssignment(Loc, MethodDecl); 16730 } 16731 } else if (isa<CXXConversionDecl>(MethodDecl) && 16732 MethodDecl->getParent()->isLambda()) { 16733 CXXConversionDecl *Conversion = 16734 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16735 if (Conversion->isLambdaToBlockPointerConversion()) 16736 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16737 else 16738 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16739 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16740 MarkVTableUsed(Loc, MethodDecl->getParent()); 16741 } 16742 16743 if (Func->isDefaulted() && !Func->isDeleted()) { 16744 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16745 if (DCK != DefaultedComparisonKind::None) 16746 DefineDefaultedComparison(Loc, Func, DCK); 16747 } 16748 16749 // Implicit instantiation of function templates and member functions of 16750 // class templates. 16751 if (Func->isImplicitlyInstantiable()) { 16752 TemplateSpecializationKind TSK = 16753 Func->getTemplateSpecializationKindForInstantiation(); 16754 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16755 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16756 if (FirstInstantiation) { 16757 PointOfInstantiation = Loc; 16758 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16759 } else if (TSK != TSK_ImplicitInstantiation) { 16760 // Use the point of use as the point of instantiation, instead of the 16761 // point of explicit instantiation (which we track as the actual point 16762 // of instantiation). This gives better backtraces in diagnostics. 16763 PointOfInstantiation = Loc; 16764 } 16765 16766 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16767 Func->isConstexpr()) { 16768 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16769 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16770 CodeSynthesisContexts.size()) 16771 PendingLocalImplicitInstantiations.push_back( 16772 std::make_pair(Func, PointOfInstantiation)); 16773 else if (Func->isConstexpr()) 16774 // Do not defer instantiations of constexpr functions, to avoid the 16775 // expression evaluator needing to call back into Sema if it sees a 16776 // call to such a function. 16777 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16778 else { 16779 Func->setInstantiationIsPending(true); 16780 PendingInstantiations.push_back( 16781 std::make_pair(Func, PointOfInstantiation)); 16782 // Notify the consumer that a function was implicitly instantiated. 16783 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16784 } 16785 } 16786 } else { 16787 // Walk redefinitions, as some of them may be instantiable. 16788 for (auto i : Func->redecls()) { 16789 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16790 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16791 } 16792 } 16793 }); 16794 } 16795 16796 // C++14 [except.spec]p17: 16797 // An exception-specification is considered to be needed when: 16798 // - the function is odr-used or, if it appears in an unevaluated operand, 16799 // would be odr-used if the expression were potentially-evaluated; 16800 // 16801 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16802 // function is a pure virtual function we're calling, and in that case the 16803 // function was selected by overload resolution and we need to resolve its 16804 // exception specification for a different reason. 16805 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16806 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16807 ResolveExceptionSpec(Loc, FPT); 16808 16809 // If this is the first "real" use, act on that. 16810 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16811 // Keep track of used but undefined functions. 16812 if (!Func->isDefined()) { 16813 if (mightHaveNonExternalLinkage(Func)) 16814 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16815 else if (Func->getMostRecentDecl()->isInlined() && 16816 !LangOpts.GNUInline && 16817 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16818 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16819 else if (isExternalWithNoLinkageType(Func)) 16820 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16821 } 16822 16823 // Some x86 Windows calling conventions mangle the size of the parameter 16824 // pack into the name. Computing the size of the parameters requires the 16825 // parameter types to be complete. Check that now. 16826 if (funcHasParameterSizeMangling(*this, Func)) 16827 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16828 16829 // In the MS C++ ABI, the compiler emits destructor variants where they are 16830 // used. If the destructor is used here but defined elsewhere, mark the 16831 // virtual base destructors referenced. If those virtual base destructors 16832 // are inline, this will ensure they are defined when emitting the complete 16833 // destructor variant. This checking may be redundant if the destructor is 16834 // provided later in this TU. 16835 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16836 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16837 CXXRecordDecl *Parent = Dtor->getParent(); 16838 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16839 CheckCompleteDestructorVariant(Loc, Dtor); 16840 } 16841 } 16842 16843 Func->markUsed(Context); 16844 } 16845 } 16846 16847 /// Directly mark a variable odr-used. Given a choice, prefer to use 16848 /// MarkVariableReferenced since it does additional checks and then 16849 /// calls MarkVarDeclODRUsed. 16850 /// If the variable must be captured: 16851 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16852 /// - else capture it in the DeclContext that maps to the 16853 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16854 static void 16855 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16856 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16857 // Keep track of used but undefined variables. 16858 // FIXME: We shouldn't suppress this warning for static data members. 16859 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16860 (!Var->isExternallyVisible() || Var->isInline() || 16861 SemaRef.isExternalWithNoLinkageType(Var)) && 16862 !(Var->isStaticDataMember() && Var->hasInit())) { 16863 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16864 if (old.isInvalid()) 16865 old = Loc; 16866 } 16867 QualType CaptureType, DeclRefType; 16868 if (SemaRef.LangOpts.OpenMP) 16869 SemaRef.tryCaptureOpenMPLambdas(Var); 16870 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16871 /*EllipsisLoc*/ SourceLocation(), 16872 /*BuildAndDiagnose*/ true, 16873 CaptureType, DeclRefType, 16874 FunctionScopeIndexToStopAt); 16875 16876 Var->markUsed(SemaRef.Context); 16877 } 16878 16879 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16880 SourceLocation Loc, 16881 unsigned CapturingScopeIndex) { 16882 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16883 } 16884 16885 static void 16886 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16887 ValueDecl *var, DeclContext *DC) { 16888 DeclContext *VarDC = var->getDeclContext(); 16889 16890 // If the parameter still belongs to the translation unit, then 16891 // we're actually just using one parameter in the declaration of 16892 // the next. 16893 if (isa<ParmVarDecl>(var) && 16894 isa<TranslationUnitDecl>(VarDC)) 16895 return; 16896 16897 // For C code, don't diagnose about capture if we're not actually in code 16898 // right now; it's impossible to write a non-constant expression outside of 16899 // function context, so we'll get other (more useful) diagnostics later. 16900 // 16901 // For C++, things get a bit more nasty... it would be nice to suppress this 16902 // diagnostic for certain cases like using a local variable in an array bound 16903 // for a member of a local class, but the correct predicate is not obvious. 16904 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16905 return; 16906 16907 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16908 unsigned ContextKind = 3; // unknown 16909 if (isa<CXXMethodDecl>(VarDC) && 16910 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16911 ContextKind = 2; 16912 } else if (isa<FunctionDecl>(VarDC)) { 16913 ContextKind = 0; 16914 } else if (isa<BlockDecl>(VarDC)) { 16915 ContextKind = 1; 16916 } 16917 16918 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16919 << var << ValueKind << ContextKind << VarDC; 16920 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16921 << var; 16922 16923 // FIXME: Add additional diagnostic info about class etc. which prevents 16924 // capture. 16925 } 16926 16927 16928 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16929 bool &SubCapturesAreNested, 16930 QualType &CaptureType, 16931 QualType &DeclRefType) { 16932 // Check whether we've already captured it. 16933 if (CSI->CaptureMap.count(Var)) { 16934 // If we found a capture, any subcaptures are nested. 16935 SubCapturesAreNested = true; 16936 16937 // Retrieve the capture type for this variable. 16938 CaptureType = CSI->getCapture(Var).getCaptureType(); 16939 16940 // Compute the type of an expression that refers to this variable. 16941 DeclRefType = CaptureType.getNonReferenceType(); 16942 16943 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16944 // are mutable in the sense that user can change their value - they are 16945 // private instances of the captured declarations. 16946 const Capture &Cap = CSI->getCapture(Var); 16947 if (Cap.isCopyCapture() && 16948 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16949 !(isa<CapturedRegionScopeInfo>(CSI) && 16950 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16951 DeclRefType.addConst(); 16952 return true; 16953 } 16954 return false; 16955 } 16956 16957 // Only block literals, captured statements, and lambda expressions can 16958 // capture; other scopes don't work. 16959 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16960 SourceLocation Loc, 16961 const bool Diagnose, Sema &S) { 16962 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16963 return getLambdaAwareParentOfDeclContext(DC); 16964 else if (Var->hasLocalStorage()) { 16965 if (Diagnose) 16966 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16967 } 16968 return nullptr; 16969 } 16970 16971 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16972 // certain types of variables (unnamed, variably modified types etc.) 16973 // so check for eligibility. 16974 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16975 SourceLocation Loc, 16976 const bool Diagnose, Sema &S) { 16977 16978 bool IsBlock = isa<BlockScopeInfo>(CSI); 16979 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16980 16981 // Lambdas are not allowed to capture unnamed variables 16982 // (e.g. anonymous unions). 16983 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16984 // assuming that's the intent. 16985 if (IsLambda && !Var->getDeclName()) { 16986 if (Diagnose) { 16987 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16988 S.Diag(Var->getLocation(), diag::note_declared_at); 16989 } 16990 return false; 16991 } 16992 16993 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16994 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16995 if (Diagnose) { 16996 S.Diag(Loc, diag::err_ref_vm_type); 16997 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 16998 } 16999 return false; 17000 } 17001 // Prohibit structs with flexible array members too. 17002 // We cannot capture what is in the tail end of the struct. 17003 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17004 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17005 if (Diagnose) { 17006 if (IsBlock) 17007 S.Diag(Loc, diag::err_ref_flexarray_type); 17008 else 17009 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17010 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17011 } 17012 return false; 17013 } 17014 } 17015 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17016 // Lambdas and captured statements are not allowed to capture __block 17017 // variables; they don't support the expected semantics. 17018 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17019 if (Diagnose) { 17020 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17021 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17022 } 17023 return false; 17024 } 17025 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17026 if (S.getLangOpts().OpenCL && IsBlock && 17027 Var->getType()->isBlockPointerType()) { 17028 if (Diagnose) 17029 S.Diag(Loc, diag::err_opencl_block_ref_block); 17030 return false; 17031 } 17032 17033 return true; 17034 } 17035 17036 // Returns true if the capture by block was successful. 17037 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17038 SourceLocation Loc, 17039 const bool BuildAndDiagnose, 17040 QualType &CaptureType, 17041 QualType &DeclRefType, 17042 const bool Nested, 17043 Sema &S, bool Invalid) { 17044 bool ByRef = false; 17045 17046 // Blocks are not allowed to capture arrays, excepting OpenCL. 17047 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17048 // (decayed to pointers). 17049 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17050 if (BuildAndDiagnose) { 17051 S.Diag(Loc, diag::err_ref_array_type); 17052 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17053 Invalid = true; 17054 } else { 17055 return false; 17056 } 17057 } 17058 17059 // Forbid the block-capture of autoreleasing variables. 17060 if (!Invalid && 17061 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17062 if (BuildAndDiagnose) { 17063 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17064 << /*block*/ 0; 17065 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17066 Invalid = true; 17067 } else { 17068 return false; 17069 } 17070 } 17071 17072 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17073 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17074 QualType PointeeTy = PT->getPointeeType(); 17075 17076 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17077 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17078 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17079 if (BuildAndDiagnose) { 17080 SourceLocation VarLoc = Var->getLocation(); 17081 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17082 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17083 } 17084 } 17085 } 17086 17087 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17088 if (HasBlocksAttr || CaptureType->isReferenceType() || 17089 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17090 // Block capture by reference does not change the capture or 17091 // declaration reference types. 17092 ByRef = true; 17093 } else { 17094 // Block capture by copy introduces 'const'. 17095 CaptureType = CaptureType.getNonReferenceType().withConst(); 17096 DeclRefType = CaptureType; 17097 } 17098 17099 // Actually capture the variable. 17100 if (BuildAndDiagnose) 17101 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17102 CaptureType, Invalid); 17103 17104 return !Invalid; 17105 } 17106 17107 17108 /// Capture the given variable in the captured region. 17109 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17110 VarDecl *Var, 17111 SourceLocation Loc, 17112 const bool BuildAndDiagnose, 17113 QualType &CaptureType, 17114 QualType &DeclRefType, 17115 const bool RefersToCapturedVariable, 17116 Sema &S, bool Invalid) { 17117 // By default, capture variables by reference. 17118 bool ByRef = true; 17119 // Using an LValue reference type is consistent with Lambdas (see below). 17120 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17121 if (S.isOpenMPCapturedDecl(Var)) { 17122 bool HasConst = DeclRefType.isConstQualified(); 17123 DeclRefType = DeclRefType.getUnqualifiedType(); 17124 // Don't lose diagnostics about assignments to const. 17125 if (HasConst) 17126 DeclRefType.addConst(); 17127 } 17128 // Do not capture firstprivates in tasks. 17129 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17130 OMPC_unknown) 17131 return true; 17132 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17133 RSI->OpenMPCaptureLevel); 17134 } 17135 17136 if (ByRef) 17137 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17138 else 17139 CaptureType = DeclRefType; 17140 17141 // Actually capture the variable. 17142 if (BuildAndDiagnose) 17143 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17144 Loc, SourceLocation(), CaptureType, Invalid); 17145 17146 return !Invalid; 17147 } 17148 17149 /// Capture the given variable in the lambda. 17150 static bool captureInLambda(LambdaScopeInfo *LSI, 17151 VarDecl *Var, 17152 SourceLocation Loc, 17153 const bool BuildAndDiagnose, 17154 QualType &CaptureType, 17155 QualType &DeclRefType, 17156 const bool RefersToCapturedVariable, 17157 const Sema::TryCaptureKind Kind, 17158 SourceLocation EllipsisLoc, 17159 const bool IsTopScope, 17160 Sema &S, bool Invalid) { 17161 // Determine whether we are capturing by reference or by value. 17162 bool ByRef = false; 17163 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17164 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17165 } else { 17166 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17167 } 17168 17169 // Compute the type of the field that will capture this variable. 17170 if (ByRef) { 17171 // C++11 [expr.prim.lambda]p15: 17172 // An entity is captured by reference if it is implicitly or 17173 // explicitly captured but not captured by copy. It is 17174 // unspecified whether additional unnamed non-static data 17175 // members are declared in the closure type for entities 17176 // captured by reference. 17177 // 17178 // FIXME: It is not clear whether we want to build an lvalue reference 17179 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17180 // to do the former, while EDG does the latter. Core issue 1249 will 17181 // clarify, but for now we follow GCC because it's a more permissive and 17182 // easily defensible position. 17183 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17184 } else { 17185 // C++11 [expr.prim.lambda]p14: 17186 // For each entity captured by copy, an unnamed non-static 17187 // data member is declared in the closure type. The 17188 // declaration order of these members is unspecified. The type 17189 // of such a data member is the type of the corresponding 17190 // captured entity if the entity is not a reference to an 17191 // object, or the referenced type otherwise. [Note: If the 17192 // captured entity is a reference to a function, the 17193 // corresponding data member is also a reference to a 17194 // function. - end note ] 17195 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17196 if (!RefType->getPointeeType()->isFunctionType()) 17197 CaptureType = RefType->getPointeeType(); 17198 } 17199 17200 // Forbid the lambda copy-capture of autoreleasing variables. 17201 if (!Invalid && 17202 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17203 if (BuildAndDiagnose) { 17204 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17205 S.Diag(Var->getLocation(), diag::note_previous_decl) 17206 << Var->getDeclName(); 17207 Invalid = true; 17208 } else { 17209 return false; 17210 } 17211 } 17212 17213 // Make sure that by-copy captures are of a complete and non-abstract type. 17214 if (!Invalid && BuildAndDiagnose) { 17215 if (!CaptureType->isDependentType() && 17216 S.RequireCompleteSizedType( 17217 Loc, CaptureType, 17218 diag::err_capture_of_incomplete_or_sizeless_type, 17219 Var->getDeclName())) 17220 Invalid = true; 17221 else if (S.RequireNonAbstractType(Loc, CaptureType, 17222 diag::err_capture_of_abstract_type)) 17223 Invalid = true; 17224 } 17225 } 17226 17227 // Compute the type of a reference to this captured variable. 17228 if (ByRef) 17229 DeclRefType = CaptureType.getNonReferenceType(); 17230 else { 17231 // C++ [expr.prim.lambda]p5: 17232 // The closure type for a lambda-expression has a public inline 17233 // function call operator [...]. This function call operator is 17234 // declared const (9.3.1) if and only if the lambda-expression's 17235 // parameter-declaration-clause is not followed by mutable. 17236 DeclRefType = CaptureType.getNonReferenceType(); 17237 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17238 DeclRefType.addConst(); 17239 } 17240 17241 // Add the capture. 17242 if (BuildAndDiagnose) 17243 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17244 Loc, EllipsisLoc, CaptureType, Invalid); 17245 17246 return !Invalid; 17247 } 17248 17249 bool Sema::tryCaptureVariable( 17250 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17251 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17252 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17253 // An init-capture is notionally from the context surrounding its 17254 // declaration, but its parent DC is the lambda class. 17255 DeclContext *VarDC = Var->getDeclContext(); 17256 if (Var->isInitCapture()) 17257 VarDC = VarDC->getParent(); 17258 17259 DeclContext *DC = CurContext; 17260 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17261 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17262 // We need to sync up the Declaration Context with the 17263 // FunctionScopeIndexToStopAt 17264 if (FunctionScopeIndexToStopAt) { 17265 unsigned FSIndex = FunctionScopes.size() - 1; 17266 while (FSIndex != MaxFunctionScopesIndex) { 17267 DC = getLambdaAwareParentOfDeclContext(DC); 17268 --FSIndex; 17269 } 17270 } 17271 17272 17273 // If the variable is declared in the current context, there is no need to 17274 // capture it. 17275 if (VarDC == DC) return true; 17276 17277 // Capture global variables if it is required to use private copy of this 17278 // variable. 17279 bool IsGlobal = !Var->hasLocalStorage(); 17280 if (IsGlobal && 17281 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17282 MaxFunctionScopesIndex))) 17283 return true; 17284 Var = Var->getCanonicalDecl(); 17285 17286 // Walk up the stack to determine whether we can capture the variable, 17287 // performing the "simple" checks that don't depend on type. We stop when 17288 // we've either hit the declared scope of the variable or find an existing 17289 // capture of that variable. We start from the innermost capturing-entity 17290 // (the DC) and ensure that all intervening capturing-entities 17291 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17292 // declcontext can either capture the variable or have already captured 17293 // the variable. 17294 CaptureType = Var->getType(); 17295 DeclRefType = CaptureType.getNonReferenceType(); 17296 bool Nested = false; 17297 bool Explicit = (Kind != TryCapture_Implicit); 17298 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17299 do { 17300 // Only block literals, captured statements, and lambda expressions can 17301 // capture; other scopes don't work. 17302 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17303 ExprLoc, 17304 BuildAndDiagnose, 17305 *this); 17306 // We need to check for the parent *first* because, if we *have* 17307 // private-captured a global variable, we need to recursively capture it in 17308 // intermediate blocks, lambdas, etc. 17309 if (!ParentDC) { 17310 if (IsGlobal) { 17311 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17312 break; 17313 } 17314 return true; 17315 } 17316 17317 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17318 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17319 17320 17321 // Check whether we've already captured it. 17322 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17323 DeclRefType)) { 17324 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17325 break; 17326 } 17327 // If we are instantiating a generic lambda call operator body, 17328 // we do not want to capture new variables. What was captured 17329 // during either a lambdas transformation or initial parsing 17330 // should be used. 17331 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17332 if (BuildAndDiagnose) { 17333 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17334 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17335 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17336 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17337 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17338 } else 17339 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17340 } 17341 return true; 17342 } 17343 17344 // Try to capture variable-length arrays types. 17345 if (Var->getType()->isVariablyModifiedType()) { 17346 // We're going to walk down into the type and look for VLA 17347 // expressions. 17348 QualType QTy = Var->getType(); 17349 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17350 QTy = PVD->getOriginalType(); 17351 captureVariablyModifiedType(Context, QTy, CSI); 17352 } 17353 17354 if (getLangOpts().OpenMP) { 17355 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17356 // OpenMP private variables should not be captured in outer scope, so 17357 // just break here. Similarly, global variables that are captured in a 17358 // target region should not be captured outside the scope of the region. 17359 if (RSI->CapRegionKind == CR_OpenMP) { 17360 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17361 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17362 // If the variable is private (i.e. not captured) and has variably 17363 // modified type, we still need to capture the type for correct 17364 // codegen in all regions, associated with the construct. Currently, 17365 // it is captured in the innermost captured region only. 17366 if (IsOpenMPPrivateDecl != OMPC_unknown && 17367 Var->getType()->isVariablyModifiedType()) { 17368 QualType QTy = Var->getType(); 17369 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17370 QTy = PVD->getOriginalType(); 17371 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17372 I < E; ++I) { 17373 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17374 FunctionScopes[FunctionScopesIndex - I]); 17375 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17376 "Wrong number of captured regions associated with the " 17377 "OpenMP construct."); 17378 captureVariablyModifiedType(Context, QTy, OuterRSI); 17379 } 17380 } 17381 bool IsTargetCap = 17382 IsOpenMPPrivateDecl != OMPC_private && 17383 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17384 RSI->OpenMPCaptureLevel); 17385 // Do not capture global if it is not privatized in outer regions. 17386 bool IsGlobalCap = 17387 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17388 RSI->OpenMPCaptureLevel); 17389 17390 // When we detect target captures we are looking from inside the 17391 // target region, therefore we need to propagate the capture from the 17392 // enclosing region. Therefore, the capture is not initially nested. 17393 if (IsTargetCap) 17394 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17395 17396 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17397 (IsGlobal && !IsGlobalCap)) { 17398 Nested = !IsTargetCap; 17399 DeclRefType = DeclRefType.getUnqualifiedType(); 17400 CaptureType = Context.getLValueReferenceType(DeclRefType); 17401 break; 17402 } 17403 } 17404 } 17405 } 17406 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17407 // No capture-default, and this is not an explicit capture 17408 // so cannot capture this variable. 17409 if (BuildAndDiagnose) { 17410 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17411 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17412 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17413 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17414 diag::note_lambda_decl); 17415 // FIXME: If we error out because an outer lambda can not implicitly 17416 // capture a variable that an inner lambda explicitly captures, we 17417 // should have the inner lambda do the explicit capture - because 17418 // it makes for cleaner diagnostics later. This would purely be done 17419 // so that the diagnostic does not misleadingly claim that a variable 17420 // can not be captured by a lambda implicitly even though it is captured 17421 // explicitly. Suggestion: 17422 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17423 // at the function head 17424 // - cache the StartingDeclContext - this must be a lambda 17425 // - captureInLambda in the innermost lambda the variable. 17426 } 17427 return true; 17428 } 17429 17430 FunctionScopesIndex--; 17431 DC = ParentDC; 17432 Explicit = false; 17433 } while (!VarDC->Equals(DC)); 17434 17435 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17436 // computing the type of the capture at each step, checking type-specific 17437 // requirements, and adding captures if requested. 17438 // If the variable had already been captured previously, we start capturing 17439 // at the lambda nested within that one. 17440 bool Invalid = false; 17441 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17442 ++I) { 17443 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17444 17445 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17446 // certain types of variables (unnamed, variably modified types etc.) 17447 // so check for eligibility. 17448 if (!Invalid) 17449 Invalid = 17450 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17451 17452 // After encountering an error, if we're actually supposed to capture, keep 17453 // capturing in nested contexts to suppress any follow-on diagnostics. 17454 if (Invalid && !BuildAndDiagnose) 17455 return true; 17456 17457 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17458 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17459 DeclRefType, Nested, *this, Invalid); 17460 Nested = true; 17461 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17462 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17463 CaptureType, DeclRefType, Nested, 17464 *this, Invalid); 17465 Nested = true; 17466 } else { 17467 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17468 Invalid = 17469 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17470 DeclRefType, Nested, Kind, EllipsisLoc, 17471 /*IsTopScope*/ I == N - 1, *this, Invalid); 17472 Nested = true; 17473 } 17474 17475 if (Invalid && !BuildAndDiagnose) 17476 return true; 17477 } 17478 return Invalid; 17479 } 17480 17481 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17482 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17483 QualType CaptureType; 17484 QualType DeclRefType; 17485 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17486 /*BuildAndDiagnose=*/true, CaptureType, 17487 DeclRefType, nullptr); 17488 } 17489 17490 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17491 QualType CaptureType; 17492 QualType DeclRefType; 17493 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17494 /*BuildAndDiagnose=*/false, CaptureType, 17495 DeclRefType, nullptr); 17496 } 17497 17498 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17499 QualType CaptureType; 17500 QualType DeclRefType; 17501 17502 // Determine whether we can capture this variable. 17503 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17504 /*BuildAndDiagnose=*/false, CaptureType, 17505 DeclRefType, nullptr)) 17506 return QualType(); 17507 17508 return DeclRefType; 17509 } 17510 17511 namespace { 17512 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17513 // The produced TemplateArgumentListInfo* points to data stored within this 17514 // object, so should only be used in contexts where the pointer will not be 17515 // used after the CopiedTemplateArgs object is destroyed. 17516 class CopiedTemplateArgs { 17517 bool HasArgs; 17518 TemplateArgumentListInfo TemplateArgStorage; 17519 public: 17520 template<typename RefExpr> 17521 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17522 if (HasArgs) 17523 E->copyTemplateArgumentsInto(TemplateArgStorage); 17524 } 17525 operator TemplateArgumentListInfo*() 17526 #ifdef __has_cpp_attribute 17527 #if __has_cpp_attribute(clang::lifetimebound) 17528 [[clang::lifetimebound]] 17529 #endif 17530 #endif 17531 { 17532 return HasArgs ? &TemplateArgStorage : nullptr; 17533 } 17534 }; 17535 } 17536 17537 /// Walk the set of potential results of an expression and mark them all as 17538 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17539 /// 17540 /// \return A new expression if we found any potential results, ExprEmpty() if 17541 /// not, and ExprError() if we diagnosed an error. 17542 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17543 NonOdrUseReason NOUR) { 17544 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17545 // an object that satisfies the requirements for appearing in a 17546 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17547 // is immediately applied." This function handles the lvalue-to-rvalue 17548 // conversion part. 17549 // 17550 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17551 // transform it into the relevant kind of non-odr-use node and rebuild the 17552 // tree of nodes leading to it. 17553 // 17554 // This is a mini-TreeTransform that only transforms a restricted subset of 17555 // nodes (and only certain operands of them). 17556 17557 // Rebuild a subexpression. 17558 auto Rebuild = [&](Expr *Sub) { 17559 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17560 }; 17561 17562 // Check whether a potential result satisfies the requirements of NOUR. 17563 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17564 // Any entity other than a VarDecl is always odr-used whenever it's named 17565 // in a potentially-evaluated expression. 17566 auto *VD = dyn_cast<VarDecl>(D); 17567 if (!VD) 17568 return true; 17569 17570 // C++2a [basic.def.odr]p4: 17571 // A variable x whose name appears as a potentially-evalauted expression 17572 // e is odr-used by e unless 17573 // -- x is a reference that is usable in constant expressions, or 17574 // -- x is a variable of non-reference type that is usable in constant 17575 // expressions and has no mutable subobjects, and e is an element of 17576 // the set of potential results of an expression of 17577 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17578 // conversion is applied, or 17579 // -- x is a variable of non-reference type, and e is an element of the 17580 // set of potential results of a discarded-value expression to which 17581 // the lvalue-to-rvalue conversion is not applied 17582 // 17583 // We check the first bullet and the "potentially-evaluated" condition in 17584 // BuildDeclRefExpr. We check the type requirements in the second bullet 17585 // in CheckLValueToRValueConversionOperand below. 17586 switch (NOUR) { 17587 case NOUR_None: 17588 case NOUR_Unevaluated: 17589 llvm_unreachable("unexpected non-odr-use-reason"); 17590 17591 case NOUR_Constant: 17592 // Constant references were handled when they were built. 17593 if (VD->getType()->isReferenceType()) 17594 return true; 17595 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17596 if (RD->hasMutableFields()) 17597 return true; 17598 if (!VD->isUsableInConstantExpressions(S.Context)) 17599 return true; 17600 break; 17601 17602 case NOUR_Discarded: 17603 if (VD->getType()->isReferenceType()) 17604 return true; 17605 break; 17606 } 17607 return false; 17608 }; 17609 17610 // Mark that this expression does not constitute an odr-use. 17611 auto MarkNotOdrUsed = [&] { 17612 S.MaybeODRUseExprs.remove(E); 17613 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17614 LSI->markVariableExprAsNonODRUsed(E); 17615 }; 17616 17617 // C++2a [basic.def.odr]p2: 17618 // The set of potential results of an expression e is defined as follows: 17619 switch (E->getStmtClass()) { 17620 // -- If e is an id-expression, ... 17621 case Expr::DeclRefExprClass: { 17622 auto *DRE = cast<DeclRefExpr>(E); 17623 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17624 break; 17625 17626 // Rebuild as a non-odr-use DeclRefExpr. 17627 MarkNotOdrUsed(); 17628 return DeclRefExpr::Create( 17629 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17630 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17631 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17632 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17633 } 17634 17635 case Expr::FunctionParmPackExprClass: { 17636 auto *FPPE = cast<FunctionParmPackExpr>(E); 17637 // If any of the declarations in the pack is odr-used, then the expression 17638 // as a whole constitutes an odr-use. 17639 for (VarDecl *D : *FPPE) 17640 if (IsPotentialResultOdrUsed(D)) 17641 return ExprEmpty(); 17642 17643 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17644 // nothing cares about whether we marked this as an odr-use, but it might 17645 // be useful for non-compiler tools. 17646 MarkNotOdrUsed(); 17647 break; 17648 } 17649 17650 // -- If e is a subscripting operation with an array operand... 17651 case Expr::ArraySubscriptExprClass: { 17652 auto *ASE = cast<ArraySubscriptExpr>(E); 17653 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17654 if (!OldBase->getType()->isArrayType()) 17655 break; 17656 ExprResult Base = Rebuild(OldBase); 17657 if (!Base.isUsable()) 17658 return Base; 17659 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17660 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17661 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17662 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17663 ASE->getRBracketLoc()); 17664 } 17665 17666 case Expr::MemberExprClass: { 17667 auto *ME = cast<MemberExpr>(E); 17668 // -- If e is a class member access expression [...] naming a non-static 17669 // data member... 17670 if (isa<FieldDecl>(ME->getMemberDecl())) { 17671 ExprResult Base = Rebuild(ME->getBase()); 17672 if (!Base.isUsable()) 17673 return Base; 17674 return MemberExpr::Create( 17675 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17676 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17677 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17678 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17679 ME->getObjectKind(), ME->isNonOdrUse()); 17680 } 17681 17682 if (ME->getMemberDecl()->isCXXInstanceMember()) 17683 break; 17684 17685 // -- If e is a class member access expression naming a static data member, 17686 // ... 17687 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17688 break; 17689 17690 // Rebuild as a non-odr-use MemberExpr. 17691 MarkNotOdrUsed(); 17692 return MemberExpr::Create( 17693 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17694 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17695 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17696 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17697 return ExprEmpty(); 17698 } 17699 17700 case Expr::BinaryOperatorClass: { 17701 auto *BO = cast<BinaryOperator>(E); 17702 Expr *LHS = BO->getLHS(); 17703 Expr *RHS = BO->getRHS(); 17704 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17705 if (BO->getOpcode() == BO_PtrMemD) { 17706 ExprResult Sub = Rebuild(LHS); 17707 if (!Sub.isUsable()) 17708 return Sub; 17709 LHS = Sub.get(); 17710 // -- If e is a comma expression, ... 17711 } else if (BO->getOpcode() == BO_Comma) { 17712 ExprResult Sub = Rebuild(RHS); 17713 if (!Sub.isUsable()) 17714 return Sub; 17715 RHS = Sub.get(); 17716 } else { 17717 break; 17718 } 17719 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17720 LHS, RHS); 17721 } 17722 17723 // -- If e has the form (e1)... 17724 case Expr::ParenExprClass: { 17725 auto *PE = cast<ParenExpr>(E); 17726 ExprResult Sub = Rebuild(PE->getSubExpr()); 17727 if (!Sub.isUsable()) 17728 return Sub; 17729 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17730 } 17731 17732 // -- If e is a glvalue conditional expression, ... 17733 // We don't apply this to a binary conditional operator. FIXME: Should we? 17734 case Expr::ConditionalOperatorClass: { 17735 auto *CO = cast<ConditionalOperator>(E); 17736 ExprResult LHS = Rebuild(CO->getLHS()); 17737 if (LHS.isInvalid()) 17738 return ExprError(); 17739 ExprResult RHS = Rebuild(CO->getRHS()); 17740 if (RHS.isInvalid()) 17741 return ExprError(); 17742 if (!LHS.isUsable() && !RHS.isUsable()) 17743 return ExprEmpty(); 17744 if (!LHS.isUsable()) 17745 LHS = CO->getLHS(); 17746 if (!RHS.isUsable()) 17747 RHS = CO->getRHS(); 17748 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17749 CO->getCond(), LHS.get(), RHS.get()); 17750 } 17751 17752 // [Clang extension] 17753 // -- If e has the form __extension__ e1... 17754 case Expr::UnaryOperatorClass: { 17755 auto *UO = cast<UnaryOperator>(E); 17756 if (UO->getOpcode() != UO_Extension) 17757 break; 17758 ExprResult Sub = Rebuild(UO->getSubExpr()); 17759 if (!Sub.isUsable()) 17760 return Sub; 17761 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17762 Sub.get()); 17763 } 17764 17765 // [Clang extension] 17766 // -- If e has the form _Generic(...), the set of potential results is the 17767 // union of the sets of potential results of the associated expressions. 17768 case Expr::GenericSelectionExprClass: { 17769 auto *GSE = cast<GenericSelectionExpr>(E); 17770 17771 SmallVector<Expr *, 4> AssocExprs; 17772 bool AnyChanged = false; 17773 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17774 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17775 if (AssocExpr.isInvalid()) 17776 return ExprError(); 17777 if (AssocExpr.isUsable()) { 17778 AssocExprs.push_back(AssocExpr.get()); 17779 AnyChanged = true; 17780 } else { 17781 AssocExprs.push_back(OrigAssocExpr); 17782 } 17783 } 17784 17785 return AnyChanged ? S.CreateGenericSelectionExpr( 17786 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17787 GSE->getRParenLoc(), GSE->getControllingExpr(), 17788 GSE->getAssocTypeSourceInfos(), AssocExprs) 17789 : ExprEmpty(); 17790 } 17791 17792 // [Clang extension] 17793 // -- If e has the form __builtin_choose_expr(...), the set of potential 17794 // results is the union of the sets of potential results of the 17795 // second and third subexpressions. 17796 case Expr::ChooseExprClass: { 17797 auto *CE = cast<ChooseExpr>(E); 17798 17799 ExprResult LHS = Rebuild(CE->getLHS()); 17800 if (LHS.isInvalid()) 17801 return ExprError(); 17802 17803 ExprResult RHS = Rebuild(CE->getLHS()); 17804 if (RHS.isInvalid()) 17805 return ExprError(); 17806 17807 if (!LHS.get() && !RHS.get()) 17808 return ExprEmpty(); 17809 if (!LHS.isUsable()) 17810 LHS = CE->getLHS(); 17811 if (!RHS.isUsable()) 17812 RHS = CE->getRHS(); 17813 17814 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17815 RHS.get(), CE->getRParenLoc()); 17816 } 17817 17818 // Step through non-syntactic nodes. 17819 case Expr::ConstantExprClass: { 17820 auto *CE = cast<ConstantExpr>(E); 17821 ExprResult Sub = Rebuild(CE->getSubExpr()); 17822 if (!Sub.isUsable()) 17823 return Sub; 17824 return ConstantExpr::Create(S.Context, Sub.get()); 17825 } 17826 17827 // We could mostly rely on the recursive rebuilding to rebuild implicit 17828 // casts, but not at the top level, so rebuild them here. 17829 case Expr::ImplicitCastExprClass: { 17830 auto *ICE = cast<ImplicitCastExpr>(E); 17831 // Only step through the narrow set of cast kinds we expect to encounter. 17832 // Anything else suggests we've left the region in which potential results 17833 // can be found. 17834 switch (ICE->getCastKind()) { 17835 case CK_NoOp: 17836 case CK_DerivedToBase: 17837 case CK_UncheckedDerivedToBase: { 17838 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17839 if (!Sub.isUsable()) 17840 return Sub; 17841 CXXCastPath Path(ICE->path()); 17842 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17843 ICE->getValueKind(), &Path); 17844 } 17845 17846 default: 17847 break; 17848 } 17849 break; 17850 } 17851 17852 default: 17853 break; 17854 } 17855 17856 // Can't traverse through this node. Nothing to do. 17857 return ExprEmpty(); 17858 } 17859 17860 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17861 // Check whether the operand is or contains an object of non-trivial C union 17862 // type. 17863 if (E->getType().isVolatileQualified() && 17864 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17865 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17866 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17867 Sema::NTCUC_LValueToRValueVolatile, 17868 NTCUK_Destruct|NTCUK_Copy); 17869 17870 // C++2a [basic.def.odr]p4: 17871 // [...] an expression of non-volatile-qualified non-class type to which 17872 // the lvalue-to-rvalue conversion is applied [...] 17873 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17874 return E; 17875 17876 ExprResult Result = 17877 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17878 if (Result.isInvalid()) 17879 return ExprError(); 17880 return Result.get() ? Result : E; 17881 } 17882 17883 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17884 Res = CorrectDelayedTyposInExpr(Res); 17885 17886 if (!Res.isUsable()) 17887 return Res; 17888 17889 // If a constant-expression is a reference to a variable where we delay 17890 // deciding whether it is an odr-use, just assume we will apply the 17891 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17892 // (a non-type template argument), we have special handling anyway. 17893 return CheckLValueToRValueConversionOperand(Res.get()); 17894 } 17895 17896 void Sema::CleanupVarDeclMarking() { 17897 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17898 // call. 17899 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17900 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17901 17902 for (Expr *E : LocalMaybeODRUseExprs) { 17903 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17904 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17905 DRE->getLocation(), *this); 17906 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17907 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17908 *this); 17909 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17910 for (VarDecl *VD : *FP) 17911 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17912 } else { 17913 llvm_unreachable("Unexpected expression"); 17914 } 17915 } 17916 17917 assert(MaybeODRUseExprs.empty() && 17918 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17919 } 17920 17921 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17922 VarDecl *Var, Expr *E) { 17923 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17924 isa<FunctionParmPackExpr>(E)) && 17925 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17926 Var->setReferenced(); 17927 17928 if (Var->isInvalidDecl()) 17929 return; 17930 17931 // Record a CUDA/HIP static device/constant variable if it is referenced 17932 // by host code. This is done conservatively, when the variable is referenced 17933 // in any of the following contexts: 17934 // - a non-function context 17935 // - a host function 17936 // - a host device function 17937 // This also requires the reference of the static device/constant variable by 17938 // host code to be visible in the device compilation for the compiler to be 17939 // able to externalize the static device/constant variable. 17940 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 17941 auto *CurContext = SemaRef.CurContext; 17942 if (!CurContext || !isa<FunctionDecl>(CurContext) || 17943 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 17944 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 17945 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 17946 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 17947 } 17948 17949 auto *MSI = Var->getMemberSpecializationInfo(); 17950 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17951 : Var->getTemplateSpecializationKind(); 17952 17953 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17954 bool UsableInConstantExpr = 17955 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17956 17957 // C++20 [expr.const]p12: 17958 // A variable [...] is needed for constant evaluation if it is [...] a 17959 // variable whose name appears as a potentially constant evaluated 17960 // expression that is either a contexpr variable or is of non-volatile 17961 // const-qualified integral type or of reference type 17962 bool NeededForConstantEvaluation = 17963 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17964 17965 bool NeedDefinition = 17966 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17967 17968 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17969 "Can't instantiate a partial template specialization."); 17970 17971 // If this might be a member specialization of a static data member, check 17972 // the specialization is visible. We already did the checks for variable 17973 // template specializations when we created them. 17974 if (NeedDefinition && TSK != TSK_Undeclared && 17975 !isa<VarTemplateSpecializationDecl>(Var)) 17976 SemaRef.checkSpecializationVisibility(Loc, Var); 17977 17978 // Perform implicit instantiation of static data members, static data member 17979 // templates of class templates, and variable template specializations. Delay 17980 // instantiations of variable templates, except for those that could be used 17981 // in a constant expression. 17982 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17983 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17984 // instantiation declaration if a variable is usable in a constant 17985 // expression (among other cases). 17986 bool TryInstantiating = 17987 TSK == TSK_ImplicitInstantiation || 17988 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17989 17990 if (TryInstantiating) { 17991 SourceLocation PointOfInstantiation = 17992 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17993 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17994 if (FirstInstantiation) { 17995 PointOfInstantiation = Loc; 17996 if (MSI) 17997 MSI->setPointOfInstantiation(PointOfInstantiation); 17998 else 17999 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18000 } 18001 18002 if (UsableInConstantExpr) { 18003 // Do not defer instantiations of variables that could be used in a 18004 // constant expression. 18005 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18006 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18007 }); 18008 } else if (FirstInstantiation || 18009 isa<VarTemplateSpecializationDecl>(Var)) { 18010 // FIXME: For a specialization of a variable template, we don't 18011 // distinguish between "declaration and type implicitly instantiated" 18012 // and "implicit instantiation of definition requested", so we have 18013 // no direct way to avoid enqueueing the pending instantiation 18014 // multiple times. 18015 SemaRef.PendingInstantiations 18016 .push_back(std::make_pair(Var, PointOfInstantiation)); 18017 } 18018 } 18019 } 18020 18021 // C++2a [basic.def.odr]p4: 18022 // A variable x whose name appears as a potentially-evaluated expression e 18023 // is odr-used by e unless 18024 // -- x is a reference that is usable in constant expressions 18025 // -- x is a variable of non-reference type that is usable in constant 18026 // expressions and has no mutable subobjects [FIXME], and e is an 18027 // element of the set of potential results of an expression of 18028 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18029 // conversion is applied 18030 // -- x is a variable of non-reference type, and e is an element of the set 18031 // of potential results of a discarded-value expression to which the 18032 // lvalue-to-rvalue conversion is not applied [FIXME] 18033 // 18034 // We check the first part of the second bullet here, and 18035 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18036 // FIXME: To get the third bullet right, we need to delay this even for 18037 // variables that are not usable in constant expressions. 18038 18039 // If we already know this isn't an odr-use, there's nothing more to do. 18040 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18041 if (DRE->isNonOdrUse()) 18042 return; 18043 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18044 if (ME->isNonOdrUse()) 18045 return; 18046 18047 switch (OdrUse) { 18048 case OdrUseContext::None: 18049 assert((!E || isa<FunctionParmPackExpr>(E)) && 18050 "missing non-odr-use marking for unevaluated decl ref"); 18051 break; 18052 18053 case OdrUseContext::FormallyOdrUsed: 18054 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18055 // behavior. 18056 break; 18057 18058 case OdrUseContext::Used: 18059 // If we might later find that this expression isn't actually an odr-use, 18060 // delay the marking. 18061 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18062 SemaRef.MaybeODRUseExprs.insert(E); 18063 else 18064 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18065 break; 18066 18067 case OdrUseContext::Dependent: 18068 // If this is a dependent context, we don't need to mark variables as 18069 // odr-used, but we may still need to track them for lambda capture. 18070 // FIXME: Do we also need to do this inside dependent typeid expressions 18071 // (which are modeled as unevaluated at this point)? 18072 const bool RefersToEnclosingScope = 18073 (SemaRef.CurContext != Var->getDeclContext() && 18074 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18075 if (RefersToEnclosingScope) { 18076 LambdaScopeInfo *const LSI = 18077 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18078 if (LSI && (!LSI->CallOperator || 18079 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18080 // If a variable could potentially be odr-used, defer marking it so 18081 // until we finish analyzing the full expression for any 18082 // lvalue-to-rvalue 18083 // or discarded value conversions that would obviate odr-use. 18084 // Add it to the list of potential captures that will be analyzed 18085 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18086 // unless the variable is a reference that was initialized by a constant 18087 // expression (this will never need to be captured or odr-used). 18088 // 18089 // FIXME: We can simplify this a lot after implementing P0588R1. 18090 assert(E && "Capture variable should be used in an expression."); 18091 if (!Var->getType()->isReferenceType() || 18092 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18093 LSI->addPotentialCapture(E->IgnoreParens()); 18094 } 18095 } 18096 break; 18097 } 18098 } 18099 18100 /// Mark a variable referenced, and check whether it is odr-used 18101 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18102 /// used directly for normal expressions referring to VarDecl. 18103 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18104 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18105 } 18106 18107 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18108 Decl *D, Expr *E, bool MightBeOdrUse) { 18109 if (SemaRef.isInOpenMPDeclareTargetContext()) 18110 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18111 18112 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18113 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18114 return; 18115 } 18116 18117 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18118 18119 // If this is a call to a method via a cast, also mark the method in the 18120 // derived class used in case codegen can devirtualize the call. 18121 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18122 if (!ME) 18123 return; 18124 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18125 if (!MD) 18126 return; 18127 // Only attempt to devirtualize if this is truly a virtual call. 18128 bool IsVirtualCall = MD->isVirtual() && 18129 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18130 if (!IsVirtualCall) 18131 return; 18132 18133 // If it's possible to devirtualize the call, mark the called function 18134 // referenced. 18135 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18136 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18137 if (DM) 18138 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18139 } 18140 18141 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18142 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18143 // TODO: update this with DR# once a defect report is filed. 18144 // C++11 defect. The address of a pure member should not be an ODR use, even 18145 // if it's a qualified reference. 18146 bool OdrUse = true; 18147 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18148 if (Method->isVirtual() && 18149 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18150 OdrUse = false; 18151 18152 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18153 if (!isConstantEvaluated() && FD->isConsteval() && 18154 !RebuildingImmediateInvocation) 18155 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18156 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18157 } 18158 18159 /// Perform reference-marking and odr-use handling for a MemberExpr. 18160 void Sema::MarkMemberReferenced(MemberExpr *E) { 18161 // C++11 [basic.def.odr]p2: 18162 // A non-overloaded function whose name appears as a potentially-evaluated 18163 // expression or a member of a set of candidate functions, if selected by 18164 // overload resolution when referred to from a potentially-evaluated 18165 // expression, is odr-used, unless it is a pure virtual function and its 18166 // name is not explicitly qualified. 18167 bool MightBeOdrUse = true; 18168 if (E->performsVirtualDispatch(getLangOpts())) { 18169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18170 if (Method->isPure()) 18171 MightBeOdrUse = false; 18172 } 18173 SourceLocation Loc = 18174 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18175 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18176 } 18177 18178 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18179 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18180 for (VarDecl *VD : *E) 18181 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18182 } 18183 18184 /// Perform marking for a reference to an arbitrary declaration. It 18185 /// marks the declaration referenced, and performs odr-use checking for 18186 /// functions and variables. This method should not be used when building a 18187 /// normal expression which refers to a variable. 18188 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18189 bool MightBeOdrUse) { 18190 if (MightBeOdrUse) { 18191 if (auto *VD = dyn_cast<VarDecl>(D)) { 18192 MarkVariableReferenced(Loc, VD); 18193 return; 18194 } 18195 } 18196 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18197 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18198 return; 18199 } 18200 D->setReferenced(); 18201 } 18202 18203 namespace { 18204 // Mark all of the declarations used by a type as referenced. 18205 // FIXME: Not fully implemented yet! We need to have a better understanding 18206 // of when we're entering a context we should not recurse into. 18207 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18208 // TreeTransforms rebuilding the type in a new context. Rather than 18209 // duplicating the TreeTransform logic, we should consider reusing it here. 18210 // Currently that causes problems when rebuilding LambdaExprs. 18211 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18212 Sema &S; 18213 SourceLocation Loc; 18214 18215 public: 18216 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18217 18218 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18219 18220 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18221 }; 18222 } 18223 18224 bool MarkReferencedDecls::TraverseTemplateArgument( 18225 const TemplateArgument &Arg) { 18226 { 18227 // A non-type template argument is a constant-evaluated context. 18228 EnterExpressionEvaluationContext Evaluated( 18229 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18230 if (Arg.getKind() == TemplateArgument::Declaration) { 18231 if (Decl *D = Arg.getAsDecl()) 18232 S.MarkAnyDeclReferenced(Loc, D, true); 18233 } else if (Arg.getKind() == TemplateArgument::Expression) { 18234 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18235 } 18236 } 18237 18238 return Inherited::TraverseTemplateArgument(Arg); 18239 } 18240 18241 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18242 MarkReferencedDecls Marker(*this, Loc); 18243 Marker.TraverseType(T); 18244 } 18245 18246 namespace { 18247 /// Helper class that marks all of the declarations referenced by 18248 /// potentially-evaluated subexpressions as "referenced". 18249 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18250 public: 18251 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18252 bool SkipLocalVariables; 18253 18254 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18255 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18256 18257 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18258 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18259 } 18260 18261 void VisitDeclRefExpr(DeclRefExpr *E) { 18262 // If we were asked not to visit local variables, don't. 18263 if (SkipLocalVariables) { 18264 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18265 if (VD->hasLocalStorage()) 18266 return; 18267 } 18268 S.MarkDeclRefReferenced(E); 18269 } 18270 18271 void VisitMemberExpr(MemberExpr *E) { 18272 S.MarkMemberReferenced(E); 18273 Visit(E->getBase()); 18274 } 18275 }; 18276 } // namespace 18277 18278 /// Mark any declarations that appear within this expression or any 18279 /// potentially-evaluated subexpressions as "referenced". 18280 /// 18281 /// \param SkipLocalVariables If true, don't mark local variables as 18282 /// 'referenced'. 18283 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18284 bool SkipLocalVariables) { 18285 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18286 } 18287 18288 /// Emit a diagnostic that describes an effect on the run-time behavior 18289 /// of the program being compiled. 18290 /// 18291 /// This routine emits the given diagnostic when the code currently being 18292 /// type-checked is "potentially evaluated", meaning that there is a 18293 /// possibility that the code will actually be executable. Code in sizeof() 18294 /// expressions, code used only during overload resolution, etc., are not 18295 /// potentially evaluated. This routine will suppress such diagnostics or, 18296 /// in the absolutely nutty case of potentially potentially evaluated 18297 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18298 /// later. 18299 /// 18300 /// This routine should be used for all diagnostics that describe the run-time 18301 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18302 /// Failure to do so will likely result in spurious diagnostics or failures 18303 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18304 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18305 const PartialDiagnostic &PD) { 18306 switch (ExprEvalContexts.back().Context) { 18307 case ExpressionEvaluationContext::Unevaluated: 18308 case ExpressionEvaluationContext::UnevaluatedList: 18309 case ExpressionEvaluationContext::UnevaluatedAbstract: 18310 case ExpressionEvaluationContext::DiscardedStatement: 18311 // The argument will never be evaluated, so don't complain. 18312 break; 18313 18314 case ExpressionEvaluationContext::ConstantEvaluated: 18315 // Relevant diagnostics should be produced by constant evaluation. 18316 break; 18317 18318 case ExpressionEvaluationContext::PotentiallyEvaluated: 18319 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18320 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18321 FunctionScopes.back()->PossiblyUnreachableDiags. 18322 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18323 return true; 18324 } 18325 18326 // The initializer of a constexpr variable or of the first declaration of a 18327 // static data member is not syntactically a constant evaluated constant, 18328 // but nonetheless is always required to be a constant expression, so we 18329 // can skip diagnosing. 18330 // FIXME: Using the mangling context here is a hack. 18331 if (auto *VD = dyn_cast_or_null<VarDecl>( 18332 ExprEvalContexts.back().ManglingContextDecl)) { 18333 if (VD->isConstexpr() || 18334 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18335 break; 18336 // FIXME: For any other kind of variable, we should build a CFG for its 18337 // initializer and check whether the context in question is reachable. 18338 } 18339 18340 Diag(Loc, PD); 18341 return true; 18342 } 18343 18344 return false; 18345 } 18346 18347 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18348 const PartialDiagnostic &PD) { 18349 return DiagRuntimeBehavior( 18350 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18351 } 18352 18353 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18354 CallExpr *CE, FunctionDecl *FD) { 18355 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18356 return false; 18357 18358 // If we're inside a decltype's expression, don't check for a valid return 18359 // type or construct temporaries until we know whether this is the last call. 18360 if (ExprEvalContexts.back().ExprContext == 18361 ExpressionEvaluationContextRecord::EK_Decltype) { 18362 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18363 return false; 18364 } 18365 18366 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18367 FunctionDecl *FD; 18368 CallExpr *CE; 18369 18370 public: 18371 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18372 : FD(FD), CE(CE) { } 18373 18374 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18375 if (!FD) { 18376 S.Diag(Loc, diag::err_call_incomplete_return) 18377 << T << CE->getSourceRange(); 18378 return; 18379 } 18380 18381 S.Diag(Loc, diag::err_call_function_incomplete_return) 18382 << CE->getSourceRange() << FD << T; 18383 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18384 << FD->getDeclName(); 18385 } 18386 } Diagnoser(FD, CE); 18387 18388 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18389 return true; 18390 18391 return false; 18392 } 18393 18394 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18395 // will prevent this condition from triggering, which is what we want. 18396 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18397 SourceLocation Loc; 18398 18399 unsigned diagnostic = diag::warn_condition_is_assignment; 18400 bool IsOrAssign = false; 18401 18402 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18403 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18404 return; 18405 18406 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18407 18408 // Greylist some idioms by putting them into a warning subcategory. 18409 if (ObjCMessageExpr *ME 18410 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18411 Selector Sel = ME->getSelector(); 18412 18413 // self = [<foo> init...] 18414 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18415 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18416 18417 // <foo> = [<bar> nextObject] 18418 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18419 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18420 } 18421 18422 Loc = Op->getOperatorLoc(); 18423 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18424 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18425 return; 18426 18427 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18428 Loc = Op->getOperatorLoc(); 18429 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18430 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18431 else { 18432 // Not an assignment. 18433 return; 18434 } 18435 18436 Diag(Loc, diagnostic) << E->getSourceRange(); 18437 18438 SourceLocation Open = E->getBeginLoc(); 18439 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18440 Diag(Loc, diag::note_condition_assign_silence) 18441 << FixItHint::CreateInsertion(Open, "(") 18442 << FixItHint::CreateInsertion(Close, ")"); 18443 18444 if (IsOrAssign) 18445 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18446 << FixItHint::CreateReplacement(Loc, "!="); 18447 else 18448 Diag(Loc, diag::note_condition_assign_to_comparison) 18449 << FixItHint::CreateReplacement(Loc, "=="); 18450 } 18451 18452 /// Redundant parentheses over an equality comparison can indicate 18453 /// that the user intended an assignment used as condition. 18454 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18455 // Don't warn if the parens came from a macro. 18456 SourceLocation parenLoc = ParenE->getBeginLoc(); 18457 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18458 return; 18459 // Don't warn for dependent expressions. 18460 if (ParenE->isTypeDependent()) 18461 return; 18462 18463 Expr *E = ParenE->IgnoreParens(); 18464 18465 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18466 if (opE->getOpcode() == BO_EQ && 18467 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18468 == Expr::MLV_Valid) { 18469 SourceLocation Loc = opE->getOperatorLoc(); 18470 18471 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18472 SourceRange ParenERange = ParenE->getSourceRange(); 18473 Diag(Loc, diag::note_equality_comparison_silence) 18474 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18475 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18476 Diag(Loc, diag::note_equality_comparison_to_assign) 18477 << FixItHint::CreateReplacement(Loc, "="); 18478 } 18479 } 18480 18481 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18482 bool IsConstexpr) { 18483 DiagnoseAssignmentAsCondition(E); 18484 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18485 DiagnoseEqualityWithExtraParens(parenE); 18486 18487 ExprResult result = CheckPlaceholderExpr(E); 18488 if (result.isInvalid()) return ExprError(); 18489 E = result.get(); 18490 18491 if (!E->isTypeDependent()) { 18492 if (getLangOpts().CPlusPlus) 18493 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18494 18495 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18496 if (ERes.isInvalid()) 18497 return ExprError(); 18498 E = ERes.get(); 18499 18500 QualType T = E->getType(); 18501 if (!T->isScalarType()) { // C99 6.8.4.1p1 18502 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18503 << T << E->getSourceRange(); 18504 return ExprError(); 18505 } 18506 CheckBoolLikeConversion(E, Loc); 18507 } 18508 18509 return E; 18510 } 18511 18512 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18513 Expr *SubExpr, ConditionKind CK) { 18514 // Empty conditions are valid in for-statements. 18515 if (!SubExpr) 18516 return ConditionResult(); 18517 18518 ExprResult Cond; 18519 switch (CK) { 18520 case ConditionKind::Boolean: 18521 Cond = CheckBooleanCondition(Loc, SubExpr); 18522 break; 18523 18524 case ConditionKind::ConstexprIf: 18525 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18526 break; 18527 18528 case ConditionKind::Switch: 18529 Cond = CheckSwitchCondition(Loc, SubExpr); 18530 break; 18531 } 18532 if (Cond.isInvalid()) { 18533 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18534 {SubExpr}); 18535 if (!Cond.get()) 18536 return ConditionError(); 18537 } 18538 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18539 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18540 if (!FullExpr.get()) 18541 return ConditionError(); 18542 18543 return ConditionResult(*this, nullptr, FullExpr, 18544 CK == ConditionKind::ConstexprIf); 18545 } 18546 18547 namespace { 18548 /// A visitor for rebuilding a call to an __unknown_any expression 18549 /// to have an appropriate type. 18550 struct RebuildUnknownAnyFunction 18551 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18552 18553 Sema &S; 18554 18555 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18556 18557 ExprResult VisitStmt(Stmt *S) { 18558 llvm_unreachable("unexpected statement!"); 18559 } 18560 18561 ExprResult VisitExpr(Expr *E) { 18562 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18563 << E->getSourceRange(); 18564 return ExprError(); 18565 } 18566 18567 /// Rebuild an expression which simply semantically wraps another 18568 /// expression which it shares the type and value kind of. 18569 template <class T> ExprResult rebuildSugarExpr(T *E) { 18570 ExprResult SubResult = Visit(E->getSubExpr()); 18571 if (SubResult.isInvalid()) return ExprError(); 18572 18573 Expr *SubExpr = SubResult.get(); 18574 E->setSubExpr(SubExpr); 18575 E->setType(SubExpr->getType()); 18576 E->setValueKind(SubExpr->getValueKind()); 18577 assert(E->getObjectKind() == OK_Ordinary); 18578 return E; 18579 } 18580 18581 ExprResult VisitParenExpr(ParenExpr *E) { 18582 return rebuildSugarExpr(E); 18583 } 18584 18585 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18586 return rebuildSugarExpr(E); 18587 } 18588 18589 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18590 ExprResult SubResult = Visit(E->getSubExpr()); 18591 if (SubResult.isInvalid()) return ExprError(); 18592 18593 Expr *SubExpr = SubResult.get(); 18594 E->setSubExpr(SubExpr); 18595 E->setType(S.Context.getPointerType(SubExpr->getType())); 18596 assert(E->getValueKind() == VK_RValue); 18597 assert(E->getObjectKind() == OK_Ordinary); 18598 return E; 18599 } 18600 18601 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18602 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18603 18604 E->setType(VD->getType()); 18605 18606 assert(E->getValueKind() == VK_RValue); 18607 if (S.getLangOpts().CPlusPlus && 18608 !(isa<CXXMethodDecl>(VD) && 18609 cast<CXXMethodDecl>(VD)->isInstance())) 18610 E->setValueKind(VK_LValue); 18611 18612 return E; 18613 } 18614 18615 ExprResult VisitMemberExpr(MemberExpr *E) { 18616 return resolveDecl(E, E->getMemberDecl()); 18617 } 18618 18619 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18620 return resolveDecl(E, E->getDecl()); 18621 } 18622 }; 18623 } 18624 18625 /// Given a function expression of unknown-any type, try to rebuild it 18626 /// to have a function type. 18627 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18628 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18629 if (Result.isInvalid()) return ExprError(); 18630 return S.DefaultFunctionArrayConversion(Result.get()); 18631 } 18632 18633 namespace { 18634 /// A visitor for rebuilding an expression of type __unknown_anytype 18635 /// into one which resolves the type directly on the referring 18636 /// expression. Strict preservation of the original source 18637 /// structure is not a goal. 18638 struct RebuildUnknownAnyExpr 18639 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18640 18641 Sema &S; 18642 18643 /// The current destination type. 18644 QualType DestType; 18645 18646 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18647 : S(S), DestType(CastType) {} 18648 18649 ExprResult VisitStmt(Stmt *S) { 18650 llvm_unreachable("unexpected statement!"); 18651 } 18652 18653 ExprResult VisitExpr(Expr *E) { 18654 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18655 << E->getSourceRange(); 18656 return ExprError(); 18657 } 18658 18659 ExprResult VisitCallExpr(CallExpr *E); 18660 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18661 18662 /// Rebuild an expression which simply semantically wraps another 18663 /// expression which it shares the type and value kind of. 18664 template <class T> ExprResult rebuildSugarExpr(T *E) { 18665 ExprResult SubResult = Visit(E->getSubExpr()); 18666 if (SubResult.isInvalid()) return ExprError(); 18667 Expr *SubExpr = SubResult.get(); 18668 E->setSubExpr(SubExpr); 18669 E->setType(SubExpr->getType()); 18670 E->setValueKind(SubExpr->getValueKind()); 18671 assert(E->getObjectKind() == OK_Ordinary); 18672 return E; 18673 } 18674 18675 ExprResult VisitParenExpr(ParenExpr *E) { 18676 return rebuildSugarExpr(E); 18677 } 18678 18679 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18680 return rebuildSugarExpr(E); 18681 } 18682 18683 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18684 const PointerType *Ptr = DestType->getAs<PointerType>(); 18685 if (!Ptr) { 18686 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18687 << E->getSourceRange(); 18688 return ExprError(); 18689 } 18690 18691 if (isa<CallExpr>(E->getSubExpr())) { 18692 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18693 << E->getSourceRange(); 18694 return ExprError(); 18695 } 18696 18697 assert(E->getValueKind() == VK_RValue); 18698 assert(E->getObjectKind() == OK_Ordinary); 18699 E->setType(DestType); 18700 18701 // Build the sub-expression as if it were an object of the pointee type. 18702 DestType = Ptr->getPointeeType(); 18703 ExprResult SubResult = Visit(E->getSubExpr()); 18704 if (SubResult.isInvalid()) return ExprError(); 18705 E->setSubExpr(SubResult.get()); 18706 return E; 18707 } 18708 18709 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18710 18711 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18712 18713 ExprResult VisitMemberExpr(MemberExpr *E) { 18714 return resolveDecl(E, E->getMemberDecl()); 18715 } 18716 18717 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18718 return resolveDecl(E, E->getDecl()); 18719 } 18720 }; 18721 } 18722 18723 /// Rebuilds a call expression which yielded __unknown_anytype. 18724 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18725 Expr *CalleeExpr = E->getCallee(); 18726 18727 enum FnKind { 18728 FK_MemberFunction, 18729 FK_FunctionPointer, 18730 FK_BlockPointer 18731 }; 18732 18733 FnKind Kind; 18734 QualType CalleeType = CalleeExpr->getType(); 18735 if (CalleeType == S.Context.BoundMemberTy) { 18736 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18737 Kind = FK_MemberFunction; 18738 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18739 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18740 CalleeType = Ptr->getPointeeType(); 18741 Kind = FK_FunctionPointer; 18742 } else { 18743 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18744 Kind = FK_BlockPointer; 18745 } 18746 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18747 18748 // Verify that this is a legal result type of a function. 18749 if (DestType->isArrayType() || DestType->isFunctionType()) { 18750 unsigned diagID = diag::err_func_returning_array_function; 18751 if (Kind == FK_BlockPointer) 18752 diagID = diag::err_block_returning_array_function; 18753 18754 S.Diag(E->getExprLoc(), diagID) 18755 << DestType->isFunctionType() << DestType; 18756 return ExprError(); 18757 } 18758 18759 // Otherwise, go ahead and set DestType as the call's result. 18760 E->setType(DestType.getNonLValueExprType(S.Context)); 18761 E->setValueKind(Expr::getValueKindForType(DestType)); 18762 assert(E->getObjectKind() == OK_Ordinary); 18763 18764 // Rebuild the function type, replacing the result type with DestType. 18765 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18766 if (Proto) { 18767 // __unknown_anytype(...) is a special case used by the debugger when 18768 // it has no idea what a function's signature is. 18769 // 18770 // We want to build this call essentially under the K&R 18771 // unprototyped rules, but making a FunctionNoProtoType in C++ 18772 // would foul up all sorts of assumptions. However, we cannot 18773 // simply pass all arguments as variadic arguments, nor can we 18774 // portably just call the function under a non-variadic type; see 18775 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18776 // However, it turns out that in practice it is generally safe to 18777 // call a function declared as "A foo(B,C,D);" under the prototype 18778 // "A foo(B,C,D,...);". The only known exception is with the 18779 // Windows ABI, where any variadic function is implicitly cdecl 18780 // regardless of its normal CC. Therefore we change the parameter 18781 // types to match the types of the arguments. 18782 // 18783 // This is a hack, but it is far superior to moving the 18784 // corresponding target-specific code from IR-gen to Sema/AST. 18785 18786 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18787 SmallVector<QualType, 8> ArgTypes; 18788 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18789 ArgTypes.reserve(E->getNumArgs()); 18790 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18791 Expr *Arg = E->getArg(i); 18792 QualType ArgType = Arg->getType(); 18793 if (E->isLValue()) { 18794 ArgType = S.Context.getLValueReferenceType(ArgType); 18795 } else if (E->isXValue()) { 18796 ArgType = S.Context.getRValueReferenceType(ArgType); 18797 } 18798 ArgTypes.push_back(ArgType); 18799 } 18800 ParamTypes = ArgTypes; 18801 } 18802 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18803 Proto->getExtProtoInfo()); 18804 } else { 18805 DestType = S.Context.getFunctionNoProtoType(DestType, 18806 FnType->getExtInfo()); 18807 } 18808 18809 // Rebuild the appropriate pointer-to-function type. 18810 switch (Kind) { 18811 case FK_MemberFunction: 18812 // Nothing to do. 18813 break; 18814 18815 case FK_FunctionPointer: 18816 DestType = S.Context.getPointerType(DestType); 18817 break; 18818 18819 case FK_BlockPointer: 18820 DestType = S.Context.getBlockPointerType(DestType); 18821 break; 18822 } 18823 18824 // Finally, we can recurse. 18825 ExprResult CalleeResult = Visit(CalleeExpr); 18826 if (!CalleeResult.isUsable()) return ExprError(); 18827 E->setCallee(CalleeResult.get()); 18828 18829 // Bind a temporary if necessary. 18830 return S.MaybeBindToTemporary(E); 18831 } 18832 18833 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18834 // Verify that this is a legal result type of a call. 18835 if (DestType->isArrayType() || DestType->isFunctionType()) { 18836 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18837 << DestType->isFunctionType() << DestType; 18838 return ExprError(); 18839 } 18840 18841 // Rewrite the method result type if available. 18842 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18843 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18844 Method->setReturnType(DestType); 18845 } 18846 18847 // Change the type of the message. 18848 E->setType(DestType.getNonReferenceType()); 18849 E->setValueKind(Expr::getValueKindForType(DestType)); 18850 18851 return S.MaybeBindToTemporary(E); 18852 } 18853 18854 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18855 // The only case we should ever see here is a function-to-pointer decay. 18856 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18857 assert(E->getValueKind() == VK_RValue); 18858 assert(E->getObjectKind() == OK_Ordinary); 18859 18860 E->setType(DestType); 18861 18862 // Rebuild the sub-expression as the pointee (function) type. 18863 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18864 18865 ExprResult Result = Visit(E->getSubExpr()); 18866 if (!Result.isUsable()) return ExprError(); 18867 18868 E->setSubExpr(Result.get()); 18869 return E; 18870 } else if (E->getCastKind() == CK_LValueToRValue) { 18871 assert(E->getValueKind() == VK_RValue); 18872 assert(E->getObjectKind() == OK_Ordinary); 18873 18874 assert(isa<BlockPointerType>(E->getType())); 18875 18876 E->setType(DestType); 18877 18878 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18879 DestType = S.Context.getLValueReferenceType(DestType); 18880 18881 ExprResult Result = Visit(E->getSubExpr()); 18882 if (!Result.isUsable()) return ExprError(); 18883 18884 E->setSubExpr(Result.get()); 18885 return E; 18886 } else { 18887 llvm_unreachable("Unhandled cast type!"); 18888 } 18889 } 18890 18891 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18892 ExprValueKind ValueKind = VK_LValue; 18893 QualType Type = DestType; 18894 18895 // We know how to make this work for certain kinds of decls: 18896 18897 // - functions 18898 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18899 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18900 DestType = Ptr->getPointeeType(); 18901 ExprResult Result = resolveDecl(E, VD); 18902 if (Result.isInvalid()) return ExprError(); 18903 return S.ImpCastExprToType(Result.get(), Type, 18904 CK_FunctionToPointerDecay, VK_RValue); 18905 } 18906 18907 if (!Type->isFunctionType()) { 18908 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18909 << VD << E->getSourceRange(); 18910 return ExprError(); 18911 } 18912 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18913 // We must match the FunctionDecl's type to the hack introduced in 18914 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18915 // type. See the lengthy commentary in that routine. 18916 QualType FDT = FD->getType(); 18917 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18918 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18919 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18920 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18921 SourceLocation Loc = FD->getLocation(); 18922 FunctionDecl *NewFD = FunctionDecl::Create( 18923 S.Context, FD->getDeclContext(), Loc, Loc, 18924 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18925 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18926 /*ConstexprKind*/ CSK_unspecified); 18927 18928 if (FD->getQualifier()) 18929 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18930 18931 SmallVector<ParmVarDecl*, 16> Params; 18932 for (const auto &AI : FT->param_types()) { 18933 ParmVarDecl *Param = 18934 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18935 Param->setScopeInfo(0, Params.size()); 18936 Params.push_back(Param); 18937 } 18938 NewFD->setParams(Params); 18939 DRE->setDecl(NewFD); 18940 VD = DRE->getDecl(); 18941 } 18942 } 18943 18944 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18945 if (MD->isInstance()) { 18946 ValueKind = VK_RValue; 18947 Type = S.Context.BoundMemberTy; 18948 } 18949 18950 // Function references aren't l-values in C. 18951 if (!S.getLangOpts().CPlusPlus) 18952 ValueKind = VK_RValue; 18953 18954 // - variables 18955 } else if (isa<VarDecl>(VD)) { 18956 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18957 Type = RefTy->getPointeeType(); 18958 } else if (Type->isFunctionType()) { 18959 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18960 << VD << E->getSourceRange(); 18961 return ExprError(); 18962 } 18963 18964 // - nothing else 18965 } else { 18966 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18967 << VD << E->getSourceRange(); 18968 return ExprError(); 18969 } 18970 18971 // Modifying the declaration like this is friendly to IR-gen but 18972 // also really dangerous. 18973 VD->setType(DestType); 18974 E->setType(Type); 18975 E->setValueKind(ValueKind); 18976 return E; 18977 } 18978 18979 /// Check a cast of an unknown-any type. We intentionally only 18980 /// trigger this for C-style casts. 18981 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18982 Expr *CastExpr, CastKind &CastKind, 18983 ExprValueKind &VK, CXXCastPath &Path) { 18984 // The type we're casting to must be either void or complete. 18985 if (!CastType->isVoidType() && 18986 RequireCompleteType(TypeRange.getBegin(), CastType, 18987 diag::err_typecheck_cast_to_incomplete)) 18988 return ExprError(); 18989 18990 // Rewrite the casted expression from scratch. 18991 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18992 if (!result.isUsable()) return ExprError(); 18993 18994 CastExpr = result.get(); 18995 VK = CastExpr->getValueKind(); 18996 CastKind = CK_NoOp; 18997 18998 return CastExpr; 18999 } 19000 19001 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19002 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19003 } 19004 19005 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19006 Expr *arg, QualType ¶mType) { 19007 // If the syntactic form of the argument is not an explicit cast of 19008 // any sort, just do default argument promotion. 19009 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19010 if (!castArg) { 19011 ExprResult result = DefaultArgumentPromotion(arg); 19012 if (result.isInvalid()) return ExprError(); 19013 paramType = result.get()->getType(); 19014 return result; 19015 } 19016 19017 // Otherwise, use the type that was written in the explicit cast. 19018 assert(!arg->hasPlaceholderType()); 19019 paramType = castArg->getTypeAsWritten(); 19020 19021 // Copy-initialize a parameter of that type. 19022 InitializedEntity entity = 19023 InitializedEntity::InitializeParameter(Context, paramType, 19024 /*consumed*/ false); 19025 return PerformCopyInitialization(entity, callLoc, arg); 19026 } 19027 19028 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19029 Expr *orig = E; 19030 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19031 while (true) { 19032 E = E->IgnoreParenImpCasts(); 19033 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19034 E = call->getCallee(); 19035 diagID = diag::err_uncasted_call_of_unknown_any; 19036 } else { 19037 break; 19038 } 19039 } 19040 19041 SourceLocation loc; 19042 NamedDecl *d; 19043 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19044 loc = ref->getLocation(); 19045 d = ref->getDecl(); 19046 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19047 loc = mem->getMemberLoc(); 19048 d = mem->getMemberDecl(); 19049 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19050 diagID = diag::err_uncasted_call_of_unknown_any; 19051 loc = msg->getSelectorStartLoc(); 19052 d = msg->getMethodDecl(); 19053 if (!d) { 19054 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19055 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19056 << orig->getSourceRange(); 19057 return ExprError(); 19058 } 19059 } else { 19060 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19061 << E->getSourceRange(); 19062 return ExprError(); 19063 } 19064 19065 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19066 19067 // Never recoverable. 19068 return ExprError(); 19069 } 19070 19071 /// Check for operands with placeholder types and complain if found. 19072 /// Returns ExprError() if there was an error and no recovery was possible. 19073 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19074 if (!Context.isDependenceAllowed()) { 19075 // C cannot handle TypoExpr nodes on either side of a binop because it 19076 // doesn't handle dependent types properly, so make sure any TypoExprs have 19077 // been dealt with before checking the operands. 19078 ExprResult Result = CorrectDelayedTyposInExpr(E); 19079 if (!Result.isUsable()) return ExprError(); 19080 E = Result.get(); 19081 } 19082 19083 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19084 if (!placeholderType) return E; 19085 19086 switch (placeholderType->getKind()) { 19087 19088 // Overloaded expressions. 19089 case BuiltinType::Overload: { 19090 // Try to resolve a single function template specialization. 19091 // This is obligatory. 19092 ExprResult Result = E; 19093 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19094 return Result; 19095 19096 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19097 // leaves Result unchanged on failure. 19098 Result = E; 19099 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19100 return Result; 19101 19102 // If that failed, try to recover with a call. 19103 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19104 /*complain*/ true); 19105 return Result; 19106 } 19107 19108 // Bound member functions. 19109 case BuiltinType::BoundMember: { 19110 ExprResult result = E; 19111 const Expr *BME = E->IgnoreParens(); 19112 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19113 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19114 if (isa<CXXPseudoDestructorExpr>(BME)) { 19115 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19116 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19117 if (ME->getMemberNameInfo().getName().getNameKind() == 19118 DeclarationName::CXXDestructorName) 19119 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19120 } 19121 tryToRecoverWithCall(result, PD, 19122 /*complain*/ true); 19123 return result; 19124 } 19125 19126 // ARC unbridged casts. 19127 case BuiltinType::ARCUnbridgedCast: { 19128 Expr *realCast = stripARCUnbridgedCast(E); 19129 diagnoseARCUnbridgedCast(realCast); 19130 return realCast; 19131 } 19132 19133 // Expressions of unknown type. 19134 case BuiltinType::UnknownAny: 19135 return diagnoseUnknownAnyExpr(*this, E); 19136 19137 // Pseudo-objects. 19138 case BuiltinType::PseudoObject: 19139 return checkPseudoObjectRValue(E); 19140 19141 case BuiltinType::BuiltinFn: { 19142 // Accept __noop without parens by implicitly converting it to a call expr. 19143 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19144 if (DRE) { 19145 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19146 if (FD->getBuiltinID() == Builtin::BI__noop) { 19147 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19148 CK_BuiltinFnToFnPtr) 19149 .get(); 19150 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19151 VK_RValue, SourceLocation(), 19152 FPOptionsOverride()); 19153 } 19154 } 19155 19156 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19157 return ExprError(); 19158 } 19159 19160 case BuiltinType::IncompleteMatrixIdx: 19161 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19162 ->getRowIdx() 19163 ->getBeginLoc(), 19164 diag::err_matrix_incomplete_index); 19165 return ExprError(); 19166 19167 // Expressions of unknown type. 19168 case BuiltinType::OMPArraySection: 19169 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19170 return ExprError(); 19171 19172 // Expressions of unknown type. 19173 case BuiltinType::OMPArrayShaping: 19174 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19175 19176 case BuiltinType::OMPIterator: 19177 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19178 19179 // Everything else should be impossible. 19180 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19181 case BuiltinType::Id: 19182 #include "clang/Basic/OpenCLImageTypes.def" 19183 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19184 case BuiltinType::Id: 19185 #include "clang/Basic/OpenCLExtensionTypes.def" 19186 #define SVE_TYPE(Name, Id, SingletonId) \ 19187 case BuiltinType::Id: 19188 #include "clang/Basic/AArch64SVEACLETypes.def" 19189 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19190 #define PLACEHOLDER_TYPE(Id, SingletonId) 19191 #include "clang/AST/BuiltinTypes.def" 19192 break; 19193 } 19194 19195 llvm_unreachable("invalid placeholder type!"); 19196 } 19197 19198 bool Sema::CheckCaseExpression(Expr *E) { 19199 if (E->isTypeDependent()) 19200 return true; 19201 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19202 return E->getType()->isIntegralOrEnumerationType(); 19203 return false; 19204 } 19205 19206 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19207 ExprResult 19208 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19209 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19210 "Unknown Objective-C Boolean value!"); 19211 QualType BoolT = Context.ObjCBuiltinBoolTy; 19212 if (!Context.getBOOLDecl()) { 19213 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19214 Sema::LookupOrdinaryName); 19215 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19216 NamedDecl *ND = Result.getFoundDecl(); 19217 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19218 Context.setBOOLDecl(TD); 19219 } 19220 } 19221 if (Context.getBOOLDecl()) 19222 BoolT = Context.getBOOLType(); 19223 return new (Context) 19224 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19225 } 19226 19227 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19228 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19229 SourceLocation RParen) { 19230 19231 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19232 19233 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19234 return Spec.getPlatform() == Platform; 19235 }); 19236 19237 VersionTuple Version; 19238 if (Spec != AvailSpecs.end()) 19239 Version = Spec->getVersion(); 19240 19241 // The use of `@available` in the enclosing function should be analyzed to 19242 // warn when it's used inappropriately (i.e. not if(@available)). 19243 if (getCurFunctionOrMethodDecl()) 19244 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19245 else if (getCurBlock() || getCurLambda()) 19246 getCurFunction()->HasPotentialAvailabilityViolations = true; 19247 19248 return new (Context) 19249 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19250 } 19251 19252 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19253 ArrayRef<Expr *> SubExprs, QualType T) { 19254 if (!Context.getLangOpts().RecoveryAST) 19255 return ExprError(); 19256 19257 if (isSFINAEContext()) 19258 return ExprError(); 19259 19260 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19261 // We don't know the concrete type, fallback to dependent type. 19262 T = Context.DependentTy; 19263 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19264 } 19265