1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/ADT/STLExtras.h" 50 #include "llvm/Support/ConvertUTF.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 using namespace clang; 53 using namespace sema; 54 using llvm::RoundingMode; 55 56 /// Determine whether the use of this declaration is valid, without 57 /// emitting diagnostics. 58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 59 // See if this is an auto-typed variable whose initializer we are parsing. 60 if (ParsingInitForAutoVars.count(D)) 61 return false; 62 63 // See if this is a deleted function. 64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 65 if (FD->isDeleted()) 66 return false; 67 68 // If the function has a deduced return type, and we can't deduce it, 69 // then we can't use it either. 70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 72 return false; 73 74 // See if this is an aligned allocation/deallocation function that is 75 // unavailable. 76 if (TreatUnavailableAsInvalid && 77 isUnavailableAlignedAllocationFunction(*FD)) 78 return false; 79 } 80 81 // See if this function is unavailable. 82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 84 return false; 85 86 return true; 87 } 88 89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 90 // Warn if this is used but marked unused. 91 if (const auto *A = D->getAttr<UnusedAttr>()) { 92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 93 // should diagnose them. 94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 97 if (DC && !DC->hasAttr<UnusedAttr>()) 98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 99 } 100 } 101 } 102 103 /// Emit a note explaining that this function is deleted. 104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 105 assert(Decl && Decl->isDeleted()); 106 107 if (Decl->isDefaulted()) { 108 // If the method was explicitly defaulted, point at that declaration. 109 if (!Decl->isImplicit()) 110 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 111 112 // Try to diagnose why this special member function was implicitly 113 // deleted. This might fail, if that reason no longer applies. 114 DiagnoseDeletedDefaultedFunction(Decl); 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 253 // See if this is a deleted function. 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // [expr.prim.id]p4 267 // A program that refers explicitly or implicitly to a function with a 268 // trailing requires-clause whose constraint-expression is not satisfied, 269 // other than to declare it, is ill-formed. [...] 270 // 271 // See if this is a function with constraints that need to be satisfied. 272 // Check this before deducing the return type, as it might instantiate the 273 // definition. 274 if (FD->getTrailingRequiresClause()) { 275 ConstraintSatisfaction Satisfaction; 276 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 277 // A diagnostic will have already been generated (non-constant 278 // constraint expression, for example) 279 return true; 280 if (!Satisfaction.IsSatisfied) { 281 Diag(Loc, 282 diag::err_reference_to_function_with_unsatisfied_constraints) 283 << D; 284 DiagnoseUnsatisfiedConstraint(Satisfaction); 285 return true; 286 } 287 } 288 289 // If the function has a deduced return type, and we can't deduce it, 290 // then we can't use it either. 291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 292 DeduceReturnType(FD, Loc)) 293 return true; 294 295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 296 return true; 297 298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 299 return true; 300 } 301 302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 303 // Lambdas are only default-constructible or assignable in C++2a onwards. 304 if (MD->getParent()->isLambda() && 305 ((isa<CXXConstructorDecl>(MD) && 306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 309 << !isa<CXXConstructorDecl>(MD); 310 } 311 } 312 313 auto getReferencedObjCProp = [](const NamedDecl *D) -> 314 const ObjCPropertyDecl * { 315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 316 return MD->findPropertyDecl(); 317 return nullptr; 318 }; 319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 321 return true; 322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 323 return true; 324 } 325 326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 327 // Only the variables omp_in and omp_out are allowed in the combiner. 328 // Only the variables omp_priv and omp_orig are allowed in the 329 // initializer-clause. 330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 332 isa<VarDecl>(D)) { 333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 334 << getCurFunction()->HasOMPDeclareReductionCombiner; 335 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 336 return true; 337 } 338 339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 340 // List-items in map clauses on this construct may only refer to the declared 341 // variable var and entities that could be referenced by a procedure defined 342 // at the same location 343 if (LangOpts.OpenMP && isa<VarDecl>(D) && 344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << getOpenMPDeclareMapperVarName(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 359 if (auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (!Context.getTargetInfo().isTLSSupported()) 363 if (const auto *VD = dyn_cast<VarDecl>(D)) 364 if (VD->getTLSKind() != VarDecl::TLS_None) 365 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 366 } 367 368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 369 !isUnevaluatedContext()) { 370 // C++ [expr.prim.req.nested] p3 371 // A local parameter shall only appear as an unevaluated operand 372 // (Clause 8) within the constraint-expression. 373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 374 << D; 375 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 376 return true; 377 } 378 379 return false; 380 } 381 382 /// DiagnoseSentinelCalls - This routine checks whether a call or 383 /// message-send is to a declaration with the sentinel attribute, and 384 /// if so, it checks that the requirements of the sentinel are 385 /// satisfied. 386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 387 ArrayRef<Expr *> Args) { 388 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 389 if (!attr) 390 return; 391 392 // The number of formal parameters of the declaration. 393 unsigned numFormalParams; 394 395 // The kind of declaration. This is also an index into a %select in 396 // the diagnostic. 397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 398 399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 400 numFormalParams = MD->param_size(); 401 calleeType = CT_Method; 402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 403 numFormalParams = FD->param_size(); 404 calleeType = CT_Function; 405 } else if (isa<VarDecl>(D)) { 406 QualType type = cast<ValueDecl>(D)->getType(); 407 const FunctionType *fn = nullptr; 408 if (const PointerType *ptr = type->getAs<PointerType>()) { 409 fn = ptr->getPointeeType()->getAs<FunctionType>(); 410 if (!fn) return; 411 calleeType = CT_Function; 412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 413 fn = ptr->getPointeeType()->castAs<FunctionType>(); 414 calleeType = CT_Block; 415 } else { 416 return; 417 } 418 419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 420 numFormalParams = proto->getNumParams(); 421 } else { 422 numFormalParams = 0; 423 } 424 } else { 425 return; 426 } 427 428 // "nullPos" is the number of formal parameters at the end which 429 // effectively count as part of the variadic arguments. This is 430 // useful if you would prefer to not have *any* formal parameters, 431 // but the language forces you to have at least one. 432 unsigned nullPos = attr->getNullPos(); 433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 435 436 // The number of arguments which should follow the sentinel. 437 unsigned numArgsAfterSentinel = attr->getSentinel(); 438 439 // If there aren't enough arguments for all the formal parameters, 440 // the sentinel, and the args after the sentinel, complain. 441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 444 return; 445 } 446 447 // Otherwise, find the sentinel expression. 448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 449 if (!sentinelExpr) return; 450 if (sentinelExpr->isValueDependent()) return; 451 if (Context.isSentinelNullExpr(sentinelExpr)) return; 452 453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 454 // or 'NULL' if those are actually defined in the context. Only use 455 // 'nil' for ObjC methods, where it's much more likely that the 456 // variadic arguments form a list of object pointers. 457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 458 std::string NullValue; 459 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 460 NullValue = "nil"; 461 else if (getLangOpts().CPlusPlus11) 462 NullValue = "nullptr"; 463 else if (PP.isMacroDefined("NULL")) 464 NullValue = "NULL"; 465 else 466 NullValue = "(void*) 0"; 467 468 if (MissingNilLoc.isInvalid()) 469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 470 else 471 Diag(MissingNilLoc, diag::warn_missing_sentinel) 472 << int(calleeType) 473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 475 } 476 477 SourceRange Sema::getExprRange(Expr *E) const { 478 return E ? E->getSourceRange() : SourceRange(); 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Standard Promotions and Conversions 483 //===----------------------------------------------------------------------===// 484 485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 487 // Handle any placeholder expressions which made it here. 488 if (E->getType()->isPlaceholderType()) { 489 ExprResult result = CheckPlaceholderExpr(E); 490 if (result.isInvalid()) return ExprError(); 491 E = result.get(); 492 } 493 494 QualType Ty = E->getType(); 495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 496 497 if (Ty->isFunctionType()) { 498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 501 return ExprError(); 502 503 E = ImpCastExprToType(E, Context.getPointerType(Ty), 504 CK_FunctionToPointerDecay).get(); 505 } else if (Ty->isArrayType()) { 506 // In C90 mode, arrays only promote to pointers if the array expression is 507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 508 // type 'array of type' is converted to an expression that has type 'pointer 509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 510 // that has type 'array of type' ...". The relevant change is "an lvalue" 511 // (C90) to "an expression" (C99). 512 // 513 // C++ 4.2p1: 514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 515 // T" can be converted to an rvalue of type "pointer to T". 516 // 517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 519 CK_ArrayToPointerDecay).get(); 520 } 521 return E; 522 } 523 524 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 525 // Check to see if we are dereferencing a null pointer. If so, 526 // and if not volatile-qualified, this is undefined behavior that the 527 // optimizer will delete, so warn about it. People sometimes try to use this 528 // to get a deterministic trap and are surprised by clang's behavior. This 529 // only handles the pattern "*null", which is a very syntactic check. 530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 531 if (UO && UO->getOpcode() == UO_Deref && 532 UO->getSubExpr()->getType()->isPointerType()) { 533 const LangAS AS = 534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 535 if ((!isTargetAddressSpace(AS) || 536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 538 S.Context, Expr::NPC_ValueDependentIsNotNull) && 539 !UO->getType().isVolatileQualified()) { 540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 541 S.PDiag(diag::warn_indirection_through_null) 542 << UO->getSubExpr()->getSourceRange()); 543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 544 S.PDiag(diag::note_indirection_through_null)); 545 } 546 } 547 } 548 549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 550 SourceLocation AssignLoc, 551 const Expr* RHS) { 552 const ObjCIvarDecl *IV = OIRE->getDecl(); 553 if (!IV) 554 return; 555 556 DeclarationName MemberName = IV->getDeclName(); 557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 558 if (!Member || !Member->isStr("isa")) 559 return; 560 561 const Expr *Base = OIRE->getBase(); 562 QualType BaseType = Base->getType(); 563 if (OIRE->isArrow()) 564 BaseType = BaseType->getPointeeType(); 565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 567 ObjCInterfaceDecl *ClassDeclared = nullptr; 568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 569 if (!ClassDeclared->getSuperClass() 570 && (*ClassDeclared->ivar_begin()) == IV) { 571 if (RHS) { 572 NamedDecl *ObjectSetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_setClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectSetClass) { 577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_setClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 583 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 584 } 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 587 } else { 588 NamedDecl *ObjectGetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_getClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectGetClass) 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_getClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 598 else 599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 600 } 601 S.Diag(IV->getLocation(), diag::note_ivar_decl); 602 } 603 } 604 } 605 606 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 607 // Handle any placeholder expressions which made it here. 608 if (E->getType()->isPlaceholderType()) { 609 ExprResult result = CheckPlaceholderExpr(E); 610 if (result.isInvalid()) return ExprError(); 611 E = result.get(); 612 } 613 614 // C++ [conv.lval]p1: 615 // A glvalue of a non-function, non-array type T can be 616 // converted to a prvalue. 617 if (!E->isGLValue()) return E; 618 619 QualType T = E->getType(); 620 assert(!T.isNull() && "r-value conversion on typeless expression?"); 621 622 // lvalue-to-rvalue conversion cannot be applied to function or array types. 623 if (T->isFunctionType() || T->isArrayType()) 624 return E; 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && 644 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 658 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 659 << FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 // Under the MS ABI, lock down the inheritance model now. 681 if (T->isMemberPointerType() && 682 Context.getTargetInfo().getCXXABI().isMicrosoft()) 683 (void)isCompleteType(E->getExprLoc(), T); 684 685 ExprResult Res = CheckLValueToRValueConversionOperand(E); 686 if (Res.isInvalid()) 687 return Res; 688 E = Res.get(); 689 690 // Loading a __weak object implicitly retains the value, so we need a cleanup to 691 // balance that. 692 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 693 Cleanup.setExprNeedsCleanups(true); 694 695 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 696 Cleanup.setExprNeedsCleanups(true); 697 698 // C++ [conv.lval]p3: 699 // If T is cv std::nullptr_t, the result is a null pointer constant. 700 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 701 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 702 CurFPFeatureOverrides()); 703 704 // C11 6.3.2.1p2: 705 // ... if the lvalue has atomic type, the value has the non-atomic version 706 // of the type of the lvalue ... 707 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 708 T = Atomic->getValueType().getUnqualifiedType(); 709 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 710 nullptr, VK_RValue, FPOptionsOverride()); 711 } 712 713 return Res; 714 } 715 716 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 717 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 718 if (Res.isInvalid()) 719 return ExprError(); 720 Res = DefaultLvalueConversion(Res.get()); 721 if (Res.isInvalid()) 722 return ExprError(); 723 return Res; 724 } 725 726 /// CallExprUnaryConversions - a special case of an unary conversion 727 /// performed on a function designator of a call expression. 728 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 729 QualType Ty = E->getType(); 730 ExprResult Res = E; 731 // Only do implicit cast for a function type, but not for a pointer 732 // to function type. 733 if (Ty->isFunctionType()) { 734 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 735 CK_FunctionToPointerDecay); 736 if (Res.isInvalid()) 737 return ExprError(); 738 } 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res.get(); 743 } 744 745 /// UsualUnaryConversions - Performs various conversions that are common to most 746 /// operators (C99 6.3). The conversions of array and function types are 747 /// sometimes suppressed. For example, the array->pointer conversion doesn't 748 /// apply if the array is an argument to the sizeof or address (&) operators. 749 /// In these instances, this routine should *not* be called. 750 ExprResult Sema::UsualUnaryConversions(Expr *E) { 751 // First, convert to an r-value. 752 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 753 if (Res.isInvalid()) 754 return ExprError(); 755 E = Res.get(); 756 757 QualType Ty = E->getType(); 758 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 759 760 // Half FP have to be promoted to float unless it is natively supported 761 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 762 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 763 764 // Try to perform integral promotions if the object has a theoretically 765 // promotable type. 766 if (Ty->isIntegralOrUnscopedEnumerationType()) { 767 // C99 6.3.1.1p2: 768 // 769 // The following may be used in an expression wherever an int or 770 // unsigned int may be used: 771 // - an object or expression with an integer type whose integer 772 // conversion rank is less than or equal to the rank of int 773 // and unsigned int. 774 // - A bit-field of type _Bool, int, signed int, or unsigned int. 775 // 776 // If an int can represent all values of the original type, the 777 // value is converted to an int; otherwise, it is converted to an 778 // unsigned int. These are called the integer promotions. All 779 // other types are unchanged by the integer promotions. 780 781 QualType PTy = Context.isPromotableBitField(E); 782 if (!PTy.isNull()) { 783 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 784 return E; 785 } 786 if (Ty->isPromotableIntegerType()) { 787 QualType PT = Context.getPromotedIntegerType(Ty); 788 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 789 return E; 790 } 791 } 792 return E; 793 } 794 795 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 796 /// do not have a prototype. Arguments that have type float or __fp16 797 /// are promoted to double. All other argument types are converted by 798 /// UsualUnaryConversions(). 799 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 800 QualType Ty = E->getType(); 801 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 802 803 ExprResult Res = UsualUnaryConversions(E); 804 if (Res.isInvalid()) 805 return ExprError(); 806 E = Res.get(); 807 808 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 809 // promote to double. 810 // Note that default argument promotion applies only to float (and 811 // half/fp16); it does not apply to _Float16. 812 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 813 if (BTy && (BTy->getKind() == BuiltinType::Half || 814 BTy->getKind() == BuiltinType::Float)) { 815 if (getLangOpts().OpenCL && 816 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 817 if (BTy->getKind() == BuiltinType::Half) { 818 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 819 } 820 } else { 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 } 823 } 824 825 // C++ performs lvalue-to-rvalue conversion as a default argument 826 // promotion, even on class types, but note: 827 // C++11 [conv.lval]p2: 828 // When an lvalue-to-rvalue conversion occurs in an unevaluated 829 // operand or a subexpression thereof the value contained in the 830 // referenced object is not accessed. Otherwise, if the glvalue 831 // has a class type, the conversion copy-initializes a temporary 832 // of type T from the glvalue and the result of the conversion 833 // is a prvalue for the temporary. 834 // FIXME: add some way to gate this entire thing for correctness in 835 // potentially potentially evaluated contexts. 836 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 837 ExprResult Temp = PerformCopyInitialization( 838 InitializedEntity::InitializeTemporary(E->getType()), 839 E->getExprLoc(), E); 840 if (Temp.isInvalid()) 841 return ExprError(); 842 E = Temp.get(); 843 } 844 845 return E; 846 } 847 848 /// Determine the degree of POD-ness for an expression. 849 /// Incomplete types are considered POD, since this check can be performed 850 /// when we're in an unevaluated context. 851 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 852 if (Ty->isIncompleteType()) { 853 // C++11 [expr.call]p7: 854 // After these conversions, if the argument does not have arithmetic, 855 // enumeration, pointer, pointer to member, or class type, the program 856 // is ill-formed. 857 // 858 // Since we've already performed array-to-pointer and function-to-pointer 859 // decay, the only such type in C++ is cv void. This also handles 860 // initializer lists as variadic arguments. 861 if (Ty->isVoidType()) 862 return VAK_Invalid; 863 864 if (Ty->isObjCObjectType()) 865 return VAK_Invalid; 866 return VAK_Valid; 867 } 868 869 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 870 return VAK_Invalid; 871 872 if (Ty.isCXX98PODType(Context)) 873 return VAK_Valid; 874 875 // C++11 [expr.call]p7: 876 // Passing a potentially-evaluated argument of class type (Clause 9) 877 // having a non-trivial copy constructor, a non-trivial move constructor, 878 // or a non-trivial destructor, with no corresponding parameter, 879 // is conditionally-supported with implementation-defined semantics. 880 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 881 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 882 if (!Record->hasNonTrivialCopyConstructor() && 883 !Record->hasNonTrivialMoveConstructor() && 884 !Record->hasNonTrivialDestructor()) 885 return VAK_ValidInCXX11; 886 887 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 888 return VAK_Valid; 889 890 if (Ty->isObjCObjectType()) 891 return VAK_Invalid; 892 893 if (getLangOpts().MSVCCompat) 894 return VAK_MSVCUndefined; 895 896 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 897 // permitted to reject them. We should consider doing so. 898 return VAK_Undefined; 899 } 900 901 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 902 // Don't allow one to pass an Objective-C interface to a vararg. 903 const QualType &Ty = E->getType(); 904 VarArgKind VAK = isValidVarArgType(Ty); 905 906 // Complain about passing non-POD types through varargs. 907 switch (VAK) { 908 case VAK_ValidInCXX11: 909 DiagRuntimeBehavior( 910 E->getBeginLoc(), nullptr, 911 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 912 LLVM_FALLTHROUGH; 913 case VAK_Valid: 914 if (Ty->isRecordType()) { 915 // This is unlikely to be what the user intended. If the class has a 916 // 'c_str' member function, the user probably meant to call that. 917 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 918 PDiag(diag::warn_pass_class_arg_to_vararg) 919 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 920 } 921 break; 922 923 case VAK_Undefined: 924 case VAK_MSVCUndefined: 925 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 926 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 927 << getLangOpts().CPlusPlus11 << Ty << CT); 928 break; 929 930 case VAK_Invalid: 931 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 932 Diag(E->getBeginLoc(), 933 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 934 << Ty << CT; 935 else if (Ty->isObjCObjectType()) 936 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 937 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 938 << Ty << CT); 939 else 940 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 941 << isa<InitListExpr>(E) << Ty << CT; 942 break; 943 } 944 } 945 946 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 947 /// will create a trap if the resulting type is not a POD type. 948 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 949 FunctionDecl *FDecl) { 950 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 951 // Strip the unbridged-cast placeholder expression off, if applicable. 952 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 953 (CT == VariadicMethod || 954 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 955 E = stripARCUnbridgedCast(E); 956 957 // Otherwise, do normal placeholder checking. 958 } else { 959 ExprResult ExprRes = CheckPlaceholderExpr(E); 960 if (ExprRes.isInvalid()) 961 return ExprError(); 962 E = ExprRes.get(); 963 } 964 } 965 966 ExprResult ExprRes = DefaultArgumentPromotion(E); 967 if (ExprRes.isInvalid()) 968 return ExprError(); 969 970 // Copy blocks to the heap. 971 if (ExprRes.get()->getType()->isBlockPointerType()) 972 maybeExtendBlockObject(ExprRes); 973 974 E = ExprRes.get(); 975 976 // Diagnostics regarding non-POD argument types are 977 // emitted along with format string checking in Sema::CheckFunctionCall(). 978 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 979 // Turn this into a trap. 980 CXXScopeSpec SS; 981 SourceLocation TemplateKWLoc; 982 UnqualifiedId Name; 983 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 984 E->getBeginLoc()); 985 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 986 /*HasTrailingLParen=*/true, 987 /*IsAddressOfOperand=*/false); 988 if (TrapFn.isInvalid()) 989 return ExprError(); 990 991 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 992 None, E->getEndLoc()); 993 if (Call.isInvalid()) 994 return ExprError(); 995 996 ExprResult Comma = 997 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 998 if (Comma.isInvalid()) 999 return ExprError(); 1000 return Comma.get(); 1001 } 1002 1003 if (!getLangOpts().CPlusPlus && 1004 RequireCompleteType(E->getExprLoc(), E->getType(), 1005 diag::err_call_incomplete_argument)) 1006 return ExprError(); 1007 1008 return E; 1009 } 1010 1011 /// Converts an integer to complex float type. Helper function of 1012 /// UsualArithmeticConversions() 1013 /// 1014 /// \return false if the integer expression is an integer type and is 1015 /// successfully converted to the complex type. 1016 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1017 ExprResult &ComplexExpr, 1018 QualType IntTy, 1019 QualType ComplexTy, 1020 bool SkipCast) { 1021 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1022 if (SkipCast) return false; 1023 if (IntTy->isIntegerType()) { 1024 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1026 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1027 CK_FloatingRealToComplex); 1028 } else { 1029 assert(IntTy->isComplexIntegerType()); 1030 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1031 CK_IntegralComplexToFloatingComplex); 1032 } 1033 return false; 1034 } 1035 1036 /// Handle arithmetic conversion with complex types. Helper function of 1037 /// UsualArithmeticConversions() 1038 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1039 ExprResult &RHS, QualType LHSType, 1040 QualType RHSType, 1041 bool IsCompAssign) { 1042 // if we have an integer operand, the result is the complex type. 1043 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1044 /*skipCast*/false)) 1045 return LHSType; 1046 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1047 /*skipCast*/IsCompAssign)) 1048 return RHSType; 1049 1050 // This handles complex/complex, complex/float, or float/complex. 1051 // When both operands are complex, the shorter operand is converted to the 1052 // type of the longer, and that is the type of the result. This corresponds 1053 // to what is done when combining two real floating-point operands. 1054 // The fun begins when size promotion occur across type domains. 1055 // From H&S 6.3.4: When one operand is complex and the other is a real 1056 // floating-point type, the less precise type is converted, within it's 1057 // real or complex domain, to the precision of the other type. For example, 1058 // when combining a "long double" with a "double _Complex", the 1059 // "double _Complex" is promoted to "long double _Complex". 1060 1061 // Compute the rank of the two types, regardless of whether they are complex. 1062 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1063 1064 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1065 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1066 QualType LHSElementType = 1067 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1068 QualType RHSElementType = 1069 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1070 1071 QualType ResultType = S.Context.getComplexType(LHSElementType); 1072 if (Order < 0) { 1073 // Promote the precision of the LHS if not an assignment. 1074 ResultType = S.Context.getComplexType(RHSElementType); 1075 if (!IsCompAssign) { 1076 if (LHSComplexType) 1077 LHS = 1078 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1079 else 1080 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1081 } 1082 } else if (Order > 0) { 1083 // Promote the precision of the RHS. 1084 if (RHSComplexType) 1085 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1086 else 1087 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1088 } 1089 return ResultType; 1090 } 1091 1092 /// Handle arithmetic conversion from integer to float. Helper function 1093 /// of UsualArithmeticConversions() 1094 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1095 ExprResult &IntExpr, 1096 QualType FloatTy, QualType IntTy, 1097 bool ConvertFloat, bool ConvertInt) { 1098 if (IntTy->isIntegerType()) { 1099 if (ConvertInt) 1100 // Convert intExpr to the lhs floating point type. 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1102 CK_IntegralToFloating); 1103 return FloatTy; 1104 } 1105 1106 // Convert both sides to the appropriate complex float. 1107 assert(IntTy->isComplexIntegerType()); 1108 QualType result = S.Context.getComplexType(FloatTy); 1109 1110 // _Complex int -> _Complex float 1111 if (ConvertInt) 1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1113 CK_IntegralComplexToFloatingComplex); 1114 1115 // float -> _Complex float 1116 if (ConvertFloat) 1117 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1118 CK_FloatingRealToComplex); 1119 1120 return result; 1121 } 1122 1123 /// Handle arithmethic conversion with floating point types. Helper 1124 /// function of UsualArithmeticConversions() 1125 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1126 ExprResult &RHS, QualType LHSType, 1127 QualType RHSType, bool IsCompAssign) { 1128 bool LHSFloat = LHSType->isRealFloatingType(); 1129 bool RHSFloat = RHSType->isRealFloatingType(); 1130 1131 // N1169 4.1.4: If one of the operands has a floating type and the other 1132 // operand has a fixed-point type, the fixed-point operand 1133 // is converted to the floating type [...] 1134 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1135 if (LHSFloat) 1136 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1137 else if (!IsCompAssign) 1138 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1139 return LHSFloat ? LHSType : RHSType; 1140 } 1141 1142 // If we have two real floating types, convert the smaller operand 1143 // to the bigger result. 1144 if (LHSFloat && RHSFloat) { 1145 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1146 if (order > 0) { 1147 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1148 return LHSType; 1149 } 1150 1151 assert(order < 0 && "illegal float comparison"); 1152 if (!IsCompAssign) 1153 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1154 return RHSType; 1155 } 1156 1157 if (LHSFloat) { 1158 // Half FP has to be promoted to float unless it is natively supported 1159 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1160 LHSType = S.Context.FloatTy; 1161 1162 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1163 /*ConvertFloat=*/!IsCompAssign, 1164 /*ConvertInt=*/ true); 1165 } 1166 assert(RHSFloat); 1167 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1168 /*ConvertFloat=*/ true, 1169 /*ConvertInt=*/!IsCompAssign); 1170 } 1171 1172 /// Diagnose attempts to convert between __float128 and long double if 1173 /// there is no support for such conversion. Helper function of 1174 /// UsualArithmeticConversions(). 1175 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1176 QualType RHSType) { 1177 /* No issue converting if at least one of the types is not a floating point 1178 type or the two types have the same rank. 1179 */ 1180 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1181 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1182 return false; 1183 1184 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1185 "The remaining types must be floating point types."); 1186 1187 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1188 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1189 1190 QualType LHSElemType = LHSComplex ? 1191 LHSComplex->getElementType() : LHSType; 1192 QualType RHSElemType = RHSComplex ? 1193 RHSComplex->getElementType() : RHSType; 1194 1195 // No issue if the two types have the same representation 1196 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1197 &S.Context.getFloatTypeSemantics(RHSElemType)) 1198 return false; 1199 1200 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1201 RHSElemType == S.Context.LongDoubleTy); 1202 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1203 RHSElemType == S.Context.Float128Ty); 1204 1205 // We've handled the situation where __float128 and long double have the same 1206 // representation. We allow all conversions for all possible long double types 1207 // except PPC's double double. 1208 return Float128AndLongDouble && 1209 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1210 &llvm::APFloat::PPCDoubleDouble()); 1211 } 1212 1213 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1214 1215 namespace { 1216 /// These helper callbacks are placed in an anonymous namespace to 1217 /// permit their use as function template parameters. 1218 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1219 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1220 } 1221 1222 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1223 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1224 CK_IntegralComplexCast); 1225 } 1226 } 1227 1228 /// Handle integer arithmetic conversions. Helper function of 1229 /// UsualArithmeticConversions() 1230 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1231 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1232 ExprResult &RHS, QualType LHSType, 1233 QualType RHSType, bool IsCompAssign) { 1234 // The rules for this case are in C99 6.3.1.8 1235 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1236 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1237 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1238 if (LHSSigned == RHSSigned) { 1239 // Same signedness; use the higher-ranked type 1240 if (order >= 0) { 1241 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1242 return LHSType; 1243 } else if (!IsCompAssign) 1244 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1245 return RHSType; 1246 } else if (order != (LHSSigned ? 1 : -1)) { 1247 // The unsigned type has greater than or equal rank to the 1248 // signed type, so use the unsigned type 1249 if (RHSSigned) { 1250 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1251 return LHSType; 1252 } else if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1254 return RHSType; 1255 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1256 // The two types are different widths; if we are here, that 1257 // means the signed type is larger than the unsigned type, so 1258 // use the signed type. 1259 if (LHSSigned) { 1260 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1261 return LHSType; 1262 } else if (!IsCompAssign) 1263 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1264 return RHSType; 1265 } else { 1266 // The signed type is higher-ranked than the unsigned type, 1267 // but isn't actually any bigger (like unsigned int and long 1268 // on most 32-bit systems). Use the unsigned type corresponding 1269 // to the signed type. 1270 QualType result = 1271 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1272 RHS = (*doRHSCast)(S, RHS.get(), result); 1273 if (!IsCompAssign) 1274 LHS = (*doLHSCast)(S, LHS.get(), result); 1275 return result; 1276 } 1277 } 1278 1279 /// Handle conversions with GCC complex int extension. Helper function 1280 /// of UsualArithmeticConversions() 1281 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1282 ExprResult &RHS, QualType LHSType, 1283 QualType RHSType, 1284 bool IsCompAssign) { 1285 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1286 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1287 1288 if (LHSComplexInt && RHSComplexInt) { 1289 QualType LHSEltType = LHSComplexInt->getElementType(); 1290 QualType RHSEltType = RHSComplexInt->getElementType(); 1291 QualType ScalarType = 1292 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1293 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1294 1295 return S.Context.getComplexType(ScalarType); 1296 } 1297 1298 if (LHSComplexInt) { 1299 QualType LHSEltType = LHSComplexInt->getElementType(); 1300 QualType ScalarType = 1301 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1302 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1303 QualType ComplexType = S.Context.getComplexType(ScalarType); 1304 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1305 CK_IntegralRealToComplex); 1306 1307 return ComplexType; 1308 } 1309 1310 assert(RHSComplexInt); 1311 1312 QualType RHSEltType = RHSComplexInt->getElementType(); 1313 QualType ScalarType = 1314 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1315 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1316 QualType ComplexType = S.Context.getComplexType(ScalarType); 1317 1318 if (!IsCompAssign) 1319 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1320 CK_IntegralRealToComplex); 1321 return ComplexType; 1322 } 1323 1324 /// Return the rank of a given fixed point or integer type. The value itself 1325 /// doesn't matter, but the values must be increasing with proper increasing 1326 /// rank as described in N1169 4.1.1. 1327 static unsigned GetFixedPointRank(QualType Ty) { 1328 const auto *BTy = Ty->getAs<BuiltinType>(); 1329 assert(BTy && "Expected a builtin type."); 1330 1331 switch (BTy->getKind()) { 1332 case BuiltinType::ShortFract: 1333 case BuiltinType::UShortFract: 1334 case BuiltinType::SatShortFract: 1335 case BuiltinType::SatUShortFract: 1336 return 1; 1337 case BuiltinType::Fract: 1338 case BuiltinType::UFract: 1339 case BuiltinType::SatFract: 1340 case BuiltinType::SatUFract: 1341 return 2; 1342 case BuiltinType::LongFract: 1343 case BuiltinType::ULongFract: 1344 case BuiltinType::SatLongFract: 1345 case BuiltinType::SatULongFract: 1346 return 3; 1347 case BuiltinType::ShortAccum: 1348 case BuiltinType::UShortAccum: 1349 case BuiltinType::SatShortAccum: 1350 case BuiltinType::SatUShortAccum: 1351 return 4; 1352 case BuiltinType::Accum: 1353 case BuiltinType::UAccum: 1354 case BuiltinType::SatAccum: 1355 case BuiltinType::SatUAccum: 1356 return 5; 1357 case BuiltinType::LongAccum: 1358 case BuiltinType::ULongAccum: 1359 case BuiltinType::SatLongAccum: 1360 case BuiltinType::SatULongAccum: 1361 return 6; 1362 default: 1363 if (BTy->isInteger()) 1364 return 0; 1365 llvm_unreachable("Unexpected fixed point or integer type"); 1366 } 1367 } 1368 1369 /// handleFixedPointConversion - Fixed point operations between fixed 1370 /// point types and integers or other fixed point types do not fall under 1371 /// usual arithmetic conversion since these conversions could result in loss 1372 /// of precsision (N1169 4.1.4). These operations should be calculated with 1373 /// the full precision of their result type (N1169 4.1.6.2.1). 1374 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1375 QualType RHSTy) { 1376 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1377 "Expected at least one of the operands to be a fixed point type"); 1378 assert((LHSTy->isFixedPointOrIntegerType() || 1379 RHSTy->isFixedPointOrIntegerType()) && 1380 "Special fixed point arithmetic operation conversions are only " 1381 "applied to ints or other fixed point types"); 1382 1383 // If one operand has signed fixed-point type and the other operand has 1384 // unsigned fixed-point type, then the unsigned fixed-point operand is 1385 // converted to its corresponding signed fixed-point type and the resulting 1386 // type is the type of the converted operand. 1387 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1388 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1389 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1390 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1391 1392 // The result type is the type with the highest rank, whereby a fixed-point 1393 // conversion rank is always greater than an integer conversion rank; if the 1394 // type of either of the operands is a saturating fixedpoint type, the result 1395 // type shall be the saturating fixed-point type corresponding to the type 1396 // with the highest rank; the resulting value is converted (taking into 1397 // account rounding and overflow) to the precision of the resulting type. 1398 // Same ranks between signed and unsigned types are resolved earlier, so both 1399 // types are either signed or both unsigned at this point. 1400 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1401 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1402 1403 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1404 1405 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1406 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1407 1408 return ResultTy; 1409 } 1410 1411 /// Check that the usual arithmetic conversions can be performed on this pair of 1412 /// expressions that might be of enumeration type. 1413 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1414 SourceLocation Loc, 1415 Sema::ArithConvKind ACK) { 1416 // C++2a [expr.arith.conv]p1: 1417 // If one operand is of enumeration type and the other operand is of a 1418 // different enumeration type or a floating-point type, this behavior is 1419 // deprecated ([depr.arith.conv.enum]). 1420 // 1421 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1422 // Eventually we will presumably reject these cases (in C++23 onwards?). 1423 QualType L = LHS->getType(), R = RHS->getType(); 1424 bool LEnum = L->isUnscopedEnumerationType(), 1425 REnum = R->isUnscopedEnumerationType(); 1426 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1427 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1428 (REnum && L->isFloatingType())) { 1429 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1430 ? diag::warn_arith_conv_enum_float_cxx20 1431 : diag::warn_arith_conv_enum_float) 1432 << LHS->getSourceRange() << RHS->getSourceRange() 1433 << (int)ACK << LEnum << L << R; 1434 } else if (!IsCompAssign && LEnum && REnum && 1435 !S.Context.hasSameUnqualifiedType(L, R)) { 1436 unsigned DiagID; 1437 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1438 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1439 // If either enumeration type is unnamed, it's less likely that the 1440 // user cares about this, but this situation is still deprecated in 1441 // C++2a. Use a different warning group. 1442 DiagID = S.getLangOpts().CPlusPlus20 1443 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1444 : diag::warn_arith_conv_mixed_anon_enum_types; 1445 } else if (ACK == Sema::ACK_Conditional) { 1446 // Conditional expressions are separated out because they have 1447 // historically had a different warning flag. 1448 DiagID = S.getLangOpts().CPlusPlus20 1449 ? diag::warn_conditional_mixed_enum_types_cxx20 1450 : diag::warn_conditional_mixed_enum_types; 1451 } else if (ACK == Sema::ACK_Comparison) { 1452 // Comparison expressions are separated out because they have 1453 // historically had a different warning flag. 1454 DiagID = S.getLangOpts().CPlusPlus20 1455 ? diag::warn_comparison_mixed_enum_types_cxx20 1456 : diag::warn_comparison_mixed_enum_types; 1457 } else { 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_enum_types; 1461 } 1462 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1463 << (int)ACK << L << R; 1464 } 1465 } 1466 1467 /// UsualArithmeticConversions - Performs various conversions that are common to 1468 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1469 /// routine returns the first non-arithmetic type found. The client is 1470 /// responsible for emitting appropriate error diagnostics. 1471 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1472 SourceLocation Loc, 1473 ArithConvKind ACK) { 1474 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1475 1476 if (ACK != ACK_CompAssign) { 1477 LHS = UsualUnaryConversions(LHS.get()); 1478 if (LHS.isInvalid()) 1479 return QualType(); 1480 } 1481 1482 RHS = UsualUnaryConversions(RHS.get()); 1483 if (RHS.isInvalid()) 1484 return QualType(); 1485 1486 // For conversion purposes, we ignore any qualifiers. 1487 // For example, "const float" and "float" are equivalent. 1488 QualType LHSType = 1489 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1490 QualType RHSType = 1491 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1492 1493 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1494 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1495 LHSType = AtomicLHS->getValueType(); 1496 1497 // If both types are identical, no conversion is needed. 1498 if (LHSType == RHSType) 1499 return LHSType; 1500 1501 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1502 // The caller can deal with this (e.g. pointer + int). 1503 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1504 return QualType(); 1505 1506 // Apply unary and bitfield promotions to the LHS's type. 1507 QualType LHSUnpromotedType = LHSType; 1508 if (LHSType->isPromotableIntegerType()) 1509 LHSType = Context.getPromotedIntegerType(LHSType); 1510 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1511 if (!LHSBitfieldPromoteTy.isNull()) 1512 LHSType = LHSBitfieldPromoteTy; 1513 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1514 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1515 1516 // If both types are identical, no conversion is needed. 1517 if (LHSType == RHSType) 1518 return LHSType; 1519 1520 // ExtInt types aren't subject to conversions between them or normal integers, 1521 // so this fails. 1522 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1523 return QualType(); 1524 1525 // At this point, we have two different arithmetic types. 1526 1527 // Diagnose attempts to convert between __float128 and long double where 1528 // such conversions currently can't be handled. 1529 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1530 return QualType(); 1531 1532 // Handle complex types first (C99 6.3.1.8p1). 1533 if (LHSType->isComplexType() || RHSType->isComplexType()) 1534 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1535 ACK == ACK_CompAssign); 1536 1537 // Now handle "real" floating types (i.e. float, double, long double). 1538 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1539 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1540 ACK == ACK_CompAssign); 1541 1542 // Handle GCC complex int extension. 1543 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1544 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1545 ACK == ACK_CompAssign); 1546 1547 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1548 return handleFixedPointConversion(*this, LHSType, RHSType); 1549 1550 // Finally, we have two differing integer types. 1551 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1552 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1553 } 1554 1555 //===----------------------------------------------------------------------===// 1556 // Semantic Analysis for various Expression Types 1557 //===----------------------------------------------------------------------===// 1558 1559 1560 ExprResult 1561 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1562 SourceLocation DefaultLoc, 1563 SourceLocation RParenLoc, 1564 Expr *ControllingExpr, 1565 ArrayRef<ParsedType> ArgTypes, 1566 ArrayRef<Expr *> ArgExprs) { 1567 unsigned NumAssocs = ArgTypes.size(); 1568 assert(NumAssocs == ArgExprs.size()); 1569 1570 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1571 for (unsigned i = 0; i < NumAssocs; ++i) { 1572 if (ArgTypes[i]) 1573 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1574 else 1575 Types[i] = nullptr; 1576 } 1577 1578 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1579 ControllingExpr, 1580 llvm::makeArrayRef(Types, NumAssocs), 1581 ArgExprs); 1582 delete [] Types; 1583 return ER; 1584 } 1585 1586 ExprResult 1587 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1588 SourceLocation DefaultLoc, 1589 SourceLocation RParenLoc, 1590 Expr *ControllingExpr, 1591 ArrayRef<TypeSourceInfo *> Types, 1592 ArrayRef<Expr *> Exprs) { 1593 unsigned NumAssocs = Types.size(); 1594 assert(NumAssocs == Exprs.size()); 1595 1596 // Decay and strip qualifiers for the controlling expression type, and handle 1597 // placeholder type replacement. See committee discussion from WG14 DR423. 1598 { 1599 EnterExpressionEvaluationContext Unevaluated( 1600 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1601 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1602 if (R.isInvalid()) 1603 return ExprError(); 1604 ControllingExpr = R.get(); 1605 } 1606 1607 // The controlling expression is an unevaluated operand, so side effects are 1608 // likely unintended. 1609 if (!inTemplateInstantiation() && 1610 ControllingExpr->HasSideEffects(Context, false)) 1611 Diag(ControllingExpr->getExprLoc(), 1612 diag::warn_side_effects_unevaluated_context); 1613 1614 bool TypeErrorFound = false, 1615 IsResultDependent = ControllingExpr->isTypeDependent(), 1616 ContainsUnexpandedParameterPack 1617 = ControllingExpr->containsUnexpandedParameterPack(); 1618 1619 for (unsigned i = 0; i < NumAssocs; ++i) { 1620 if (Exprs[i]->containsUnexpandedParameterPack()) 1621 ContainsUnexpandedParameterPack = true; 1622 1623 if (Types[i]) { 1624 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1625 ContainsUnexpandedParameterPack = true; 1626 1627 if (Types[i]->getType()->isDependentType()) { 1628 IsResultDependent = true; 1629 } else { 1630 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1631 // complete object type other than a variably modified type." 1632 unsigned D = 0; 1633 if (Types[i]->getType()->isIncompleteType()) 1634 D = diag::err_assoc_type_incomplete; 1635 else if (!Types[i]->getType()->isObjectType()) 1636 D = diag::err_assoc_type_nonobject; 1637 else if (Types[i]->getType()->isVariablyModifiedType()) 1638 D = diag::err_assoc_type_variably_modified; 1639 1640 if (D != 0) { 1641 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1642 << Types[i]->getTypeLoc().getSourceRange() 1643 << Types[i]->getType(); 1644 TypeErrorFound = true; 1645 } 1646 1647 // C11 6.5.1.1p2 "No two generic associations in the same generic 1648 // selection shall specify compatible types." 1649 for (unsigned j = i+1; j < NumAssocs; ++j) 1650 if (Types[j] && !Types[j]->getType()->isDependentType() && 1651 Context.typesAreCompatible(Types[i]->getType(), 1652 Types[j]->getType())) { 1653 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1654 diag::err_assoc_compatible_types) 1655 << Types[j]->getTypeLoc().getSourceRange() 1656 << Types[j]->getType() 1657 << Types[i]->getType(); 1658 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1659 diag::note_compat_assoc) 1660 << Types[i]->getTypeLoc().getSourceRange() 1661 << Types[i]->getType(); 1662 TypeErrorFound = true; 1663 } 1664 } 1665 } 1666 } 1667 if (TypeErrorFound) 1668 return ExprError(); 1669 1670 // If we determined that the generic selection is result-dependent, don't 1671 // try to compute the result expression. 1672 if (IsResultDependent) 1673 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1674 Exprs, DefaultLoc, RParenLoc, 1675 ContainsUnexpandedParameterPack); 1676 1677 SmallVector<unsigned, 1> CompatIndices; 1678 unsigned DefaultIndex = -1U; 1679 for (unsigned i = 0; i < NumAssocs; ++i) { 1680 if (!Types[i]) 1681 DefaultIndex = i; 1682 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1683 Types[i]->getType())) 1684 CompatIndices.push_back(i); 1685 } 1686 1687 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1688 // type compatible with at most one of the types named in its generic 1689 // association list." 1690 if (CompatIndices.size() > 1) { 1691 // We strip parens here because the controlling expression is typically 1692 // parenthesized in macro definitions. 1693 ControllingExpr = ControllingExpr->IgnoreParens(); 1694 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1695 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1696 << (unsigned)CompatIndices.size(); 1697 for (unsigned I : CompatIndices) { 1698 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1699 diag::note_compat_assoc) 1700 << Types[I]->getTypeLoc().getSourceRange() 1701 << Types[I]->getType(); 1702 } 1703 return ExprError(); 1704 } 1705 1706 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1707 // its controlling expression shall have type compatible with exactly one of 1708 // the types named in its generic association list." 1709 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1710 // We strip parens here because the controlling expression is typically 1711 // parenthesized in macro definitions. 1712 ControllingExpr = ControllingExpr->IgnoreParens(); 1713 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1714 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1719 // type name that is compatible with the type of the controlling expression, 1720 // then the result expression of the generic selection is the expression 1721 // in that generic association. Otherwise, the result expression of the 1722 // generic selection is the expression in the default generic association." 1723 unsigned ResultIndex = 1724 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1725 1726 return GenericSelectionExpr::Create( 1727 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1728 ContainsUnexpandedParameterPack, ResultIndex); 1729 } 1730 1731 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1732 /// location of the token and the offset of the ud-suffix within it. 1733 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1734 unsigned Offset) { 1735 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1736 S.getLangOpts()); 1737 } 1738 1739 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1740 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1741 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1742 IdentifierInfo *UDSuffix, 1743 SourceLocation UDSuffixLoc, 1744 ArrayRef<Expr*> Args, 1745 SourceLocation LitEndLoc) { 1746 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1747 1748 QualType ArgTy[2]; 1749 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1750 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1751 if (ArgTy[ArgIdx]->isArrayType()) 1752 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1753 } 1754 1755 DeclarationName OpName = 1756 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1757 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1758 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1759 1760 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1761 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1762 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1763 /*AllowStringTemplatePack*/ false, 1764 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1765 return ExprError(); 1766 1767 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1768 } 1769 1770 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1771 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1772 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1773 /// multiple tokens. However, the common case is that StringToks points to one 1774 /// string. 1775 /// 1776 ExprResult 1777 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1778 assert(!StringToks.empty() && "Must have at least one string!"); 1779 1780 StringLiteralParser Literal(StringToks, PP); 1781 if (Literal.hadError) 1782 return ExprError(); 1783 1784 SmallVector<SourceLocation, 4> StringTokLocs; 1785 for (const Token &Tok : StringToks) 1786 StringTokLocs.push_back(Tok.getLocation()); 1787 1788 QualType CharTy = Context.CharTy; 1789 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1790 if (Literal.isWide()) { 1791 CharTy = Context.getWideCharType(); 1792 Kind = StringLiteral::Wide; 1793 } else if (Literal.isUTF8()) { 1794 if (getLangOpts().Char8) 1795 CharTy = Context.Char8Ty; 1796 Kind = StringLiteral::UTF8; 1797 } else if (Literal.isUTF16()) { 1798 CharTy = Context.Char16Ty; 1799 Kind = StringLiteral::UTF16; 1800 } else if (Literal.isUTF32()) { 1801 CharTy = Context.Char32Ty; 1802 Kind = StringLiteral::UTF32; 1803 } else if (Literal.isPascal()) { 1804 CharTy = Context.UnsignedCharTy; 1805 } 1806 1807 // Warn on initializing an array of char from a u8 string literal; this 1808 // becomes ill-formed in C++2a. 1809 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1810 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1811 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1812 1813 // Create removals for all 'u8' prefixes in the string literal(s). This 1814 // ensures C++2a compatibility (but may change the program behavior when 1815 // built by non-Clang compilers for which the execution character set is 1816 // not always UTF-8). 1817 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1818 SourceLocation RemovalDiagLoc; 1819 for (const Token &Tok : StringToks) { 1820 if (Tok.getKind() == tok::utf8_string_literal) { 1821 if (RemovalDiagLoc.isInvalid()) 1822 RemovalDiagLoc = Tok.getLocation(); 1823 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1824 Tok.getLocation(), 1825 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1826 getSourceManager(), getLangOpts()))); 1827 } 1828 } 1829 Diag(RemovalDiagLoc, RemovalDiag); 1830 } 1831 1832 QualType StrTy = 1833 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1834 1835 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1836 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1837 Kind, Literal.Pascal, StrTy, 1838 &StringTokLocs[0], 1839 StringTokLocs.size()); 1840 if (Literal.getUDSuffix().empty()) 1841 return Lit; 1842 1843 // We're building a user-defined literal. 1844 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1845 SourceLocation UDSuffixLoc = 1846 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1847 Literal.getUDSuffixOffset()); 1848 1849 // Make sure we're allowed user-defined literals here. 1850 if (!UDLScope) 1851 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1852 1853 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1854 // operator "" X (str, len) 1855 QualType SizeType = Context.getSizeType(); 1856 1857 DeclarationName OpName = 1858 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1861 1862 QualType ArgTy[] = { 1863 Context.getArrayDecayedType(StrTy), SizeType 1864 }; 1865 1866 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1867 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1868 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1869 /*AllowStringTemplatePack*/ true, 1870 /*DiagnoseMissing*/ true, Lit)) { 1871 1872 case LOLR_Cooked: { 1873 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1874 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1875 StringTokLocs[0]); 1876 Expr *Args[] = { Lit, LenArg }; 1877 1878 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1879 } 1880 1881 case LOLR_Template: { 1882 TemplateArgumentListInfo ExplicitArgs; 1883 TemplateArgument Arg(Lit); 1884 TemplateArgumentLocInfo ArgInfo(Lit); 1885 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1886 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1887 &ExplicitArgs); 1888 } 1889 1890 case LOLR_StringTemplatePack: { 1891 TemplateArgumentListInfo ExplicitArgs; 1892 1893 unsigned CharBits = Context.getIntWidth(CharTy); 1894 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1895 llvm::APSInt Value(CharBits, CharIsUnsigned); 1896 1897 TemplateArgument TypeArg(CharTy); 1898 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1899 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1900 1901 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1902 Value = Lit->getCodeUnit(I); 1903 TemplateArgument Arg(Context, Value, CharTy); 1904 TemplateArgumentLocInfo ArgInfo; 1905 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1906 } 1907 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1908 &ExplicitArgs); 1909 } 1910 case LOLR_Raw: 1911 case LOLR_ErrorNoDiagnostic: 1912 llvm_unreachable("unexpected literal operator lookup result"); 1913 case LOLR_Error: 1914 return ExprError(); 1915 } 1916 llvm_unreachable("unexpected literal operator lookup result"); 1917 } 1918 1919 DeclRefExpr * 1920 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1921 SourceLocation Loc, 1922 const CXXScopeSpec *SS) { 1923 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1924 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1925 } 1926 1927 DeclRefExpr * 1928 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1929 const DeclarationNameInfo &NameInfo, 1930 const CXXScopeSpec *SS, NamedDecl *FoundD, 1931 SourceLocation TemplateKWLoc, 1932 const TemplateArgumentListInfo *TemplateArgs) { 1933 NestedNameSpecifierLoc NNS = 1934 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1935 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1936 TemplateArgs); 1937 } 1938 1939 // CUDA/HIP: Check whether a captured reference variable is referencing a 1940 // host variable in a device or host device lambda. 1941 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1942 VarDecl *VD) { 1943 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1944 return false; 1945 assert(VD->getType()->isReferenceType()); 1946 1947 // Check whether the reference variable is referencing a host variable. 1948 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1949 if (!DRE) 1950 return false; 1951 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1952 if (!Referee || !Referee->hasGlobalStorage() || 1953 Referee->hasAttr<CUDADeviceAttr>()) 1954 return false; 1955 1956 // Check whether the current function is a device or host device lambda. 1957 // Check whether the reference variable is a capture by getDeclContext() 1958 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1959 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1960 if (MD && MD->getParent()->isLambda() && 1961 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1962 VD->getDeclContext() != MD) 1963 return true; 1964 1965 return false; 1966 } 1967 1968 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1969 // A declaration named in an unevaluated operand never constitutes an odr-use. 1970 if (isUnevaluatedContext()) 1971 return NOUR_Unevaluated; 1972 1973 // C++2a [basic.def.odr]p4: 1974 // A variable x whose name appears as a potentially-evaluated expression e 1975 // is odr-used by e unless [...] x is a reference that is usable in 1976 // constant expressions. 1977 // CUDA/HIP: 1978 // If a reference variable referencing a host variable is captured in a 1979 // device or host device lambda, the value of the referee must be copied 1980 // to the capture and the reference variable must be treated as odr-use 1981 // since the value of the referee is not known at compile time and must 1982 // be loaded from the captured. 1983 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1984 if (VD->getType()->isReferenceType() && 1985 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1986 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1987 VD->isUsableInConstantExpressions(Context)) 1988 return NOUR_Constant; 1989 } 1990 1991 // All remaining non-variable cases constitute an odr-use. For variables, we 1992 // need to wait and see how the expression is used. 1993 return NOUR_None; 1994 } 1995 1996 /// BuildDeclRefExpr - Build an expression that references a 1997 /// declaration that does not require a closure capture. 1998 DeclRefExpr * 1999 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2000 const DeclarationNameInfo &NameInfo, 2001 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2002 SourceLocation TemplateKWLoc, 2003 const TemplateArgumentListInfo *TemplateArgs) { 2004 bool RefersToCapturedVariable = 2005 isa<VarDecl>(D) && 2006 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2007 2008 DeclRefExpr *E = DeclRefExpr::Create( 2009 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2010 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2011 MarkDeclRefReferenced(E); 2012 2013 // C++ [except.spec]p17: 2014 // An exception-specification is considered to be needed when: 2015 // - in an expression, the function is the unique lookup result or 2016 // the selected member of a set of overloaded functions. 2017 // 2018 // We delay doing this until after we've built the function reference and 2019 // marked it as used so that: 2020 // a) if the function is defaulted, we get errors from defining it before / 2021 // instead of errors from computing its exception specification, and 2022 // b) if the function is a defaulted comparison, we can use the body we 2023 // build when defining it as input to the exception specification 2024 // computation rather than computing a new body. 2025 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2026 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2027 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2028 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2029 } 2030 } 2031 2032 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2033 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2034 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2035 getCurFunction()->recordUseOfWeak(E); 2036 2037 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2038 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2039 FD = IFD->getAnonField(); 2040 if (FD) { 2041 UnusedPrivateFields.remove(FD); 2042 // Just in case we're building an illegal pointer-to-member. 2043 if (FD->isBitField()) 2044 E->setObjectKind(OK_BitField); 2045 } 2046 2047 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2048 // designates a bit-field. 2049 if (auto *BD = dyn_cast<BindingDecl>(D)) 2050 if (auto *BE = BD->getBinding()) 2051 E->setObjectKind(BE->getObjectKind()); 2052 2053 return E; 2054 } 2055 2056 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2057 /// possibly a list of template arguments. 2058 /// 2059 /// If this produces template arguments, it is permitted to call 2060 /// DecomposeTemplateName. 2061 /// 2062 /// This actually loses a lot of source location information for 2063 /// non-standard name kinds; we should consider preserving that in 2064 /// some way. 2065 void 2066 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2067 TemplateArgumentListInfo &Buffer, 2068 DeclarationNameInfo &NameInfo, 2069 const TemplateArgumentListInfo *&TemplateArgs) { 2070 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2071 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2072 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2073 2074 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2075 Id.TemplateId->NumArgs); 2076 translateTemplateArguments(TemplateArgsPtr, Buffer); 2077 2078 TemplateName TName = Id.TemplateId->Template.get(); 2079 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2080 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2081 TemplateArgs = &Buffer; 2082 } else { 2083 NameInfo = GetNameFromUnqualifiedId(Id); 2084 TemplateArgs = nullptr; 2085 } 2086 } 2087 2088 static void emitEmptyLookupTypoDiagnostic( 2089 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2090 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2091 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2092 DeclContext *Ctx = 2093 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2094 if (!TC) { 2095 // Emit a special diagnostic for failed member lookups. 2096 // FIXME: computing the declaration context might fail here (?) 2097 if (Ctx) 2098 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2099 << SS.getRange(); 2100 else 2101 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2102 return; 2103 } 2104 2105 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2106 bool DroppedSpecifier = 2107 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2108 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2109 ? diag::note_implicit_param_decl 2110 : diag::note_previous_decl; 2111 if (!Ctx) 2112 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2113 SemaRef.PDiag(NoteID)); 2114 else 2115 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2116 << Typo << Ctx << DroppedSpecifier 2117 << SS.getRange(), 2118 SemaRef.PDiag(NoteID)); 2119 } 2120 2121 /// Diagnose a lookup that found results in an enclosing class during error 2122 /// recovery. This usually indicates that the results were found in a dependent 2123 /// base class that could not be searched as part of a template definition. 2124 /// Always issues a diagnostic (though this may be only a warning in MS 2125 /// compatibility mode). 2126 /// 2127 /// Return \c true if the error is unrecoverable, or \c false if the caller 2128 /// should attempt to recover using these lookup results. 2129 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2130 // During a default argument instantiation the CurContext points 2131 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2132 // function parameter list, hence add an explicit check. 2133 bool isDefaultArgument = 2134 !CodeSynthesisContexts.empty() && 2135 CodeSynthesisContexts.back().Kind == 2136 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2137 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2138 bool isInstance = CurMethod && CurMethod->isInstance() && 2139 R.getNamingClass() == CurMethod->getParent() && 2140 !isDefaultArgument; 2141 2142 // There are two ways we can find a class-scope declaration during template 2143 // instantiation that we did not find in the template definition: if it is a 2144 // member of a dependent base class, or if it is declared after the point of 2145 // use in the same class. Distinguish these by comparing the class in which 2146 // the member was found to the naming class of the lookup. 2147 unsigned DiagID = diag::err_found_in_dependent_base; 2148 unsigned NoteID = diag::note_member_declared_at; 2149 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2150 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2151 : diag::err_found_later_in_class; 2152 } else if (getLangOpts().MSVCCompat) { 2153 DiagID = diag::ext_found_in_dependent_base; 2154 NoteID = diag::note_dependent_member_use; 2155 } 2156 2157 if (isInstance) { 2158 // Give a code modification hint to insert 'this->'. 2159 Diag(R.getNameLoc(), DiagID) 2160 << R.getLookupName() 2161 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2162 CheckCXXThisCapture(R.getNameLoc()); 2163 } else { 2164 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2165 // they're not shadowed). 2166 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2167 } 2168 2169 for (NamedDecl *D : R) 2170 Diag(D->getLocation(), NoteID); 2171 2172 // Return true if we are inside a default argument instantiation 2173 // and the found name refers to an instance member function, otherwise 2174 // the caller will try to create an implicit member call and this is wrong 2175 // for default arguments. 2176 // 2177 // FIXME: Is this special case necessary? We could allow the caller to 2178 // diagnose this. 2179 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2180 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2181 return true; 2182 } 2183 2184 // Tell the callee to try to recover. 2185 return false; 2186 } 2187 2188 /// Diagnose an empty lookup. 2189 /// 2190 /// \return false if new lookup candidates were found 2191 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2192 CorrectionCandidateCallback &CCC, 2193 TemplateArgumentListInfo *ExplicitTemplateArgs, 2194 ArrayRef<Expr *> Args, TypoExpr **Out) { 2195 DeclarationName Name = R.getLookupName(); 2196 2197 unsigned diagnostic = diag::err_undeclared_var_use; 2198 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2199 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2200 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2201 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2202 diagnostic = diag::err_undeclared_use; 2203 diagnostic_suggest = diag::err_undeclared_use_suggest; 2204 } 2205 2206 // If the original lookup was an unqualified lookup, fake an 2207 // unqualified lookup. This is useful when (for example) the 2208 // original lookup would not have found something because it was a 2209 // dependent name. 2210 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2211 while (DC) { 2212 if (isa<CXXRecordDecl>(DC)) { 2213 LookupQualifiedName(R, DC); 2214 2215 if (!R.empty()) { 2216 // Don't give errors about ambiguities in this lookup. 2217 R.suppressDiagnostics(); 2218 2219 // If there's a best viable function among the results, only mention 2220 // that one in the notes. 2221 OverloadCandidateSet Candidates(R.getNameLoc(), 2222 OverloadCandidateSet::CSK_Normal); 2223 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2224 OverloadCandidateSet::iterator Best; 2225 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2226 OR_Success) { 2227 R.clear(); 2228 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2229 R.resolveKind(); 2230 } 2231 2232 return DiagnoseDependentMemberLookup(R); 2233 } 2234 2235 R.clear(); 2236 } 2237 2238 DC = DC->getLookupParent(); 2239 } 2240 2241 // We didn't find anything, so try to correct for a typo. 2242 TypoCorrection Corrected; 2243 if (S && Out) { 2244 SourceLocation TypoLoc = R.getNameLoc(); 2245 assert(!ExplicitTemplateArgs && 2246 "Diagnosing an empty lookup with explicit template args!"); 2247 *Out = CorrectTypoDelayed( 2248 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2249 [=](const TypoCorrection &TC) { 2250 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2251 diagnostic, diagnostic_suggest); 2252 }, 2253 nullptr, CTK_ErrorRecovery); 2254 if (*Out) 2255 return true; 2256 } else if (S && 2257 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2258 S, &SS, CCC, CTK_ErrorRecovery))) { 2259 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2260 bool DroppedSpecifier = 2261 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2262 R.setLookupName(Corrected.getCorrection()); 2263 2264 bool AcceptableWithRecovery = false; 2265 bool AcceptableWithoutRecovery = false; 2266 NamedDecl *ND = Corrected.getFoundDecl(); 2267 if (ND) { 2268 if (Corrected.isOverloaded()) { 2269 OverloadCandidateSet OCS(R.getNameLoc(), 2270 OverloadCandidateSet::CSK_Normal); 2271 OverloadCandidateSet::iterator Best; 2272 for (NamedDecl *CD : Corrected) { 2273 if (FunctionTemplateDecl *FTD = 2274 dyn_cast<FunctionTemplateDecl>(CD)) 2275 AddTemplateOverloadCandidate( 2276 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2277 Args, OCS); 2278 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2279 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2280 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2281 Args, OCS); 2282 } 2283 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2284 case OR_Success: 2285 ND = Best->FoundDecl; 2286 Corrected.setCorrectionDecl(ND); 2287 break; 2288 default: 2289 // FIXME: Arbitrarily pick the first declaration for the note. 2290 Corrected.setCorrectionDecl(ND); 2291 break; 2292 } 2293 } 2294 R.addDecl(ND); 2295 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2296 CXXRecordDecl *Record = nullptr; 2297 if (Corrected.getCorrectionSpecifier()) { 2298 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2299 Record = Ty->getAsCXXRecordDecl(); 2300 } 2301 if (!Record) 2302 Record = cast<CXXRecordDecl>( 2303 ND->getDeclContext()->getRedeclContext()); 2304 R.setNamingClass(Record); 2305 } 2306 2307 auto *UnderlyingND = ND->getUnderlyingDecl(); 2308 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2309 isa<FunctionTemplateDecl>(UnderlyingND); 2310 // FIXME: If we ended up with a typo for a type name or 2311 // Objective-C class name, we're in trouble because the parser 2312 // is in the wrong place to recover. Suggest the typo 2313 // correction, but don't make it a fix-it since we're not going 2314 // to recover well anyway. 2315 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2316 getAsTypeTemplateDecl(UnderlyingND) || 2317 isa<ObjCInterfaceDecl>(UnderlyingND); 2318 } else { 2319 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2320 // because we aren't able to recover. 2321 AcceptableWithoutRecovery = true; 2322 } 2323 2324 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2325 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2326 ? diag::note_implicit_param_decl 2327 : diag::note_previous_decl; 2328 if (SS.isEmpty()) 2329 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2330 PDiag(NoteID), AcceptableWithRecovery); 2331 else 2332 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2333 << Name << computeDeclContext(SS, false) 2334 << DroppedSpecifier << SS.getRange(), 2335 PDiag(NoteID), AcceptableWithRecovery); 2336 2337 // Tell the callee whether to try to recover. 2338 return !AcceptableWithRecovery; 2339 } 2340 } 2341 R.clear(); 2342 2343 // Emit a special diagnostic for failed member lookups. 2344 // FIXME: computing the declaration context might fail here (?) 2345 if (!SS.isEmpty()) { 2346 Diag(R.getNameLoc(), diag::err_no_member) 2347 << Name << computeDeclContext(SS, false) 2348 << SS.getRange(); 2349 return true; 2350 } 2351 2352 // Give up, we can't recover. 2353 Diag(R.getNameLoc(), diagnostic) << Name; 2354 return true; 2355 } 2356 2357 /// In Microsoft mode, if we are inside a template class whose parent class has 2358 /// dependent base classes, and we can't resolve an unqualified identifier, then 2359 /// assume the identifier is a member of a dependent base class. We can only 2360 /// recover successfully in static methods, instance methods, and other contexts 2361 /// where 'this' is available. This doesn't precisely match MSVC's 2362 /// instantiation model, but it's close enough. 2363 static Expr * 2364 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2365 DeclarationNameInfo &NameInfo, 2366 SourceLocation TemplateKWLoc, 2367 const TemplateArgumentListInfo *TemplateArgs) { 2368 // Only try to recover from lookup into dependent bases in static methods or 2369 // contexts where 'this' is available. 2370 QualType ThisType = S.getCurrentThisType(); 2371 const CXXRecordDecl *RD = nullptr; 2372 if (!ThisType.isNull()) 2373 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2374 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2375 RD = MD->getParent(); 2376 if (!RD || !RD->hasAnyDependentBases()) 2377 return nullptr; 2378 2379 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2380 // is available, suggest inserting 'this->' as a fixit. 2381 SourceLocation Loc = NameInfo.getLoc(); 2382 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2383 DB << NameInfo.getName() << RD; 2384 2385 if (!ThisType.isNull()) { 2386 DB << FixItHint::CreateInsertion(Loc, "this->"); 2387 return CXXDependentScopeMemberExpr::Create( 2388 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2389 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2390 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2391 } 2392 2393 // Synthesize a fake NNS that points to the derived class. This will 2394 // perform name lookup during template instantiation. 2395 CXXScopeSpec SS; 2396 auto *NNS = 2397 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2398 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2399 return DependentScopeDeclRefExpr::Create( 2400 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2401 TemplateArgs); 2402 } 2403 2404 ExprResult 2405 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2406 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2407 bool HasTrailingLParen, bool IsAddressOfOperand, 2408 CorrectionCandidateCallback *CCC, 2409 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2410 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2411 "cannot be direct & operand and have a trailing lparen"); 2412 if (SS.isInvalid()) 2413 return ExprError(); 2414 2415 TemplateArgumentListInfo TemplateArgsBuffer; 2416 2417 // Decompose the UnqualifiedId into the following data. 2418 DeclarationNameInfo NameInfo; 2419 const TemplateArgumentListInfo *TemplateArgs; 2420 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2421 2422 DeclarationName Name = NameInfo.getName(); 2423 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2424 SourceLocation NameLoc = NameInfo.getLoc(); 2425 2426 if (II && II->isEditorPlaceholder()) { 2427 // FIXME: When typed placeholders are supported we can create a typed 2428 // placeholder expression node. 2429 return ExprError(); 2430 } 2431 2432 // C++ [temp.dep.expr]p3: 2433 // An id-expression is type-dependent if it contains: 2434 // -- an identifier that was declared with a dependent type, 2435 // (note: handled after lookup) 2436 // -- a template-id that is dependent, 2437 // (note: handled in BuildTemplateIdExpr) 2438 // -- a conversion-function-id that specifies a dependent type, 2439 // -- a nested-name-specifier that contains a class-name that 2440 // names a dependent type. 2441 // Determine whether this is a member of an unknown specialization; 2442 // we need to handle these differently. 2443 bool DependentID = false; 2444 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2445 Name.getCXXNameType()->isDependentType()) { 2446 DependentID = true; 2447 } else if (SS.isSet()) { 2448 if (DeclContext *DC = computeDeclContext(SS, false)) { 2449 if (RequireCompleteDeclContext(SS, DC)) 2450 return ExprError(); 2451 } else { 2452 DependentID = true; 2453 } 2454 } 2455 2456 if (DependentID) 2457 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2458 IsAddressOfOperand, TemplateArgs); 2459 2460 // Perform the required lookup. 2461 LookupResult R(*this, NameInfo, 2462 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2463 ? LookupObjCImplicitSelfParam 2464 : LookupOrdinaryName); 2465 if (TemplateKWLoc.isValid() || TemplateArgs) { 2466 // Lookup the template name again to correctly establish the context in 2467 // which it was found. This is really unfortunate as we already did the 2468 // lookup to determine that it was a template name in the first place. If 2469 // this becomes a performance hit, we can work harder to preserve those 2470 // results until we get here but it's likely not worth it. 2471 bool MemberOfUnknownSpecialization; 2472 AssumedTemplateKind AssumedTemplate; 2473 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2474 MemberOfUnknownSpecialization, TemplateKWLoc, 2475 &AssumedTemplate)) 2476 return ExprError(); 2477 2478 if (MemberOfUnknownSpecialization || 2479 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2480 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2481 IsAddressOfOperand, TemplateArgs); 2482 } else { 2483 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2484 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2485 2486 // If the result might be in a dependent base class, this is a dependent 2487 // id-expression. 2488 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2489 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2490 IsAddressOfOperand, TemplateArgs); 2491 2492 // If this reference is in an Objective-C method, then we need to do 2493 // some special Objective-C lookup, too. 2494 if (IvarLookupFollowUp) { 2495 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2496 if (E.isInvalid()) 2497 return ExprError(); 2498 2499 if (Expr *Ex = E.getAs<Expr>()) 2500 return Ex; 2501 } 2502 } 2503 2504 if (R.isAmbiguous()) 2505 return ExprError(); 2506 2507 // This could be an implicitly declared function reference (legal in C90, 2508 // extension in C99, forbidden in C++). 2509 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2510 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2511 if (D) R.addDecl(D); 2512 } 2513 2514 // Determine whether this name might be a candidate for 2515 // argument-dependent lookup. 2516 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2517 2518 if (R.empty() && !ADL) { 2519 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2520 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2521 TemplateKWLoc, TemplateArgs)) 2522 return E; 2523 } 2524 2525 // Don't diagnose an empty lookup for inline assembly. 2526 if (IsInlineAsmIdentifier) 2527 return ExprError(); 2528 2529 // If this name wasn't predeclared and if this is not a function 2530 // call, diagnose the problem. 2531 TypoExpr *TE = nullptr; 2532 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2533 : nullptr); 2534 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2535 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2536 "Typo correction callback misconfigured"); 2537 if (CCC) { 2538 // Make sure the callback knows what the typo being diagnosed is. 2539 CCC->setTypoName(II); 2540 if (SS.isValid()) 2541 CCC->setTypoNNS(SS.getScopeRep()); 2542 } 2543 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2544 // a template name, but we happen to have always already looked up the name 2545 // before we get here if it must be a template name. 2546 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2547 None, &TE)) { 2548 if (TE && KeywordReplacement) { 2549 auto &State = getTypoExprState(TE); 2550 auto BestTC = State.Consumer->getNextCorrection(); 2551 if (BestTC.isKeyword()) { 2552 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2553 if (State.DiagHandler) 2554 State.DiagHandler(BestTC); 2555 KeywordReplacement->startToken(); 2556 KeywordReplacement->setKind(II->getTokenID()); 2557 KeywordReplacement->setIdentifierInfo(II); 2558 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2559 // Clean up the state associated with the TypoExpr, since it has 2560 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2561 clearDelayedTypo(TE); 2562 // Signal that a correction to a keyword was performed by returning a 2563 // valid-but-null ExprResult. 2564 return (Expr*)nullptr; 2565 } 2566 State.Consumer->resetCorrectionStream(); 2567 } 2568 return TE ? TE : ExprError(); 2569 } 2570 2571 assert(!R.empty() && 2572 "DiagnoseEmptyLookup returned false but added no results"); 2573 2574 // If we found an Objective-C instance variable, let 2575 // LookupInObjCMethod build the appropriate expression to 2576 // reference the ivar. 2577 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2578 R.clear(); 2579 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2580 // In a hopelessly buggy code, Objective-C instance variable 2581 // lookup fails and no expression will be built to reference it. 2582 if (!E.isInvalid() && !E.get()) 2583 return ExprError(); 2584 return E; 2585 } 2586 } 2587 2588 // This is guaranteed from this point on. 2589 assert(!R.empty() || ADL); 2590 2591 // Check whether this might be a C++ implicit instance member access. 2592 // C++ [class.mfct.non-static]p3: 2593 // When an id-expression that is not part of a class member access 2594 // syntax and not used to form a pointer to member is used in the 2595 // body of a non-static member function of class X, if name lookup 2596 // resolves the name in the id-expression to a non-static non-type 2597 // member of some class C, the id-expression is transformed into a 2598 // class member access expression using (*this) as the 2599 // postfix-expression to the left of the . operator. 2600 // 2601 // But we don't actually need to do this for '&' operands if R 2602 // resolved to a function or overloaded function set, because the 2603 // expression is ill-formed if it actually works out to be a 2604 // non-static member function: 2605 // 2606 // C++ [expr.ref]p4: 2607 // Otherwise, if E1.E2 refers to a non-static member function. . . 2608 // [t]he expression can be used only as the left-hand operand of a 2609 // member function call. 2610 // 2611 // There are other safeguards against such uses, but it's important 2612 // to get this right here so that we don't end up making a 2613 // spuriously dependent expression if we're inside a dependent 2614 // instance method. 2615 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2616 bool MightBeImplicitMember; 2617 if (!IsAddressOfOperand) 2618 MightBeImplicitMember = true; 2619 else if (!SS.isEmpty()) 2620 MightBeImplicitMember = false; 2621 else if (R.isOverloadedResult()) 2622 MightBeImplicitMember = false; 2623 else if (R.isUnresolvableResult()) 2624 MightBeImplicitMember = true; 2625 else 2626 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2627 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2628 isa<MSPropertyDecl>(R.getFoundDecl()); 2629 2630 if (MightBeImplicitMember) 2631 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2632 R, TemplateArgs, S); 2633 } 2634 2635 if (TemplateArgs || TemplateKWLoc.isValid()) { 2636 2637 // In C++1y, if this is a variable template id, then check it 2638 // in BuildTemplateIdExpr(). 2639 // The single lookup result must be a variable template declaration. 2640 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2641 Id.TemplateId->Kind == TNK_Var_template) { 2642 assert(R.getAsSingle<VarTemplateDecl>() && 2643 "There should only be one declaration found."); 2644 } 2645 2646 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2647 } 2648 2649 return BuildDeclarationNameExpr(SS, R, ADL); 2650 } 2651 2652 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2653 /// declaration name, generally during template instantiation. 2654 /// There's a large number of things which don't need to be done along 2655 /// this path. 2656 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2657 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2658 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2659 DeclContext *DC = computeDeclContext(SS, false); 2660 if (!DC) 2661 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2662 NameInfo, /*TemplateArgs=*/nullptr); 2663 2664 if (RequireCompleteDeclContext(SS, DC)) 2665 return ExprError(); 2666 2667 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2668 LookupQualifiedName(R, DC); 2669 2670 if (R.isAmbiguous()) 2671 return ExprError(); 2672 2673 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2674 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2675 NameInfo, /*TemplateArgs=*/nullptr); 2676 2677 if (R.empty()) { 2678 // Don't diagnose problems with invalid record decl, the secondary no_member 2679 // diagnostic during template instantiation is likely bogus, e.g. if a class 2680 // is invalid because it's derived from an invalid base class, then missing 2681 // members were likely supposed to be inherited. 2682 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2683 if (CD->isInvalidDecl()) 2684 return ExprError(); 2685 Diag(NameInfo.getLoc(), diag::err_no_member) 2686 << NameInfo.getName() << DC << SS.getRange(); 2687 return ExprError(); 2688 } 2689 2690 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2691 // Diagnose a missing typename if this resolved unambiguously to a type in 2692 // a dependent context. If we can recover with a type, downgrade this to 2693 // a warning in Microsoft compatibility mode. 2694 unsigned DiagID = diag::err_typename_missing; 2695 if (RecoveryTSI && getLangOpts().MSVCCompat) 2696 DiagID = diag::ext_typename_missing; 2697 SourceLocation Loc = SS.getBeginLoc(); 2698 auto D = Diag(Loc, DiagID); 2699 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2700 << SourceRange(Loc, NameInfo.getEndLoc()); 2701 2702 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2703 // context. 2704 if (!RecoveryTSI) 2705 return ExprError(); 2706 2707 // Only issue the fixit if we're prepared to recover. 2708 D << FixItHint::CreateInsertion(Loc, "typename "); 2709 2710 // Recover by pretending this was an elaborated type. 2711 QualType Ty = Context.getTypeDeclType(TD); 2712 TypeLocBuilder TLB; 2713 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2714 2715 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2716 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2717 QTL.setElaboratedKeywordLoc(SourceLocation()); 2718 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2719 2720 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2721 2722 return ExprEmpty(); 2723 } 2724 2725 // Defend against this resolving to an implicit member access. We usually 2726 // won't get here if this might be a legitimate a class member (we end up in 2727 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2728 // a pointer-to-member or in an unevaluated context in C++11. 2729 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2730 return BuildPossibleImplicitMemberExpr(SS, 2731 /*TemplateKWLoc=*/SourceLocation(), 2732 R, /*TemplateArgs=*/nullptr, S); 2733 2734 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2735 } 2736 2737 /// The parser has read a name in, and Sema has detected that we're currently 2738 /// inside an ObjC method. Perform some additional checks and determine if we 2739 /// should form a reference to an ivar. 2740 /// 2741 /// Ideally, most of this would be done by lookup, but there's 2742 /// actually quite a lot of extra work involved. 2743 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2744 IdentifierInfo *II) { 2745 SourceLocation Loc = Lookup.getNameLoc(); 2746 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2747 2748 // Check for error condition which is already reported. 2749 if (!CurMethod) 2750 return DeclResult(true); 2751 2752 // There are two cases to handle here. 1) scoped lookup could have failed, 2753 // in which case we should look for an ivar. 2) scoped lookup could have 2754 // found a decl, but that decl is outside the current instance method (i.e. 2755 // a global variable). In these two cases, we do a lookup for an ivar with 2756 // this name, if the lookup sucedes, we replace it our current decl. 2757 2758 // If we're in a class method, we don't normally want to look for 2759 // ivars. But if we don't find anything else, and there's an 2760 // ivar, that's an error. 2761 bool IsClassMethod = CurMethod->isClassMethod(); 2762 2763 bool LookForIvars; 2764 if (Lookup.empty()) 2765 LookForIvars = true; 2766 else if (IsClassMethod) 2767 LookForIvars = false; 2768 else 2769 LookForIvars = (Lookup.isSingleResult() && 2770 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2771 ObjCInterfaceDecl *IFace = nullptr; 2772 if (LookForIvars) { 2773 IFace = CurMethod->getClassInterface(); 2774 ObjCInterfaceDecl *ClassDeclared; 2775 ObjCIvarDecl *IV = nullptr; 2776 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2777 // Diagnose using an ivar in a class method. 2778 if (IsClassMethod) { 2779 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2780 return DeclResult(true); 2781 } 2782 2783 // Diagnose the use of an ivar outside of the declaring class. 2784 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2785 !declaresSameEntity(ClassDeclared, IFace) && 2786 !getLangOpts().DebuggerSupport) 2787 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2788 2789 // Success. 2790 return IV; 2791 } 2792 } else if (CurMethod->isInstanceMethod()) { 2793 // We should warn if a local variable hides an ivar. 2794 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2795 ObjCInterfaceDecl *ClassDeclared; 2796 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2797 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2798 declaresSameEntity(IFace, ClassDeclared)) 2799 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2800 } 2801 } 2802 } else if (Lookup.isSingleResult() && 2803 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2804 // If accessing a stand-alone ivar in a class method, this is an error. 2805 if (const ObjCIvarDecl *IV = 2806 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2807 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2808 return DeclResult(true); 2809 } 2810 } 2811 2812 // Didn't encounter an error, didn't find an ivar. 2813 return DeclResult(false); 2814 } 2815 2816 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2817 ObjCIvarDecl *IV) { 2818 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2819 assert(CurMethod && CurMethod->isInstanceMethod() && 2820 "should not reference ivar from this context"); 2821 2822 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2823 assert(IFace && "should not reference ivar from this context"); 2824 2825 // If we're referencing an invalid decl, just return this as a silent 2826 // error node. The error diagnostic was already emitted on the decl. 2827 if (IV->isInvalidDecl()) 2828 return ExprError(); 2829 2830 // Check if referencing a field with __attribute__((deprecated)). 2831 if (DiagnoseUseOfDecl(IV, Loc)) 2832 return ExprError(); 2833 2834 // FIXME: This should use a new expr for a direct reference, don't 2835 // turn this into Self->ivar, just return a BareIVarExpr or something. 2836 IdentifierInfo &II = Context.Idents.get("self"); 2837 UnqualifiedId SelfName; 2838 SelfName.setImplicitSelfParam(&II); 2839 CXXScopeSpec SelfScopeSpec; 2840 SourceLocation TemplateKWLoc; 2841 ExprResult SelfExpr = 2842 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2843 /*HasTrailingLParen=*/false, 2844 /*IsAddressOfOperand=*/false); 2845 if (SelfExpr.isInvalid()) 2846 return ExprError(); 2847 2848 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2849 if (SelfExpr.isInvalid()) 2850 return ExprError(); 2851 2852 MarkAnyDeclReferenced(Loc, IV, true); 2853 2854 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2855 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2856 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2857 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2858 2859 ObjCIvarRefExpr *Result = new (Context) 2860 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2861 IV->getLocation(), SelfExpr.get(), true, true); 2862 2863 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2864 if (!isUnevaluatedContext() && 2865 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2866 getCurFunction()->recordUseOfWeak(Result); 2867 } 2868 if (getLangOpts().ObjCAutoRefCount) 2869 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2870 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2871 2872 return Result; 2873 } 2874 2875 /// The parser has read a name in, and Sema has detected that we're currently 2876 /// inside an ObjC method. Perform some additional checks and determine if we 2877 /// should form a reference to an ivar. If so, build an expression referencing 2878 /// that ivar. 2879 ExprResult 2880 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2881 IdentifierInfo *II, bool AllowBuiltinCreation) { 2882 // FIXME: Integrate this lookup step into LookupParsedName. 2883 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2884 if (Ivar.isInvalid()) 2885 return ExprError(); 2886 if (Ivar.isUsable()) 2887 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2888 cast<ObjCIvarDecl>(Ivar.get())); 2889 2890 if (Lookup.empty() && II && AllowBuiltinCreation) 2891 LookupBuiltin(Lookup); 2892 2893 // Sentinel value saying that we didn't do anything special. 2894 return ExprResult(false); 2895 } 2896 2897 /// Cast a base object to a member's actual type. 2898 /// 2899 /// There are two relevant checks: 2900 /// 2901 /// C++ [class.access.base]p7: 2902 /// 2903 /// If a class member access operator [...] is used to access a non-static 2904 /// data member or non-static member function, the reference is ill-formed if 2905 /// the left operand [...] cannot be implicitly converted to a pointer to the 2906 /// naming class of the right operand. 2907 /// 2908 /// C++ [expr.ref]p7: 2909 /// 2910 /// If E2 is a non-static data member or a non-static member function, the 2911 /// program is ill-formed if the class of which E2 is directly a member is an 2912 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2913 /// 2914 /// Note that the latter check does not consider access; the access of the 2915 /// "real" base class is checked as appropriate when checking the access of the 2916 /// member name. 2917 ExprResult 2918 Sema::PerformObjectMemberConversion(Expr *From, 2919 NestedNameSpecifier *Qualifier, 2920 NamedDecl *FoundDecl, 2921 NamedDecl *Member) { 2922 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2923 if (!RD) 2924 return From; 2925 2926 QualType DestRecordType; 2927 QualType DestType; 2928 QualType FromRecordType; 2929 QualType FromType = From->getType(); 2930 bool PointerConversions = false; 2931 if (isa<FieldDecl>(Member)) { 2932 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2933 auto FromPtrType = FromType->getAs<PointerType>(); 2934 DestRecordType = Context.getAddrSpaceQualType( 2935 DestRecordType, FromPtrType 2936 ? FromType->getPointeeType().getAddressSpace() 2937 : FromType.getAddressSpace()); 2938 2939 if (FromPtrType) { 2940 DestType = Context.getPointerType(DestRecordType); 2941 FromRecordType = FromPtrType->getPointeeType(); 2942 PointerConversions = true; 2943 } else { 2944 DestType = DestRecordType; 2945 FromRecordType = FromType; 2946 } 2947 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2948 if (Method->isStatic()) 2949 return From; 2950 2951 DestType = Method->getThisType(); 2952 DestRecordType = DestType->getPointeeType(); 2953 2954 if (FromType->getAs<PointerType>()) { 2955 FromRecordType = FromType->getPointeeType(); 2956 PointerConversions = true; 2957 } else { 2958 FromRecordType = FromType; 2959 DestType = DestRecordType; 2960 } 2961 2962 LangAS FromAS = FromRecordType.getAddressSpace(); 2963 LangAS DestAS = DestRecordType.getAddressSpace(); 2964 if (FromAS != DestAS) { 2965 QualType FromRecordTypeWithoutAS = 2966 Context.removeAddrSpaceQualType(FromRecordType); 2967 QualType FromTypeWithDestAS = 2968 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2969 if (PointerConversions) 2970 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2971 From = ImpCastExprToType(From, FromTypeWithDestAS, 2972 CK_AddressSpaceConversion, From->getValueKind()) 2973 .get(); 2974 } 2975 } else { 2976 // No conversion necessary. 2977 return From; 2978 } 2979 2980 if (DestType->isDependentType() || FromType->isDependentType()) 2981 return From; 2982 2983 // If the unqualified types are the same, no conversion is necessary. 2984 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2985 return From; 2986 2987 SourceRange FromRange = From->getSourceRange(); 2988 SourceLocation FromLoc = FromRange.getBegin(); 2989 2990 ExprValueKind VK = From->getValueKind(); 2991 2992 // C++ [class.member.lookup]p8: 2993 // [...] Ambiguities can often be resolved by qualifying a name with its 2994 // class name. 2995 // 2996 // If the member was a qualified name and the qualified referred to a 2997 // specific base subobject type, we'll cast to that intermediate type 2998 // first and then to the object in which the member is declared. That allows 2999 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3000 // 3001 // class Base { public: int x; }; 3002 // class Derived1 : public Base { }; 3003 // class Derived2 : public Base { }; 3004 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3005 // 3006 // void VeryDerived::f() { 3007 // x = 17; // error: ambiguous base subobjects 3008 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3009 // } 3010 if (Qualifier && Qualifier->getAsType()) { 3011 QualType QType = QualType(Qualifier->getAsType(), 0); 3012 assert(QType->isRecordType() && "lookup done with non-record type"); 3013 3014 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3015 3016 // In C++98, the qualifier type doesn't actually have to be a base 3017 // type of the object type, in which case we just ignore it. 3018 // Otherwise build the appropriate casts. 3019 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3020 CXXCastPath BasePath; 3021 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3022 FromLoc, FromRange, &BasePath)) 3023 return ExprError(); 3024 3025 if (PointerConversions) 3026 QType = Context.getPointerType(QType); 3027 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3028 VK, &BasePath).get(); 3029 3030 FromType = QType; 3031 FromRecordType = QRecordType; 3032 3033 // If the qualifier type was the same as the destination type, 3034 // we're done. 3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3036 return From; 3037 } 3038 } 3039 3040 CXXCastPath BasePath; 3041 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3042 FromLoc, FromRange, &BasePath, 3043 /*IgnoreAccess=*/true)) 3044 return ExprError(); 3045 3046 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3047 VK, &BasePath); 3048 } 3049 3050 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3051 const LookupResult &R, 3052 bool HasTrailingLParen) { 3053 // Only when used directly as the postfix-expression of a call. 3054 if (!HasTrailingLParen) 3055 return false; 3056 3057 // Never if a scope specifier was provided. 3058 if (SS.isSet()) 3059 return false; 3060 3061 // Only in C++ or ObjC++. 3062 if (!getLangOpts().CPlusPlus) 3063 return false; 3064 3065 // Turn off ADL when we find certain kinds of declarations during 3066 // normal lookup: 3067 for (NamedDecl *D : R) { 3068 // C++0x [basic.lookup.argdep]p3: 3069 // -- a declaration of a class member 3070 // Since using decls preserve this property, we check this on the 3071 // original decl. 3072 if (D->isCXXClassMember()) 3073 return false; 3074 3075 // C++0x [basic.lookup.argdep]p3: 3076 // -- a block-scope function declaration that is not a 3077 // using-declaration 3078 // NOTE: we also trigger this for function templates (in fact, we 3079 // don't check the decl type at all, since all other decl types 3080 // turn off ADL anyway). 3081 if (isa<UsingShadowDecl>(D)) 3082 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3083 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3084 return false; 3085 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a declaration that is neither a function or a function 3088 // template 3089 // And also for builtin functions. 3090 if (isa<FunctionDecl>(D)) { 3091 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3092 3093 // But also builtin functions. 3094 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3095 return false; 3096 } else if (!isa<FunctionTemplateDecl>(D)) 3097 return false; 3098 } 3099 3100 return true; 3101 } 3102 3103 3104 /// Diagnoses obvious problems with the use of the given declaration 3105 /// as an expression. This is only actually called for lookups that 3106 /// were not overloaded, and it doesn't promise that the declaration 3107 /// will in fact be used. 3108 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3109 if (D->isInvalidDecl()) 3110 return true; 3111 3112 if (isa<TypedefNameDecl>(D)) { 3113 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3114 return true; 3115 } 3116 3117 if (isa<ObjCInterfaceDecl>(D)) { 3118 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3119 return true; 3120 } 3121 3122 if (isa<NamespaceDecl>(D)) { 3123 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3124 return true; 3125 } 3126 3127 return false; 3128 } 3129 3130 // Certain multiversion types should be treated as overloaded even when there is 3131 // only one result. 3132 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3133 assert(R.isSingleResult() && "Expected only a single result"); 3134 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3135 return FD && 3136 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3137 } 3138 3139 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3140 LookupResult &R, bool NeedsADL, 3141 bool AcceptInvalidDecl) { 3142 // If this is a single, fully-resolved result and we don't need ADL, 3143 // just build an ordinary singleton decl ref. 3144 if (!NeedsADL && R.isSingleResult() && 3145 !R.getAsSingle<FunctionTemplateDecl>() && 3146 !ShouldLookupResultBeMultiVersionOverload(R)) 3147 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3148 R.getRepresentativeDecl(), nullptr, 3149 AcceptInvalidDecl); 3150 3151 // We only need to check the declaration if there's exactly one 3152 // result, because in the overloaded case the results can only be 3153 // functions and function templates. 3154 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3155 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3156 return ExprError(); 3157 3158 // Otherwise, just build an unresolved lookup expression. Suppress 3159 // any lookup-related diagnostics; we'll hash these out later, when 3160 // we've picked a target. 3161 R.suppressDiagnostics(); 3162 3163 UnresolvedLookupExpr *ULE 3164 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3165 SS.getWithLocInContext(Context), 3166 R.getLookupNameInfo(), 3167 NeedsADL, R.isOverloadedResult(), 3168 R.begin(), R.end()); 3169 3170 return ULE; 3171 } 3172 3173 static void 3174 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3175 ValueDecl *var, DeclContext *DC); 3176 3177 /// Complete semantic analysis for a reference to the given declaration. 3178 ExprResult Sema::BuildDeclarationNameExpr( 3179 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3180 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3181 bool AcceptInvalidDecl) { 3182 assert(D && "Cannot refer to a NULL declaration"); 3183 assert(!isa<FunctionTemplateDecl>(D) && 3184 "Cannot refer unambiguously to a function template"); 3185 3186 SourceLocation Loc = NameInfo.getLoc(); 3187 if (CheckDeclInExpr(*this, Loc, D)) 3188 return ExprError(); 3189 3190 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3191 // Specifically diagnose references to class templates that are missing 3192 // a template argument list. 3193 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3194 return ExprError(); 3195 } 3196 3197 // Make sure that we're referring to a value. 3198 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3199 if (!VD) { 3200 Diag(Loc, diag::err_ref_non_value) 3201 << D << SS.getRange(); 3202 Diag(D->getLocation(), diag::note_declared_at); 3203 return ExprError(); 3204 } 3205 3206 // Check whether this declaration can be used. Note that we suppress 3207 // this check when we're going to perform argument-dependent lookup 3208 // on this function name, because this might not be the function 3209 // that overload resolution actually selects. 3210 if (DiagnoseUseOfDecl(VD, Loc)) 3211 return ExprError(); 3212 3213 // Only create DeclRefExpr's for valid Decl's. 3214 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3215 return ExprError(); 3216 3217 // Handle members of anonymous structs and unions. If we got here, 3218 // and the reference is to a class member indirect field, then this 3219 // must be the subject of a pointer-to-member expression. 3220 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3221 if (!indirectField->isCXXClassMember()) 3222 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3223 indirectField); 3224 3225 { 3226 QualType type = VD->getType(); 3227 if (type.isNull()) 3228 return ExprError(); 3229 ExprValueKind valueKind = VK_RValue; 3230 3231 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3232 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3233 // is expanded by some outer '...' in the context of the use. 3234 type = type.getNonPackExpansionType(); 3235 3236 switch (D->getKind()) { 3237 // Ignore all the non-ValueDecl kinds. 3238 #define ABSTRACT_DECL(kind) 3239 #define VALUE(type, base) 3240 #define DECL(type, base) \ 3241 case Decl::type: 3242 #include "clang/AST/DeclNodes.inc" 3243 llvm_unreachable("invalid value decl kind"); 3244 3245 // These shouldn't make it here. 3246 case Decl::ObjCAtDefsField: 3247 llvm_unreachable("forming non-member reference to ivar?"); 3248 3249 // Enum constants are always r-values and never references. 3250 // Unresolved using declarations are dependent. 3251 case Decl::EnumConstant: 3252 case Decl::UnresolvedUsingValue: 3253 case Decl::OMPDeclareReduction: 3254 case Decl::OMPDeclareMapper: 3255 valueKind = VK_RValue; 3256 break; 3257 3258 // Fields and indirect fields that got here must be for 3259 // pointer-to-member expressions; we just call them l-values for 3260 // internal consistency, because this subexpression doesn't really 3261 // exist in the high-level semantics. 3262 case Decl::Field: 3263 case Decl::IndirectField: 3264 case Decl::ObjCIvar: 3265 assert(getLangOpts().CPlusPlus && 3266 "building reference to field in C?"); 3267 3268 // These can't have reference type in well-formed programs, but 3269 // for internal consistency we do this anyway. 3270 type = type.getNonReferenceType(); 3271 valueKind = VK_LValue; 3272 break; 3273 3274 // Non-type template parameters are either l-values or r-values 3275 // depending on the type. 3276 case Decl::NonTypeTemplateParm: { 3277 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3278 type = reftype->getPointeeType(); 3279 valueKind = VK_LValue; // even if the parameter is an r-value reference 3280 break; 3281 } 3282 3283 // [expr.prim.id.unqual]p2: 3284 // If the entity is a template parameter object for a template 3285 // parameter of type T, the type of the expression is const T. 3286 // [...] The expression is an lvalue if the entity is a [...] template 3287 // parameter object. 3288 if (type->isRecordType()) { 3289 type = type.getUnqualifiedType().withConst(); 3290 valueKind = VK_LValue; 3291 break; 3292 } 3293 3294 // For non-references, we need to strip qualifiers just in case 3295 // the template parameter was declared as 'const int' or whatever. 3296 valueKind = VK_RValue; 3297 type = type.getUnqualifiedType(); 3298 break; 3299 } 3300 3301 case Decl::Var: 3302 case Decl::VarTemplateSpecialization: 3303 case Decl::VarTemplatePartialSpecialization: 3304 case Decl::Decomposition: 3305 case Decl::OMPCapturedExpr: 3306 // In C, "extern void blah;" is valid and is an r-value. 3307 if (!getLangOpts().CPlusPlus && 3308 !type.hasQualifiers() && 3309 type->isVoidType()) { 3310 valueKind = VK_RValue; 3311 break; 3312 } 3313 LLVM_FALLTHROUGH; 3314 3315 case Decl::ImplicitParam: 3316 case Decl::ParmVar: { 3317 // These are always l-values. 3318 valueKind = VK_LValue; 3319 type = type.getNonReferenceType(); 3320 3321 // FIXME: Does the addition of const really only apply in 3322 // potentially-evaluated contexts? Since the variable isn't actually 3323 // captured in an unevaluated context, it seems that the answer is no. 3324 if (!isUnevaluatedContext()) { 3325 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3326 if (!CapturedType.isNull()) 3327 type = CapturedType; 3328 } 3329 3330 break; 3331 } 3332 3333 case Decl::Binding: { 3334 // These are always lvalues. 3335 valueKind = VK_LValue; 3336 type = type.getNonReferenceType(); 3337 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3338 // decides how that's supposed to work. 3339 auto *BD = cast<BindingDecl>(VD); 3340 if (BD->getDeclContext() != CurContext) { 3341 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3342 if (DD && DD->hasLocalStorage()) 3343 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3344 } 3345 break; 3346 } 3347 3348 case Decl::Function: { 3349 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3350 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3351 type = Context.BuiltinFnTy; 3352 valueKind = VK_RValue; 3353 break; 3354 } 3355 } 3356 3357 const FunctionType *fty = type->castAs<FunctionType>(); 3358 3359 // If we're referring to a function with an __unknown_anytype 3360 // result type, make the entire expression __unknown_anytype. 3361 if (fty->getReturnType() == Context.UnknownAnyTy) { 3362 type = Context.UnknownAnyTy; 3363 valueKind = VK_RValue; 3364 break; 3365 } 3366 3367 // Functions are l-values in C++. 3368 if (getLangOpts().CPlusPlus) { 3369 valueKind = VK_LValue; 3370 break; 3371 } 3372 3373 // C99 DR 316 says that, if a function type comes from a 3374 // function definition (without a prototype), that type is only 3375 // used for checking compatibility. Therefore, when referencing 3376 // the function, we pretend that we don't have the full function 3377 // type. 3378 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3379 isa<FunctionProtoType>(fty)) 3380 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3381 fty->getExtInfo()); 3382 3383 // Functions are r-values in C. 3384 valueKind = VK_RValue; 3385 break; 3386 } 3387 3388 case Decl::CXXDeductionGuide: 3389 llvm_unreachable("building reference to deduction guide"); 3390 3391 case Decl::MSProperty: 3392 case Decl::MSGuid: 3393 case Decl::TemplateParamObject: 3394 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3395 // capture in OpenMP, or duplicated between host and device? 3396 valueKind = VK_LValue; 3397 break; 3398 3399 case Decl::CXXMethod: 3400 // If we're referring to a method with an __unknown_anytype 3401 // result type, make the entire expression __unknown_anytype. 3402 // This should only be possible with a type written directly. 3403 if (const FunctionProtoType *proto 3404 = dyn_cast<FunctionProtoType>(VD->getType())) 3405 if (proto->getReturnType() == Context.UnknownAnyTy) { 3406 type = Context.UnknownAnyTy; 3407 valueKind = VK_RValue; 3408 break; 3409 } 3410 3411 // C++ methods are l-values if static, r-values if non-static. 3412 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3413 valueKind = VK_LValue; 3414 break; 3415 } 3416 LLVM_FALLTHROUGH; 3417 3418 case Decl::CXXConversion: 3419 case Decl::CXXDestructor: 3420 case Decl::CXXConstructor: 3421 valueKind = VK_RValue; 3422 break; 3423 } 3424 3425 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3426 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3427 TemplateArgs); 3428 } 3429 } 3430 3431 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3432 SmallString<32> &Target) { 3433 Target.resize(CharByteWidth * (Source.size() + 1)); 3434 char *ResultPtr = &Target[0]; 3435 const llvm::UTF8 *ErrorPtr; 3436 bool success = 3437 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3438 (void)success; 3439 assert(success); 3440 Target.resize(ResultPtr - &Target[0]); 3441 } 3442 3443 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3444 PredefinedExpr::IdentKind IK) { 3445 // Pick the current block, lambda, captured statement or function. 3446 Decl *currentDecl = nullptr; 3447 if (const BlockScopeInfo *BSI = getCurBlock()) 3448 currentDecl = BSI->TheDecl; 3449 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3450 currentDecl = LSI->CallOperator; 3451 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3452 currentDecl = CSI->TheCapturedDecl; 3453 else 3454 currentDecl = getCurFunctionOrMethodDecl(); 3455 3456 if (!currentDecl) { 3457 Diag(Loc, diag::ext_predef_outside_function); 3458 currentDecl = Context.getTranslationUnitDecl(); 3459 } 3460 3461 QualType ResTy; 3462 StringLiteral *SL = nullptr; 3463 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3464 ResTy = Context.DependentTy; 3465 else { 3466 // Pre-defined identifiers are of type char[x], where x is the length of 3467 // the string. 3468 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3469 unsigned Length = Str.length(); 3470 3471 llvm::APInt LengthI(32, Length + 1); 3472 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3473 ResTy = 3474 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3475 SmallString<32> RawChars; 3476 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3477 Str, RawChars); 3478 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3479 ArrayType::Normal, 3480 /*IndexTypeQuals*/ 0); 3481 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3482 /*Pascal*/ false, ResTy, Loc); 3483 } else { 3484 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3485 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3486 ArrayType::Normal, 3487 /*IndexTypeQuals*/ 0); 3488 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3489 /*Pascal*/ false, ResTy, Loc); 3490 } 3491 } 3492 3493 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3494 } 3495 3496 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3497 PredefinedExpr::IdentKind IK; 3498 3499 switch (Kind) { 3500 default: llvm_unreachable("Unknown simple primary expr!"); 3501 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3502 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3503 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3504 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3505 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3506 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3507 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3508 } 3509 3510 return BuildPredefinedExpr(Loc, IK); 3511 } 3512 3513 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3514 SmallString<16> CharBuffer; 3515 bool Invalid = false; 3516 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3517 if (Invalid) 3518 return ExprError(); 3519 3520 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3521 PP, Tok.getKind()); 3522 if (Literal.hadError()) 3523 return ExprError(); 3524 3525 QualType Ty; 3526 if (Literal.isWide()) 3527 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3528 else if (Literal.isUTF8() && getLangOpts().Char8) 3529 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3530 else if (Literal.isUTF16()) 3531 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3532 else if (Literal.isUTF32()) 3533 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3534 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3535 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3536 else 3537 Ty = Context.CharTy; // 'x' -> char in C++ 3538 3539 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3540 if (Literal.isWide()) 3541 Kind = CharacterLiteral::Wide; 3542 else if (Literal.isUTF16()) 3543 Kind = CharacterLiteral::UTF16; 3544 else if (Literal.isUTF32()) 3545 Kind = CharacterLiteral::UTF32; 3546 else if (Literal.isUTF8()) 3547 Kind = CharacterLiteral::UTF8; 3548 3549 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3550 Tok.getLocation()); 3551 3552 if (Literal.getUDSuffix().empty()) 3553 return Lit; 3554 3555 // We're building a user-defined literal. 3556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3557 SourceLocation UDSuffixLoc = 3558 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3559 3560 // Make sure we're allowed user-defined literals here. 3561 if (!UDLScope) 3562 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3563 3564 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3565 // operator "" X (ch) 3566 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3567 Lit, Tok.getLocation()); 3568 } 3569 3570 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3571 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3572 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3573 Context.IntTy, Loc); 3574 } 3575 3576 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3577 QualType Ty, SourceLocation Loc) { 3578 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3579 3580 using llvm::APFloat; 3581 APFloat Val(Format); 3582 3583 APFloat::opStatus result = Literal.GetFloatValue(Val); 3584 3585 // Overflow is always an error, but underflow is only an error if 3586 // we underflowed to zero (APFloat reports denormals as underflow). 3587 if ((result & APFloat::opOverflow) || 3588 ((result & APFloat::opUnderflow) && Val.isZero())) { 3589 unsigned diagnostic; 3590 SmallString<20> buffer; 3591 if (result & APFloat::opOverflow) { 3592 diagnostic = diag::warn_float_overflow; 3593 APFloat::getLargest(Format).toString(buffer); 3594 } else { 3595 diagnostic = diag::warn_float_underflow; 3596 APFloat::getSmallest(Format).toString(buffer); 3597 } 3598 3599 S.Diag(Loc, diagnostic) 3600 << Ty 3601 << StringRef(buffer.data(), buffer.size()); 3602 } 3603 3604 bool isExact = (result == APFloat::opOK); 3605 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3606 } 3607 3608 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3609 assert(E && "Invalid expression"); 3610 3611 if (E->isValueDependent()) 3612 return false; 3613 3614 QualType QT = E->getType(); 3615 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3616 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3617 return true; 3618 } 3619 3620 llvm::APSInt ValueAPS; 3621 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3622 3623 if (R.isInvalid()) 3624 return true; 3625 3626 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3627 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3628 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3629 << ValueAPS.toString(10) << ValueIsPositive; 3630 return true; 3631 } 3632 3633 return false; 3634 } 3635 3636 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3637 // Fast path for a single digit (which is quite common). A single digit 3638 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3639 if (Tok.getLength() == 1) { 3640 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3641 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3642 } 3643 3644 SmallString<128> SpellingBuffer; 3645 // NumericLiteralParser wants to overread by one character. Add padding to 3646 // the buffer in case the token is copied to the buffer. If getSpelling() 3647 // returns a StringRef to the memory buffer, it should have a null char at 3648 // the EOF, so it is also safe. 3649 SpellingBuffer.resize(Tok.getLength() + 1); 3650 3651 // Get the spelling of the token, which eliminates trigraphs, etc. 3652 bool Invalid = false; 3653 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3654 if (Invalid) 3655 return ExprError(); 3656 3657 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3658 PP.getSourceManager(), PP.getLangOpts(), 3659 PP.getTargetInfo(), PP.getDiagnostics()); 3660 if (Literal.hadError) 3661 return ExprError(); 3662 3663 if (Literal.hasUDSuffix()) { 3664 // We're building a user-defined literal. 3665 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3666 SourceLocation UDSuffixLoc = 3667 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3668 3669 // Make sure we're allowed user-defined literals here. 3670 if (!UDLScope) 3671 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3672 3673 QualType CookedTy; 3674 if (Literal.isFloatingLiteral()) { 3675 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3676 // long double, the literal is treated as a call of the form 3677 // operator "" X (f L) 3678 CookedTy = Context.LongDoubleTy; 3679 } else { 3680 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3681 // unsigned long long, the literal is treated as a call of the form 3682 // operator "" X (n ULL) 3683 CookedTy = Context.UnsignedLongLongTy; 3684 } 3685 3686 DeclarationName OpName = 3687 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3688 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3689 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3690 3691 SourceLocation TokLoc = Tok.getLocation(); 3692 3693 // Perform literal operator lookup to determine if we're building a raw 3694 // literal or a cooked one. 3695 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3696 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3697 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3698 /*AllowStringTemplatePack*/ false, 3699 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3700 case LOLR_ErrorNoDiagnostic: 3701 // Lookup failure for imaginary constants isn't fatal, there's still the 3702 // GNU extension producing _Complex types. 3703 break; 3704 case LOLR_Error: 3705 return ExprError(); 3706 case LOLR_Cooked: { 3707 Expr *Lit; 3708 if (Literal.isFloatingLiteral()) { 3709 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3710 } else { 3711 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3712 if (Literal.GetIntegerValue(ResultVal)) 3713 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3714 << /* Unsigned */ 1; 3715 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3716 Tok.getLocation()); 3717 } 3718 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3719 } 3720 3721 case LOLR_Raw: { 3722 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3723 // literal is treated as a call of the form 3724 // operator "" X ("n") 3725 unsigned Length = Literal.getUDSuffixOffset(); 3726 QualType StrTy = Context.getConstantArrayType( 3727 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3728 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3729 Expr *Lit = StringLiteral::Create( 3730 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3731 /*Pascal*/false, StrTy, &TokLoc, 1); 3732 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3733 } 3734 3735 case LOLR_Template: { 3736 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3737 // template), L is treated as a call fo the form 3738 // operator "" X <'c1', 'c2', ... 'ck'>() 3739 // where n is the source character sequence c1 c2 ... ck. 3740 TemplateArgumentListInfo ExplicitArgs; 3741 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3742 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3743 llvm::APSInt Value(CharBits, CharIsUnsigned); 3744 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3745 Value = TokSpelling[I]; 3746 TemplateArgument Arg(Context, Value, Context.CharTy); 3747 TemplateArgumentLocInfo ArgInfo; 3748 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3749 } 3750 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3751 &ExplicitArgs); 3752 } 3753 case LOLR_StringTemplatePack: 3754 llvm_unreachable("unexpected literal operator lookup result"); 3755 } 3756 } 3757 3758 Expr *Res; 3759 3760 if (Literal.isFixedPointLiteral()) { 3761 QualType Ty; 3762 3763 if (Literal.isAccum) { 3764 if (Literal.isHalf) { 3765 Ty = Context.ShortAccumTy; 3766 } else if (Literal.isLong) { 3767 Ty = Context.LongAccumTy; 3768 } else { 3769 Ty = Context.AccumTy; 3770 } 3771 } else if (Literal.isFract) { 3772 if (Literal.isHalf) { 3773 Ty = Context.ShortFractTy; 3774 } else if (Literal.isLong) { 3775 Ty = Context.LongFractTy; 3776 } else { 3777 Ty = Context.FractTy; 3778 } 3779 } 3780 3781 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3782 3783 bool isSigned = !Literal.isUnsigned; 3784 unsigned scale = Context.getFixedPointScale(Ty); 3785 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3786 3787 llvm::APInt Val(bit_width, 0, isSigned); 3788 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3789 bool ValIsZero = Val.isNullValue() && !Overflowed; 3790 3791 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3792 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3793 // Clause 6.4.4 - The value of a constant shall be in the range of 3794 // representable values for its type, with exception for constants of a 3795 // fract type with a value of exactly 1; such a constant shall denote 3796 // the maximal value for the type. 3797 --Val; 3798 else if (Val.ugt(MaxVal) || Overflowed) 3799 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3800 3801 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3802 Tok.getLocation(), scale); 3803 } else if (Literal.isFloatingLiteral()) { 3804 QualType Ty; 3805 if (Literal.isHalf){ 3806 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3807 Ty = Context.HalfTy; 3808 else { 3809 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3810 return ExprError(); 3811 } 3812 } else if (Literal.isFloat) 3813 Ty = Context.FloatTy; 3814 else if (Literal.isLong) 3815 Ty = Context.LongDoubleTy; 3816 else if (Literal.isFloat16) 3817 Ty = Context.Float16Ty; 3818 else if (Literal.isFloat128) 3819 Ty = Context.Float128Ty; 3820 else 3821 Ty = Context.DoubleTy; 3822 3823 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3824 3825 if (Ty == Context.DoubleTy) { 3826 if (getLangOpts().SinglePrecisionConstants) { 3827 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3828 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3829 } 3830 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3831 "cl_khr_fp64", getLangOpts())) { 3832 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3833 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3834 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3835 } 3836 } 3837 } else if (!Literal.isIntegerLiteral()) { 3838 return ExprError(); 3839 } else { 3840 QualType Ty; 3841 3842 // 'long long' is a C99 or C++11 feature. 3843 if (!getLangOpts().C99 && Literal.isLongLong) { 3844 if (getLangOpts().CPlusPlus) 3845 Diag(Tok.getLocation(), 3846 getLangOpts().CPlusPlus11 ? 3847 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3848 else 3849 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3850 } 3851 3852 // 'z/uz' literals are a C++2b feature. 3853 if (Literal.isSizeT) 3854 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3855 ? getLangOpts().CPlusPlus2b 3856 ? diag::warn_cxx20_compat_size_t_suffix 3857 : diag::ext_cxx2b_size_t_suffix 3858 : diag::err_cxx2b_size_t_suffix); 3859 3860 // Get the value in the widest-possible width. 3861 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3862 llvm::APInt ResultVal(MaxWidth, 0); 3863 3864 if (Literal.GetIntegerValue(ResultVal)) { 3865 // If this value didn't fit into uintmax_t, error and force to ull. 3866 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3867 << /* Unsigned */ 1; 3868 Ty = Context.UnsignedLongLongTy; 3869 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3870 "long long is not intmax_t?"); 3871 } else { 3872 // If this value fits into a ULL, try to figure out what else it fits into 3873 // according to the rules of C99 6.4.4.1p5. 3874 3875 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3876 // be an unsigned int. 3877 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3878 3879 // Check from smallest to largest, picking the smallest type we can. 3880 unsigned Width = 0; 3881 3882 // Microsoft specific integer suffixes are explicitly sized. 3883 if (Literal.MicrosoftInteger) { 3884 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3885 Width = 8; 3886 Ty = Context.CharTy; 3887 } else { 3888 Width = Literal.MicrosoftInteger; 3889 Ty = Context.getIntTypeForBitwidth(Width, 3890 /*Signed=*/!Literal.isUnsigned); 3891 } 3892 } 3893 3894 // Check C++2b size_t literals. 3895 if (Literal.isSizeT) { 3896 assert(!Literal.MicrosoftInteger && 3897 "size_t literals can't be Microsoft literals"); 3898 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3899 Context.getTargetInfo().getSizeType()); 3900 3901 // Does it fit in size_t? 3902 if (ResultVal.isIntN(SizeTSize)) { 3903 // Does it fit in ssize_t? 3904 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3905 Ty = Context.getSignedSizeType(); 3906 else if (AllowUnsigned) 3907 Ty = Context.getSizeType(); 3908 Width = SizeTSize; 3909 } 3910 } 3911 3912 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3913 !Literal.isSizeT) { 3914 // Are int/unsigned possibilities? 3915 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3916 3917 // Does it fit in a unsigned int? 3918 if (ResultVal.isIntN(IntSize)) { 3919 // Does it fit in a signed int? 3920 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3921 Ty = Context.IntTy; 3922 else if (AllowUnsigned) 3923 Ty = Context.UnsignedIntTy; 3924 Width = IntSize; 3925 } 3926 } 3927 3928 // Are long/unsigned long possibilities? 3929 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3930 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3931 3932 // Does it fit in a unsigned long? 3933 if (ResultVal.isIntN(LongSize)) { 3934 // Does it fit in a signed long? 3935 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3936 Ty = Context.LongTy; 3937 else if (AllowUnsigned) 3938 Ty = Context.UnsignedLongTy; 3939 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3940 // is compatible. 3941 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3942 const unsigned LongLongSize = 3943 Context.getTargetInfo().getLongLongWidth(); 3944 Diag(Tok.getLocation(), 3945 getLangOpts().CPlusPlus 3946 ? Literal.isLong 3947 ? diag::warn_old_implicitly_unsigned_long_cxx 3948 : /*C++98 UB*/ diag:: 3949 ext_old_implicitly_unsigned_long_cxx 3950 : diag::warn_old_implicitly_unsigned_long) 3951 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3952 : /*will be ill-formed*/ 1); 3953 Ty = Context.UnsignedLongTy; 3954 } 3955 Width = LongSize; 3956 } 3957 } 3958 3959 // Check long long if needed. 3960 if (Ty.isNull() && !Literal.isSizeT) { 3961 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3962 3963 // Does it fit in a unsigned long long? 3964 if (ResultVal.isIntN(LongLongSize)) { 3965 // Does it fit in a signed long long? 3966 // To be compatible with MSVC, hex integer literals ending with the 3967 // LL or i64 suffix are always signed in Microsoft mode. 3968 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3969 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3970 Ty = Context.LongLongTy; 3971 else if (AllowUnsigned) 3972 Ty = Context.UnsignedLongLongTy; 3973 Width = LongLongSize; 3974 } 3975 } 3976 3977 // If we still couldn't decide a type, we either have 'size_t' literal 3978 // that is out of range, or a decimal literal that does not fit in a 3979 // signed long long and has no U suffix. 3980 if (Ty.isNull()) { 3981 if (Literal.isSizeT) 3982 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 3983 << Literal.isUnsigned; 3984 else 3985 Diag(Tok.getLocation(), 3986 diag::ext_integer_literal_too_large_for_signed); 3987 Ty = Context.UnsignedLongLongTy; 3988 Width = Context.getTargetInfo().getLongLongWidth(); 3989 } 3990 3991 if (ResultVal.getBitWidth() != Width) 3992 ResultVal = ResultVal.trunc(Width); 3993 } 3994 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3995 } 3996 3997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3998 if (Literal.isImaginary) { 3999 Res = new (Context) ImaginaryLiteral(Res, 4000 Context.getComplexType(Res->getType())); 4001 4002 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4003 } 4004 return Res; 4005 } 4006 4007 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4008 assert(E && "ActOnParenExpr() missing expr"); 4009 return new (Context) ParenExpr(L, R, E); 4010 } 4011 4012 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4013 SourceLocation Loc, 4014 SourceRange ArgRange) { 4015 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4016 // scalar or vector data type argument..." 4017 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4018 // type (C99 6.2.5p18) or void. 4019 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4020 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4021 << T << ArgRange; 4022 return true; 4023 } 4024 4025 assert((T->isVoidType() || !T->isIncompleteType()) && 4026 "Scalar types should always be complete"); 4027 return false; 4028 } 4029 4030 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4031 SourceLocation Loc, 4032 SourceRange ArgRange, 4033 UnaryExprOrTypeTrait TraitKind) { 4034 // Invalid types must be hard errors for SFINAE in C++. 4035 if (S.LangOpts.CPlusPlus) 4036 return true; 4037 4038 // C99 6.5.3.4p1: 4039 if (T->isFunctionType() && 4040 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4041 TraitKind == UETT_PreferredAlignOf)) { 4042 // sizeof(function)/alignof(function) is allowed as an extension. 4043 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4044 << getTraitSpelling(TraitKind) << ArgRange; 4045 return false; 4046 } 4047 4048 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4049 // this is an error (OpenCL v1.1 s6.3.k) 4050 if (T->isVoidType()) { 4051 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4052 : diag::ext_sizeof_alignof_void_type; 4053 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4054 return false; 4055 } 4056 4057 return true; 4058 } 4059 4060 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4061 SourceLocation Loc, 4062 SourceRange ArgRange, 4063 UnaryExprOrTypeTrait TraitKind) { 4064 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4065 // runtime doesn't allow it. 4066 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4067 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4068 << T << (TraitKind == UETT_SizeOf) 4069 << ArgRange; 4070 return true; 4071 } 4072 4073 return false; 4074 } 4075 4076 /// Check whether E is a pointer from a decayed array type (the decayed 4077 /// pointer type is equal to T) and emit a warning if it is. 4078 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4079 Expr *E) { 4080 // Don't warn if the operation changed the type. 4081 if (T != E->getType()) 4082 return; 4083 4084 // Now look for array decays. 4085 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4086 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4087 return; 4088 4089 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4090 << ICE->getType() 4091 << ICE->getSubExpr()->getType(); 4092 } 4093 4094 /// Check the constraints on expression operands to unary type expression 4095 /// and type traits. 4096 /// 4097 /// Completes any types necessary and validates the constraints on the operand 4098 /// expression. The logic mostly mirrors the type-based overload, but may modify 4099 /// the expression as it completes the type for that expression through template 4100 /// instantiation, etc. 4101 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4102 UnaryExprOrTypeTrait ExprKind) { 4103 QualType ExprTy = E->getType(); 4104 assert(!ExprTy->isReferenceType()); 4105 4106 bool IsUnevaluatedOperand = 4107 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4108 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4109 if (IsUnevaluatedOperand) { 4110 ExprResult Result = CheckUnevaluatedOperand(E); 4111 if (Result.isInvalid()) 4112 return true; 4113 E = Result.get(); 4114 } 4115 4116 // The operand for sizeof and alignof is in an unevaluated expression context, 4117 // so side effects could result in unintended consequences. 4118 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4119 // used to build SFINAE gadgets. 4120 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4121 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4122 !E->isInstantiationDependent() && 4123 E->HasSideEffects(Context, false)) 4124 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4125 4126 if (ExprKind == UETT_VecStep) 4127 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4128 E->getSourceRange()); 4129 4130 // Explicitly list some types as extensions. 4131 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4132 E->getSourceRange(), ExprKind)) 4133 return false; 4134 4135 // 'alignof' applied to an expression only requires the base element type of 4136 // the expression to be complete. 'sizeof' requires the expression's type to 4137 // be complete (and will attempt to complete it if it's an array of unknown 4138 // bound). 4139 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4140 if (RequireCompleteSizedType( 4141 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4142 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4143 getTraitSpelling(ExprKind), E->getSourceRange())) 4144 return true; 4145 } else { 4146 if (RequireCompleteSizedExprType( 4147 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4148 getTraitSpelling(ExprKind), E->getSourceRange())) 4149 return true; 4150 } 4151 4152 // Completing the expression's type may have changed it. 4153 ExprTy = E->getType(); 4154 assert(!ExprTy->isReferenceType()); 4155 4156 if (ExprTy->isFunctionType()) { 4157 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4158 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4159 return true; 4160 } 4161 4162 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4163 E->getSourceRange(), ExprKind)) 4164 return true; 4165 4166 if (ExprKind == UETT_SizeOf) { 4167 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4168 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4169 QualType OType = PVD->getOriginalType(); 4170 QualType Type = PVD->getType(); 4171 if (Type->isPointerType() && OType->isArrayType()) { 4172 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4173 << Type << OType; 4174 Diag(PVD->getLocation(), diag::note_declared_at); 4175 } 4176 } 4177 } 4178 4179 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4180 // decays into a pointer and returns an unintended result. This is most 4181 // likely a typo for "sizeof(array) op x". 4182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4183 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4184 BO->getLHS()); 4185 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4186 BO->getRHS()); 4187 } 4188 } 4189 4190 return false; 4191 } 4192 4193 /// Check the constraints on operands to unary expression and type 4194 /// traits. 4195 /// 4196 /// This will complete any types necessary, and validate the various constraints 4197 /// on those operands. 4198 /// 4199 /// The UsualUnaryConversions() function is *not* called by this routine. 4200 /// C99 6.3.2.1p[2-4] all state: 4201 /// Except when it is the operand of the sizeof operator ... 4202 /// 4203 /// C++ [expr.sizeof]p4 4204 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4205 /// standard conversions are not applied to the operand of sizeof. 4206 /// 4207 /// This policy is followed for all of the unary trait expressions. 4208 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4209 SourceLocation OpLoc, 4210 SourceRange ExprRange, 4211 UnaryExprOrTypeTrait ExprKind) { 4212 if (ExprType->isDependentType()) 4213 return false; 4214 4215 // C++ [expr.sizeof]p2: 4216 // When applied to a reference or a reference type, the result 4217 // is the size of the referenced type. 4218 // C++11 [expr.alignof]p3: 4219 // When alignof is applied to a reference type, the result 4220 // shall be the alignment of the referenced type. 4221 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4222 ExprType = Ref->getPointeeType(); 4223 4224 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4225 // When alignof or _Alignof is applied to an array type, the result 4226 // is the alignment of the element type. 4227 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4228 ExprKind == UETT_OpenMPRequiredSimdAlign) 4229 ExprType = Context.getBaseElementType(ExprType); 4230 4231 if (ExprKind == UETT_VecStep) 4232 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4233 4234 // Explicitly list some types as extensions. 4235 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4236 ExprKind)) 4237 return false; 4238 4239 if (RequireCompleteSizedType( 4240 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4241 getTraitSpelling(ExprKind), ExprRange)) 4242 return true; 4243 4244 if (ExprType->isFunctionType()) { 4245 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4246 << getTraitSpelling(ExprKind) << ExprRange; 4247 return true; 4248 } 4249 4250 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4251 ExprKind)) 4252 return true; 4253 4254 return false; 4255 } 4256 4257 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4258 // Cannot know anything else if the expression is dependent. 4259 if (E->isTypeDependent()) 4260 return false; 4261 4262 if (E->getObjectKind() == OK_BitField) { 4263 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4264 << 1 << E->getSourceRange(); 4265 return true; 4266 } 4267 4268 ValueDecl *D = nullptr; 4269 Expr *Inner = E->IgnoreParens(); 4270 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4271 D = DRE->getDecl(); 4272 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4273 D = ME->getMemberDecl(); 4274 } 4275 4276 // If it's a field, require the containing struct to have a 4277 // complete definition so that we can compute the layout. 4278 // 4279 // This can happen in C++11 onwards, either by naming the member 4280 // in a way that is not transformed into a member access expression 4281 // (in an unevaluated operand, for instance), or by naming the member 4282 // in a trailing-return-type. 4283 // 4284 // For the record, since __alignof__ on expressions is a GCC 4285 // extension, GCC seems to permit this but always gives the 4286 // nonsensical answer 0. 4287 // 4288 // We don't really need the layout here --- we could instead just 4289 // directly check for all the appropriate alignment-lowing 4290 // attributes --- but that would require duplicating a lot of 4291 // logic that just isn't worth duplicating for such a marginal 4292 // use-case. 4293 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4294 // Fast path this check, since we at least know the record has a 4295 // definition if we can find a member of it. 4296 if (!FD->getParent()->isCompleteDefinition()) { 4297 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4298 << E->getSourceRange(); 4299 return true; 4300 } 4301 4302 // Otherwise, if it's a field, and the field doesn't have 4303 // reference type, then it must have a complete type (or be a 4304 // flexible array member, which we explicitly want to 4305 // white-list anyway), which makes the following checks trivial. 4306 if (!FD->getType()->isReferenceType()) 4307 return false; 4308 } 4309 4310 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4311 } 4312 4313 bool Sema::CheckVecStepExpr(Expr *E) { 4314 E = E->IgnoreParens(); 4315 4316 // Cannot know anything else if the expression is dependent. 4317 if (E->isTypeDependent()) 4318 return false; 4319 4320 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4321 } 4322 4323 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4324 CapturingScopeInfo *CSI) { 4325 assert(T->isVariablyModifiedType()); 4326 assert(CSI != nullptr); 4327 4328 // We're going to walk down into the type and look for VLA expressions. 4329 do { 4330 const Type *Ty = T.getTypePtr(); 4331 switch (Ty->getTypeClass()) { 4332 #define TYPE(Class, Base) 4333 #define ABSTRACT_TYPE(Class, Base) 4334 #define NON_CANONICAL_TYPE(Class, Base) 4335 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4336 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4337 #include "clang/AST/TypeNodes.inc" 4338 T = QualType(); 4339 break; 4340 // These types are never variably-modified. 4341 case Type::Builtin: 4342 case Type::Complex: 4343 case Type::Vector: 4344 case Type::ExtVector: 4345 case Type::ConstantMatrix: 4346 case Type::Record: 4347 case Type::Enum: 4348 case Type::Elaborated: 4349 case Type::TemplateSpecialization: 4350 case Type::ObjCObject: 4351 case Type::ObjCInterface: 4352 case Type::ObjCObjectPointer: 4353 case Type::ObjCTypeParam: 4354 case Type::Pipe: 4355 case Type::ExtInt: 4356 llvm_unreachable("type class is never variably-modified!"); 4357 case Type::Adjusted: 4358 T = cast<AdjustedType>(Ty)->getOriginalType(); 4359 break; 4360 case Type::Decayed: 4361 T = cast<DecayedType>(Ty)->getPointeeType(); 4362 break; 4363 case Type::Pointer: 4364 T = cast<PointerType>(Ty)->getPointeeType(); 4365 break; 4366 case Type::BlockPointer: 4367 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4368 break; 4369 case Type::LValueReference: 4370 case Type::RValueReference: 4371 T = cast<ReferenceType>(Ty)->getPointeeType(); 4372 break; 4373 case Type::MemberPointer: 4374 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4375 break; 4376 case Type::ConstantArray: 4377 case Type::IncompleteArray: 4378 // Losing element qualification here is fine. 4379 T = cast<ArrayType>(Ty)->getElementType(); 4380 break; 4381 case Type::VariableArray: { 4382 // Losing element qualification here is fine. 4383 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4384 4385 // Unknown size indication requires no size computation. 4386 // Otherwise, evaluate and record it. 4387 auto Size = VAT->getSizeExpr(); 4388 if (Size && !CSI->isVLATypeCaptured(VAT) && 4389 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4390 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4391 4392 T = VAT->getElementType(); 4393 break; 4394 } 4395 case Type::FunctionProto: 4396 case Type::FunctionNoProto: 4397 T = cast<FunctionType>(Ty)->getReturnType(); 4398 break; 4399 case Type::Paren: 4400 case Type::TypeOf: 4401 case Type::UnaryTransform: 4402 case Type::Attributed: 4403 case Type::SubstTemplateTypeParm: 4404 case Type::MacroQualified: 4405 // Keep walking after single level desugaring. 4406 T = T.getSingleStepDesugaredType(Context); 4407 break; 4408 case Type::Typedef: 4409 T = cast<TypedefType>(Ty)->desugar(); 4410 break; 4411 case Type::Decltype: 4412 T = cast<DecltypeType>(Ty)->desugar(); 4413 break; 4414 case Type::Auto: 4415 case Type::DeducedTemplateSpecialization: 4416 T = cast<DeducedType>(Ty)->getDeducedType(); 4417 break; 4418 case Type::TypeOfExpr: 4419 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4420 break; 4421 case Type::Atomic: 4422 T = cast<AtomicType>(Ty)->getValueType(); 4423 break; 4424 } 4425 } while (!T.isNull() && T->isVariablyModifiedType()); 4426 } 4427 4428 /// Build a sizeof or alignof expression given a type operand. 4429 ExprResult 4430 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4431 SourceLocation OpLoc, 4432 UnaryExprOrTypeTrait ExprKind, 4433 SourceRange R) { 4434 if (!TInfo) 4435 return ExprError(); 4436 4437 QualType T = TInfo->getType(); 4438 4439 if (!T->isDependentType() && 4440 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4441 return ExprError(); 4442 4443 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4444 if (auto *TT = T->getAs<TypedefType>()) { 4445 for (auto I = FunctionScopes.rbegin(), 4446 E = std::prev(FunctionScopes.rend()); 4447 I != E; ++I) { 4448 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4449 if (CSI == nullptr) 4450 break; 4451 DeclContext *DC = nullptr; 4452 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4453 DC = LSI->CallOperator; 4454 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4455 DC = CRSI->TheCapturedDecl; 4456 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4457 DC = BSI->TheDecl; 4458 if (DC) { 4459 if (DC->containsDecl(TT->getDecl())) 4460 break; 4461 captureVariablyModifiedType(Context, T, CSI); 4462 } 4463 } 4464 } 4465 } 4466 4467 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4468 return new (Context) UnaryExprOrTypeTraitExpr( 4469 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4470 } 4471 4472 /// Build a sizeof or alignof expression given an expression 4473 /// operand. 4474 ExprResult 4475 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4476 UnaryExprOrTypeTrait ExprKind) { 4477 ExprResult PE = CheckPlaceholderExpr(E); 4478 if (PE.isInvalid()) 4479 return ExprError(); 4480 4481 E = PE.get(); 4482 4483 // Verify that the operand is valid. 4484 bool isInvalid = false; 4485 if (E->isTypeDependent()) { 4486 // Delay type-checking for type-dependent expressions. 4487 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4488 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4489 } else if (ExprKind == UETT_VecStep) { 4490 isInvalid = CheckVecStepExpr(E); 4491 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4492 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4493 isInvalid = true; 4494 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4495 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4496 isInvalid = true; 4497 } else { 4498 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4499 } 4500 4501 if (isInvalid) 4502 return ExprError(); 4503 4504 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4505 PE = TransformToPotentiallyEvaluated(E); 4506 if (PE.isInvalid()) return ExprError(); 4507 E = PE.get(); 4508 } 4509 4510 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4511 return new (Context) UnaryExprOrTypeTraitExpr( 4512 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4513 } 4514 4515 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4516 /// expr and the same for @c alignof and @c __alignof 4517 /// Note that the ArgRange is invalid if isType is false. 4518 ExprResult 4519 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4520 UnaryExprOrTypeTrait ExprKind, bool IsType, 4521 void *TyOrEx, SourceRange ArgRange) { 4522 // If error parsing type, ignore. 4523 if (!TyOrEx) return ExprError(); 4524 4525 if (IsType) { 4526 TypeSourceInfo *TInfo; 4527 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4528 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4529 } 4530 4531 Expr *ArgEx = (Expr *)TyOrEx; 4532 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4533 return Result; 4534 } 4535 4536 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4537 bool IsReal) { 4538 if (V.get()->isTypeDependent()) 4539 return S.Context.DependentTy; 4540 4541 // _Real and _Imag are only l-values for normal l-values. 4542 if (V.get()->getObjectKind() != OK_Ordinary) { 4543 V = S.DefaultLvalueConversion(V.get()); 4544 if (V.isInvalid()) 4545 return QualType(); 4546 } 4547 4548 // These operators return the element type of a complex type. 4549 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4550 return CT->getElementType(); 4551 4552 // Otherwise they pass through real integer and floating point types here. 4553 if (V.get()->getType()->isArithmeticType()) 4554 return V.get()->getType(); 4555 4556 // Test for placeholders. 4557 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4558 if (PR.isInvalid()) return QualType(); 4559 if (PR.get() != V.get()) { 4560 V = PR; 4561 return CheckRealImagOperand(S, V, Loc, IsReal); 4562 } 4563 4564 // Reject anything else. 4565 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4566 << (IsReal ? "__real" : "__imag"); 4567 return QualType(); 4568 } 4569 4570 4571 4572 ExprResult 4573 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4574 tok::TokenKind Kind, Expr *Input) { 4575 UnaryOperatorKind Opc; 4576 switch (Kind) { 4577 default: llvm_unreachable("Unknown unary op!"); 4578 case tok::plusplus: Opc = UO_PostInc; break; 4579 case tok::minusminus: Opc = UO_PostDec; break; 4580 } 4581 4582 // Since this might is a postfix expression, get rid of ParenListExprs. 4583 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4584 if (Result.isInvalid()) return ExprError(); 4585 Input = Result.get(); 4586 4587 return BuildUnaryOp(S, OpLoc, Opc, Input); 4588 } 4589 4590 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4591 /// 4592 /// \return true on error 4593 static bool checkArithmeticOnObjCPointer(Sema &S, 4594 SourceLocation opLoc, 4595 Expr *op) { 4596 assert(op->getType()->isObjCObjectPointerType()); 4597 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4598 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4599 return false; 4600 4601 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4602 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4603 << op->getSourceRange(); 4604 return true; 4605 } 4606 4607 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4608 auto *BaseNoParens = Base->IgnoreParens(); 4609 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4610 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4611 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4612 } 4613 4614 ExprResult 4615 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4616 Expr *idx, SourceLocation rbLoc) { 4617 if (base && !base->getType().isNull() && 4618 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4619 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4620 SourceLocation(), /*Length*/ nullptr, 4621 /*Stride=*/nullptr, rbLoc); 4622 4623 // Since this might be a postfix expression, get rid of ParenListExprs. 4624 if (isa<ParenListExpr>(base)) { 4625 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4626 if (result.isInvalid()) return ExprError(); 4627 base = result.get(); 4628 } 4629 4630 // Check if base and idx form a MatrixSubscriptExpr. 4631 // 4632 // Helper to check for comma expressions, which are not allowed as indices for 4633 // matrix subscript expressions. 4634 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4635 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4636 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4637 << SourceRange(base->getBeginLoc(), rbLoc); 4638 return true; 4639 } 4640 return false; 4641 }; 4642 // The matrix subscript operator ([][])is considered a single operator. 4643 // Separating the index expressions by parenthesis is not allowed. 4644 if (base->getType()->isSpecificPlaceholderType( 4645 BuiltinType::IncompleteMatrixIdx) && 4646 !isa<MatrixSubscriptExpr>(base)) { 4647 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4648 << SourceRange(base->getBeginLoc(), rbLoc); 4649 return ExprError(); 4650 } 4651 // If the base is a MatrixSubscriptExpr, try to create a new 4652 // MatrixSubscriptExpr. 4653 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4654 if (matSubscriptE) { 4655 if (CheckAndReportCommaError(idx)) 4656 return ExprError(); 4657 4658 assert(matSubscriptE->isIncomplete() && 4659 "base has to be an incomplete matrix subscript"); 4660 return CreateBuiltinMatrixSubscriptExpr( 4661 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4662 } 4663 4664 // Handle any non-overload placeholder types in the base and index 4665 // expressions. We can't handle overloads here because the other 4666 // operand might be an overloadable type, in which case the overload 4667 // resolution for the operator overload should get the first crack 4668 // at the overload. 4669 bool IsMSPropertySubscript = false; 4670 if (base->getType()->isNonOverloadPlaceholderType()) { 4671 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4672 if (!IsMSPropertySubscript) { 4673 ExprResult result = CheckPlaceholderExpr(base); 4674 if (result.isInvalid()) 4675 return ExprError(); 4676 base = result.get(); 4677 } 4678 } 4679 4680 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4681 if (base->getType()->isMatrixType()) { 4682 if (CheckAndReportCommaError(idx)) 4683 return ExprError(); 4684 4685 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4686 } 4687 4688 // A comma-expression as the index is deprecated in C++2a onwards. 4689 if (getLangOpts().CPlusPlus20 && 4690 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4691 (isa<CXXOperatorCallExpr>(idx) && 4692 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4693 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4694 << SourceRange(base->getBeginLoc(), rbLoc); 4695 } 4696 4697 if (idx->getType()->isNonOverloadPlaceholderType()) { 4698 ExprResult result = CheckPlaceholderExpr(idx); 4699 if (result.isInvalid()) return ExprError(); 4700 idx = result.get(); 4701 } 4702 4703 // Build an unanalyzed expression if either operand is type-dependent. 4704 if (getLangOpts().CPlusPlus && 4705 (base->isTypeDependent() || idx->isTypeDependent())) { 4706 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4707 VK_LValue, OK_Ordinary, rbLoc); 4708 } 4709 4710 // MSDN, property (C++) 4711 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4712 // This attribute can also be used in the declaration of an empty array in a 4713 // class or structure definition. For example: 4714 // __declspec(property(get=GetX, put=PutX)) int x[]; 4715 // The above statement indicates that x[] can be used with one or more array 4716 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4717 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4718 if (IsMSPropertySubscript) { 4719 // Build MS property subscript expression if base is MS property reference 4720 // or MS property subscript. 4721 return new (Context) MSPropertySubscriptExpr( 4722 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4723 } 4724 4725 // Use C++ overloaded-operator rules if either operand has record 4726 // type. The spec says to do this if either type is *overloadable*, 4727 // but enum types can't declare subscript operators or conversion 4728 // operators, so there's nothing interesting for overload resolution 4729 // to do if there aren't any record types involved. 4730 // 4731 // ObjC pointers have their own subscripting logic that is not tied 4732 // to overload resolution and so should not take this path. 4733 if (getLangOpts().CPlusPlus && 4734 (base->getType()->isRecordType() || 4735 (!base->getType()->isObjCObjectPointerType() && 4736 idx->getType()->isRecordType()))) { 4737 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4738 } 4739 4740 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4741 4742 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4743 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4744 4745 return Res; 4746 } 4747 4748 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4749 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4750 InitializationKind Kind = 4751 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4752 InitializationSequence InitSeq(*this, Entity, Kind, E); 4753 return InitSeq.Perform(*this, Entity, Kind, E); 4754 } 4755 4756 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4757 Expr *ColumnIdx, 4758 SourceLocation RBLoc) { 4759 ExprResult BaseR = CheckPlaceholderExpr(Base); 4760 if (BaseR.isInvalid()) 4761 return BaseR; 4762 Base = BaseR.get(); 4763 4764 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4765 if (RowR.isInvalid()) 4766 return RowR; 4767 RowIdx = RowR.get(); 4768 4769 if (!ColumnIdx) 4770 return new (Context) MatrixSubscriptExpr( 4771 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4772 4773 // Build an unanalyzed expression if any of the operands is type-dependent. 4774 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4775 ColumnIdx->isTypeDependent()) 4776 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4777 Context.DependentTy, RBLoc); 4778 4779 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4780 if (ColumnR.isInvalid()) 4781 return ColumnR; 4782 ColumnIdx = ColumnR.get(); 4783 4784 // Check that IndexExpr is an integer expression. If it is a constant 4785 // expression, check that it is less than Dim (= the number of elements in the 4786 // corresponding dimension). 4787 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4788 bool IsColumnIdx) -> Expr * { 4789 if (!IndexExpr->getType()->isIntegerType() && 4790 !IndexExpr->isTypeDependent()) { 4791 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4792 << IsColumnIdx; 4793 return nullptr; 4794 } 4795 4796 if (Optional<llvm::APSInt> Idx = 4797 IndexExpr->getIntegerConstantExpr(Context)) { 4798 if ((*Idx < 0 || *Idx >= Dim)) { 4799 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4800 << IsColumnIdx << Dim; 4801 return nullptr; 4802 } 4803 } 4804 4805 ExprResult ConvExpr = 4806 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4807 assert(!ConvExpr.isInvalid() && 4808 "should be able to convert any integer type to size type"); 4809 return ConvExpr.get(); 4810 }; 4811 4812 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4813 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4814 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4815 if (!RowIdx || !ColumnIdx) 4816 return ExprError(); 4817 4818 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4819 MTy->getElementType(), RBLoc); 4820 } 4821 4822 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4823 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4824 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4825 4826 // For expressions like `&(*s).b`, the base is recorded and what should be 4827 // checked. 4828 const MemberExpr *Member = nullptr; 4829 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4830 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4831 4832 LastRecord.PossibleDerefs.erase(StrippedExpr); 4833 } 4834 4835 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4836 if (isUnevaluatedContext()) 4837 return; 4838 4839 QualType ResultTy = E->getType(); 4840 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4841 4842 // Bail if the element is an array since it is not memory access. 4843 if (isa<ArrayType>(ResultTy)) 4844 return; 4845 4846 if (ResultTy->hasAttr(attr::NoDeref)) { 4847 LastRecord.PossibleDerefs.insert(E); 4848 return; 4849 } 4850 4851 // Check if the base type is a pointer to a member access of a struct 4852 // marked with noderef. 4853 const Expr *Base = E->getBase(); 4854 QualType BaseTy = Base->getType(); 4855 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4856 // Not a pointer access 4857 return; 4858 4859 const MemberExpr *Member = nullptr; 4860 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4861 Member->isArrow()) 4862 Base = Member->getBase(); 4863 4864 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4865 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4866 LastRecord.PossibleDerefs.insert(E); 4867 } 4868 } 4869 4870 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4871 Expr *LowerBound, 4872 SourceLocation ColonLocFirst, 4873 SourceLocation ColonLocSecond, 4874 Expr *Length, Expr *Stride, 4875 SourceLocation RBLoc) { 4876 if (Base->getType()->isPlaceholderType() && 4877 !Base->getType()->isSpecificPlaceholderType( 4878 BuiltinType::OMPArraySection)) { 4879 ExprResult Result = CheckPlaceholderExpr(Base); 4880 if (Result.isInvalid()) 4881 return ExprError(); 4882 Base = Result.get(); 4883 } 4884 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4885 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4886 if (Result.isInvalid()) 4887 return ExprError(); 4888 Result = DefaultLvalueConversion(Result.get()); 4889 if (Result.isInvalid()) 4890 return ExprError(); 4891 LowerBound = Result.get(); 4892 } 4893 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4894 ExprResult Result = CheckPlaceholderExpr(Length); 4895 if (Result.isInvalid()) 4896 return ExprError(); 4897 Result = DefaultLvalueConversion(Result.get()); 4898 if (Result.isInvalid()) 4899 return ExprError(); 4900 Length = Result.get(); 4901 } 4902 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4903 ExprResult Result = CheckPlaceholderExpr(Stride); 4904 if (Result.isInvalid()) 4905 return ExprError(); 4906 Result = DefaultLvalueConversion(Result.get()); 4907 if (Result.isInvalid()) 4908 return ExprError(); 4909 Stride = Result.get(); 4910 } 4911 4912 // Build an unanalyzed expression if either operand is type-dependent. 4913 if (Base->isTypeDependent() || 4914 (LowerBound && 4915 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4916 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4917 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4918 return new (Context) OMPArraySectionExpr( 4919 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4920 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4921 } 4922 4923 // Perform default conversions. 4924 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4925 QualType ResultTy; 4926 if (OriginalTy->isAnyPointerType()) { 4927 ResultTy = OriginalTy->getPointeeType(); 4928 } else if (OriginalTy->isArrayType()) { 4929 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4930 } else { 4931 return ExprError( 4932 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4933 << Base->getSourceRange()); 4934 } 4935 // C99 6.5.2.1p1 4936 if (LowerBound) { 4937 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4938 LowerBound); 4939 if (Res.isInvalid()) 4940 return ExprError(Diag(LowerBound->getExprLoc(), 4941 diag::err_omp_typecheck_section_not_integer) 4942 << 0 << LowerBound->getSourceRange()); 4943 LowerBound = Res.get(); 4944 4945 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4946 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4947 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4948 << 0 << LowerBound->getSourceRange(); 4949 } 4950 if (Length) { 4951 auto Res = 4952 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4953 if (Res.isInvalid()) 4954 return ExprError(Diag(Length->getExprLoc(), 4955 diag::err_omp_typecheck_section_not_integer) 4956 << 1 << Length->getSourceRange()); 4957 Length = Res.get(); 4958 4959 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4960 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4961 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4962 << 1 << Length->getSourceRange(); 4963 } 4964 if (Stride) { 4965 ExprResult Res = 4966 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4967 if (Res.isInvalid()) 4968 return ExprError(Diag(Stride->getExprLoc(), 4969 diag::err_omp_typecheck_section_not_integer) 4970 << 1 << Stride->getSourceRange()); 4971 Stride = Res.get(); 4972 4973 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4974 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4975 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4976 << 1 << Stride->getSourceRange(); 4977 } 4978 4979 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4980 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4981 // type. Note that functions are not objects, and that (in C99 parlance) 4982 // incomplete types are not object types. 4983 if (ResultTy->isFunctionType()) { 4984 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4985 << ResultTy << Base->getSourceRange(); 4986 return ExprError(); 4987 } 4988 4989 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4990 diag::err_omp_section_incomplete_type, Base)) 4991 return ExprError(); 4992 4993 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4994 Expr::EvalResult Result; 4995 if (LowerBound->EvaluateAsInt(Result, Context)) { 4996 // OpenMP 5.0, [2.1.5 Array Sections] 4997 // The array section must be a subset of the original array. 4998 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4999 if (LowerBoundValue.isNegative()) { 5000 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5001 << LowerBound->getSourceRange(); 5002 return ExprError(); 5003 } 5004 } 5005 } 5006 5007 if (Length) { 5008 Expr::EvalResult Result; 5009 if (Length->EvaluateAsInt(Result, Context)) { 5010 // OpenMP 5.0, [2.1.5 Array Sections] 5011 // The length must evaluate to non-negative integers. 5012 llvm::APSInt LengthValue = Result.Val.getInt(); 5013 if (LengthValue.isNegative()) { 5014 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5015 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5016 << Length->getSourceRange(); 5017 return ExprError(); 5018 } 5019 } 5020 } else if (ColonLocFirst.isValid() && 5021 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5022 !OriginalTy->isVariableArrayType()))) { 5023 // OpenMP 5.0, [2.1.5 Array Sections] 5024 // When the size of the array dimension is not known, the length must be 5025 // specified explicitly. 5026 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5027 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5028 return ExprError(); 5029 } 5030 5031 if (Stride) { 5032 Expr::EvalResult Result; 5033 if (Stride->EvaluateAsInt(Result, Context)) { 5034 // OpenMP 5.0, [2.1.5 Array Sections] 5035 // The stride must evaluate to a positive integer. 5036 llvm::APSInt StrideValue = Result.Val.getInt(); 5037 if (!StrideValue.isStrictlyPositive()) { 5038 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5039 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5040 << Stride->getSourceRange(); 5041 return ExprError(); 5042 } 5043 } 5044 } 5045 5046 if (!Base->getType()->isSpecificPlaceholderType( 5047 BuiltinType::OMPArraySection)) { 5048 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5049 if (Result.isInvalid()) 5050 return ExprError(); 5051 Base = Result.get(); 5052 } 5053 return new (Context) OMPArraySectionExpr( 5054 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5055 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5056 } 5057 5058 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5059 SourceLocation RParenLoc, 5060 ArrayRef<Expr *> Dims, 5061 ArrayRef<SourceRange> Brackets) { 5062 if (Base->getType()->isPlaceholderType()) { 5063 ExprResult Result = CheckPlaceholderExpr(Base); 5064 if (Result.isInvalid()) 5065 return ExprError(); 5066 Result = DefaultLvalueConversion(Result.get()); 5067 if (Result.isInvalid()) 5068 return ExprError(); 5069 Base = Result.get(); 5070 } 5071 QualType BaseTy = Base->getType(); 5072 // Delay analysis of the types/expressions if instantiation/specialization is 5073 // required. 5074 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5075 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5076 LParenLoc, RParenLoc, Dims, Brackets); 5077 if (!BaseTy->isPointerType() || 5078 (!Base->isTypeDependent() && 5079 BaseTy->getPointeeType()->isIncompleteType())) 5080 return ExprError(Diag(Base->getExprLoc(), 5081 diag::err_omp_non_pointer_type_array_shaping_base) 5082 << Base->getSourceRange()); 5083 5084 SmallVector<Expr *, 4> NewDims; 5085 bool ErrorFound = false; 5086 for (Expr *Dim : Dims) { 5087 if (Dim->getType()->isPlaceholderType()) { 5088 ExprResult Result = CheckPlaceholderExpr(Dim); 5089 if (Result.isInvalid()) { 5090 ErrorFound = true; 5091 continue; 5092 } 5093 Result = DefaultLvalueConversion(Result.get()); 5094 if (Result.isInvalid()) { 5095 ErrorFound = true; 5096 continue; 5097 } 5098 Dim = Result.get(); 5099 } 5100 if (!Dim->isTypeDependent()) { 5101 ExprResult Result = 5102 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5103 if (Result.isInvalid()) { 5104 ErrorFound = true; 5105 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5106 << Dim->getSourceRange(); 5107 continue; 5108 } 5109 Dim = Result.get(); 5110 Expr::EvalResult EvResult; 5111 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5112 // OpenMP 5.0, [2.1.4 Array Shaping] 5113 // Each si is an integral type expression that must evaluate to a 5114 // positive integer. 5115 llvm::APSInt Value = EvResult.Val.getInt(); 5116 if (!Value.isStrictlyPositive()) { 5117 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5118 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5119 << Dim->getSourceRange(); 5120 ErrorFound = true; 5121 continue; 5122 } 5123 } 5124 } 5125 NewDims.push_back(Dim); 5126 } 5127 if (ErrorFound) 5128 return ExprError(); 5129 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5130 LParenLoc, RParenLoc, NewDims, Brackets); 5131 } 5132 5133 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5134 SourceLocation LLoc, SourceLocation RLoc, 5135 ArrayRef<OMPIteratorData> Data) { 5136 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5137 bool IsCorrect = true; 5138 for (const OMPIteratorData &D : Data) { 5139 TypeSourceInfo *TInfo = nullptr; 5140 SourceLocation StartLoc; 5141 QualType DeclTy; 5142 if (!D.Type.getAsOpaquePtr()) { 5143 // OpenMP 5.0, 2.1.6 Iterators 5144 // In an iterator-specifier, if the iterator-type is not specified then 5145 // the type of that iterator is of int type. 5146 DeclTy = Context.IntTy; 5147 StartLoc = D.DeclIdentLoc; 5148 } else { 5149 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5150 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5151 } 5152 5153 bool IsDeclTyDependent = DeclTy->isDependentType() || 5154 DeclTy->containsUnexpandedParameterPack() || 5155 DeclTy->isInstantiationDependentType(); 5156 if (!IsDeclTyDependent) { 5157 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5158 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5159 // The iterator-type must be an integral or pointer type. 5160 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5161 << DeclTy; 5162 IsCorrect = false; 5163 continue; 5164 } 5165 if (DeclTy.isConstant(Context)) { 5166 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5167 // The iterator-type must not be const qualified. 5168 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5169 << DeclTy; 5170 IsCorrect = false; 5171 continue; 5172 } 5173 } 5174 5175 // Iterator declaration. 5176 assert(D.DeclIdent && "Identifier expected."); 5177 // Always try to create iterator declarator to avoid extra error messages 5178 // about unknown declarations use. 5179 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5180 D.DeclIdent, DeclTy, TInfo, SC_None); 5181 VD->setImplicit(); 5182 if (S) { 5183 // Check for conflicting previous declaration. 5184 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5185 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5186 ForVisibleRedeclaration); 5187 Previous.suppressDiagnostics(); 5188 LookupName(Previous, S); 5189 5190 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5191 /*AllowInlineNamespace=*/false); 5192 if (!Previous.empty()) { 5193 NamedDecl *Old = Previous.getRepresentativeDecl(); 5194 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5195 Diag(Old->getLocation(), diag::note_previous_definition); 5196 } else { 5197 PushOnScopeChains(VD, S); 5198 } 5199 } else { 5200 CurContext->addDecl(VD); 5201 } 5202 Expr *Begin = D.Range.Begin; 5203 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5204 ExprResult BeginRes = 5205 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5206 Begin = BeginRes.get(); 5207 } 5208 Expr *End = D.Range.End; 5209 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5210 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5211 End = EndRes.get(); 5212 } 5213 Expr *Step = D.Range.Step; 5214 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5215 if (!Step->getType()->isIntegralType(Context)) { 5216 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5217 << Step << Step->getSourceRange(); 5218 IsCorrect = false; 5219 continue; 5220 } 5221 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5222 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5223 // If the step expression of a range-specification equals zero, the 5224 // behavior is unspecified. 5225 if (Result && Result->isNullValue()) { 5226 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5227 << Step << Step->getSourceRange(); 5228 IsCorrect = false; 5229 continue; 5230 } 5231 } 5232 if (!Begin || !End || !IsCorrect) { 5233 IsCorrect = false; 5234 continue; 5235 } 5236 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5237 IDElem.IteratorDecl = VD; 5238 IDElem.AssignmentLoc = D.AssignLoc; 5239 IDElem.Range.Begin = Begin; 5240 IDElem.Range.End = End; 5241 IDElem.Range.Step = Step; 5242 IDElem.ColonLoc = D.ColonLoc; 5243 IDElem.SecondColonLoc = D.SecColonLoc; 5244 } 5245 if (!IsCorrect) { 5246 // Invalidate all created iterator declarations if error is found. 5247 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5248 if (Decl *ID = D.IteratorDecl) 5249 ID->setInvalidDecl(); 5250 } 5251 return ExprError(); 5252 } 5253 SmallVector<OMPIteratorHelperData, 4> Helpers; 5254 if (!CurContext->isDependentContext()) { 5255 // Build number of ityeration for each iteration range. 5256 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5257 // ((Begini-Stepi-1-Endi) / -Stepi); 5258 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5259 // (Endi - Begini) 5260 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5261 D.Range.Begin); 5262 if(!Res.isUsable()) { 5263 IsCorrect = false; 5264 continue; 5265 } 5266 ExprResult St, St1; 5267 if (D.Range.Step) { 5268 St = D.Range.Step; 5269 // (Endi - Begini) + Stepi 5270 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5271 if (!Res.isUsable()) { 5272 IsCorrect = false; 5273 continue; 5274 } 5275 // (Endi - Begini) + Stepi - 1 5276 Res = 5277 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5278 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5279 if (!Res.isUsable()) { 5280 IsCorrect = false; 5281 continue; 5282 } 5283 // ((Endi - Begini) + Stepi - 1) / Stepi 5284 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5285 if (!Res.isUsable()) { 5286 IsCorrect = false; 5287 continue; 5288 } 5289 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5290 // (Begini - Endi) 5291 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5292 D.Range.Begin, D.Range.End); 5293 if (!Res1.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 // (Begini - Endi) - Stepi 5298 Res1 = 5299 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5300 if (!Res1.isUsable()) { 5301 IsCorrect = false; 5302 continue; 5303 } 5304 // (Begini - Endi) - Stepi - 1 5305 Res1 = 5306 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5307 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5308 if (!Res1.isUsable()) { 5309 IsCorrect = false; 5310 continue; 5311 } 5312 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5313 Res1 = 5314 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5315 if (!Res1.isUsable()) { 5316 IsCorrect = false; 5317 continue; 5318 } 5319 // Stepi > 0. 5320 ExprResult CmpRes = 5321 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5322 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5323 if (!CmpRes.isUsable()) { 5324 IsCorrect = false; 5325 continue; 5326 } 5327 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5328 Res.get(), Res1.get()); 5329 if (!Res.isUsable()) { 5330 IsCorrect = false; 5331 continue; 5332 } 5333 } 5334 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5335 if (!Res.isUsable()) { 5336 IsCorrect = false; 5337 continue; 5338 } 5339 5340 // Build counter update. 5341 // Build counter. 5342 auto *CounterVD = 5343 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5344 D.IteratorDecl->getBeginLoc(), nullptr, 5345 Res.get()->getType(), nullptr, SC_None); 5346 CounterVD->setImplicit(); 5347 ExprResult RefRes = 5348 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5349 D.IteratorDecl->getBeginLoc()); 5350 // Build counter update. 5351 // I = Begini + counter * Stepi; 5352 ExprResult UpdateRes; 5353 if (D.Range.Step) { 5354 UpdateRes = CreateBuiltinBinOp( 5355 D.AssignmentLoc, BO_Mul, 5356 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5357 } else { 5358 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5359 } 5360 if (!UpdateRes.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5365 UpdateRes.get()); 5366 if (!UpdateRes.isUsable()) { 5367 IsCorrect = false; 5368 continue; 5369 } 5370 ExprResult VDRes = 5371 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5372 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5373 D.IteratorDecl->getBeginLoc()); 5374 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5375 UpdateRes.get()); 5376 if (!UpdateRes.isUsable()) { 5377 IsCorrect = false; 5378 continue; 5379 } 5380 UpdateRes = 5381 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5382 if (!UpdateRes.isUsable()) { 5383 IsCorrect = false; 5384 continue; 5385 } 5386 ExprResult CounterUpdateRes = 5387 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5388 if (!CounterUpdateRes.isUsable()) { 5389 IsCorrect = false; 5390 continue; 5391 } 5392 CounterUpdateRes = 5393 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5394 if (!CounterUpdateRes.isUsable()) { 5395 IsCorrect = false; 5396 continue; 5397 } 5398 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5399 HD.CounterVD = CounterVD; 5400 HD.Upper = Res.get(); 5401 HD.Update = UpdateRes.get(); 5402 HD.CounterUpdate = CounterUpdateRes.get(); 5403 } 5404 } else { 5405 Helpers.assign(ID.size(), {}); 5406 } 5407 if (!IsCorrect) { 5408 // Invalidate all created iterator declarations if error is found. 5409 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5410 if (Decl *ID = D.IteratorDecl) 5411 ID->setInvalidDecl(); 5412 } 5413 return ExprError(); 5414 } 5415 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5416 LLoc, RLoc, ID, Helpers); 5417 } 5418 5419 ExprResult 5420 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5421 Expr *Idx, SourceLocation RLoc) { 5422 Expr *LHSExp = Base; 5423 Expr *RHSExp = Idx; 5424 5425 ExprValueKind VK = VK_LValue; 5426 ExprObjectKind OK = OK_Ordinary; 5427 5428 // Per C++ core issue 1213, the result is an xvalue if either operand is 5429 // a non-lvalue array, and an lvalue otherwise. 5430 if (getLangOpts().CPlusPlus11) { 5431 for (auto *Op : {LHSExp, RHSExp}) { 5432 Op = Op->IgnoreImplicit(); 5433 if (Op->getType()->isArrayType() && !Op->isLValue()) 5434 VK = VK_XValue; 5435 } 5436 } 5437 5438 // Perform default conversions. 5439 if (!LHSExp->getType()->getAs<VectorType>()) { 5440 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5441 if (Result.isInvalid()) 5442 return ExprError(); 5443 LHSExp = Result.get(); 5444 } 5445 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5446 if (Result.isInvalid()) 5447 return ExprError(); 5448 RHSExp = Result.get(); 5449 5450 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5451 5452 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5453 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5454 // in the subscript position. As a result, we need to derive the array base 5455 // and index from the expression types. 5456 Expr *BaseExpr, *IndexExpr; 5457 QualType ResultType; 5458 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5459 BaseExpr = LHSExp; 5460 IndexExpr = RHSExp; 5461 ResultType = Context.DependentTy; 5462 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5463 BaseExpr = LHSExp; 5464 IndexExpr = RHSExp; 5465 ResultType = PTy->getPointeeType(); 5466 } else if (const ObjCObjectPointerType *PTy = 5467 LHSTy->getAs<ObjCObjectPointerType>()) { 5468 BaseExpr = LHSExp; 5469 IndexExpr = RHSExp; 5470 5471 // Use custom logic if this should be the pseudo-object subscript 5472 // expression. 5473 if (!LangOpts.isSubscriptPointerArithmetic()) 5474 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5475 nullptr); 5476 5477 ResultType = PTy->getPointeeType(); 5478 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5479 // Handle the uncommon case of "123[Ptr]". 5480 BaseExpr = RHSExp; 5481 IndexExpr = LHSExp; 5482 ResultType = PTy->getPointeeType(); 5483 } else if (const ObjCObjectPointerType *PTy = 5484 RHSTy->getAs<ObjCObjectPointerType>()) { 5485 // Handle the uncommon case of "123[Ptr]". 5486 BaseExpr = RHSExp; 5487 IndexExpr = LHSExp; 5488 ResultType = PTy->getPointeeType(); 5489 if (!LangOpts.isSubscriptPointerArithmetic()) { 5490 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5491 << ResultType << BaseExpr->getSourceRange(); 5492 return ExprError(); 5493 } 5494 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5495 BaseExpr = LHSExp; // vectors: V[123] 5496 IndexExpr = RHSExp; 5497 // We apply C++ DR1213 to vector subscripting too. 5498 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5499 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5500 if (Materialized.isInvalid()) 5501 return ExprError(); 5502 LHSExp = Materialized.get(); 5503 } 5504 VK = LHSExp->getValueKind(); 5505 if (VK != VK_RValue) 5506 OK = OK_VectorComponent; 5507 5508 ResultType = VTy->getElementType(); 5509 QualType BaseType = BaseExpr->getType(); 5510 Qualifiers BaseQuals = BaseType.getQualifiers(); 5511 Qualifiers MemberQuals = ResultType.getQualifiers(); 5512 Qualifiers Combined = BaseQuals + MemberQuals; 5513 if (Combined != MemberQuals) 5514 ResultType = Context.getQualifiedType(ResultType, Combined); 5515 } else if (LHSTy->isArrayType()) { 5516 // If we see an array that wasn't promoted by 5517 // DefaultFunctionArrayLvalueConversion, it must be an array that 5518 // wasn't promoted because of the C90 rule that doesn't 5519 // allow promoting non-lvalue arrays. Warn, then 5520 // force the promotion here. 5521 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5522 << LHSExp->getSourceRange(); 5523 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5524 CK_ArrayToPointerDecay).get(); 5525 LHSTy = LHSExp->getType(); 5526 5527 BaseExpr = LHSExp; 5528 IndexExpr = RHSExp; 5529 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5530 } else if (RHSTy->isArrayType()) { 5531 // Same as previous, except for 123[f().a] case 5532 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5533 << RHSExp->getSourceRange(); 5534 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5535 CK_ArrayToPointerDecay).get(); 5536 RHSTy = RHSExp->getType(); 5537 5538 BaseExpr = RHSExp; 5539 IndexExpr = LHSExp; 5540 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5541 } else { 5542 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5543 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5544 } 5545 // C99 6.5.2.1p1 5546 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5547 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5548 << IndexExpr->getSourceRange()); 5549 5550 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5551 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5552 && !IndexExpr->isTypeDependent()) 5553 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5554 5555 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5556 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5557 // type. Note that Functions are not objects, and that (in C99 parlance) 5558 // incomplete types are not object types. 5559 if (ResultType->isFunctionType()) { 5560 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5561 << ResultType << BaseExpr->getSourceRange(); 5562 return ExprError(); 5563 } 5564 5565 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5566 // GNU extension: subscripting on pointer to void 5567 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5568 << BaseExpr->getSourceRange(); 5569 5570 // C forbids expressions of unqualified void type from being l-values. 5571 // See IsCForbiddenLValueType. 5572 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5573 } else if (!ResultType->isDependentType() && 5574 RequireCompleteSizedType( 5575 LLoc, ResultType, 5576 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5577 return ExprError(); 5578 5579 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5580 !ResultType.isCForbiddenLValueType()); 5581 5582 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5583 FunctionScopes.size() > 1) { 5584 if (auto *TT = 5585 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5586 for (auto I = FunctionScopes.rbegin(), 5587 E = std::prev(FunctionScopes.rend()); 5588 I != E; ++I) { 5589 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5590 if (CSI == nullptr) 5591 break; 5592 DeclContext *DC = nullptr; 5593 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5594 DC = LSI->CallOperator; 5595 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5596 DC = CRSI->TheCapturedDecl; 5597 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5598 DC = BSI->TheDecl; 5599 if (DC) { 5600 if (DC->containsDecl(TT->getDecl())) 5601 break; 5602 captureVariablyModifiedType( 5603 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5604 } 5605 } 5606 } 5607 } 5608 5609 return new (Context) 5610 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5611 } 5612 5613 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5614 ParmVarDecl *Param) { 5615 if (Param->hasUnparsedDefaultArg()) { 5616 // If we've already cleared out the location for the default argument, 5617 // that means we're parsing it right now. 5618 if (!UnparsedDefaultArgLocs.count(Param)) { 5619 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5620 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5621 Param->setInvalidDecl(); 5622 return true; 5623 } 5624 5625 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5626 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5627 Diag(UnparsedDefaultArgLocs[Param], 5628 diag::note_default_argument_declared_here); 5629 return true; 5630 } 5631 5632 if (Param->hasUninstantiatedDefaultArg() && 5633 InstantiateDefaultArgument(CallLoc, FD, Param)) 5634 return true; 5635 5636 assert(Param->hasInit() && "default argument but no initializer?"); 5637 5638 // If the default expression creates temporaries, we need to 5639 // push them to the current stack of expression temporaries so they'll 5640 // be properly destroyed. 5641 // FIXME: We should really be rebuilding the default argument with new 5642 // bound temporaries; see the comment in PR5810. 5643 // We don't need to do that with block decls, though, because 5644 // blocks in default argument expression can never capture anything. 5645 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5646 // Set the "needs cleanups" bit regardless of whether there are 5647 // any explicit objects. 5648 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5649 5650 // Append all the objects to the cleanup list. Right now, this 5651 // should always be a no-op, because blocks in default argument 5652 // expressions should never be able to capture anything. 5653 assert(!Init->getNumObjects() && 5654 "default argument expression has capturing blocks?"); 5655 } 5656 5657 // We already type-checked the argument, so we know it works. 5658 // Just mark all of the declarations in this potentially-evaluated expression 5659 // as being "referenced". 5660 EnterExpressionEvaluationContext EvalContext( 5661 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5662 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5663 /*SkipLocalVariables=*/true); 5664 return false; 5665 } 5666 5667 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5668 FunctionDecl *FD, ParmVarDecl *Param) { 5669 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5670 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5671 return ExprError(); 5672 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5673 } 5674 5675 Sema::VariadicCallType 5676 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5677 Expr *Fn) { 5678 if (Proto && Proto->isVariadic()) { 5679 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5680 return VariadicConstructor; 5681 else if (Fn && Fn->getType()->isBlockPointerType()) 5682 return VariadicBlock; 5683 else if (FDecl) { 5684 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5685 if (Method->isInstance()) 5686 return VariadicMethod; 5687 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5688 return VariadicMethod; 5689 return VariadicFunction; 5690 } 5691 return VariadicDoesNotApply; 5692 } 5693 5694 namespace { 5695 class FunctionCallCCC final : public FunctionCallFilterCCC { 5696 public: 5697 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5698 unsigned NumArgs, MemberExpr *ME) 5699 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5700 FunctionName(FuncName) {} 5701 5702 bool ValidateCandidate(const TypoCorrection &candidate) override { 5703 if (!candidate.getCorrectionSpecifier() || 5704 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5705 return false; 5706 } 5707 5708 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5709 } 5710 5711 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5712 return std::make_unique<FunctionCallCCC>(*this); 5713 } 5714 5715 private: 5716 const IdentifierInfo *const FunctionName; 5717 }; 5718 } 5719 5720 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5721 FunctionDecl *FDecl, 5722 ArrayRef<Expr *> Args) { 5723 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5724 DeclarationName FuncName = FDecl->getDeclName(); 5725 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5726 5727 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5728 if (TypoCorrection Corrected = S.CorrectTypo( 5729 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5730 S.getScopeForContext(S.CurContext), nullptr, CCC, 5731 Sema::CTK_ErrorRecovery)) { 5732 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5733 if (Corrected.isOverloaded()) { 5734 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5735 OverloadCandidateSet::iterator Best; 5736 for (NamedDecl *CD : Corrected) { 5737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5738 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5739 OCS); 5740 } 5741 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5742 case OR_Success: 5743 ND = Best->FoundDecl; 5744 Corrected.setCorrectionDecl(ND); 5745 break; 5746 default: 5747 break; 5748 } 5749 } 5750 ND = ND->getUnderlyingDecl(); 5751 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5752 return Corrected; 5753 } 5754 } 5755 return TypoCorrection(); 5756 } 5757 5758 /// ConvertArgumentsForCall - Converts the arguments specified in 5759 /// Args/NumArgs to the parameter types of the function FDecl with 5760 /// function prototype Proto. Call is the call expression itself, and 5761 /// Fn is the function expression. For a C++ member function, this 5762 /// routine does not attempt to convert the object argument. Returns 5763 /// true if the call is ill-formed. 5764 bool 5765 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5766 FunctionDecl *FDecl, 5767 const FunctionProtoType *Proto, 5768 ArrayRef<Expr *> Args, 5769 SourceLocation RParenLoc, 5770 bool IsExecConfig) { 5771 // Bail out early if calling a builtin with custom typechecking. 5772 if (FDecl) 5773 if (unsigned ID = FDecl->getBuiltinID()) 5774 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5775 return false; 5776 5777 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5778 // assignment, to the types of the corresponding parameter, ... 5779 unsigned NumParams = Proto->getNumParams(); 5780 bool Invalid = false; 5781 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5782 unsigned FnKind = Fn->getType()->isBlockPointerType() 5783 ? 1 /* block */ 5784 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5785 : 0 /* function */); 5786 5787 // If too few arguments are available (and we don't have default 5788 // arguments for the remaining parameters), don't make the call. 5789 if (Args.size() < NumParams) { 5790 if (Args.size() < MinArgs) { 5791 TypoCorrection TC; 5792 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5793 unsigned diag_id = 5794 MinArgs == NumParams && !Proto->isVariadic() 5795 ? diag::err_typecheck_call_too_few_args_suggest 5796 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5797 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5798 << static_cast<unsigned>(Args.size()) 5799 << TC.getCorrectionRange()); 5800 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5801 Diag(RParenLoc, 5802 MinArgs == NumParams && !Proto->isVariadic() 5803 ? diag::err_typecheck_call_too_few_args_one 5804 : diag::err_typecheck_call_too_few_args_at_least_one) 5805 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5806 else 5807 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5808 ? diag::err_typecheck_call_too_few_args 5809 : diag::err_typecheck_call_too_few_args_at_least) 5810 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5811 << Fn->getSourceRange(); 5812 5813 // Emit the location of the prototype. 5814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5815 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5816 5817 return true; 5818 } 5819 // We reserve space for the default arguments when we create 5820 // the call expression, before calling ConvertArgumentsForCall. 5821 assert((Call->getNumArgs() == NumParams) && 5822 "We should have reserved space for the default arguments before!"); 5823 } 5824 5825 // If too many are passed and not variadic, error on the extras and drop 5826 // them. 5827 if (Args.size() > NumParams) { 5828 if (!Proto->isVariadic()) { 5829 TypoCorrection TC; 5830 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5831 unsigned diag_id = 5832 MinArgs == NumParams && !Proto->isVariadic() 5833 ? diag::err_typecheck_call_too_many_args_suggest 5834 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5835 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5836 << static_cast<unsigned>(Args.size()) 5837 << TC.getCorrectionRange()); 5838 } else if (NumParams == 1 && FDecl && 5839 FDecl->getParamDecl(0)->getDeclName()) 5840 Diag(Args[NumParams]->getBeginLoc(), 5841 MinArgs == NumParams 5842 ? diag::err_typecheck_call_too_many_args_one 5843 : diag::err_typecheck_call_too_many_args_at_most_one) 5844 << FnKind << FDecl->getParamDecl(0) 5845 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5846 << SourceRange(Args[NumParams]->getBeginLoc(), 5847 Args.back()->getEndLoc()); 5848 else 5849 Diag(Args[NumParams]->getBeginLoc(), 5850 MinArgs == NumParams 5851 ? diag::err_typecheck_call_too_many_args 5852 : diag::err_typecheck_call_too_many_args_at_most) 5853 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5854 << Fn->getSourceRange() 5855 << SourceRange(Args[NumParams]->getBeginLoc(), 5856 Args.back()->getEndLoc()); 5857 5858 // Emit the location of the prototype. 5859 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5860 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5861 5862 // This deletes the extra arguments. 5863 Call->shrinkNumArgs(NumParams); 5864 return true; 5865 } 5866 } 5867 SmallVector<Expr *, 8> AllArgs; 5868 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5869 5870 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5871 AllArgs, CallType); 5872 if (Invalid) 5873 return true; 5874 unsigned TotalNumArgs = AllArgs.size(); 5875 for (unsigned i = 0; i < TotalNumArgs; ++i) 5876 Call->setArg(i, AllArgs[i]); 5877 5878 return false; 5879 } 5880 5881 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5882 const FunctionProtoType *Proto, 5883 unsigned FirstParam, ArrayRef<Expr *> Args, 5884 SmallVectorImpl<Expr *> &AllArgs, 5885 VariadicCallType CallType, bool AllowExplicit, 5886 bool IsListInitialization) { 5887 unsigned NumParams = Proto->getNumParams(); 5888 bool Invalid = false; 5889 size_t ArgIx = 0; 5890 // Continue to check argument types (even if we have too few/many args). 5891 for (unsigned i = FirstParam; i < NumParams; i++) { 5892 QualType ProtoArgType = Proto->getParamType(i); 5893 5894 Expr *Arg; 5895 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5896 if (ArgIx < Args.size()) { 5897 Arg = Args[ArgIx++]; 5898 5899 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5900 diag::err_call_incomplete_argument, Arg)) 5901 return true; 5902 5903 // Strip the unbridged-cast placeholder expression off, if applicable. 5904 bool CFAudited = false; 5905 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5906 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5907 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5908 Arg = stripARCUnbridgedCast(Arg); 5909 else if (getLangOpts().ObjCAutoRefCount && 5910 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5911 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5912 CFAudited = true; 5913 5914 if (Proto->getExtParameterInfo(i).isNoEscape() && 5915 ProtoArgType->isBlockPointerType()) 5916 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5917 BE->getBlockDecl()->setDoesNotEscape(); 5918 5919 InitializedEntity Entity = 5920 Param ? InitializedEntity::InitializeParameter(Context, Param, 5921 ProtoArgType) 5922 : InitializedEntity::InitializeParameter( 5923 Context, ProtoArgType, Proto->isParamConsumed(i)); 5924 5925 // Remember that parameter belongs to a CF audited API. 5926 if (CFAudited) 5927 Entity.setParameterCFAudited(); 5928 5929 ExprResult ArgE = PerformCopyInitialization( 5930 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5931 if (ArgE.isInvalid()) 5932 return true; 5933 5934 Arg = ArgE.getAs<Expr>(); 5935 } else { 5936 assert(Param && "can't use default arguments without a known callee"); 5937 5938 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5939 if (ArgExpr.isInvalid()) 5940 return true; 5941 5942 Arg = ArgExpr.getAs<Expr>(); 5943 } 5944 5945 // Check for array bounds violations for each argument to the call. This 5946 // check only triggers warnings when the argument isn't a more complex Expr 5947 // with its own checking, such as a BinaryOperator. 5948 CheckArrayAccess(Arg); 5949 5950 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5951 CheckStaticArrayArgument(CallLoc, Param, Arg); 5952 5953 AllArgs.push_back(Arg); 5954 } 5955 5956 // If this is a variadic call, handle args passed through "...". 5957 if (CallType != VariadicDoesNotApply) { 5958 // Assume that extern "C" functions with variadic arguments that 5959 // return __unknown_anytype aren't *really* variadic. 5960 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5961 FDecl->isExternC()) { 5962 for (Expr *A : Args.slice(ArgIx)) { 5963 QualType paramType; // ignored 5964 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5965 Invalid |= arg.isInvalid(); 5966 AllArgs.push_back(arg.get()); 5967 } 5968 5969 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5970 } else { 5971 for (Expr *A : Args.slice(ArgIx)) { 5972 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5973 Invalid |= Arg.isInvalid(); 5974 AllArgs.push_back(Arg.get()); 5975 } 5976 } 5977 5978 // Check for array bounds violations. 5979 for (Expr *A : Args.slice(ArgIx)) 5980 CheckArrayAccess(A); 5981 } 5982 return Invalid; 5983 } 5984 5985 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5986 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5987 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5988 TL = DTL.getOriginalLoc(); 5989 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5990 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5991 << ATL.getLocalSourceRange(); 5992 } 5993 5994 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5995 /// array parameter, check that it is non-null, and that if it is formed by 5996 /// array-to-pointer decay, the underlying array is sufficiently large. 5997 /// 5998 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5999 /// array type derivation, then for each call to the function, the value of the 6000 /// corresponding actual argument shall provide access to the first element of 6001 /// an array with at least as many elements as specified by the size expression. 6002 void 6003 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6004 ParmVarDecl *Param, 6005 const Expr *ArgExpr) { 6006 // Static array parameters are not supported in C++. 6007 if (!Param || getLangOpts().CPlusPlus) 6008 return; 6009 6010 QualType OrigTy = Param->getOriginalType(); 6011 6012 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6013 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6014 return; 6015 6016 if (ArgExpr->isNullPointerConstant(Context, 6017 Expr::NPC_NeverValueDependent)) { 6018 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6019 DiagnoseCalleeStaticArrayParam(*this, Param); 6020 return; 6021 } 6022 6023 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6024 if (!CAT) 6025 return; 6026 6027 const ConstantArrayType *ArgCAT = 6028 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6029 if (!ArgCAT) 6030 return; 6031 6032 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6033 ArgCAT->getElementType())) { 6034 if (ArgCAT->getSize().ult(CAT->getSize())) { 6035 Diag(CallLoc, diag::warn_static_array_too_small) 6036 << ArgExpr->getSourceRange() 6037 << (unsigned)ArgCAT->getSize().getZExtValue() 6038 << (unsigned)CAT->getSize().getZExtValue() << 0; 6039 DiagnoseCalleeStaticArrayParam(*this, Param); 6040 } 6041 return; 6042 } 6043 6044 Optional<CharUnits> ArgSize = 6045 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6046 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6047 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6048 Diag(CallLoc, diag::warn_static_array_too_small) 6049 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6050 << (unsigned)ParmSize->getQuantity() << 1; 6051 DiagnoseCalleeStaticArrayParam(*this, Param); 6052 } 6053 } 6054 6055 /// Given a function expression of unknown-any type, try to rebuild it 6056 /// to have a function type. 6057 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6058 6059 /// Is the given type a placeholder that we need to lower out 6060 /// immediately during argument processing? 6061 static bool isPlaceholderToRemoveAsArg(QualType type) { 6062 // Placeholders are never sugared. 6063 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6064 if (!placeholder) return false; 6065 6066 switch (placeholder->getKind()) { 6067 // Ignore all the non-placeholder types. 6068 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6069 case BuiltinType::Id: 6070 #include "clang/Basic/OpenCLImageTypes.def" 6071 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6072 case BuiltinType::Id: 6073 #include "clang/Basic/OpenCLExtensionTypes.def" 6074 // In practice we'll never use this, since all SVE types are sugared 6075 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6076 #define SVE_TYPE(Name, Id, SingletonId) \ 6077 case BuiltinType::Id: 6078 #include "clang/Basic/AArch64SVEACLETypes.def" 6079 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6080 case BuiltinType::Id: 6081 #include "clang/Basic/PPCTypes.def" 6082 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6083 #include "clang/Basic/RISCVVTypes.def" 6084 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6085 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6086 #include "clang/AST/BuiltinTypes.def" 6087 return false; 6088 6089 // We cannot lower out overload sets; they might validly be resolved 6090 // by the call machinery. 6091 case BuiltinType::Overload: 6092 return false; 6093 6094 // Unbridged casts in ARC can be handled in some call positions and 6095 // should be left in place. 6096 case BuiltinType::ARCUnbridgedCast: 6097 return false; 6098 6099 // Pseudo-objects should be converted as soon as possible. 6100 case BuiltinType::PseudoObject: 6101 return true; 6102 6103 // The debugger mode could theoretically but currently does not try 6104 // to resolve unknown-typed arguments based on known parameter types. 6105 case BuiltinType::UnknownAny: 6106 return true; 6107 6108 // These are always invalid as call arguments and should be reported. 6109 case BuiltinType::BoundMember: 6110 case BuiltinType::BuiltinFn: 6111 case BuiltinType::IncompleteMatrixIdx: 6112 case BuiltinType::OMPArraySection: 6113 case BuiltinType::OMPArrayShaping: 6114 case BuiltinType::OMPIterator: 6115 return true; 6116 6117 } 6118 llvm_unreachable("bad builtin type kind"); 6119 } 6120 6121 /// Check an argument list for placeholders that we won't try to 6122 /// handle later. 6123 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6124 // Apply this processing to all the arguments at once instead of 6125 // dying at the first failure. 6126 bool hasInvalid = false; 6127 for (size_t i = 0, e = args.size(); i != e; i++) { 6128 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6129 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6130 if (result.isInvalid()) hasInvalid = true; 6131 else args[i] = result.get(); 6132 } 6133 } 6134 return hasInvalid; 6135 } 6136 6137 /// If a builtin function has a pointer argument with no explicit address 6138 /// space, then it should be able to accept a pointer to any address 6139 /// space as input. In order to do this, we need to replace the 6140 /// standard builtin declaration with one that uses the same address space 6141 /// as the call. 6142 /// 6143 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6144 /// it does not contain any pointer arguments without 6145 /// an address space qualifer. Otherwise the rewritten 6146 /// FunctionDecl is returned. 6147 /// TODO: Handle pointer return types. 6148 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6149 FunctionDecl *FDecl, 6150 MultiExprArg ArgExprs) { 6151 6152 QualType DeclType = FDecl->getType(); 6153 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6154 6155 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6156 ArgExprs.size() < FT->getNumParams()) 6157 return nullptr; 6158 6159 bool NeedsNewDecl = false; 6160 unsigned i = 0; 6161 SmallVector<QualType, 8> OverloadParams; 6162 6163 for (QualType ParamType : FT->param_types()) { 6164 6165 // Convert array arguments to pointer to simplify type lookup. 6166 ExprResult ArgRes = 6167 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6168 if (ArgRes.isInvalid()) 6169 return nullptr; 6170 Expr *Arg = ArgRes.get(); 6171 QualType ArgType = Arg->getType(); 6172 if (!ParamType->isPointerType() || 6173 ParamType.hasAddressSpace() || 6174 !ArgType->isPointerType() || 6175 !ArgType->getPointeeType().hasAddressSpace()) { 6176 OverloadParams.push_back(ParamType); 6177 continue; 6178 } 6179 6180 QualType PointeeType = ParamType->getPointeeType(); 6181 if (PointeeType.hasAddressSpace()) 6182 continue; 6183 6184 NeedsNewDecl = true; 6185 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6186 6187 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6188 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6189 } 6190 6191 if (!NeedsNewDecl) 6192 return nullptr; 6193 6194 FunctionProtoType::ExtProtoInfo EPI; 6195 EPI.Variadic = FT->isVariadic(); 6196 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6197 OverloadParams, EPI); 6198 DeclContext *Parent = FDecl->getParent(); 6199 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6200 FDecl->getLocation(), 6201 FDecl->getLocation(), 6202 FDecl->getIdentifier(), 6203 OverloadTy, 6204 /*TInfo=*/nullptr, 6205 SC_Extern, false, 6206 /*hasPrototype=*/true); 6207 SmallVector<ParmVarDecl*, 16> Params; 6208 FT = cast<FunctionProtoType>(OverloadTy); 6209 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6210 QualType ParamType = FT->getParamType(i); 6211 ParmVarDecl *Parm = 6212 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6213 SourceLocation(), nullptr, ParamType, 6214 /*TInfo=*/nullptr, SC_None, nullptr); 6215 Parm->setScopeInfo(0, i); 6216 Params.push_back(Parm); 6217 } 6218 OverloadDecl->setParams(Params); 6219 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6220 return OverloadDecl; 6221 } 6222 6223 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6224 FunctionDecl *Callee, 6225 MultiExprArg ArgExprs) { 6226 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6227 // similar attributes) really don't like it when functions are called with an 6228 // invalid number of args. 6229 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6230 /*PartialOverloading=*/false) && 6231 !Callee->isVariadic()) 6232 return; 6233 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6234 return; 6235 6236 if (const EnableIfAttr *Attr = 6237 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6238 S.Diag(Fn->getBeginLoc(), 6239 isa<CXXMethodDecl>(Callee) 6240 ? diag::err_ovl_no_viable_member_function_in_call 6241 : diag::err_ovl_no_viable_function_in_call) 6242 << Callee << Callee->getSourceRange(); 6243 S.Diag(Callee->getLocation(), 6244 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6245 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6246 return; 6247 } 6248 } 6249 6250 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6251 const UnresolvedMemberExpr *const UME, Sema &S) { 6252 6253 const auto GetFunctionLevelDCIfCXXClass = 6254 [](Sema &S) -> const CXXRecordDecl * { 6255 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6256 if (!DC || !DC->getParent()) 6257 return nullptr; 6258 6259 // If the call to some member function was made from within a member 6260 // function body 'M' return return 'M's parent. 6261 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6262 return MD->getParent()->getCanonicalDecl(); 6263 // else the call was made from within a default member initializer of a 6264 // class, so return the class. 6265 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6266 return RD->getCanonicalDecl(); 6267 return nullptr; 6268 }; 6269 // If our DeclContext is neither a member function nor a class (in the 6270 // case of a lambda in a default member initializer), we can't have an 6271 // enclosing 'this'. 6272 6273 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6274 if (!CurParentClass) 6275 return false; 6276 6277 // The naming class for implicit member functions call is the class in which 6278 // name lookup starts. 6279 const CXXRecordDecl *const NamingClass = 6280 UME->getNamingClass()->getCanonicalDecl(); 6281 assert(NamingClass && "Must have naming class even for implicit access"); 6282 6283 // If the unresolved member functions were found in a 'naming class' that is 6284 // related (either the same or derived from) to the class that contains the 6285 // member function that itself contained the implicit member access. 6286 6287 return CurParentClass == NamingClass || 6288 CurParentClass->isDerivedFrom(NamingClass); 6289 } 6290 6291 static void 6292 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6293 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6294 6295 if (!UME) 6296 return; 6297 6298 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6299 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6300 // already been captured, or if this is an implicit member function call (if 6301 // it isn't, an attempt to capture 'this' should already have been made). 6302 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6303 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6304 return; 6305 6306 // Check if the naming class in which the unresolved members were found is 6307 // related (same as or is a base of) to the enclosing class. 6308 6309 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6310 return; 6311 6312 6313 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6314 // If the enclosing function is not dependent, then this lambda is 6315 // capture ready, so if we can capture this, do so. 6316 if (!EnclosingFunctionCtx->isDependentContext()) { 6317 // If the current lambda and all enclosing lambdas can capture 'this' - 6318 // then go ahead and capture 'this' (since our unresolved overload set 6319 // contains at least one non-static member function). 6320 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6321 S.CheckCXXThisCapture(CallLoc); 6322 } else if (S.CurContext->isDependentContext()) { 6323 // ... since this is an implicit member reference, that might potentially 6324 // involve a 'this' capture, mark 'this' for potential capture in 6325 // enclosing lambdas. 6326 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6327 CurLSI->addPotentialThisCapture(CallLoc); 6328 } 6329 } 6330 6331 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6332 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6333 Expr *ExecConfig) { 6334 ExprResult Call = 6335 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6336 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6337 if (Call.isInvalid()) 6338 return Call; 6339 6340 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6341 // language modes. 6342 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6343 if (ULE->hasExplicitTemplateArgs() && 6344 ULE->decls_begin() == ULE->decls_end()) { 6345 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6346 ? diag::warn_cxx17_compat_adl_only_template_id 6347 : diag::ext_adl_only_template_id) 6348 << ULE->getName(); 6349 } 6350 } 6351 6352 if (LangOpts.OpenMP) 6353 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6354 ExecConfig); 6355 6356 return Call; 6357 } 6358 6359 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6360 /// This provides the location of the left/right parens and a list of comma 6361 /// locations. 6362 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6363 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6364 Expr *ExecConfig, bool IsExecConfig, 6365 bool AllowRecovery) { 6366 // Since this might be a postfix expression, get rid of ParenListExprs. 6367 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6368 if (Result.isInvalid()) return ExprError(); 6369 Fn = Result.get(); 6370 6371 if (checkArgsForPlaceholders(*this, ArgExprs)) 6372 return ExprError(); 6373 6374 if (getLangOpts().CPlusPlus) { 6375 // If this is a pseudo-destructor expression, build the call immediately. 6376 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6377 if (!ArgExprs.empty()) { 6378 // Pseudo-destructor calls should not have any arguments. 6379 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6380 << FixItHint::CreateRemoval( 6381 SourceRange(ArgExprs.front()->getBeginLoc(), 6382 ArgExprs.back()->getEndLoc())); 6383 } 6384 6385 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6386 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6387 } 6388 if (Fn->getType() == Context.PseudoObjectTy) { 6389 ExprResult result = CheckPlaceholderExpr(Fn); 6390 if (result.isInvalid()) return ExprError(); 6391 Fn = result.get(); 6392 } 6393 6394 // Determine whether this is a dependent call inside a C++ template, 6395 // in which case we won't do any semantic analysis now. 6396 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6397 if (ExecConfig) { 6398 return CUDAKernelCallExpr::Create( 6399 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6400 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6401 } else { 6402 6403 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6404 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6405 Fn->getBeginLoc()); 6406 6407 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6408 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6409 } 6410 } 6411 6412 // Determine whether this is a call to an object (C++ [over.call.object]). 6413 if (Fn->getType()->isRecordType()) 6414 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6415 RParenLoc); 6416 6417 if (Fn->getType() == Context.UnknownAnyTy) { 6418 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6419 if (result.isInvalid()) return ExprError(); 6420 Fn = result.get(); 6421 } 6422 6423 if (Fn->getType() == Context.BoundMemberTy) { 6424 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6425 RParenLoc, AllowRecovery); 6426 } 6427 } 6428 6429 // Check for overloaded calls. This can happen even in C due to extensions. 6430 if (Fn->getType() == Context.OverloadTy) { 6431 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6432 6433 // We aren't supposed to apply this logic if there's an '&' involved. 6434 if (!find.HasFormOfMemberPointer) { 6435 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6436 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6437 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6438 OverloadExpr *ovl = find.Expression; 6439 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6440 return BuildOverloadedCallExpr( 6441 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6442 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6443 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6444 RParenLoc, AllowRecovery); 6445 } 6446 } 6447 6448 // If we're directly calling a function, get the appropriate declaration. 6449 if (Fn->getType() == Context.UnknownAnyTy) { 6450 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6451 if (result.isInvalid()) return ExprError(); 6452 Fn = result.get(); 6453 } 6454 6455 Expr *NakedFn = Fn->IgnoreParens(); 6456 6457 bool CallingNDeclIndirectly = false; 6458 NamedDecl *NDecl = nullptr; 6459 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6460 if (UnOp->getOpcode() == UO_AddrOf) { 6461 CallingNDeclIndirectly = true; 6462 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6463 } 6464 } 6465 6466 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6467 NDecl = DRE->getDecl(); 6468 6469 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6470 if (FDecl && FDecl->getBuiltinID()) { 6471 // Rewrite the function decl for this builtin by replacing parameters 6472 // with no explicit address space with the address space of the arguments 6473 // in ArgExprs. 6474 if ((FDecl = 6475 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6476 NDecl = FDecl; 6477 Fn = DeclRefExpr::Create( 6478 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6479 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6480 nullptr, DRE->isNonOdrUse()); 6481 } 6482 } 6483 } else if (isa<MemberExpr>(NakedFn)) 6484 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6485 6486 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6487 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6488 FD, /*Complain=*/true, Fn->getBeginLoc())) 6489 return ExprError(); 6490 6491 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6492 return ExprError(); 6493 6494 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6495 } 6496 6497 if (Context.isDependenceAllowed() && 6498 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6499 assert(!getLangOpts().CPlusPlus); 6500 assert((Fn->containsErrors() || 6501 llvm::any_of(ArgExprs, 6502 [](clang::Expr *E) { return E->containsErrors(); })) && 6503 "should only occur in error-recovery path."); 6504 QualType ReturnType = 6505 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6506 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6507 : Context.DependentTy; 6508 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6509 Expr::getValueKindForType(ReturnType), RParenLoc, 6510 CurFPFeatureOverrides()); 6511 } 6512 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6513 ExecConfig, IsExecConfig); 6514 } 6515 6516 /// Parse a __builtin_astype expression. 6517 /// 6518 /// __builtin_astype( value, dst type ) 6519 /// 6520 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6521 SourceLocation BuiltinLoc, 6522 SourceLocation RParenLoc) { 6523 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6524 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6525 } 6526 6527 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6528 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6529 SourceLocation BuiltinLoc, 6530 SourceLocation RParenLoc) { 6531 ExprValueKind VK = VK_RValue; 6532 ExprObjectKind OK = OK_Ordinary; 6533 QualType SrcTy = E->getType(); 6534 if (!SrcTy->isDependentType() && 6535 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6536 return ExprError( 6537 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6538 << DestTy << SrcTy << E->getSourceRange()); 6539 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6540 } 6541 6542 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6543 /// provided arguments. 6544 /// 6545 /// __builtin_convertvector( value, dst type ) 6546 /// 6547 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6548 SourceLocation BuiltinLoc, 6549 SourceLocation RParenLoc) { 6550 TypeSourceInfo *TInfo; 6551 GetTypeFromParser(ParsedDestTy, &TInfo); 6552 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6553 } 6554 6555 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6556 /// i.e. an expression not of \p OverloadTy. The expression should 6557 /// unary-convert to an expression of function-pointer or 6558 /// block-pointer type. 6559 /// 6560 /// \param NDecl the declaration being called, if available 6561 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6562 SourceLocation LParenLoc, 6563 ArrayRef<Expr *> Args, 6564 SourceLocation RParenLoc, Expr *Config, 6565 bool IsExecConfig, ADLCallKind UsesADL) { 6566 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6567 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6568 6569 // Functions with 'interrupt' attribute cannot be called directly. 6570 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6571 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6572 return ExprError(); 6573 } 6574 6575 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6576 // so there's some risk when calling out to non-interrupt handler functions 6577 // that the callee might not preserve them. This is easy to diagnose here, 6578 // but can be very challenging to debug. 6579 // Likewise, X86 interrupt handlers may only call routines with attribute 6580 // no_caller_saved_registers since there is no efficient way to 6581 // save and restore the non-GPR state. 6582 if (auto *Caller = getCurFunctionDecl()) { 6583 if (Caller->hasAttr<ARMInterruptAttr>()) { 6584 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6585 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6586 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6587 if (FDecl) 6588 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6589 } 6590 } 6591 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6592 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6593 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6594 if (FDecl) 6595 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6596 } 6597 } 6598 6599 // Promote the function operand. 6600 // We special-case function promotion here because we only allow promoting 6601 // builtin functions to function pointers in the callee of a call. 6602 ExprResult Result; 6603 QualType ResultTy; 6604 if (BuiltinID && 6605 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6606 // Extract the return type from the (builtin) function pointer type. 6607 // FIXME Several builtins still have setType in 6608 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6609 // Builtins.def to ensure they are correct before removing setType calls. 6610 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6611 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6612 ResultTy = FDecl->getCallResultType(); 6613 } else { 6614 Result = CallExprUnaryConversions(Fn); 6615 ResultTy = Context.BoolTy; 6616 } 6617 if (Result.isInvalid()) 6618 return ExprError(); 6619 Fn = Result.get(); 6620 6621 // Check for a valid function type, but only if it is not a builtin which 6622 // requires custom type checking. These will be handled by 6623 // CheckBuiltinFunctionCall below just after creation of the call expression. 6624 const FunctionType *FuncT = nullptr; 6625 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6626 retry: 6627 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6628 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6629 // have type pointer to function". 6630 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6631 if (!FuncT) 6632 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6633 << Fn->getType() << Fn->getSourceRange()); 6634 } else if (const BlockPointerType *BPT = 6635 Fn->getType()->getAs<BlockPointerType>()) { 6636 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6637 } else { 6638 // Handle calls to expressions of unknown-any type. 6639 if (Fn->getType() == Context.UnknownAnyTy) { 6640 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6641 if (rewrite.isInvalid()) 6642 return ExprError(); 6643 Fn = rewrite.get(); 6644 goto retry; 6645 } 6646 6647 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6648 << Fn->getType() << Fn->getSourceRange()); 6649 } 6650 } 6651 6652 // Get the number of parameters in the function prototype, if any. 6653 // We will allocate space for max(Args.size(), NumParams) arguments 6654 // in the call expression. 6655 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6656 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6657 6658 CallExpr *TheCall; 6659 if (Config) { 6660 assert(UsesADL == ADLCallKind::NotADL && 6661 "CUDAKernelCallExpr should not use ADL"); 6662 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6663 Args, ResultTy, VK_RValue, RParenLoc, 6664 CurFPFeatureOverrides(), NumParams); 6665 } else { 6666 TheCall = 6667 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6668 CurFPFeatureOverrides(), NumParams, UsesADL); 6669 } 6670 6671 if (!Context.isDependenceAllowed()) { 6672 // Forget about the nulled arguments since typo correction 6673 // do not handle them well. 6674 TheCall->shrinkNumArgs(Args.size()); 6675 // C cannot always handle TypoExpr nodes in builtin calls and direct 6676 // function calls as their argument checking don't necessarily handle 6677 // dependent types properly, so make sure any TypoExprs have been 6678 // dealt with. 6679 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6680 if (!Result.isUsable()) return ExprError(); 6681 CallExpr *TheOldCall = TheCall; 6682 TheCall = dyn_cast<CallExpr>(Result.get()); 6683 bool CorrectedTypos = TheCall != TheOldCall; 6684 if (!TheCall) return Result; 6685 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6686 6687 // A new call expression node was created if some typos were corrected. 6688 // However it may not have been constructed with enough storage. In this 6689 // case, rebuild the node with enough storage. The waste of space is 6690 // immaterial since this only happens when some typos were corrected. 6691 if (CorrectedTypos && Args.size() < NumParams) { 6692 if (Config) 6693 TheCall = CUDAKernelCallExpr::Create( 6694 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6695 RParenLoc, CurFPFeatureOverrides(), NumParams); 6696 else 6697 TheCall = 6698 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6699 CurFPFeatureOverrides(), NumParams, UsesADL); 6700 } 6701 // We can now handle the nulled arguments for the default arguments. 6702 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6703 } 6704 6705 // Bail out early if calling a builtin with custom type checking. 6706 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6707 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6708 6709 if (getLangOpts().CUDA) { 6710 if (Config) { 6711 // CUDA: Kernel calls must be to global functions 6712 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6713 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6714 << FDecl << Fn->getSourceRange()); 6715 6716 // CUDA: Kernel function must have 'void' return type 6717 if (!FuncT->getReturnType()->isVoidType() && 6718 !FuncT->getReturnType()->getAs<AutoType>() && 6719 !FuncT->getReturnType()->isInstantiationDependentType()) 6720 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6721 << Fn->getType() << Fn->getSourceRange()); 6722 } else { 6723 // CUDA: Calls to global functions must be configured 6724 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6725 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6726 << FDecl << Fn->getSourceRange()); 6727 } 6728 } 6729 6730 // Check for a valid return type 6731 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6732 FDecl)) 6733 return ExprError(); 6734 6735 // We know the result type of the call, set it. 6736 TheCall->setType(FuncT->getCallResultType(Context)); 6737 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6738 6739 if (Proto) { 6740 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6741 IsExecConfig)) 6742 return ExprError(); 6743 } else { 6744 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6745 6746 if (FDecl) { 6747 // Check if we have too few/too many template arguments, based 6748 // on our knowledge of the function definition. 6749 const FunctionDecl *Def = nullptr; 6750 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6751 Proto = Def->getType()->getAs<FunctionProtoType>(); 6752 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6753 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6754 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6755 } 6756 6757 // If the function we're calling isn't a function prototype, but we have 6758 // a function prototype from a prior declaratiom, use that prototype. 6759 if (!FDecl->hasPrototype()) 6760 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6761 } 6762 6763 // Promote the arguments (C99 6.5.2.2p6). 6764 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6765 Expr *Arg = Args[i]; 6766 6767 if (Proto && i < Proto->getNumParams()) { 6768 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6769 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6770 ExprResult ArgE = 6771 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6772 if (ArgE.isInvalid()) 6773 return true; 6774 6775 Arg = ArgE.getAs<Expr>(); 6776 6777 } else { 6778 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6779 6780 if (ArgE.isInvalid()) 6781 return true; 6782 6783 Arg = ArgE.getAs<Expr>(); 6784 } 6785 6786 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6787 diag::err_call_incomplete_argument, Arg)) 6788 return ExprError(); 6789 6790 TheCall->setArg(i, Arg); 6791 } 6792 } 6793 6794 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6795 if (!Method->isStatic()) 6796 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6797 << Fn->getSourceRange()); 6798 6799 // Check for sentinels 6800 if (NDecl) 6801 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6802 6803 // Warn for unions passing across security boundary (CMSE). 6804 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6805 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6806 if (const auto *RT = 6807 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6808 if (RT->getDecl()->isOrContainsUnion()) 6809 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6810 << 0 << i; 6811 } 6812 } 6813 } 6814 6815 // Do special checking on direct calls to functions. 6816 if (FDecl) { 6817 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6818 return ExprError(); 6819 6820 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6821 6822 if (BuiltinID) 6823 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6824 } else if (NDecl) { 6825 if (CheckPointerCall(NDecl, TheCall, Proto)) 6826 return ExprError(); 6827 } else { 6828 if (CheckOtherCall(TheCall, Proto)) 6829 return ExprError(); 6830 } 6831 6832 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6833 } 6834 6835 ExprResult 6836 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6837 SourceLocation RParenLoc, Expr *InitExpr) { 6838 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6839 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6840 6841 TypeSourceInfo *TInfo; 6842 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6843 if (!TInfo) 6844 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6845 6846 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6847 } 6848 6849 ExprResult 6850 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6851 SourceLocation RParenLoc, Expr *LiteralExpr) { 6852 QualType literalType = TInfo->getType(); 6853 6854 if (literalType->isArrayType()) { 6855 if (RequireCompleteSizedType( 6856 LParenLoc, Context.getBaseElementType(literalType), 6857 diag::err_array_incomplete_or_sizeless_type, 6858 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6859 return ExprError(); 6860 if (literalType->isVariableArrayType()) { 6861 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6862 diag::err_variable_object_no_init)) { 6863 return ExprError(); 6864 } 6865 } 6866 } else if (!literalType->isDependentType() && 6867 RequireCompleteType(LParenLoc, literalType, 6868 diag::err_typecheck_decl_incomplete_type, 6869 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6870 return ExprError(); 6871 6872 InitializedEntity Entity 6873 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6874 InitializationKind Kind 6875 = InitializationKind::CreateCStyleCast(LParenLoc, 6876 SourceRange(LParenLoc, RParenLoc), 6877 /*InitList=*/true); 6878 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6879 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6880 &literalType); 6881 if (Result.isInvalid()) 6882 return ExprError(); 6883 LiteralExpr = Result.get(); 6884 6885 bool isFileScope = !CurContext->isFunctionOrMethod(); 6886 6887 // In C, compound literals are l-values for some reason. 6888 // For GCC compatibility, in C++, file-scope array compound literals with 6889 // constant initializers are also l-values, and compound literals are 6890 // otherwise prvalues. 6891 // 6892 // (GCC also treats C++ list-initialized file-scope array prvalues with 6893 // constant initializers as l-values, but that's non-conforming, so we don't 6894 // follow it there.) 6895 // 6896 // FIXME: It would be better to handle the lvalue cases as materializing and 6897 // lifetime-extending a temporary object, but our materialized temporaries 6898 // representation only supports lifetime extension from a variable, not "out 6899 // of thin air". 6900 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6901 // is bound to the result of applying array-to-pointer decay to the compound 6902 // literal. 6903 // FIXME: GCC supports compound literals of reference type, which should 6904 // obviously have a value kind derived from the kind of reference involved. 6905 ExprValueKind VK = 6906 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6907 ? VK_RValue 6908 : VK_LValue; 6909 6910 if (isFileScope) 6911 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6912 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6913 Expr *Init = ILE->getInit(i); 6914 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6915 } 6916 6917 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6918 VK, LiteralExpr, isFileScope); 6919 if (isFileScope) { 6920 if (!LiteralExpr->isTypeDependent() && 6921 !LiteralExpr->isValueDependent() && 6922 !literalType->isDependentType()) // C99 6.5.2.5p3 6923 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6924 return ExprError(); 6925 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6926 literalType.getAddressSpace() != LangAS::Default) { 6927 // Embedded-C extensions to C99 6.5.2.5: 6928 // "If the compound literal occurs inside the body of a function, the 6929 // type name shall not be qualified by an address-space qualifier." 6930 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6931 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6932 return ExprError(); 6933 } 6934 6935 if (!isFileScope && !getLangOpts().CPlusPlus) { 6936 // Compound literals that have automatic storage duration are destroyed at 6937 // the end of the scope in C; in C++, they're just temporaries. 6938 6939 // Emit diagnostics if it is or contains a C union type that is non-trivial 6940 // to destruct. 6941 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6942 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6943 NTCUC_CompoundLiteral, NTCUK_Destruct); 6944 6945 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6946 if (literalType.isDestructedType()) { 6947 Cleanup.setExprNeedsCleanups(true); 6948 ExprCleanupObjects.push_back(E); 6949 getCurFunction()->setHasBranchProtectedScope(); 6950 } 6951 } 6952 6953 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6954 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6955 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6956 E->getInitializer()->getExprLoc()); 6957 6958 return MaybeBindToTemporary(E); 6959 } 6960 6961 ExprResult 6962 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6963 SourceLocation RBraceLoc) { 6964 // Only produce each kind of designated initialization diagnostic once. 6965 SourceLocation FirstDesignator; 6966 bool DiagnosedArrayDesignator = false; 6967 bool DiagnosedNestedDesignator = false; 6968 bool DiagnosedMixedDesignator = false; 6969 6970 // Check that any designated initializers are syntactically valid in the 6971 // current language mode. 6972 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6973 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6974 if (FirstDesignator.isInvalid()) 6975 FirstDesignator = DIE->getBeginLoc(); 6976 6977 if (!getLangOpts().CPlusPlus) 6978 break; 6979 6980 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6981 DiagnosedNestedDesignator = true; 6982 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6983 << DIE->getDesignatorsSourceRange(); 6984 } 6985 6986 for (auto &Desig : DIE->designators()) { 6987 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6988 DiagnosedArrayDesignator = true; 6989 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6990 << Desig.getSourceRange(); 6991 } 6992 } 6993 6994 if (!DiagnosedMixedDesignator && 6995 !isa<DesignatedInitExpr>(InitArgList[0])) { 6996 DiagnosedMixedDesignator = true; 6997 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6998 << DIE->getSourceRange(); 6999 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7000 << InitArgList[0]->getSourceRange(); 7001 } 7002 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7003 isa<DesignatedInitExpr>(InitArgList[0])) { 7004 DiagnosedMixedDesignator = true; 7005 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7006 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7007 << DIE->getSourceRange(); 7008 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7009 << InitArgList[I]->getSourceRange(); 7010 } 7011 } 7012 7013 if (FirstDesignator.isValid()) { 7014 // Only diagnose designated initiaization as a C++20 extension if we didn't 7015 // already diagnose use of (non-C++20) C99 designator syntax. 7016 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7017 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7018 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7019 ? diag::warn_cxx17_compat_designated_init 7020 : diag::ext_cxx_designated_init); 7021 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7022 Diag(FirstDesignator, diag::ext_designated_init); 7023 } 7024 } 7025 7026 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7027 } 7028 7029 ExprResult 7030 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7031 SourceLocation RBraceLoc) { 7032 // Semantic analysis for initializers is done by ActOnDeclarator() and 7033 // CheckInitializer() - it requires knowledge of the object being initialized. 7034 7035 // Immediately handle non-overload placeholders. Overloads can be 7036 // resolved contextually, but everything else here can't. 7037 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7038 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7039 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7040 7041 // Ignore failures; dropping the entire initializer list because 7042 // of one failure would be terrible for indexing/etc. 7043 if (result.isInvalid()) continue; 7044 7045 InitArgList[I] = result.get(); 7046 } 7047 } 7048 7049 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7050 RBraceLoc); 7051 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7052 return E; 7053 } 7054 7055 /// Do an explicit extend of the given block pointer if we're in ARC. 7056 void Sema::maybeExtendBlockObject(ExprResult &E) { 7057 assert(E.get()->getType()->isBlockPointerType()); 7058 assert(E.get()->isRValue()); 7059 7060 // Only do this in an r-value context. 7061 if (!getLangOpts().ObjCAutoRefCount) return; 7062 7063 E = ImplicitCastExpr::Create( 7064 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7065 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7066 Cleanup.setExprNeedsCleanups(true); 7067 } 7068 7069 /// Prepare a conversion of the given expression to an ObjC object 7070 /// pointer type. 7071 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7072 QualType type = E.get()->getType(); 7073 if (type->isObjCObjectPointerType()) { 7074 return CK_BitCast; 7075 } else if (type->isBlockPointerType()) { 7076 maybeExtendBlockObject(E); 7077 return CK_BlockPointerToObjCPointerCast; 7078 } else { 7079 assert(type->isPointerType()); 7080 return CK_CPointerToObjCPointerCast; 7081 } 7082 } 7083 7084 /// Prepares for a scalar cast, performing all the necessary stages 7085 /// except the final cast and returning the kind required. 7086 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7087 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7088 // Also, callers should have filtered out the invalid cases with 7089 // pointers. Everything else should be possible. 7090 7091 QualType SrcTy = Src.get()->getType(); 7092 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7093 return CK_NoOp; 7094 7095 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7096 case Type::STK_MemberPointer: 7097 llvm_unreachable("member pointer type in C"); 7098 7099 case Type::STK_CPointer: 7100 case Type::STK_BlockPointer: 7101 case Type::STK_ObjCObjectPointer: 7102 switch (DestTy->getScalarTypeKind()) { 7103 case Type::STK_CPointer: { 7104 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7105 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7106 if (SrcAS != DestAS) 7107 return CK_AddressSpaceConversion; 7108 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7109 return CK_NoOp; 7110 return CK_BitCast; 7111 } 7112 case Type::STK_BlockPointer: 7113 return (SrcKind == Type::STK_BlockPointer 7114 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7115 case Type::STK_ObjCObjectPointer: 7116 if (SrcKind == Type::STK_ObjCObjectPointer) 7117 return CK_BitCast; 7118 if (SrcKind == Type::STK_CPointer) 7119 return CK_CPointerToObjCPointerCast; 7120 maybeExtendBlockObject(Src); 7121 return CK_BlockPointerToObjCPointerCast; 7122 case Type::STK_Bool: 7123 return CK_PointerToBoolean; 7124 case Type::STK_Integral: 7125 return CK_PointerToIntegral; 7126 case Type::STK_Floating: 7127 case Type::STK_FloatingComplex: 7128 case Type::STK_IntegralComplex: 7129 case Type::STK_MemberPointer: 7130 case Type::STK_FixedPoint: 7131 llvm_unreachable("illegal cast from pointer"); 7132 } 7133 llvm_unreachable("Should have returned before this"); 7134 7135 case Type::STK_FixedPoint: 7136 switch (DestTy->getScalarTypeKind()) { 7137 case Type::STK_FixedPoint: 7138 return CK_FixedPointCast; 7139 case Type::STK_Bool: 7140 return CK_FixedPointToBoolean; 7141 case Type::STK_Integral: 7142 return CK_FixedPointToIntegral; 7143 case Type::STK_Floating: 7144 return CK_FixedPointToFloating; 7145 case Type::STK_IntegralComplex: 7146 case Type::STK_FloatingComplex: 7147 Diag(Src.get()->getExprLoc(), 7148 diag::err_unimplemented_conversion_with_fixed_point_type) 7149 << DestTy; 7150 return CK_IntegralCast; 7151 case Type::STK_CPointer: 7152 case Type::STK_ObjCObjectPointer: 7153 case Type::STK_BlockPointer: 7154 case Type::STK_MemberPointer: 7155 llvm_unreachable("illegal cast to pointer type"); 7156 } 7157 llvm_unreachable("Should have returned before this"); 7158 7159 case Type::STK_Bool: // casting from bool is like casting from an integer 7160 case Type::STK_Integral: 7161 switch (DestTy->getScalarTypeKind()) { 7162 case Type::STK_CPointer: 7163 case Type::STK_ObjCObjectPointer: 7164 case Type::STK_BlockPointer: 7165 if (Src.get()->isNullPointerConstant(Context, 7166 Expr::NPC_ValueDependentIsNull)) 7167 return CK_NullToPointer; 7168 return CK_IntegralToPointer; 7169 case Type::STK_Bool: 7170 return CK_IntegralToBoolean; 7171 case Type::STK_Integral: 7172 return CK_IntegralCast; 7173 case Type::STK_Floating: 7174 return CK_IntegralToFloating; 7175 case Type::STK_IntegralComplex: 7176 Src = ImpCastExprToType(Src.get(), 7177 DestTy->castAs<ComplexType>()->getElementType(), 7178 CK_IntegralCast); 7179 return CK_IntegralRealToComplex; 7180 case Type::STK_FloatingComplex: 7181 Src = ImpCastExprToType(Src.get(), 7182 DestTy->castAs<ComplexType>()->getElementType(), 7183 CK_IntegralToFloating); 7184 return CK_FloatingRealToComplex; 7185 case Type::STK_MemberPointer: 7186 llvm_unreachable("member pointer type in C"); 7187 case Type::STK_FixedPoint: 7188 return CK_IntegralToFixedPoint; 7189 } 7190 llvm_unreachable("Should have returned before this"); 7191 7192 case Type::STK_Floating: 7193 switch (DestTy->getScalarTypeKind()) { 7194 case Type::STK_Floating: 7195 return CK_FloatingCast; 7196 case Type::STK_Bool: 7197 return CK_FloatingToBoolean; 7198 case Type::STK_Integral: 7199 return CK_FloatingToIntegral; 7200 case Type::STK_FloatingComplex: 7201 Src = ImpCastExprToType(Src.get(), 7202 DestTy->castAs<ComplexType>()->getElementType(), 7203 CK_FloatingCast); 7204 return CK_FloatingRealToComplex; 7205 case Type::STK_IntegralComplex: 7206 Src = ImpCastExprToType(Src.get(), 7207 DestTy->castAs<ComplexType>()->getElementType(), 7208 CK_FloatingToIntegral); 7209 return CK_IntegralRealToComplex; 7210 case Type::STK_CPointer: 7211 case Type::STK_ObjCObjectPointer: 7212 case Type::STK_BlockPointer: 7213 llvm_unreachable("valid float->pointer cast?"); 7214 case Type::STK_MemberPointer: 7215 llvm_unreachable("member pointer type in C"); 7216 case Type::STK_FixedPoint: 7217 return CK_FloatingToFixedPoint; 7218 } 7219 llvm_unreachable("Should have returned before this"); 7220 7221 case Type::STK_FloatingComplex: 7222 switch (DestTy->getScalarTypeKind()) { 7223 case Type::STK_FloatingComplex: 7224 return CK_FloatingComplexCast; 7225 case Type::STK_IntegralComplex: 7226 return CK_FloatingComplexToIntegralComplex; 7227 case Type::STK_Floating: { 7228 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7229 if (Context.hasSameType(ET, DestTy)) 7230 return CK_FloatingComplexToReal; 7231 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7232 return CK_FloatingCast; 7233 } 7234 case Type::STK_Bool: 7235 return CK_FloatingComplexToBoolean; 7236 case Type::STK_Integral: 7237 Src = ImpCastExprToType(Src.get(), 7238 SrcTy->castAs<ComplexType>()->getElementType(), 7239 CK_FloatingComplexToReal); 7240 return CK_FloatingToIntegral; 7241 case Type::STK_CPointer: 7242 case Type::STK_ObjCObjectPointer: 7243 case Type::STK_BlockPointer: 7244 llvm_unreachable("valid complex float->pointer cast?"); 7245 case Type::STK_MemberPointer: 7246 llvm_unreachable("member pointer type in C"); 7247 case Type::STK_FixedPoint: 7248 Diag(Src.get()->getExprLoc(), 7249 diag::err_unimplemented_conversion_with_fixed_point_type) 7250 << SrcTy; 7251 return CK_IntegralCast; 7252 } 7253 llvm_unreachable("Should have returned before this"); 7254 7255 case Type::STK_IntegralComplex: 7256 switch (DestTy->getScalarTypeKind()) { 7257 case Type::STK_FloatingComplex: 7258 return CK_IntegralComplexToFloatingComplex; 7259 case Type::STK_IntegralComplex: 7260 return CK_IntegralComplexCast; 7261 case Type::STK_Integral: { 7262 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7263 if (Context.hasSameType(ET, DestTy)) 7264 return CK_IntegralComplexToReal; 7265 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7266 return CK_IntegralCast; 7267 } 7268 case Type::STK_Bool: 7269 return CK_IntegralComplexToBoolean; 7270 case Type::STK_Floating: 7271 Src = ImpCastExprToType(Src.get(), 7272 SrcTy->castAs<ComplexType>()->getElementType(), 7273 CK_IntegralComplexToReal); 7274 return CK_IntegralToFloating; 7275 case Type::STK_CPointer: 7276 case Type::STK_ObjCObjectPointer: 7277 case Type::STK_BlockPointer: 7278 llvm_unreachable("valid complex int->pointer cast?"); 7279 case Type::STK_MemberPointer: 7280 llvm_unreachable("member pointer type in C"); 7281 case Type::STK_FixedPoint: 7282 Diag(Src.get()->getExprLoc(), 7283 diag::err_unimplemented_conversion_with_fixed_point_type) 7284 << SrcTy; 7285 return CK_IntegralCast; 7286 } 7287 llvm_unreachable("Should have returned before this"); 7288 } 7289 7290 llvm_unreachable("Unhandled scalar cast"); 7291 } 7292 7293 static bool breakDownVectorType(QualType type, uint64_t &len, 7294 QualType &eltType) { 7295 // Vectors are simple. 7296 if (const VectorType *vecType = type->getAs<VectorType>()) { 7297 len = vecType->getNumElements(); 7298 eltType = vecType->getElementType(); 7299 assert(eltType->isScalarType()); 7300 return true; 7301 } 7302 7303 // We allow lax conversion to and from non-vector types, but only if 7304 // they're real types (i.e. non-complex, non-pointer scalar types). 7305 if (!type->isRealType()) return false; 7306 7307 len = 1; 7308 eltType = type; 7309 return true; 7310 } 7311 7312 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7313 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7314 /// allowed? 7315 /// 7316 /// This will also return false if the two given types do not make sense from 7317 /// the perspective of SVE bitcasts. 7318 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7319 assert(srcTy->isVectorType() || destTy->isVectorType()); 7320 7321 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7322 if (!FirstType->isSizelessBuiltinType()) 7323 return false; 7324 7325 const auto *VecTy = SecondType->getAs<VectorType>(); 7326 return VecTy && 7327 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7328 }; 7329 7330 return ValidScalableConversion(srcTy, destTy) || 7331 ValidScalableConversion(destTy, srcTy); 7332 } 7333 7334 /// Are the two types matrix types and do they have the same dimensions i.e. 7335 /// do they have the same number of rows and the same number of columns? 7336 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7337 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7338 return false; 7339 7340 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7341 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7342 7343 return matSrcType->getNumRows() == matDestType->getNumRows() && 7344 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7345 } 7346 7347 /// Are the two types lax-compatible vector types? That is, given 7348 /// that one of them is a vector, do they have equal storage sizes, 7349 /// where the storage size is the number of elements times the element 7350 /// size? 7351 /// 7352 /// This will also return false if either of the types is neither a 7353 /// vector nor a real type. 7354 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7355 assert(destTy->isVectorType() || srcTy->isVectorType()); 7356 7357 // Disallow lax conversions between scalars and ExtVectors (these 7358 // conversions are allowed for other vector types because common headers 7359 // depend on them). Most scalar OP ExtVector cases are handled by the 7360 // splat path anyway, which does what we want (convert, not bitcast). 7361 // What this rules out for ExtVectors is crazy things like char4*float. 7362 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7363 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7364 7365 uint64_t srcLen, destLen; 7366 QualType srcEltTy, destEltTy; 7367 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7368 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7369 7370 // ASTContext::getTypeSize will return the size rounded up to a 7371 // power of 2, so instead of using that, we need to use the raw 7372 // element size multiplied by the element count. 7373 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7374 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7375 7376 return (srcLen * srcEltSize == destLen * destEltSize); 7377 } 7378 7379 /// Is this a legal conversion between two types, one of which is 7380 /// known to be a vector type? 7381 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7382 assert(destTy->isVectorType() || srcTy->isVectorType()); 7383 7384 switch (Context.getLangOpts().getLaxVectorConversions()) { 7385 case LangOptions::LaxVectorConversionKind::None: 7386 return false; 7387 7388 case LangOptions::LaxVectorConversionKind::Integer: 7389 if (!srcTy->isIntegralOrEnumerationType()) { 7390 auto *Vec = srcTy->getAs<VectorType>(); 7391 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7392 return false; 7393 } 7394 if (!destTy->isIntegralOrEnumerationType()) { 7395 auto *Vec = destTy->getAs<VectorType>(); 7396 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7397 return false; 7398 } 7399 // OK, integer (vector) -> integer (vector) bitcast. 7400 break; 7401 7402 case LangOptions::LaxVectorConversionKind::All: 7403 break; 7404 } 7405 7406 return areLaxCompatibleVectorTypes(srcTy, destTy); 7407 } 7408 7409 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7410 CastKind &Kind) { 7411 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7412 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7413 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7414 << DestTy << SrcTy << R; 7415 } 7416 } else if (SrcTy->isMatrixType()) { 7417 return Diag(R.getBegin(), 7418 diag::err_invalid_conversion_between_matrix_and_type) 7419 << SrcTy << DestTy << R; 7420 } else if (DestTy->isMatrixType()) { 7421 return Diag(R.getBegin(), 7422 diag::err_invalid_conversion_between_matrix_and_type) 7423 << DestTy << SrcTy << R; 7424 } 7425 7426 Kind = CK_MatrixCast; 7427 return false; 7428 } 7429 7430 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7431 CastKind &Kind) { 7432 assert(VectorTy->isVectorType() && "Not a vector type!"); 7433 7434 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7435 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7436 return Diag(R.getBegin(), 7437 Ty->isVectorType() ? 7438 diag::err_invalid_conversion_between_vectors : 7439 diag::err_invalid_conversion_between_vector_and_integer) 7440 << VectorTy << Ty << R; 7441 } else 7442 return Diag(R.getBegin(), 7443 diag::err_invalid_conversion_between_vector_and_scalar) 7444 << VectorTy << Ty << R; 7445 7446 Kind = CK_BitCast; 7447 return false; 7448 } 7449 7450 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7451 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7452 7453 if (DestElemTy == SplattedExpr->getType()) 7454 return SplattedExpr; 7455 7456 assert(DestElemTy->isFloatingType() || 7457 DestElemTy->isIntegralOrEnumerationType()); 7458 7459 CastKind CK; 7460 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7461 // OpenCL requires that we convert `true` boolean expressions to -1, but 7462 // only when splatting vectors. 7463 if (DestElemTy->isFloatingType()) { 7464 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7465 // in two steps: boolean to signed integral, then to floating. 7466 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7467 CK_BooleanToSignedIntegral); 7468 SplattedExpr = CastExprRes.get(); 7469 CK = CK_IntegralToFloating; 7470 } else { 7471 CK = CK_BooleanToSignedIntegral; 7472 } 7473 } else { 7474 ExprResult CastExprRes = SplattedExpr; 7475 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7476 if (CastExprRes.isInvalid()) 7477 return ExprError(); 7478 SplattedExpr = CastExprRes.get(); 7479 } 7480 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7481 } 7482 7483 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7484 Expr *CastExpr, CastKind &Kind) { 7485 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7486 7487 QualType SrcTy = CastExpr->getType(); 7488 7489 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7490 // an ExtVectorType. 7491 // In OpenCL, casts between vectors of different types are not allowed. 7492 // (See OpenCL 6.2). 7493 if (SrcTy->isVectorType()) { 7494 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7495 (getLangOpts().OpenCL && 7496 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7497 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7498 << DestTy << SrcTy << R; 7499 return ExprError(); 7500 } 7501 Kind = CK_BitCast; 7502 return CastExpr; 7503 } 7504 7505 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7506 // conversion will take place first from scalar to elt type, and then 7507 // splat from elt type to vector. 7508 if (SrcTy->isPointerType()) 7509 return Diag(R.getBegin(), 7510 diag::err_invalid_conversion_between_vector_and_scalar) 7511 << DestTy << SrcTy << R; 7512 7513 Kind = CK_VectorSplat; 7514 return prepareVectorSplat(DestTy, CastExpr); 7515 } 7516 7517 ExprResult 7518 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7519 Declarator &D, ParsedType &Ty, 7520 SourceLocation RParenLoc, Expr *CastExpr) { 7521 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7522 "ActOnCastExpr(): missing type or expr"); 7523 7524 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7525 if (D.isInvalidType()) 7526 return ExprError(); 7527 7528 if (getLangOpts().CPlusPlus) { 7529 // Check that there are no default arguments (C++ only). 7530 CheckExtraCXXDefaultArguments(D); 7531 } else { 7532 // Make sure any TypoExprs have been dealt with. 7533 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7534 if (!Res.isUsable()) 7535 return ExprError(); 7536 CastExpr = Res.get(); 7537 } 7538 7539 checkUnusedDeclAttributes(D); 7540 7541 QualType castType = castTInfo->getType(); 7542 Ty = CreateParsedType(castType, castTInfo); 7543 7544 bool isVectorLiteral = false; 7545 7546 // Check for an altivec or OpenCL literal, 7547 // i.e. all the elements are integer constants. 7548 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7549 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7550 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7551 && castType->isVectorType() && (PE || PLE)) { 7552 if (PLE && PLE->getNumExprs() == 0) { 7553 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7554 return ExprError(); 7555 } 7556 if (PE || PLE->getNumExprs() == 1) { 7557 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7558 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7559 isVectorLiteral = true; 7560 } 7561 else 7562 isVectorLiteral = true; 7563 } 7564 7565 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7566 // then handle it as such. 7567 if (isVectorLiteral) 7568 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7569 7570 // If the Expr being casted is a ParenListExpr, handle it specially. 7571 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7572 // sequence of BinOp comma operators. 7573 if (isa<ParenListExpr>(CastExpr)) { 7574 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7575 if (Result.isInvalid()) return ExprError(); 7576 CastExpr = Result.get(); 7577 } 7578 7579 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7580 !getSourceManager().isInSystemMacro(LParenLoc)) 7581 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7582 7583 CheckTollFreeBridgeCast(castType, CastExpr); 7584 7585 CheckObjCBridgeRelatedCast(castType, CastExpr); 7586 7587 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7588 7589 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7590 } 7591 7592 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7593 SourceLocation RParenLoc, Expr *E, 7594 TypeSourceInfo *TInfo) { 7595 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7596 "Expected paren or paren list expression"); 7597 7598 Expr **exprs; 7599 unsigned numExprs; 7600 Expr *subExpr; 7601 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7602 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7603 LiteralLParenLoc = PE->getLParenLoc(); 7604 LiteralRParenLoc = PE->getRParenLoc(); 7605 exprs = PE->getExprs(); 7606 numExprs = PE->getNumExprs(); 7607 } else { // isa<ParenExpr> by assertion at function entrance 7608 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7609 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7610 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7611 exprs = &subExpr; 7612 numExprs = 1; 7613 } 7614 7615 QualType Ty = TInfo->getType(); 7616 assert(Ty->isVectorType() && "Expected vector type"); 7617 7618 SmallVector<Expr *, 8> initExprs; 7619 const VectorType *VTy = Ty->castAs<VectorType>(); 7620 unsigned numElems = VTy->getNumElements(); 7621 7622 // '(...)' form of vector initialization in AltiVec: the number of 7623 // initializers must be one or must match the size of the vector. 7624 // If a single value is specified in the initializer then it will be 7625 // replicated to all the components of the vector 7626 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7627 // The number of initializers must be one or must match the size of the 7628 // vector. If a single value is specified in the initializer then it will 7629 // be replicated to all the components of the vector 7630 if (numExprs == 1) { 7631 QualType ElemTy = VTy->getElementType(); 7632 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7633 if (Literal.isInvalid()) 7634 return ExprError(); 7635 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7636 PrepareScalarCast(Literal, ElemTy)); 7637 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7638 } 7639 else if (numExprs < numElems) { 7640 Diag(E->getExprLoc(), 7641 diag::err_incorrect_number_of_vector_initializers); 7642 return ExprError(); 7643 } 7644 else 7645 initExprs.append(exprs, exprs + numExprs); 7646 } 7647 else { 7648 // For OpenCL, when the number of initializers is a single value, 7649 // it will be replicated to all components of the vector. 7650 if (getLangOpts().OpenCL && 7651 VTy->getVectorKind() == VectorType::GenericVector && 7652 numExprs == 1) { 7653 QualType ElemTy = VTy->getElementType(); 7654 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7655 if (Literal.isInvalid()) 7656 return ExprError(); 7657 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7658 PrepareScalarCast(Literal, ElemTy)); 7659 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7660 } 7661 7662 initExprs.append(exprs, exprs + numExprs); 7663 } 7664 // FIXME: This means that pretty-printing the final AST will produce curly 7665 // braces instead of the original commas. 7666 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7667 initExprs, LiteralRParenLoc); 7668 initE->setType(Ty); 7669 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7670 } 7671 7672 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7673 /// the ParenListExpr into a sequence of comma binary operators. 7674 ExprResult 7675 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7676 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7677 if (!E) 7678 return OrigExpr; 7679 7680 ExprResult Result(E->getExpr(0)); 7681 7682 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7683 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7684 E->getExpr(i)); 7685 7686 if (Result.isInvalid()) return ExprError(); 7687 7688 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7689 } 7690 7691 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7692 SourceLocation R, 7693 MultiExprArg Val) { 7694 return ParenListExpr::Create(Context, L, Val, R); 7695 } 7696 7697 /// Emit a specialized diagnostic when one expression is a null pointer 7698 /// constant and the other is not a pointer. Returns true if a diagnostic is 7699 /// emitted. 7700 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7701 SourceLocation QuestionLoc) { 7702 Expr *NullExpr = LHSExpr; 7703 Expr *NonPointerExpr = RHSExpr; 7704 Expr::NullPointerConstantKind NullKind = 7705 NullExpr->isNullPointerConstant(Context, 7706 Expr::NPC_ValueDependentIsNotNull); 7707 7708 if (NullKind == Expr::NPCK_NotNull) { 7709 NullExpr = RHSExpr; 7710 NonPointerExpr = LHSExpr; 7711 NullKind = 7712 NullExpr->isNullPointerConstant(Context, 7713 Expr::NPC_ValueDependentIsNotNull); 7714 } 7715 7716 if (NullKind == Expr::NPCK_NotNull) 7717 return false; 7718 7719 if (NullKind == Expr::NPCK_ZeroExpression) 7720 return false; 7721 7722 if (NullKind == Expr::NPCK_ZeroLiteral) { 7723 // In this case, check to make sure that we got here from a "NULL" 7724 // string in the source code. 7725 NullExpr = NullExpr->IgnoreParenImpCasts(); 7726 SourceLocation loc = NullExpr->getExprLoc(); 7727 if (!findMacroSpelling(loc, "NULL")) 7728 return false; 7729 } 7730 7731 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7732 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7733 << NonPointerExpr->getType() << DiagType 7734 << NonPointerExpr->getSourceRange(); 7735 return true; 7736 } 7737 7738 /// Return false if the condition expression is valid, true otherwise. 7739 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7740 QualType CondTy = Cond->getType(); 7741 7742 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7743 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7744 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7745 << CondTy << Cond->getSourceRange(); 7746 return true; 7747 } 7748 7749 // C99 6.5.15p2 7750 if (CondTy->isScalarType()) return false; 7751 7752 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7753 << CondTy << Cond->getSourceRange(); 7754 return true; 7755 } 7756 7757 /// Handle when one or both operands are void type. 7758 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7759 ExprResult &RHS) { 7760 Expr *LHSExpr = LHS.get(); 7761 Expr *RHSExpr = RHS.get(); 7762 7763 if (!LHSExpr->getType()->isVoidType()) 7764 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7765 << RHSExpr->getSourceRange(); 7766 if (!RHSExpr->getType()->isVoidType()) 7767 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7768 << LHSExpr->getSourceRange(); 7769 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7770 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7771 return S.Context.VoidTy; 7772 } 7773 7774 /// Return false if the NullExpr can be promoted to PointerTy, 7775 /// true otherwise. 7776 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7777 QualType PointerTy) { 7778 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7779 !NullExpr.get()->isNullPointerConstant(S.Context, 7780 Expr::NPC_ValueDependentIsNull)) 7781 return true; 7782 7783 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7784 return false; 7785 } 7786 7787 /// Checks compatibility between two pointers and return the resulting 7788 /// type. 7789 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7790 ExprResult &RHS, 7791 SourceLocation Loc) { 7792 QualType LHSTy = LHS.get()->getType(); 7793 QualType RHSTy = RHS.get()->getType(); 7794 7795 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7796 // Two identical pointers types are always compatible. 7797 return LHSTy; 7798 } 7799 7800 QualType lhptee, rhptee; 7801 7802 // Get the pointee types. 7803 bool IsBlockPointer = false; 7804 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7805 lhptee = LHSBTy->getPointeeType(); 7806 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7807 IsBlockPointer = true; 7808 } else { 7809 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7810 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7811 } 7812 7813 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7814 // differently qualified versions of compatible types, the result type is 7815 // a pointer to an appropriately qualified version of the composite 7816 // type. 7817 7818 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7819 // clause doesn't make sense for our extensions. E.g. address space 2 should 7820 // be incompatible with address space 3: they may live on different devices or 7821 // anything. 7822 Qualifiers lhQual = lhptee.getQualifiers(); 7823 Qualifiers rhQual = rhptee.getQualifiers(); 7824 7825 LangAS ResultAddrSpace = LangAS::Default; 7826 LangAS LAddrSpace = lhQual.getAddressSpace(); 7827 LangAS RAddrSpace = rhQual.getAddressSpace(); 7828 7829 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7830 // spaces is disallowed. 7831 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7832 ResultAddrSpace = LAddrSpace; 7833 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7834 ResultAddrSpace = RAddrSpace; 7835 else { 7836 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7837 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7838 << RHS.get()->getSourceRange(); 7839 return QualType(); 7840 } 7841 7842 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7843 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7844 lhQual.removeCVRQualifiers(); 7845 rhQual.removeCVRQualifiers(); 7846 7847 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7848 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7849 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7850 // qual types are compatible iff 7851 // * corresponded types are compatible 7852 // * CVR qualifiers are equal 7853 // * address spaces are equal 7854 // Thus for conditional operator we merge CVR and address space unqualified 7855 // pointees and if there is a composite type we return a pointer to it with 7856 // merged qualifiers. 7857 LHSCastKind = 7858 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7859 RHSCastKind = 7860 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7861 lhQual.removeAddressSpace(); 7862 rhQual.removeAddressSpace(); 7863 7864 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7865 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7866 7867 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7868 7869 if (CompositeTy.isNull()) { 7870 // In this situation, we assume void* type. No especially good 7871 // reason, but this is what gcc does, and we do have to pick 7872 // to get a consistent AST. 7873 QualType incompatTy; 7874 incompatTy = S.Context.getPointerType( 7875 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7876 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7877 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7878 7879 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7880 // for casts between types with incompatible address space qualifiers. 7881 // For the following code the compiler produces casts between global and 7882 // local address spaces of the corresponded innermost pointees: 7883 // local int *global *a; 7884 // global int *global *b; 7885 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7886 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7887 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7888 << RHS.get()->getSourceRange(); 7889 7890 return incompatTy; 7891 } 7892 7893 // The pointer types are compatible. 7894 // In case of OpenCL ResultTy should have the address space qualifier 7895 // which is a superset of address spaces of both the 2nd and the 3rd 7896 // operands of the conditional operator. 7897 QualType ResultTy = [&, ResultAddrSpace]() { 7898 if (S.getLangOpts().OpenCL) { 7899 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7900 CompositeQuals.setAddressSpace(ResultAddrSpace); 7901 return S.Context 7902 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7903 .withCVRQualifiers(MergedCVRQual); 7904 } 7905 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7906 }(); 7907 if (IsBlockPointer) 7908 ResultTy = S.Context.getBlockPointerType(ResultTy); 7909 else 7910 ResultTy = S.Context.getPointerType(ResultTy); 7911 7912 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7913 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7914 return ResultTy; 7915 } 7916 7917 /// Return the resulting type when the operands are both block pointers. 7918 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7919 ExprResult &LHS, 7920 ExprResult &RHS, 7921 SourceLocation Loc) { 7922 QualType LHSTy = LHS.get()->getType(); 7923 QualType RHSTy = RHS.get()->getType(); 7924 7925 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7926 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7927 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7928 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7929 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7930 return destType; 7931 } 7932 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7933 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7934 << RHS.get()->getSourceRange(); 7935 return QualType(); 7936 } 7937 7938 // We have 2 block pointer types. 7939 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7940 } 7941 7942 /// Return the resulting type when the operands are both pointers. 7943 static QualType 7944 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7945 ExprResult &RHS, 7946 SourceLocation Loc) { 7947 // get the pointer types 7948 QualType LHSTy = LHS.get()->getType(); 7949 QualType RHSTy = RHS.get()->getType(); 7950 7951 // get the "pointed to" types 7952 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7953 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7954 7955 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7956 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7957 // Figure out necessary qualifiers (C99 6.5.15p6) 7958 QualType destPointee 7959 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7960 QualType destType = S.Context.getPointerType(destPointee); 7961 // Add qualifiers if necessary. 7962 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7963 // Promote to void*. 7964 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7965 return destType; 7966 } 7967 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7968 QualType destPointee 7969 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7970 QualType destType = S.Context.getPointerType(destPointee); 7971 // Add qualifiers if necessary. 7972 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7973 // Promote to void*. 7974 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7975 return destType; 7976 } 7977 7978 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7979 } 7980 7981 /// Return false if the first expression is not an integer and the second 7982 /// expression is not a pointer, true otherwise. 7983 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7984 Expr* PointerExpr, SourceLocation Loc, 7985 bool IsIntFirstExpr) { 7986 if (!PointerExpr->getType()->isPointerType() || 7987 !Int.get()->getType()->isIntegerType()) 7988 return false; 7989 7990 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7991 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7992 7993 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7994 << Expr1->getType() << Expr2->getType() 7995 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7996 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7997 CK_IntegralToPointer); 7998 return true; 7999 } 8000 8001 /// Simple conversion between integer and floating point types. 8002 /// 8003 /// Used when handling the OpenCL conditional operator where the 8004 /// condition is a vector while the other operands are scalar. 8005 /// 8006 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8007 /// types are either integer or floating type. Between the two 8008 /// operands, the type with the higher rank is defined as the "result 8009 /// type". The other operand needs to be promoted to the same type. No 8010 /// other type promotion is allowed. We cannot use 8011 /// UsualArithmeticConversions() for this purpose, since it always 8012 /// promotes promotable types. 8013 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8014 ExprResult &RHS, 8015 SourceLocation QuestionLoc) { 8016 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8017 if (LHS.isInvalid()) 8018 return QualType(); 8019 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8020 if (RHS.isInvalid()) 8021 return QualType(); 8022 8023 // For conversion purposes, we ignore any qualifiers. 8024 // For example, "const float" and "float" are equivalent. 8025 QualType LHSType = 8026 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8027 QualType RHSType = 8028 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8029 8030 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8031 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8032 << LHSType << LHS.get()->getSourceRange(); 8033 return QualType(); 8034 } 8035 8036 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8037 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8038 << RHSType << RHS.get()->getSourceRange(); 8039 return QualType(); 8040 } 8041 8042 // If both types are identical, no conversion is needed. 8043 if (LHSType == RHSType) 8044 return LHSType; 8045 8046 // Now handle "real" floating types (i.e. float, double, long double). 8047 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8048 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8049 /*IsCompAssign = */ false); 8050 8051 // Finally, we have two differing integer types. 8052 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8053 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8054 } 8055 8056 /// Convert scalar operands to a vector that matches the 8057 /// condition in length. 8058 /// 8059 /// Used when handling the OpenCL conditional operator where the 8060 /// condition is a vector while the other operands are scalar. 8061 /// 8062 /// We first compute the "result type" for the scalar operands 8063 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8064 /// into a vector of that type where the length matches the condition 8065 /// vector type. s6.11.6 requires that the element types of the result 8066 /// and the condition must have the same number of bits. 8067 static QualType 8068 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8069 QualType CondTy, SourceLocation QuestionLoc) { 8070 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8071 if (ResTy.isNull()) return QualType(); 8072 8073 const VectorType *CV = CondTy->getAs<VectorType>(); 8074 assert(CV); 8075 8076 // Determine the vector result type 8077 unsigned NumElements = CV->getNumElements(); 8078 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8079 8080 // Ensure that all types have the same number of bits 8081 if (S.Context.getTypeSize(CV->getElementType()) 8082 != S.Context.getTypeSize(ResTy)) { 8083 // Since VectorTy is created internally, it does not pretty print 8084 // with an OpenCL name. Instead, we just print a description. 8085 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8086 SmallString<64> Str; 8087 llvm::raw_svector_ostream OS(Str); 8088 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8089 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8090 << CondTy << OS.str(); 8091 return QualType(); 8092 } 8093 8094 // Convert operands to the vector result type 8095 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8096 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8097 8098 return VectorTy; 8099 } 8100 8101 /// Return false if this is a valid OpenCL condition vector 8102 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8103 SourceLocation QuestionLoc) { 8104 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8105 // integral type. 8106 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8107 assert(CondTy); 8108 QualType EleTy = CondTy->getElementType(); 8109 if (EleTy->isIntegerType()) return false; 8110 8111 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8112 << Cond->getType() << Cond->getSourceRange(); 8113 return true; 8114 } 8115 8116 /// Return false if the vector condition type and the vector 8117 /// result type are compatible. 8118 /// 8119 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8120 /// number of elements, and their element types have the same number 8121 /// of bits. 8122 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8123 SourceLocation QuestionLoc) { 8124 const VectorType *CV = CondTy->getAs<VectorType>(); 8125 const VectorType *RV = VecResTy->getAs<VectorType>(); 8126 assert(CV && RV); 8127 8128 if (CV->getNumElements() != RV->getNumElements()) { 8129 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8130 << CondTy << VecResTy; 8131 return true; 8132 } 8133 8134 QualType CVE = CV->getElementType(); 8135 QualType RVE = RV->getElementType(); 8136 8137 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8138 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8139 << CondTy << VecResTy; 8140 return true; 8141 } 8142 8143 return false; 8144 } 8145 8146 /// Return the resulting type for the conditional operator in 8147 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8148 /// s6.3.i) when the condition is a vector type. 8149 static QualType 8150 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8151 ExprResult &LHS, ExprResult &RHS, 8152 SourceLocation QuestionLoc) { 8153 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8154 if (Cond.isInvalid()) 8155 return QualType(); 8156 QualType CondTy = Cond.get()->getType(); 8157 8158 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8159 return QualType(); 8160 8161 // If either operand is a vector then find the vector type of the 8162 // result as specified in OpenCL v1.1 s6.3.i. 8163 if (LHS.get()->getType()->isVectorType() || 8164 RHS.get()->getType()->isVectorType()) { 8165 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8166 /*isCompAssign*/false, 8167 /*AllowBothBool*/true, 8168 /*AllowBoolConversions*/false); 8169 if (VecResTy.isNull()) return QualType(); 8170 // The result type must match the condition type as specified in 8171 // OpenCL v1.1 s6.11.6. 8172 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8173 return QualType(); 8174 return VecResTy; 8175 } 8176 8177 // Both operands are scalar. 8178 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8179 } 8180 8181 /// Return true if the Expr is block type 8182 static bool checkBlockType(Sema &S, const Expr *E) { 8183 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8184 QualType Ty = CE->getCallee()->getType(); 8185 if (Ty->isBlockPointerType()) { 8186 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8187 return true; 8188 } 8189 } 8190 return false; 8191 } 8192 8193 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8194 /// In that case, LHS = cond. 8195 /// C99 6.5.15 8196 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8197 ExprResult &RHS, ExprValueKind &VK, 8198 ExprObjectKind &OK, 8199 SourceLocation QuestionLoc) { 8200 8201 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8202 if (!LHSResult.isUsable()) return QualType(); 8203 LHS = LHSResult; 8204 8205 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8206 if (!RHSResult.isUsable()) return QualType(); 8207 RHS = RHSResult; 8208 8209 // C++ is sufficiently different to merit its own checker. 8210 if (getLangOpts().CPlusPlus) 8211 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8212 8213 VK = VK_RValue; 8214 OK = OK_Ordinary; 8215 8216 if (Context.isDependenceAllowed() && 8217 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8218 RHS.get()->isTypeDependent())) { 8219 assert(!getLangOpts().CPlusPlus); 8220 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8221 RHS.get()->containsErrors()) && 8222 "should only occur in error-recovery path."); 8223 return Context.DependentTy; 8224 } 8225 8226 // The OpenCL operator with a vector condition is sufficiently 8227 // different to merit its own checker. 8228 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8229 Cond.get()->getType()->isExtVectorType()) 8230 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8231 8232 // First, check the condition. 8233 Cond = UsualUnaryConversions(Cond.get()); 8234 if (Cond.isInvalid()) 8235 return QualType(); 8236 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8237 return QualType(); 8238 8239 // Now check the two expressions. 8240 if (LHS.get()->getType()->isVectorType() || 8241 RHS.get()->getType()->isVectorType()) 8242 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8243 /*AllowBothBool*/true, 8244 /*AllowBoolConversions*/false); 8245 8246 QualType ResTy = 8247 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8248 if (LHS.isInvalid() || RHS.isInvalid()) 8249 return QualType(); 8250 8251 QualType LHSTy = LHS.get()->getType(); 8252 QualType RHSTy = RHS.get()->getType(); 8253 8254 // Diagnose attempts to convert between __float128 and long double where 8255 // such conversions currently can't be handled. 8256 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8257 Diag(QuestionLoc, 8258 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8259 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8260 return QualType(); 8261 } 8262 8263 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8264 // selection operator (?:). 8265 if (getLangOpts().OpenCL && 8266 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8267 return QualType(); 8268 } 8269 8270 // If both operands have arithmetic type, do the usual arithmetic conversions 8271 // to find a common type: C99 6.5.15p3,5. 8272 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8273 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8274 // different sizes, or between ExtInts and other types. 8275 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8276 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8277 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8278 << RHS.get()->getSourceRange(); 8279 return QualType(); 8280 } 8281 8282 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8283 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8284 8285 return ResTy; 8286 } 8287 8288 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8289 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8290 return LHSTy; 8291 } 8292 8293 // If both operands are the same structure or union type, the result is that 8294 // type. 8295 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8296 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8297 if (LHSRT->getDecl() == RHSRT->getDecl()) 8298 // "If both the operands have structure or union type, the result has 8299 // that type." This implies that CV qualifiers are dropped. 8300 return LHSTy.getUnqualifiedType(); 8301 // FIXME: Type of conditional expression must be complete in C mode. 8302 } 8303 8304 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8305 // The following || allows only one side to be void (a GCC-ism). 8306 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8307 return checkConditionalVoidType(*this, LHS, RHS); 8308 } 8309 8310 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8311 // the type of the other operand." 8312 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8313 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8314 8315 // All objective-c pointer type analysis is done here. 8316 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8317 QuestionLoc); 8318 if (LHS.isInvalid() || RHS.isInvalid()) 8319 return QualType(); 8320 if (!compositeType.isNull()) 8321 return compositeType; 8322 8323 8324 // Handle block pointer types. 8325 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8326 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8327 QuestionLoc); 8328 8329 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8330 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8331 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8332 QuestionLoc); 8333 8334 // GCC compatibility: soften pointer/integer mismatch. Note that 8335 // null pointers have been filtered out by this point. 8336 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8337 /*IsIntFirstExpr=*/true)) 8338 return RHSTy; 8339 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8340 /*IsIntFirstExpr=*/false)) 8341 return LHSTy; 8342 8343 // Allow ?: operations in which both operands have the same 8344 // built-in sizeless type. 8345 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8346 return LHSTy; 8347 8348 // Emit a better diagnostic if one of the expressions is a null pointer 8349 // constant and the other is not a pointer type. In this case, the user most 8350 // likely forgot to take the address of the other expression. 8351 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8352 return QualType(); 8353 8354 // Otherwise, the operands are not compatible. 8355 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8356 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8357 << RHS.get()->getSourceRange(); 8358 return QualType(); 8359 } 8360 8361 /// FindCompositeObjCPointerType - Helper method to find composite type of 8362 /// two objective-c pointer types of the two input expressions. 8363 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8364 SourceLocation QuestionLoc) { 8365 QualType LHSTy = LHS.get()->getType(); 8366 QualType RHSTy = RHS.get()->getType(); 8367 8368 // Handle things like Class and struct objc_class*. Here we case the result 8369 // to the pseudo-builtin, because that will be implicitly cast back to the 8370 // redefinition type if an attempt is made to access its fields. 8371 if (LHSTy->isObjCClassType() && 8372 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8373 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8374 return LHSTy; 8375 } 8376 if (RHSTy->isObjCClassType() && 8377 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8378 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8379 return RHSTy; 8380 } 8381 // And the same for struct objc_object* / id 8382 if (LHSTy->isObjCIdType() && 8383 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8384 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8385 return LHSTy; 8386 } 8387 if (RHSTy->isObjCIdType() && 8388 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8389 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8390 return RHSTy; 8391 } 8392 // And the same for struct objc_selector* / SEL 8393 if (Context.isObjCSelType(LHSTy) && 8394 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8395 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8396 return LHSTy; 8397 } 8398 if (Context.isObjCSelType(RHSTy) && 8399 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8400 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8401 return RHSTy; 8402 } 8403 // Check constraints for Objective-C object pointers types. 8404 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8405 8406 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8407 // Two identical object pointer types are always compatible. 8408 return LHSTy; 8409 } 8410 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8411 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8412 QualType compositeType = LHSTy; 8413 8414 // If both operands are interfaces and either operand can be 8415 // assigned to the other, use that type as the composite 8416 // type. This allows 8417 // xxx ? (A*) a : (B*) b 8418 // where B is a subclass of A. 8419 // 8420 // Additionally, as for assignment, if either type is 'id' 8421 // allow silent coercion. Finally, if the types are 8422 // incompatible then make sure to use 'id' as the composite 8423 // type so the result is acceptable for sending messages to. 8424 8425 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8426 // It could return the composite type. 8427 if (!(compositeType = 8428 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8429 // Nothing more to do. 8430 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8431 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8432 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8433 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8434 } else if ((LHSOPT->isObjCQualifiedIdType() || 8435 RHSOPT->isObjCQualifiedIdType()) && 8436 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8437 true)) { 8438 // Need to handle "id<xx>" explicitly. 8439 // GCC allows qualified id and any Objective-C type to devolve to 8440 // id. Currently localizing to here until clear this should be 8441 // part of ObjCQualifiedIdTypesAreCompatible. 8442 compositeType = Context.getObjCIdType(); 8443 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8444 compositeType = Context.getObjCIdType(); 8445 } else { 8446 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8447 << LHSTy << RHSTy 8448 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8449 QualType incompatTy = Context.getObjCIdType(); 8450 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8451 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8452 return incompatTy; 8453 } 8454 // The object pointer types are compatible. 8455 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8456 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8457 return compositeType; 8458 } 8459 // Check Objective-C object pointer types and 'void *' 8460 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8461 if (getLangOpts().ObjCAutoRefCount) { 8462 // ARC forbids the implicit conversion of object pointers to 'void *', 8463 // so these types are not compatible. 8464 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8465 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8466 LHS = RHS = true; 8467 return QualType(); 8468 } 8469 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8470 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8471 QualType destPointee 8472 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8473 QualType destType = Context.getPointerType(destPointee); 8474 // Add qualifiers if necessary. 8475 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8476 // Promote to void*. 8477 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8478 return destType; 8479 } 8480 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8481 if (getLangOpts().ObjCAutoRefCount) { 8482 // ARC forbids the implicit conversion of object pointers to 'void *', 8483 // so these types are not compatible. 8484 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8485 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8486 LHS = RHS = true; 8487 return QualType(); 8488 } 8489 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8490 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8491 QualType destPointee 8492 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8493 QualType destType = Context.getPointerType(destPointee); 8494 // Add qualifiers if necessary. 8495 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8496 // Promote to void*. 8497 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8498 return destType; 8499 } 8500 return QualType(); 8501 } 8502 8503 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8504 /// ParenRange in parentheses. 8505 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8506 const PartialDiagnostic &Note, 8507 SourceRange ParenRange) { 8508 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8509 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8510 EndLoc.isValid()) { 8511 Self.Diag(Loc, Note) 8512 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8513 << FixItHint::CreateInsertion(EndLoc, ")"); 8514 } else { 8515 // We can't display the parentheses, so just show the bare note. 8516 Self.Diag(Loc, Note) << ParenRange; 8517 } 8518 } 8519 8520 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8521 return BinaryOperator::isAdditiveOp(Opc) || 8522 BinaryOperator::isMultiplicativeOp(Opc) || 8523 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8524 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8525 // not any of the logical operators. Bitwise-xor is commonly used as a 8526 // logical-xor because there is no logical-xor operator. The logical 8527 // operators, including uses of xor, have a high false positive rate for 8528 // precedence warnings. 8529 } 8530 8531 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8532 /// expression, either using a built-in or overloaded operator, 8533 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8534 /// expression. 8535 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8536 Expr **RHSExprs) { 8537 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8538 E = E->IgnoreImpCasts(); 8539 E = E->IgnoreConversionOperatorSingleStep(); 8540 E = E->IgnoreImpCasts(); 8541 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8542 E = MTE->getSubExpr(); 8543 E = E->IgnoreImpCasts(); 8544 } 8545 8546 // Built-in binary operator. 8547 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8548 if (IsArithmeticOp(OP->getOpcode())) { 8549 *Opcode = OP->getOpcode(); 8550 *RHSExprs = OP->getRHS(); 8551 return true; 8552 } 8553 } 8554 8555 // Overloaded operator. 8556 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8557 if (Call->getNumArgs() != 2) 8558 return false; 8559 8560 // Make sure this is really a binary operator that is safe to pass into 8561 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8562 OverloadedOperatorKind OO = Call->getOperator(); 8563 if (OO < OO_Plus || OO > OO_Arrow || 8564 OO == OO_PlusPlus || OO == OO_MinusMinus) 8565 return false; 8566 8567 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8568 if (IsArithmeticOp(OpKind)) { 8569 *Opcode = OpKind; 8570 *RHSExprs = Call->getArg(1); 8571 return true; 8572 } 8573 } 8574 8575 return false; 8576 } 8577 8578 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8579 /// or is a logical expression such as (x==y) which has int type, but is 8580 /// commonly interpreted as boolean. 8581 static bool ExprLooksBoolean(Expr *E) { 8582 E = E->IgnoreParenImpCasts(); 8583 8584 if (E->getType()->isBooleanType()) 8585 return true; 8586 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8587 return OP->isComparisonOp() || OP->isLogicalOp(); 8588 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8589 return OP->getOpcode() == UO_LNot; 8590 if (E->getType()->isPointerType()) 8591 return true; 8592 // FIXME: What about overloaded operator calls returning "unspecified boolean 8593 // type"s (commonly pointer-to-members)? 8594 8595 return false; 8596 } 8597 8598 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8599 /// and binary operator are mixed in a way that suggests the programmer assumed 8600 /// the conditional operator has higher precedence, for example: 8601 /// "int x = a + someBinaryCondition ? 1 : 2". 8602 static void DiagnoseConditionalPrecedence(Sema &Self, 8603 SourceLocation OpLoc, 8604 Expr *Condition, 8605 Expr *LHSExpr, 8606 Expr *RHSExpr) { 8607 BinaryOperatorKind CondOpcode; 8608 Expr *CondRHS; 8609 8610 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8611 return; 8612 if (!ExprLooksBoolean(CondRHS)) 8613 return; 8614 8615 // The condition is an arithmetic binary expression, with a right- 8616 // hand side that looks boolean, so warn. 8617 8618 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8619 ? diag::warn_precedence_bitwise_conditional 8620 : diag::warn_precedence_conditional; 8621 8622 Self.Diag(OpLoc, DiagID) 8623 << Condition->getSourceRange() 8624 << BinaryOperator::getOpcodeStr(CondOpcode); 8625 8626 SuggestParentheses( 8627 Self, OpLoc, 8628 Self.PDiag(diag::note_precedence_silence) 8629 << BinaryOperator::getOpcodeStr(CondOpcode), 8630 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8631 8632 SuggestParentheses(Self, OpLoc, 8633 Self.PDiag(diag::note_precedence_conditional_first), 8634 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8635 } 8636 8637 /// Compute the nullability of a conditional expression. 8638 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8639 QualType LHSTy, QualType RHSTy, 8640 ASTContext &Ctx) { 8641 if (!ResTy->isAnyPointerType()) 8642 return ResTy; 8643 8644 auto GetNullability = [&Ctx](QualType Ty) { 8645 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8646 if (Kind) { 8647 // For our purposes, treat _Nullable_result as _Nullable. 8648 if (*Kind == NullabilityKind::NullableResult) 8649 return NullabilityKind::Nullable; 8650 return *Kind; 8651 } 8652 return NullabilityKind::Unspecified; 8653 }; 8654 8655 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8656 NullabilityKind MergedKind; 8657 8658 // Compute nullability of a binary conditional expression. 8659 if (IsBin) { 8660 if (LHSKind == NullabilityKind::NonNull) 8661 MergedKind = NullabilityKind::NonNull; 8662 else 8663 MergedKind = RHSKind; 8664 // Compute nullability of a normal conditional expression. 8665 } else { 8666 if (LHSKind == NullabilityKind::Nullable || 8667 RHSKind == NullabilityKind::Nullable) 8668 MergedKind = NullabilityKind::Nullable; 8669 else if (LHSKind == NullabilityKind::NonNull) 8670 MergedKind = RHSKind; 8671 else if (RHSKind == NullabilityKind::NonNull) 8672 MergedKind = LHSKind; 8673 else 8674 MergedKind = NullabilityKind::Unspecified; 8675 } 8676 8677 // Return if ResTy already has the correct nullability. 8678 if (GetNullability(ResTy) == MergedKind) 8679 return ResTy; 8680 8681 // Strip all nullability from ResTy. 8682 while (ResTy->getNullability(Ctx)) 8683 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8684 8685 // Create a new AttributedType with the new nullability kind. 8686 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8687 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8688 } 8689 8690 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8691 /// in the case of a the GNU conditional expr extension. 8692 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8693 SourceLocation ColonLoc, 8694 Expr *CondExpr, Expr *LHSExpr, 8695 Expr *RHSExpr) { 8696 if (!Context.isDependenceAllowed()) { 8697 // C cannot handle TypoExpr nodes in the condition because it 8698 // doesn't handle dependent types properly, so make sure any TypoExprs have 8699 // been dealt with before checking the operands. 8700 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8701 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8702 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8703 8704 if (!CondResult.isUsable()) 8705 return ExprError(); 8706 8707 if (LHSExpr) { 8708 if (!LHSResult.isUsable()) 8709 return ExprError(); 8710 } 8711 8712 if (!RHSResult.isUsable()) 8713 return ExprError(); 8714 8715 CondExpr = CondResult.get(); 8716 LHSExpr = LHSResult.get(); 8717 RHSExpr = RHSResult.get(); 8718 } 8719 8720 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8721 // was the condition. 8722 OpaqueValueExpr *opaqueValue = nullptr; 8723 Expr *commonExpr = nullptr; 8724 if (!LHSExpr) { 8725 commonExpr = CondExpr; 8726 // Lower out placeholder types first. This is important so that we don't 8727 // try to capture a placeholder. This happens in few cases in C++; such 8728 // as Objective-C++'s dictionary subscripting syntax. 8729 if (commonExpr->hasPlaceholderType()) { 8730 ExprResult result = CheckPlaceholderExpr(commonExpr); 8731 if (!result.isUsable()) return ExprError(); 8732 commonExpr = result.get(); 8733 } 8734 // We usually want to apply unary conversions *before* saving, except 8735 // in the special case of a C++ l-value conditional. 8736 if (!(getLangOpts().CPlusPlus 8737 && !commonExpr->isTypeDependent() 8738 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8739 && commonExpr->isGLValue() 8740 && commonExpr->isOrdinaryOrBitFieldObject() 8741 && RHSExpr->isOrdinaryOrBitFieldObject() 8742 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8743 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8744 if (commonRes.isInvalid()) 8745 return ExprError(); 8746 commonExpr = commonRes.get(); 8747 } 8748 8749 // If the common expression is a class or array prvalue, materialize it 8750 // so that we can safely refer to it multiple times. 8751 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8752 commonExpr->getType()->isArrayType())) { 8753 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8754 if (MatExpr.isInvalid()) 8755 return ExprError(); 8756 commonExpr = MatExpr.get(); 8757 } 8758 8759 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8760 commonExpr->getType(), 8761 commonExpr->getValueKind(), 8762 commonExpr->getObjectKind(), 8763 commonExpr); 8764 LHSExpr = CondExpr = opaqueValue; 8765 } 8766 8767 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8768 ExprValueKind VK = VK_RValue; 8769 ExprObjectKind OK = OK_Ordinary; 8770 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8771 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8772 VK, OK, QuestionLoc); 8773 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8774 RHS.isInvalid()) 8775 return ExprError(); 8776 8777 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8778 RHS.get()); 8779 8780 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8781 8782 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8783 Context); 8784 8785 if (!commonExpr) 8786 return new (Context) 8787 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8788 RHS.get(), result, VK, OK); 8789 8790 return new (Context) BinaryConditionalOperator( 8791 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8792 ColonLoc, result, VK, OK); 8793 } 8794 8795 // Check if we have a conversion between incompatible cmse function pointer 8796 // types, that is, a conversion between a function pointer with the 8797 // cmse_nonsecure_call attribute and one without. 8798 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8799 QualType ToType) { 8800 if (const auto *ToFn = 8801 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8802 if (const auto *FromFn = 8803 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8804 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8805 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8806 8807 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8808 } 8809 } 8810 return false; 8811 } 8812 8813 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8814 // being closely modeled after the C99 spec:-). The odd characteristic of this 8815 // routine is it effectively iqnores the qualifiers on the top level pointee. 8816 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8817 // FIXME: add a couple examples in this comment. 8818 static Sema::AssignConvertType 8819 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8820 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8821 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8822 8823 // get the "pointed to" type (ignoring qualifiers at the top level) 8824 const Type *lhptee, *rhptee; 8825 Qualifiers lhq, rhq; 8826 std::tie(lhptee, lhq) = 8827 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8828 std::tie(rhptee, rhq) = 8829 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8830 8831 Sema::AssignConvertType ConvTy = Sema::Compatible; 8832 8833 // C99 6.5.16.1p1: This following citation is common to constraints 8834 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8835 // qualifiers of the type *pointed to* by the right; 8836 8837 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8838 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8839 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8840 // Ignore lifetime for further calculation. 8841 lhq.removeObjCLifetime(); 8842 rhq.removeObjCLifetime(); 8843 } 8844 8845 if (!lhq.compatiblyIncludes(rhq)) { 8846 // Treat address-space mismatches as fatal. 8847 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8848 return Sema::IncompatiblePointerDiscardsQualifiers; 8849 8850 // It's okay to add or remove GC or lifetime qualifiers when converting to 8851 // and from void*. 8852 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8853 .compatiblyIncludes( 8854 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8855 && (lhptee->isVoidType() || rhptee->isVoidType())) 8856 ; // keep old 8857 8858 // Treat lifetime mismatches as fatal. 8859 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8860 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8861 8862 // For GCC/MS compatibility, other qualifier mismatches are treated 8863 // as still compatible in C. 8864 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8865 } 8866 8867 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8868 // incomplete type and the other is a pointer to a qualified or unqualified 8869 // version of void... 8870 if (lhptee->isVoidType()) { 8871 if (rhptee->isIncompleteOrObjectType()) 8872 return ConvTy; 8873 8874 // As an extension, we allow cast to/from void* to function pointer. 8875 assert(rhptee->isFunctionType()); 8876 return Sema::FunctionVoidPointer; 8877 } 8878 8879 if (rhptee->isVoidType()) { 8880 if (lhptee->isIncompleteOrObjectType()) 8881 return ConvTy; 8882 8883 // As an extension, we allow cast to/from void* to function pointer. 8884 assert(lhptee->isFunctionType()); 8885 return Sema::FunctionVoidPointer; 8886 } 8887 8888 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8889 // unqualified versions of compatible types, ... 8890 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8891 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8892 // Check if the pointee types are compatible ignoring the sign. 8893 // We explicitly check for char so that we catch "char" vs 8894 // "unsigned char" on systems where "char" is unsigned. 8895 if (lhptee->isCharType()) 8896 ltrans = S.Context.UnsignedCharTy; 8897 else if (lhptee->hasSignedIntegerRepresentation()) 8898 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8899 8900 if (rhptee->isCharType()) 8901 rtrans = S.Context.UnsignedCharTy; 8902 else if (rhptee->hasSignedIntegerRepresentation()) 8903 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8904 8905 if (ltrans == rtrans) { 8906 // Types are compatible ignoring the sign. Qualifier incompatibility 8907 // takes priority over sign incompatibility because the sign 8908 // warning can be disabled. 8909 if (ConvTy != Sema::Compatible) 8910 return ConvTy; 8911 8912 return Sema::IncompatiblePointerSign; 8913 } 8914 8915 // If we are a multi-level pointer, it's possible that our issue is simply 8916 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8917 // the eventual target type is the same and the pointers have the same 8918 // level of indirection, this must be the issue. 8919 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8920 do { 8921 std::tie(lhptee, lhq) = 8922 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8923 std::tie(rhptee, rhq) = 8924 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8925 8926 // Inconsistent address spaces at this point is invalid, even if the 8927 // address spaces would be compatible. 8928 // FIXME: This doesn't catch address space mismatches for pointers of 8929 // different nesting levels, like: 8930 // __local int *** a; 8931 // int ** b = a; 8932 // It's not clear how to actually determine when such pointers are 8933 // invalidly incompatible. 8934 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8935 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8936 8937 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8938 8939 if (lhptee == rhptee) 8940 return Sema::IncompatibleNestedPointerQualifiers; 8941 } 8942 8943 // General pointer incompatibility takes priority over qualifiers. 8944 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8945 return Sema::IncompatibleFunctionPointer; 8946 return Sema::IncompatiblePointer; 8947 } 8948 if (!S.getLangOpts().CPlusPlus && 8949 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8950 return Sema::IncompatibleFunctionPointer; 8951 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8952 return Sema::IncompatibleFunctionPointer; 8953 return ConvTy; 8954 } 8955 8956 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8957 /// block pointer types are compatible or whether a block and normal pointer 8958 /// are compatible. It is more restrict than comparing two function pointer 8959 // types. 8960 static Sema::AssignConvertType 8961 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8962 QualType RHSType) { 8963 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8964 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8965 8966 QualType lhptee, rhptee; 8967 8968 // get the "pointed to" type (ignoring qualifiers at the top level) 8969 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8970 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8971 8972 // In C++, the types have to match exactly. 8973 if (S.getLangOpts().CPlusPlus) 8974 return Sema::IncompatibleBlockPointer; 8975 8976 Sema::AssignConvertType ConvTy = Sema::Compatible; 8977 8978 // For blocks we enforce that qualifiers are identical. 8979 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8980 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8981 if (S.getLangOpts().OpenCL) { 8982 LQuals.removeAddressSpace(); 8983 RQuals.removeAddressSpace(); 8984 } 8985 if (LQuals != RQuals) 8986 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8987 8988 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8989 // assignment. 8990 // The current behavior is similar to C++ lambdas. A block might be 8991 // assigned to a variable iff its return type and parameters are compatible 8992 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8993 // an assignment. Presumably it should behave in way that a function pointer 8994 // assignment does in C, so for each parameter and return type: 8995 // * CVR and address space of LHS should be a superset of CVR and address 8996 // space of RHS. 8997 // * unqualified types should be compatible. 8998 if (S.getLangOpts().OpenCL) { 8999 if (!S.Context.typesAreBlockPointerCompatible( 9000 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9001 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9002 return Sema::IncompatibleBlockPointer; 9003 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9004 return Sema::IncompatibleBlockPointer; 9005 9006 return ConvTy; 9007 } 9008 9009 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9010 /// for assignment compatibility. 9011 static Sema::AssignConvertType 9012 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9013 QualType RHSType) { 9014 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9015 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9016 9017 if (LHSType->isObjCBuiltinType()) { 9018 // Class is not compatible with ObjC object pointers. 9019 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9020 !RHSType->isObjCQualifiedClassType()) 9021 return Sema::IncompatiblePointer; 9022 return Sema::Compatible; 9023 } 9024 if (RHSType->isObjCBuiltinType()) { 9025 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9026 !LHSType->isObjCQualifiedClassType()) 9027 return Sema::IncompatiblePointer; 9028 return Sema::Compatible; 9029 } 9030 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9031 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9032 9033 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9034 // make an exception for id<P> 9035 !LHSType->isObjCQualifiedIdType()) 9036 return Sema::CompatiblePointerDiscardsQualifiers; 9037 9038 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9039 return Sema::Compatible; 9040 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9041 return Sema::IncompatibleObjCQualifiedId; 9042 return Sema::IncompatiblePointer; 9043 } 9044 9045 Sema::AssignConvertType 9046 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9047 QualType LHSType, QualType RHSType) { 9048 // Fake up an opaque expression. We don't actually care about what 9049 // cast operations are required, so if CheckAssignmentConstraints 9050 // adds casts to this they'll be wasted, but fortunately that doesn't 9051 // usually happen on valid code. 9052 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 9053 ExprResult RHSPtr = &RHSExpr; 9054 CastKind K; 9055 9056 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9057 } 9058 9059 /// This helper function returns true if QT is a vector type that has element 9060 /// type ElementType. 9061 static bool isVector(QualType QT, QualType ElementType) { 9062 if (const VectorType *VT = QT->getAs<VectorType>()) 9063 return VT->getElementType().getCanonicalType() == ElementType; 9064 return false; 9065 } 9066 9067 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9068 /// has code to accommodate several GCC extensions when type checking 9069 /// pointers. Here are some objectionable examples that GCC considers warnings: 9070 /// 9071 /// int a, *pint; 9072 /// short *pshort; 9073 /// struct foo *pfoo; 9074 /// 9075 /// pint = pshort; // warning: assignment from incompatible pointer type 9076 /// a = pint; // warning: assignment makes integer from pointer without a cast 9077 /// pint = a; // warning: assignment makes pointer from integer without a cast 9078 /// pint = pfoo; // warning: assignment from incompatible pointer type 9079 /// 9080 /// As a result, the code for dealing with pointers is more complex than the 9081 /// C99 spec dictates. 9082 /// 9083 /// Sets 'Kind' for any result kind except Incompatible. 9084 Sema::AssignConvertType 9085 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9086 CastKind &Kind, bool ConvertRHS) { 9087 QualType RHSType = RHS.get()->getType(); 9088 QualType OrigLHSType = LHSType; 9089 9090 // Get canonical types. We're not formatting these types, just comparing 9091 // them. 9092 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9093 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9094 9095 // Common case: no conversion required. 9096 if (LHSType == RHSType) { 9097 Kind = CK_NoOp; 9098 return Compatible; 9099 } 9100 9101 // If we have an atomic type, try a non-atomic assignment, then just add an 9102 // atomic qualification step. 9103 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9104 Sema::AssignConvertType result = 9105 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9106 if (result != Compatible) 9107 return result; 9108 if (Kind != CK_NoOp && ConvertRHS) 9109 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9110 Kind = CK_NonAtomicToAtomic; 9111 return Compatible; 9112 } 9113 9114 // If the left-hand side is a reference type, then we are in a 9115 // (rare!) case where we've allowed the use of references in C, 9116 // e.g., as a parameter type in a built-in function. In this case, 9117 // just make sure that the type referenced is compatible with the 9118 // right-hand side type. The caller is responsible for adjusting 9119 // LHSType so that the resulting expression does not have reference 9120 // type. 9121 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9122 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9123 Kind = CK_LValueBitCast; 9124 return Compatible; 9125 } 9126 return Incompatible; 9127 } 9128 9129 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9130 // to the same ExtVector type. 9131 if (LHSType->isExtVectorType()) { 9132 if (RHSType->isExtVectorType()) 9133 return Incompatible; 9134 if (RHSType->isArithmeticType()) { 9135 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9136 if (ConvertRHS) 9137 RHS = prepareVectorSplat(LHSType, RHS.get()); 9138 Kind = CK_VectorSplat; 9139 return Compatible; 9140 } 9141 } 9142 9143 // Conversions to or from vector type. 9144 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9145 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9146 // Allow assignments of an AltiVec vector type to an equivalent GCC 9147 // vector type and vice versa 9148 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9149 Kind = CK_BitCast; 9150 return Compatible; 9151 } 9152 9153 // If we are allowing lax vector conversions, and LHS and RHS are both 9154 // vectors, the total size only needs to be the same. This is a bitcast; 9155 // no bits are changed but the result type is different. 9156 if (isLaxVectorConversion(RHSType, LHSType)) { 9157 Kind = CK_BitCast; 9158 return IncompatibleVectors; 9159 } 9160 } 9161 9162 // When the RHS comes from another lax conversion (e.g. binops between 9163 // scalars and vectors) the result is canonicalized as a vector. When the 9164 // LHS is also a vector, the lax is allowed by the condition above. Handle 9165 // the case where LHS is a scalar. 9166 if (LHSType->isScalarType()) { 9167 const VectorType *VecType = RHSType->getAs<VectorType>(); 9168 if (VecType && VecType->getNumElements() == 1 && 9169 isLaxVectorConversion(RHSType, LHSType)) { 9170 ExprResult *VecExpr = &RHS; 9171 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9172 Kind = CK_BitCast; 9173 return Compatible; 9174 } 9175 } 9176 9177 // Allow assignments between fixed-length and sizeless SVE vectors. 9178 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9179 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9180 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9181 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9182 Kind = CK_BitCast; 9183 return Compatible; 9184 } 9185 9186 return Incompatible; 9187 } 9188 9189 // Diagnose attempts to convert between __float128 and long double where 9190 // such conversions currently can't be handled. 9191 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9192 return Incompatible; 9193 9194 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9195 // discards the imaginary part. 9196 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9197 !LHSType->getAs<ComplexType>()) 9198 return Incompatible; 9199 9200 // Arithmetic conversions. 9201 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9202 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9203 if (ConvertRHS) 9204 Kind = PrepareScalarCast(RHS, LHSType); 9205 return Compatible; 9206 } 9207 9208 // Conversions to normal pointers. 9209 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9210 // U* -> T* 9211 if (isa<PointerType>(RHSType)) { 9212 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9213 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9214 if (AddrSpaceL != AddrSpaceR) 9215 Kind = CK_AddressSpaceConversion; 9216 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9217 Kind = CK_NoOp; 9218 else 9219 Kind = CK_BitCast; 9220 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9221 } 9222 9223 // int -> T* 9224 if (RHSType->isIntegerType()) { 9225 Kind = CK_IntegralToPointer; // FIXME: null? 9226 return IntToPointer; 9227 } 9228 9229 // C pointers are not compatible with ObjC object pointers, 9230 // with two exceptions: 9231 if (isa<ObjCObjectPointerType>(RHSType)) { 9232 // - conversions to void* 9233 if (LHSPointer->getPointeeType()->isVoidType()) { 9234 Kind = CK_BitCast; 9235 return Compatible; 9236 } 9237 9238 // - conversions from 'Class' to the redefinition type 9239 if (RHSType->isObjCClassType() && 9240 Context.hasSameType(LHSType, 9241 Context.getObjCClassRedefinitionType())) { 9242 Kind = CK_BitCast; 9243 return Compatible; 9244 } 9245 9246 Kind = CK_BitCast; 9247 return IncompatiblePointer; 9248 } 9249 9250 // U^ -> void* 9251 if (RHSType->getAs<BlockPointerType>()) { 9252 if (LHSPointer->getPointeeType()->isVoidType()) { 9253 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9254 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9255 ->getPointeeType() 9256 .getAddressSpace(); 9257 Kind = 9258 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9259 return Compatible; 9260 } 9261 } 9262 9263 return Incompatible; 9264 } 9265 9266 // Conversions to block pointers. 9267 if (isa<BlockPointerType>(LHSType)) { 9268 // U^ -> T^ 9269 if (RHSType->isBlockPointerType()) { 9270 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9271 ->getPointeeType() 9272 .getAddressSpace(); 9273 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9274 ->getPointeeType() 9275 .getAddressSpace(); 9276 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9277 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9278 } 9279 9280 // int or null -> T^ 9281 if (RHSType->isIntegerType()) { 9282 Kind = CK_IntegralToPointer; // FIXME: null 9283 return IntToBlockPointer; 9284 } 9285 9286 // id -> T^ 9287 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9288 Kind = CK_AnyPointerToBlockPointerCast; 9289 return Compatible; 9290 } 9291 9292 // void* -> T^ 9293 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9294 if (RHSPT->getPointeeType()->isVoidType()) { 9295 Kind = CK_AnyPointerToBlockPointerCast; 9296 return Compatible; 9297 } 9298 9299 return Incompatible; 9300 } 9301 9302 // Conversions to Objective-C pointers. 9303 if (isa<ObjCObjectPointerType>(LHSType)) { 9304 // A* -> B* 9305 if (RHSType->isObjCObjectPointerType()) { 9306 Kind = CK_BitCast; 9307 Sema::AssignConvertType result = 9308 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9309 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9310 result == Compatible && 9311 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9312 result = IncompatibleObjCWeakRef; 9313 return result; 9314 } 9315 9316 // int or null -> A* 9317 if (RHSType->isIntegerType()) { 9318 Kind = CK_IntegralToPointer; // FIXME: null 9319 return IntToPointer; 9320 } 9321 9322 // In general, C pointers are not compatible with ObjC object pointers, 9323 // with two exceptions: 9324 if (isa<PointerType>(RHSType)) { 9325 Kind = CK_CPointerToObjCPointerCast; 9326 9327 // - conversions from 'void*' 9328 if (RHSType->isVoidPointerType()) { 9329 return Compatible; 9330 } 9331 9332 // - conversions to 'Class' from its redefinition type 9333 if (LHSType->isObjCClassType() && 9334 Context.hasSameType(RHSType, 9335 Context.getObjCClassRedefinitionType())) { 9336 return Compatible; 9337 } 9338 9339 return IncompatiblePointer; 9340 } 9341 9342 // Only under strict condition T^ is compatible with an Objective-C pointer. 9343 if (RHSType->isBlockPointerType() && 9344 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9345 if (ConvertRHS) 9346 maybeExtendBlockObject(RHS); 9347 Kind = CK_BlockPointerToObjCPointerCast; 9348 return Compatible; 9349 } 9350 9351 return Incompatible; 9352 } 9353 9354 // Conversions from pointers that are not covered by the above. 9355 if (isa<PointerType>(RHSType)) { 9356 // T* -> _Bool 9357 if (LHSType == Context.BoolTy) { 9358 Kind = CK_PointerToBoolean; 9359 return Compatible; 9360 } 9361 9362 // T* -> int 9363 if (LHSType->isIntegerType()) { 9364 Kind = CK_PointerToIntegral; 9365 return PointerToInt; 9366 } 9367 9368 return Incompatible; 9369 } 9370 9371 // Conversions from Objective-C pointers that are not covered by the above. 9372 if (isa<ObjCObjectPointerType>(RHSType)) { 9373 // T* -> _Bool 9374 if (LHSType == Context.BoolTy) { 9375 Kind = CK_PointerToBoolean; 9376 return Compatible; 9377 } 9378 9379 // T* -> int 9380 if (LHSType->isIntegerType()) { 9381 Kind = CK_PointerToIntegral; 9382 return PointerToInt; 9383 } 9384 9385 return Incompatible; 9386 } 9387 9388 // struct A -> struct B 9389 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9390 if (Context.typesAreCompatible(LHSType, RHSType)) { 9391 Kind = CK_NoOp; 9392 return Compatible; 9393 } 9394 } 9395 9396 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9397 Kind = CK_IntToOCLSampler; 9398 return Compatible; 9399 } 9400 9401 return Incompatible; 9402 } 9403 9404 /// Constructs a transparent union from an expression that is 9405 /// used to initialize the transparent union. 9406 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9407 ExprResult &EResult, QualType UnionType, 9408 FieldDecl *Field) { 9409 // Build an initializer list that designates the appropriate member 9410 // of the transparent union. 9411 Expr *E = EResult.get(); 9412 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9413 E, SourceLocation()); 9414 Initializer->setType(UnionType); 9415 Initializer->setInitializedFieldInUnion(Field); 9416 9417 // Build a compound literal constructing a value of the transparent 9418 // union type from this initializer list. 9419 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9420 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9421 VK_RValue, Initializer, false); 9422 } 9423 9424 Sema::AssignConvertType 9425 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9426 ExprResult &RHS) { 9427 QualType RHSType = RHS.get()->getType(); 9428 9429 // If the ArgType is a Union type, we want to handle a potential 9430 // transparent_union GCC extension. 9431 const RecordType *UT = ArgType->getAsUnionType(); 9432 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9433 return Incompatible; 9434 9435 // The field to initialize within the transparent union. 9436 RecordDecl *UD = UT->getDecl(); 9437 FieldDecl *InitField = nullptr; 9438 // It's compatible if the expression matches any of the fields. 9439 for (auto *it : UD->fields()) { 9440 if (it->getType()->isPointerType()) { 9441 // If the transparent union contains a pointer type, we allow: 9442 // 1) void pointer 9443 // 2) null pointer constant 9444 if (RHSType->isPointerType()) 9445 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9446 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9447 InitField = it; 9448 break; 9449 } 9450 9451 if (RHS.get()->isNullPointerConstant(Context, 9452 Expr::NPC_ValueDependentIsNull)) { 9453 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9454 CK_NullToPointer); 9455 InitField = it; 9456 break; 9457 } 9458 } 9459 9460 CastKind Kind; 9461 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9462 == Compatible) { 9463 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9464 InitField = it; 9465 break; 9466 } 9467 } 9468 9469 if (!InitField) 9470 return Incompatible; 9471 9472 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9473 return Compatible; 9474 } 9475 9476 Sema::AssignConvertType 9477 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9478 bool Diagnose, 9479 bool DiagnoseCFAudited, 9480 bool ConvertRHS) { 9481 // We need to be able to tell the caller whether we diagnosed a problem, if 9482 // they ask us to issue diagnostics. 9483 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9484 9485 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9486 // we can't avoid *all* modifications at the moment, so we need some somewhere 9487 // to put the updated value. 9488 ExprResult LocalRHS = CallerRHS; 9489 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9490 9491 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9492 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9493 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9494 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9495 Diag(RHS.get()->getExprLoc(), 9496 diag::warn_noderef_to_dereferenceable_pointer) 9497 << RHS.get()->getSourceRange(); 9498 } 9499 } 9500 } 9501 9502 if (getLangOpts().CPlusPlus) { 9503 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9504 // C++ 5.17p3: If the left operand is not of class type, the 9505 // expression is implicitly converted (C++ 4) to the 9506 // cv-unqualified type of the left operand. 9507 QualType RHSType = RHS.get()->getType(); 9508 if (Diagnose) { 9509 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9510 AA_Assigning); 9511 } else { 9512 ImplicitConversionSequence ICS = 9513 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9514 /*SuppressUserConversions=*/false, 9515 AllowedExplicit::None, 9516 /*InOverloadResolution=*/false, 9517 /*CStyle=*/false, 9518 /*AllowObjCWritebackConversion=*/false); 9519 if (ICS.isFailure()) 9520 return Incompatible; 9521 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9522 ICS, AA_Assigning); 9523 } 9524 if (RHS.isInvalid()) 9525 return Incompatible; 9526 Sema::AssignConvertType result = Compatible; 9527 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9528 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9529 result = IncompatibleObjCWeakRef; 9530 return result; 9531 } 9532 9533 // FIXME: Currently, we fall through and treat C++ classes like C 9534 // structures. 9535 // FIXME: We also fall through for atomics; not sure what should 9536 // happen there, though. 9537 } else if (RHS.get()->getType() == Context.OverloadTy) { 9538 // As a set of extensions to C, we support overloading on functions. These 9539 // functions need to be resolved here. 9540 DeclAccessPair DAP; 9541 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9542 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9543 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9544 else 9545 return Incompatible; 9546 } 9547 9548 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9549 // a null pointer constant. 9550 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9551 LHSType->isBlockPointerType()) && 9552 RHS.get()->isNullPointerConstant(Context, 9553 Expr::NPC_ValueDependentIsNull)) { 9554 if (Diagnose || ConvertRHS) { 9555 CastKind Kind; 9556 CXXCastPath Path; 9557 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9558 /*IgnoreBaseAccess=*/false, Diagnose); 9559 if (ConvertRHS) 9560 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9561 } 9562 return Compatible; 9563 } 9564 9565 // OpenCL queue_t type assignment. 9566 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9567 Context, Expr::NPC_ValueDependentIsNull)) { 9568 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9569 return Compatible; 9570 } 9571 9572 // This check seems unnatural, however it is necessary to ensure the proper 9573 // conversion of functions/arrays. If the conversion were done for all 9574 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9575 // expressions that suppress this implicit conversion (&, sizeof). 9576 // 9577 // Suppress this for references: C++ 8.5.3p5. 9578 if (!LHSType->isReferenceType()) { 9579 // FIXME: We potentially allocate here even if ConvertRHS is false. 9580 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9581 if (RHS.isInvalid()) 9582 return Incompatible; 9583 } 9584 CastKind Kind; 9585 Sema::AssignConvertType result = 9586 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9587 9588 // C99 6.5.16.1p2: The value of the right operand is converted to the 9589 // type of the assignment expression. 9590 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9591 // so that we can use references in built-in functions even in C. 9592 // The getNonReferenceType() call makes sure that the resulting expression 9593 // does not have reference type. 9594 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9595 QualType Ty = LHSType.getNonLValueExprType(Context); 9596 Expr *E = RHS.get(); 9597 9598 // Check for various Objective-C errors. If we are not reporting 9599 // diagnostics and just checking for errors, e.g., during overload 9600 // resolution, return Incompatible to indicate the failure. 9601 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9602 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9603 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9604 if (!Diagnose) 9605 return Incompatible; 9606 } 9607 if (getLangOpts().ObjC && 9608 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9609 E->getType(), E, Diagnose) || 9610 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9611 if (!Diagnose) 9612 return Incompatible; 9613 // Replace the expression with a corrected version and continue so we 9614 // can find further errors. 9615 RHS = E; 9616 return Compatible; 9617 } 9618 9619 if (ConvertRHS) 9620 RHS = ImpCastExprToType(E, Ty, Kind); 9621 } 9622 9623 return result; 9624 } 9625 9626 namespace { 9627 /// The original operand to an operator, prior to the application of the usual 9628 /// arithmetic conversions and converting the arguments of a builtin operator 9629 /// candidate. 9630 struct OriginalOperand { 9631 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9632 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9633 Op = MTE->getSubExpr(); 9634 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9635 Op = BTE->getSubExpr(); 9636 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9637 Orig = ICE->getSubExprAsWritten(); 9638 Conversion = ICE->getConversionFunction(); 9639 } 9640 } 9641 9642 QualType getType() const { return Orig->getType(); } 9643 9644 Expr *Orig; 9645 NamedDecl *Conversion; 9646 }; 9647 } 9648 9649 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9650 ExprResult &RHS) { 9651 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9652 9653 Diag(Loc, diag::err_typecheck_invalid_operands) 9654 << OrigLHS.getType() << OrigRHS.getType() 9655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9656 9657 // If a user-defined conversion was applied to either of the operands prior 9658 // to applying the built-in operator rules, tell the user about it. 9659 if (OrigLHS.Conversion) { 9660 Diag(OrigLHS.Conversion->getLocation(), 9661 diag::note_typecheck_invalid_operands_converted) 9662 << 0 << LHS.get()->getType(); 9663 } 9664 if (OrigRHS.Conversion) { 9665 Diag(OrigRHS.Conversion->getLocation(), 9666 diag::note_typecheck_invalid_operands_converted) 9667 << 1 << RHS.get()->getType(); 9668 } 9669 9670 return QualType(); 9671 } 9672 9673 // Diagnose cases where a scalar was implicitly converted to a vector and 9674 // diagnose the underlying types. Otherwise, diagnose the error 9675 // as invalid vector logical operands for non-C++ cases. 9676 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9677 ExprResult &RHS) { 9678 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9679 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9680 9681 bool LHSNatVec = LHSType->isVectorType(); 9682 bool RHSNatVec = RHSType->isVectorType(); 9683 9684 if (!(LHSNatVec && RHSNatVec)) { 9685 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9686 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9687 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9688 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9689 << Vector->getSourceRange(); 9690 return QualType(); 9691 } 9692 9693 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9694 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9695 << RHS.get()->getSourceRange(); 9696 9697 return QualType(); 9698 } 9699 9700 /// Try to convert a value of non-vector type to a vector type by converting 9701 /// the type to the element type of the vector and then performing a splat. 9702 /// If the language is OpenCL, we only use conversions that promote scalar 9703 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9704 /// for float->int. 9705 /// 9706 /// OpenCL V2.0 6.2.6.p2: 9707 /// An error shall occur if any scalar operand type has greater rank 9708 /// than the type of the vector element. 9709 /// 9710 /// \param scalar - if non-null, actually perform the conversions 9711 /// \return true if the operation fails (but without diagnosing the failure) 9712 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9713 QualType scalarTy, 9714 QualType vectorEltTy, 9715 QualType vectorTy, 9716 unsigned &DiagID) { 9717 // The conversion to apply to the scalar before splatting it, 9718 // if necessary. 9719 CastKind scalarCast = CK_NoOp; 9720 9721 if (vectorEltTy->isIntegralType(S.Context)) { 9722 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9723 (scalarTy->isIntegerType() && 9724 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9725 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9726 return true; 9727 } 9728 if (!scalarTy->isIntegralType(S.Context)) 9729 return true; 9730 scalarCast = CK_IntegralCast; 9731 } else if (vectorEltTy->isRealFloatingType()) { 9732 if (scalarTy->isRealFloatingType()) { 9733 if (S.getLangOpts().OpenCL && 9734 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9735 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9736 return true; 9737 } 9738 scalarCast = CK_FloatingCast; 9739 } 9740 else if (scalarTy->isIntegralType(S.Context)) 9741 scalarCast = CK_IntegralToFloating; 9742 else 9743 return true; 9744 } else { 9745 return true; 9746 } 9747 9748 // Adjust scalar if desired. 9749 if (scalar) { 9750 if (scalarCast != CK_NoOp) 9751 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9752 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9753 } 9754 return false; 9755 } 9756 9757 /// Convert vector E to a vector with the same number of elements but different 9758 /// element type. 9759 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9760 const auto *VecTy = E->getType()->getAs<VectorType>(); 9761 assert(VecTy && "Expression E must be a vector"); 9762 QualType NewVecTy = S.Context.getVectorType(ElementType, 9763 VecTy->getNumElements(), 9764 VecTy->getVectorKind()); 9765 9766 // Look through the implicit cast. Return the subexpression if its type is 9767 // NewVecTy. 9768 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9769 if (ICE->getSubExpr()->getType() == NewVecTy) 9770 return ICE->getSubExpr(); 9771 9772 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9773 return S.ImpCastExprToType(E, NewVecTy, Cast); 9774 } 9775 9776 /// Test if a (constant) integer Int can be casted to another integer type 9777 /// IntTy without losing precision. 9778 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9779 QualType OtherIntTy) { 9780 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9781 9782 // Reject cases where the value of the Int is unknown as that would 9783 // possibly cause truncation, but accept cases where the scalar can be 9784 // demoted without loss of precision. 9785 Expr::EvalResult EVResult; 9786 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9787 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9788 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9789 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9790 9791 if (CstInt) { 9792 // If the scalar is constant and is of a higher order and has more active 9793 // bits that the vector element type, reject it. 9794 llvm::APSInt Result = EVResult.Val.getInt(); 9795 unsigned NumBits = IntSigned 9796 ? (Result.isNegative() ? Result.getMinSignedBits() 9797 : Result.getActiveBits()) 9798 : Result.getActiveBits(); 9799 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9800 return true; 9801 9802 // If the signedness of the scalar type and the vector element type 9803 // differs and the number of bits is greater than that of the vector 9804 // element reject it. 9805 return (IntSigned != OtherIntSigned && 9806 NumBits > S.Context.getIntWidth(OtherIntTy)); 9807 } 9808 9809 // Reject cases where the value of the scalar is not constant and it's 9810 // order is greater than that of the vector element type. 9811 return (Order < 0); 9812 } 9813 9814 /// Test if a (constant) integer Int can be casted to floating point type 9815 /// FloatTy without losing precision. 9816 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9817 QualType FloatTy) { 9818 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9819 9820 // Determine if the integer constant can be expressed as a floating point 9821 // number of the appropriate type. 9822 Expr::EvalResult EVResult; 9823 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9824 9825 uint64_t Bits = 0; 9826 if (CstInt) { 9827 // Reject constants that would be truncated if they were converted to 9828 // the floating point type. Test by simple to/from conversion. 9829 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9830 // could be avoided if there was a convertFromAPInt method 9831 // which could signal back if implicit truncation occurred. 9832 llvm::APSInt Result = EVResult.Val.getInt(); 9833 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9834 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9835 llvm::APFloat::rmTowardZero); 9836 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9837 !IntTy->hasSignedIntegerRepresentation()); 9838 bool Ignored = false; 9839 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9840 &Ignored); 9841 if (Result != ConvertBack) 9842 return true; 9843 } else { 9844 // Reject types that cannot be fully encoded into the mantissa of 9845 // the float. 9846 Bits = S.Context.getTypeSize(IntTy); 9847 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9848 S.Context.getFloatTypeSemantics(FloatTy)); 9849 if (Bits > FloatPrec) 9850 return true; 9851 } 9852 9853 return false; 9854 } 9855 9856 /// Attempt to convert and splat Scalar into a vector whose types matches 9857 /// Vector following GCC conversion rules. The rule is that implicit 9858 /// conversion can occur when Scalar can be casted to match Vector's element 9859 /// type without causing truncation of Scalar. 9860 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9861 ExprResult *Vector) { 9862 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9863 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9864 const VectorType *VT = VectorTy->getAs<VectorType>(); 9865 9866 assert(!isa<ExtVectorType>(VT) && 9867 "ExtVectorTypes should not be handled here!"); 9868 9869 QualType VectorEltTy = VT->getElementType(); 9870 9871 // Reject cases where the vector element type or the scalar element type are 9872 // not integral or floating point types. 9873 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9874 return true; 9875 9876 // The conversion to apply to the scalar before splatting it, 9877 // if necessary. 9878 CastKind ScalarCast = CK_NoOp; 9879 9880 // Accept cases where the vector elements are integers and the scalar is 9881 // an integer. 9882 // FIXME: Notionally if the scalar was a floating point value with a precise 9883 // integral representation, we could cast it to an appropriate integer 9884 // type and then perform the rest of the checks here. GCC will perform 9885 // this conversion in some cases as determined by the input language. 9886 // We should accept it on a language independent basis. 9887 if (VectorEltTy->isIntegralType(S.Context) && 9888 ScalarTy->isIntegralType(S.Context) && 9889 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9890 9891 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9892 return true; 9893 9894 ScalarCast = CK_IntegralCast; 9895 } else if (VectorEltTy->isIntegralType(S.Context) && 9896 ScalarTy->isRealFloatingType()) { 9897 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9898 ScalarCast = CK_FloatingToIntegral; 9899 else 9900 return true; 9901 } else if (VectorEltTy->isRealFloatingType()) { 9902 if (ScalarTy->isRealFloatingType()) { 9903 9904 // Reject cases where the scalar type is not a constant and has a higher 9905 // Order than the vector element type. 9906 llvm::APFloat Result(0.0); 9907 9908 // Determine whether this is a constant scalar. In the event that the 9909 // value is dependent (and thus cannot be evaluated by the constant 9910 // evaluator), skip the evaluation. This will then diagnose once the 9911 // expression is instantiated. 9912 bool CstScalar = Scalar->get()->isValueDependent() || 9913 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9914 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9915 if (!CstScalar && Order < 0) 9916 return true; 9917 9918 // If the scalar cannot be safely casted to the vector element type, 9919 // reject it. 9920 if (CstScalar) { 9921 bool Truncated = false; 9922 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9923 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9924 if (Truncated) 9925 return true; 9926 } 9927 9928 ScalarCast = CK_FloatingCast; 9929 } else if (ScalarTy->isIntegralType(S.Context)) { 9930 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9931 return true; 9932 9933 ScalarCast = CK_IntegralToFloating; 9934 } else 9935 return true; 9936 } else if (ScalarTy->isEnumeralType()) 9937 return true; 9938 9939 // Adjust scalar if desired. 9940 if (Scalar) { 9941 if (ScalarCast != CK_NoOp) 9942 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9943 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9944 } 9945 return false; 9946 } 9947 9948 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9949 SourceLocation Loc, bool IsCompAssign, 9950 bool AllowBothBool, 9951 bool AllowBoolConversions) { 9952 if (!IsCompAssign) { 9953 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9954 if (LHS.isInvalid()) 9955 return QualType(); 9956 } 9957 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9958 if (RHS.isInvalid()) 9959 return QualType(); 9960 9961 // For conversion purposes, we ignore any qualifiers. 9962 // For example, "const float" and "float" are equivalent. 9963 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9964 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9965 9966 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9967 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9968 assert(LHSVecType || RHSVecType); 9969 9970 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9971 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9972 return InvalidOperands(Loc, LHS, RHS); 9973 9974 // AltiVec-style "vector bool op vector bool" combinations are allowed 9975 // for some operators but not others. 9976 if (!AllowBothBool && 9977 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9978 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9979 return InvalidOperands(Loc, LHS, RHS); 9980 9981 // If the vector types are identical, return. 9982 if (Context.hasSameType(LHSType, RHSType)) 9983 return LHSType; 9984 9985 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9986 if (LHSVecType && RHSVecType && 9987 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9988 if (isa<ExtVectorType>(LHSVecType)) { 9989 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9990 return LHSType; 9991 } 9992 9993 if (!IsCompAssign) 9994 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9995 return RHSType; 9996 } 9997 9998 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9999 // can be mixed, with the result being the non-bool type. The non-bool 10000 // operand must have integer element type. 10001 if (AllowBoolConversions && LHSVecType && RHSVecType && 10002 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10003 (Context.getTypeSize(LHSVecType->getElementType()) == 10004 Context.getTypeSize(RHSVecType->getElementType()))) { 10005 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10006 LHSVecType->getElementType()->isIntegerType() && 10007 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10009 return LHSType; 10010 } 10011 if (!IsCompAssign && 10012 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10013 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10014 RHSVecType->getElementType()->isIntegerType()) { 10015 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10016 return RHSType; 10017 } 10018 } 10019 10020 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10021 // since the ambiguity can affect the ABI. 10022 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10023 const VectorType *VecType = SecondType->getAs<VectorType>(); 10024 return FirstType->isSizelessBuiltinType() && VecType && 10025 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10026 VecType->getVectorKind() == 10027 VectorType::SveFixedLengthPredicateVector); 10028 }; 10029 10030 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10031 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10032 return QualType(); 10033 } 10034 10035 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10036 // since the ambiguity can affect the ABI. 10037 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10038 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10039 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10040 10041 if (FirstVecType && SecondVecType) 10042 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10043 (SecondVecType->getVectorKind() == 10044 VectorType::SveFixedLengthDataVector || 10045 SecondVecType->getVectorKind() == 10046 VectorType::SveFixedLengthPredicateVector); 10047 10048 return FirstType->isSizelessBuiltinType() && SecondVecType && 10049 SecondVecType->getVectorKind() == VectorType::GenericVector; 10050 }; 10051 10052 if (IsSveGnuConversion(LHSType, RHSType) || 10053 IsSveGnuConversion(RHSType, LHSType)) { 10054 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10055 return QualType(); 10056 } 10057 10058 // If there's a vector type and a scalar, try to convert the scalar to 10059 // the vector element type and splat. 10060 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10061 if (!RHSVecType) { 10062 if (isa<ExtVectorType>(LHSVecType)) { 10063 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10064 LHSVecType->getElementType(), LHSType, 10065 DiagID)) 10066 return LHSType; 10067 } else { 10068 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10069 return LHSType; 10070 } 10071 } 10072 if (!LHSVecType) { 10073 if (isa<ExtVectorType>(RHSVecType)) { 10074 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10075 LHSType, RHSVecType->getElementType(), 10076 RHSType, DiagID)) 10077 return RHSType; 10078 } else { 10079 if (LHS.get()->getValueKind() == VK_LValue || 10080 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10081 return RHSType; 10082 } 10083 } 10084 10085 // FIXME: The code below also handles conversion between vectors and 10086 // non-scalars, we should break this down into fine grained specific checks 10087 // and emit proper diagnostics. 10088 QualType VecType = LHSVecType ? LHSType : RHSType; 10089 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10090 QualType OtherType = LHSVecType ? RHSType : LHSType; 10091 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10092 if (isLaxVectorConversion(OtherType, VecType)) { 10093 // If we're allowing lax vector conversions, only the total (data) size 10094 // needs to be the same. For non compound assignment, if one of the types is 10095 // scalar, the result is always the vector type. 10096 if (!IsCompAssign) { 10097 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10098 return VecType; 10099 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10100 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10101 // type. Note that this is already done by non-compound assignments in 10102 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10103 // <1 x T> -> T. The result is also a vector type. 10104 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10105 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10106 ExprResult *RHSExpr = &RHS; 10107 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10108 return VecType; 10109 } 10110 } 10111 10112 // Okay, the expression is invalid. 10113 10114 // If there's a non-vector, non-real operand, diagnose that. 10115 if ((!RHSVecType && !RHSType->isRealType()) || 10116 (!LHSVecType && !LHSType->isRealType())) { 10117 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10118 << LHSType << RHSType 10119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10120 return QualType(); 10121 } 10122 10123 // OpenCL V1.1 6.2.6.p1: 10124 // If the operands are of more than one vector type, then an error shall 10125 // occur. Implicit conversions between vector types are not permitted, per 10126 // section 6.2.1. 10127 if (getLangOpts().OpenCL && 10128 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10129 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10130 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10131 << RHSType; 10132 return QualType(); 10133 } 10134 10135 10136 // If there is a vector type that is not a ExtVector and a scalar, we reach 10137 // this point if scalar could not be converted to the vector's element type 10138 // without truncation. 10139 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10140 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10141 QualType Scalar = LHSVecType ? RHSType : LHSType; 10142 QualType Vector = LHSVecType ? LHSType : RHSType; 10143 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10144 Diag(Loc, 10145 diag::err_typecheck_vector_not_convertable_implict_truncation) 10146 << ScalarOrVector << Scalar << Vector; 10147 10148 return QualType(); 10149 } 10150 10151 // Otherwise, use the generic diagnostic. 10152 Diag(Loc, DiagID) 10153 << LHSType << RHSType 10154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10155 return QualType(); 10156 } 10157 10158 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10159 // expression. These are mainly cases where the null pointer is used as an 10160 // integer instead of a pointer. 10161 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10162 SourceLocation Loc, bool IsCompare) { 10163 // The canonical way to check for a GNU null is with isNullPointerConstant, 10164 // but we use a bit of a hack here for speed; this is a relatively 10165 // hot path, and isNullPointerConstant is slow. 10166 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10167 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10168 10169 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10170 10171 // Avoid analyzing cases where the result will either be invalid (and 10172 // diagnosed as such) or entirely valid and not something to warn about. 10173 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10174 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10175 return; 10176 10177 // Comparison operations would not make sense with a null pointer no matter 10178 // what the other expression is. 10179 if (!IsCompare) { 10180 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10181 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10182 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10183 return; 10184 } 10185 10186 // The rest of the operations only make sense with a null pointer 10187 // if the other expression is a pointer. 10188 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10189 NonNullType->canDecayToPointerType()) 10190 return; 10191 10192 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10193 << LHSNull /* LHS is NULL */ << NonNullType 10194 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10195 } 10196 10197 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10198 SourceLocation Loc) { 10199 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10200 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10201 if (!LUE || !RUE) 10202 return; 10203 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10204 RUE->getKind() != UETT_SizeOf) 10205 return; 10206 10207 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10208 QualType LHSTy = LHSArg->getType(); 10209 QualType RHSTy; 10210 10211 if (RUE->isArgumentType()) 10212 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10213 else 10214 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10215 10216 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10217 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10218 return; 10219 10220 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10221 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10222 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10223 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10224 << LHSArgDecl; 10225 } 10226 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10227 QualType ArrayElemTy = ArrayTy->getElementType(); 10228 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10229 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10230 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10231 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10232 return; 10233 S.Diag(Loc, diag::warn_division_sizeof_array) 10234 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10235 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10236 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10237 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10238 << LHSArgDecl; 10239 } 10240 10241 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10242 } 10243 } 10244 10245 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10246 ExprResult &RHS, 10247 SourceLocation Loc, bool IsDiv) { 10248 // Check for division/remainder by zero. 10249 Expr::EvalResult RHSValue; 10250 if (!RHS.get()->isValueDependent() && 10251 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10252 RHSValue.Val.getInt() == 0) 10253 S.DiagRuntimeBehavior(Loc, RHS.get(), 10254 S.PDiag(diag::warn_remainder_division_by_zero) 10255 << IsDiv << RHS.get()->getSourceRange()); 10256 } 10257 10258 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10259 SourceLocation Loc, 10260 bool IsCompAssign, bool IsDiv) { 10261 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10262 10263 QualType LHSTy = LHS.get()->getType(); 10264 QualType RHSTy = RHS.get()->getType(); 10265 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10266 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10267 /*AllowBothBool*/getLangOpts().AltiVec, 10268 /*AllowBoolConversions*/false); 10269 if (!IsDiv && 10270 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10271 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10272 // For division, only matrix-by-scalar is supported. Other combinations with 10273 // matrix types are invalid. 10274 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10275 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10276 10277 QualType compType = UsualArithmeticConversions( 10278 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10279 if (LHS.isInvalid() || RHS.isInvalid()) 10280 return QualType(); 10281 10282 10283 if (compType.isNull() || !compType->isArithmeticType()) 10284 return InvalidOperands(Loc, LHS, RHS); 10285 if (IsDiv) { 10286 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10287 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10288 } 10289 return compType; 10290 } 10291 10292 QualType Sema::CheckRemainderOperands( 10293 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10294 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10295 10296 if (LHS.get()->getType()->isVectorType() || 10297 RHS.get()->getType()->isVectorType()) { 10298 if (LHS.get()->getType()->hasIntegerRepresentation() && 10299 RHS.get()->getType()->hasIntegerRepresentation()) 10300 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10301 /*AllowBothBool*/getLangOpts().AltiVec, 10302 /*AllowBoolConversions*/false); 10303 return InvalidOperands(Loc, LHS, RHS); 10304 } 10305 10306 QualType compType = UsualArithmeticConversions( 10307 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10308 if (LHS.isInvalid() || RHS.isInvalid()) 10309 return QualType(); 10310 10311 if (compType.isNull() || !compType->isIntegerType()) 10312 return InvalidOperands(Loc, LHS, RHS); 10313 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10314 return compType; 10315 } 10316 10317 /// Diagnose invalid arithmetic on two void pointers. 10318 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10319 Expr *LHSExpr, Expr *RHSExpr) { 10320 S.Diag(Loc, S.getLangOpts().CPlusPlus 10321 ? diag::err_typecheck_pointer_arith_void_type 10322 : diag::ext_gnu_void_ptr) 10323 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10324 << RHSExpr->getSourceRange(); 10325 } 10326 10327 /// Diagnose invalid arithmetic on a void pointer. 10328 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10329 Expr *Pointer) { 10330 S.Diag(Loc, S.getLangOpts().CPlusPlus 10331 ? diag::err_typecheck_pointer_arith_void_type 10332 : diag::ext_gnu_void_ptr) 10333 << 0 /* one pointer */ << Pointer->getSourceRange(); 10334 } 10335 10336 /// Diagnose invalid arithmetic on a null pointer. 10337 /// 10338 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10339 /// idiom, which we recognize as a GNU extension. 10340 /// 10341 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10342 Expr *Pointer, bool IsGNUIdiom) { 10343 if (IsGNUIdiom) 10344 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10345 << Pointer->getSourceRange(); 10346 else 10347 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10348 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10349 } 10350 10351 /// Diagnose invalid arithmetic on two function pointers. 10352 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10353 Expr *LHS, Expr *RHS) { 10354 assert(LHS->getType()->isAnyPointerType()); 10355 assert(RHS->getType()->isAnyPointerType()); 10356 S.Diag(Loc, S.getLangOpts().CPlusPlus 10357 ? diag::err_typecheck_pointer_arith_function_type 10358 : diag::ext_gnu_ptr_func_arith) 10359 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10360 // We only show the second type if it differs from the first. 10361 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10362 RHS->getType()) 10363 << RHS->getType()->getPointeeType() 10364 << LHS->getSourceRange() << RHS->getSourceRange(); 10365 } 10366 10367 /// Diagnose invalid arithmetic on a function pointer. 10368 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10369 Expr *Pointer) { 10370 assert(Pointer->getType()->isAnyPointerType()); 10371 S.Diag(Loc, S.getLangOpts().CPlusPlus 10372 ? diag::err_typecheck_pointer_arith_function_type 10373 : diag::ext_gnu_ptr_func_arith) 10374 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10375 << 0 /* one pointer, so only one type */ 10376 << Pointer->getSourceRange(); 10377 } 10378 10379 /// Emit error if Operand is incomplete pointer type 10380 /// 10381 /// \returns True if pointer has incomplete type 10382 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10383 Expr *Operand) { 10384 QualType ResType = Operand->getType(); 10385 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10386 ResType = ResAtomicType->getValueType(); 10387 10388 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10389 QualType PointeeTy = ResType->getPointeeType(); 10390 return S.RequireCompleteSizedType( 10391 Loc, PointeeTy, 10392 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10393 Operand->getSourceRange()); 10394 } 10395 10396 /// Check the validity of an arithmetic pointer operand. 10397 /// 10398 /// If the operand has pointer type, this code will check for pointer types 10399 /// which are invalid in arithmetic operations. These will be diagnosed 10400 /// appropriately, including whether or not the use is supported as an 10401 /// extension. 10402 /// 10403 /// \returns True when the operand is valid to use (even if as an extension). 10404 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10405 Expr *Operand) { 10406 QualType ResType = Operand->getType(); 10407 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10408 ResType = ResAtomicType->getValueType(); 10409 10410 if (!ResType->isAnyPointerType()) return true; 10411 10412 QualType PointeeTy = ResType->getPointeeType(); 10413 if (PointeeTy->isVoidType()) { 10414 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10415 return !S.getLangOpts().CPlusPlus; 10416 } 10417 if (PointeeTy->isFunctionType()) { 10418 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10419 return !S.getLangOpts().CPlusPlus; 10420 } 10421 10422 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10423 10424 return true; 10425 } 10426 10427 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10428 /// operands. 10429 /// 10430 /// This routine will diagnose any invalid arithmetic on pointer operands much 10431 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10432 /// for emitting a single diagnostic even for operations where both LHS and RHS 10433 /// are (potentially problematic) pointers. 10434 /// 10435 /// \returns True when the operand is valid to use (even if as an extension). 10436 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10437 Expr *LHSExpr, Expr *RHSExpr) { 10438 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10439 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10440 if (!isLHSPointer && !isRHSPointer) return true; 10441 10442 QualType LHSPointeeTy, RHSPointeeTy; 10443 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10444 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10445 10446 // if both are pointers check if operation is valid wrt address spaces 10447 if (isLHSPointer && isRHSPointer) { 10448 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10449 S.Diag(Loc, 10450 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10451 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10452 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10453 return false; 10454 } 10455 } 10456 10457 // Check for arithmetic on pointers to incomplete types. 10458 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10459 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10460 if (isLHSVoidPtr || isRHSVoidPtr) { 10461 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10462 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10463 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10464 10465 return !S.getLangOpts().CPlusPlus; 10466 } 10467 10468 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10469 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10470 if (isLHSFuncPtr || isRHSFuncPtr) { 10471 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10472 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10473 RHSExpr); 10474 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10475 10476 return !S.getLangOpts().CPlusPlus; 10477 } 10478 10479 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10480 return false; 10481 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10482 return false; 10483 10484 return true; 10485 } 10486 10487 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10488 /// literal. 10489 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10490 Expr *LHSExpr, Expr *RHSExpr) { 10491 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10492 Expr* IndexExpr = RHSExpr; 10493 if (!StrExpr) { 10494 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10495 IndexExpr = LHSExpr; 10496 } 10497 10498 bool IsStringPlusInt = StrExpr && 10499 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10500 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10501 return; 10502 10503 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10504 Self.Diag(OpLoc, diag::warn_string_plus_int) 10505 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10506 10507 // Only print a fixit for "str" + int, not for int + "str". 10508 if (IndexExpr == RHSExpr) { 10509 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10510 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10511 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10512 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10513 << FixItHint::CreateInsertion(EndLoc, "]"); 10514 } else 10515 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10516 } 10517 10518 /// Emit a warning when adding a char literal to a string. 10519 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10520 Expr *LHSExpr, Expr *RHSExpr) { 10521 const Expr *StringRefExpr = LHSExpr; 10522 const CharacterLiteral *CharExpr = 10523 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10524 10525 if (!CharExpr) { 10526 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10527 StringRefExpr = RHSExpr; 10528 } 10529 10530 if (!CharExpr || !StringRefExpr) 10531 return; 10532 10533 const QualType StringType = StringRefExpr->getType(); 10534 10535 // Return if not a PointerType. 10536 if (!StringType->isAnyPointerType()) 10537 return; 10538 10539 // Return if not a CharacterType. 10540 if (!StringType->getPointeeType()->isAnyCharacterType()) 10541 return; 10542 10543 ASTContext &Ctx = Self.getASTContext(); 10544 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10545 10546 const QualType CharType = CharExpr->getType(); 10547 if (!CharType->isAnyCharacterType() && 10548 CharType->isIntegerType() && 10549 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10550 Self.Diag(OpLoc, diag::warn_string_plus_char) 10551 << DiagRange << Ctx.CharTy; 10552 } else { 10553 Self.Diag(OpLoc, diag::warn_string_plus_char) 10554 << DiagRange << CharExpr->getType(); 10555 } 10556 10557 // Only print a fixit for str + char, not for char + str. 10558 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10559 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10560 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10561 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10562 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10563 << FixItHint::CreateInsertion(EndLoc, "]"); 10564 } else { 10565 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10566 } 10567 } 10568 10569 /// Emit error when two pointers are incompatible. 10570 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10571 Expr *LHSExpr, Expr *RHSExpr) { 10572 assert(LHSExpr->getType()->isAnyPointerType()); 10573 assert(RHSExpr->getType()->isAnyPointerType()); 10574 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10575 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10576 << RHSExpr->getSourceRange(); 10577 } 10578 10579 // C99 6.5.6 10580 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10581 SourceLocation Loc, BinaryOperatorKind Opc, 10582 QualType* CompLHSTy) { 10583 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10584 10585 if (LHS.get()->getType()->isVectorType() || 10586 RHS.get()->getType()->isVectorType()) { 10587 QualType compType = CheckVectorOperands( 10588 LHS, RHS, Loc, CompLHSTy, 10589 /*AllowBothBool*/getLangOpts().AltiVec, 10590 /*AllowBoolConversions*/getLangOpts().ZVector); 10591 if (CompLHSTy) *CompLHSTy = compType; 10592 return compType; 10593 } 10594 10595 if (LHS.get()->getType()->isConstantMatrixType() || 10596 RHS.get()->getType()->isConstantMatrixType()) { 10597 QualType compType = 10598 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10599 if (CompLHSTy) 10600 *CompLHSTy = compType; 10601 return compType; 10602 } 10603 10604 QualType compType = UsualArithmeticConversions( 10605 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10606 if (LHS.isInvalid() || RHS.isInvalid()) 10607 return QualType(); 10608 10609 // Diagnose "string literal" '+' int and string '+' "char literal". 10610 if (Opc == BO_Add) { 10611 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10612 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10613 } 10614 10615 // handle the common case first (both operands are arithmetic). 10616 if (!compType.isNull() && compType->isArithmeticType()) { 10617 if (CompLHSTy) *CompLHSTy = compType; 10618 return compType; 10619 } 10620 10621 // Type-checking. Ultimately the pointer's going to be in PExp; 10622 // note that we bias towards the LHS being the pointer. 10623 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10624 10625 bool isObjCPointer; 10626 if (PExp->getType()->isPointerType()) { 10627 isObjCPointer = false; 10628 } else if (PExp->getType()->isObjCObjectPointerType()) { 10629 isObjCPointer = true; 10630 } else { 10631 std::swap(PExp, IExp); 10632 if (PExp->getType()->isPointerType()) { 10633 isObjCPointer = false; 10634 } else if (PExp->getType()->isObjCObjectPointerType()) { 10635 isObjCPointer = true; 10636 } else { 10637 return InvalidOperands(Loc, LHS, RHS); 10638 } 10639 } 10640 assert(PExp->getType()->isAnyPointerType()); 10641 10642 if (!IExp->getType()->isIntegerType()) 10643 return InvalidOperands(Loc, LHS, RHS); 10644 10645 // Adding to a null pointer results in undefined behavior. 10646 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10647 Context, Expr::NPC_ValueDependentIsNotNull)) { 10648 // In C++ adding zero to a null pointer is defined. 10649 Expr::EvalResult KnownVal; 10650 if (!getLangOpts().CPlusPlus || 10651 (!IExp->isValueDependent() && 10652 (!IExp->EvaluateAsInt(KnownVal, Context) || 10653 KnownVal.Val.getInt() != 0))) { 10654 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10655 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10656 Context, BO_Add, PExp, IExp); 10657 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10658 } 10659 } 10660 10661 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10662 return QualType(); 10663 10664 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10665 return QualType(); 10666 10667 // Check array bounds for pointer arithemtic 10668 CheckArrayAccess(PExp, IExp); 10669 10670 if (CompLHSTy) { 10671 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10672 if (LHSTy.isNull()) { 10673 LHSTy = LHS.get()->getType(); 10674 if (LHSTy->isPromotableIntegerType()) 10675 LHSTy = Context.getPromotedIntegerType(LHSTy); 10676 } 10677 *CompLHSTy = LHSTy; 10678 } 10679 10680 return PExp->getType(); 10681 } 10682 10683 // C99 6.5.6 10684 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10685 SourceLocation Loc, 10686 QualType* CompLHSTy) { 10687 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10688 10689 if (LHS.get()->getType()->isVectorType() || 10690 RHS.get()->getType()->isVectorType()) { 10691 QualType compType = CheckVectorOperands( 10692 LHS, RHS, Loc, CompLHSTy, 10693 /*AllowBothBool*/getLangOpts().AltiVec, 10694 /*AllowBoolConversions*/getLangOpts().ZVector); 10695 if (CompLHSTy) *CompLHSTy = compType; 10696 return compType; 10697 } 10698 10699 if (LHS.get()->getType()->isConstantMatrixType() || 10700 RHS.get()->getType()->isConstantMatrixType()) { 10701 QualType compType = 10702 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10703 if (CompLHSTy) 10704 *CompLHSTy = compType; 10705 return compType; 10706 } 10707 10708 QualType compType = UsualArithmeticConversions( 10709 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10710 if (LHS.isInvalid() || RHS.isInvalid()) 10711 return QualType(); 10712 10713 // Enforce type constraints: C99 6.5.6p3. 10714 10715 // Handle the common case first (both operands are arithmetic). 10716 if (!compType.isNull() && compType->isArithmeticType()) { 10717 if (CompLHSTy) *CompLHSTy = compType; 10718 return compType; 10719 } 10720 10721 // Either ptr - int or ptr - ptr. 10722 if (LHS.get()->getType()->isAnyPointerType()) { 10723 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10724 10725 // Diagnose bad cases where we step over interface counts. 10726 if (LHS.get()->getType()->isObjCObjectPointerType() && 10727 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10728 return QualType(); 10729 10730 // The result type of a pointer-int computation is the pointer type. 10731 if (RHS.get()->getType()->isIntegerType()) { 10732 // Subtracting from a null pointer should produce a warning. 10733 // The last argument to the diagnose call says this doesn't match the 10734 // GNU int-to-pointer idiom. 10735 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10736 Expr::NPC_ValueDependentIsNotNull)) { 10737 // In C++ adding zero to a null pointer is defined. 10738 Expr::EvalResult KnownVal; 10739 if (!getLangOpts().CPlusPlus || 10740 (!RHS.get()->isValueDependent() && 10741 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10742 KnownVal.Val.getInt() != 0))) { 10743 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10744 } 10745 } 10746 10747 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10748 return QualType(); 10749 10750 // Check array bounds for pointer arithemtic 10751 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10752 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10753 10754 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10755 return LHS.get()->getType(); 10756 } 10757 10758 // Handle pointer-pointer subtractions. 10759 if (const PointerType *RHSPTy 10760 = RHS.get()->getType()->getAs<PointerType>()) { 10761 QualType rpointee = RHSPTy->getPointeeType(); 10762 10763 if (getLangOpts().CPlusPlus) { 10764 // Pointee types must be the same: C++ [expr.add] 10765 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10766 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10767 } 10768 } else { 10769 // Pointee types must be compatible C99 6.5.6p3 10770 if (!Context.typesAreCompatible( 10771 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10772 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10773 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10774 return QualType(); 10775 } 10776 } 10777 10778 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10779 LHS.get(), RHS.get())) 10780 return QualType(); 10781 10782 // FIXME: Add warnings for nullptr - ptr. 10783 10784 // The pointee type may have zero size. As an extension, a structure or 10785 // union may have zero size or an array may have zero length. In this 10786 // case subtraction does not make sense. 10787 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10788 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10789 if (ElementSize.isZero()) { 10790 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10791 << rpointee.getUnqualifiedType() 10792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10793 } 10794 } 10795 10796 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10797 return Context.getPointerDiffType(); 10798 } 10799 } 10800 10801 return InvalidOperands(Loc, LHS, RHS); 10802 } 10803 10804 static bool isScopedEnumerationType(QualType T) { 10805 if (const EnumType *ET = T->getAs<EnumType>()) 10806 return ET->getDecl()->isScoped(); 10807 return false; 10808 } 10809 10810 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10811 SourceLocation Loc, BinaryOperatorKind Opc, 10812 QualType LHSType) { 10813 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10814 // so skip remaining warnings as we don't want to modify values within Sema. 10815 if (S.getLangOpts().OpenCL) 10816 return; 10817 10818 // Check right/shifter operand 10819 Expr::EvalResult RHSResult; 10820 if (RHS.get()->isValueDependent() || 10821 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10822 return; 10823 llvm::APSInt Right = RHSResult.Val.getInt(); 10824 10825 if (Right.isNegative()) { 10826 S.DiagRuntimeBehavior(Loc, RHS.get(), 10827 S.PDiag(diag::warn_shift_negative) 10828 << RHS.get()->getSourceRange()); 10829 return; 10830 } 10831 10832 QualType LHSExprType = LHS.get()->getType(); 10833 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10834 if (LHSExprType->isExtIntType()) 10835 LeftSize = S.Context.getIntWidth(LHSExprType); 10836 else if (LHSExprType->isFixedPointType()) { 10837 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10838 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10839 } 10840 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10841 if (Right.uge(LeftBits)) { 10842 S.DiagRuntimeBehavior(Loc, RHS.get(), 10843 S.PDiag(diag::warn_shift_gt_typewidth) 10844 << RHS.get()->getSourceRange()); 10845 return; 10846 } 10847 10848 // FIXME: We probably need to handle fixed point types specially here. 10849 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10850 return; 10851 10852 // When left shifting an ICE which is signed, we can check for overflow which 10853 // according to C++ standards prior to C++2a has undefined behavior 10854 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10855 // more than the maximum value representable in the result type, so never 10856 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10857 // expression is still probably a bug.) 10858 Expr::EvalResult LHSResult; 10859 if (LHS.get()->isValueDependent() || 10860 LHSType->hasUnsignedIntegerRepresentation() || 10861 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10862 return; 10863 llvm::APSInt Left = LHSResult.Val.getInt(); 10864 10865 // If LHS does not have a signed type and non-negative value 10866 // then, the behavior is undefined before C++2a. Warn about it. 10867 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10868 !S.getLangOpts().CPlusPlus20) { 10869 S.DiagRuntimeBehavior(Loc, LHS.get(), 10870 S.PDiag(diag::warn_shift_lhs_negative) 10871 << LHS.get()->getSourceRange()); 10872 return; 10873 } 10874 10875 llvm::APInt ResultBits = 10876 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10877 if (LeftBits.uge(ResultBits)) 10878 return; 10879 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10880 Result = Result.shl(Right); 10881 10882 // Print the bit representation of the signed integer as an unsigned 10883 // hexadecimal number. 10884 SmallString<40> HexResult; 10885 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10886 10887 // If we are only missing a sign bit, this is less likely to result in actual 10888 // bugs -- if the result is cast back to an unsigned type, it will have the 10889 // expected value. Thus we place this behind a different warning that can be 10890 // turned off separately if needed. 10891 if (LeftBits == ResultBits - 1) { 10892 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10893 << HexResult << LHSType 10894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10895 return; 10896 } 10897 10898 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10899 << HexResult.str() << Result.getMinSignedBits() << LHSType 10900 << Left.getBitWidth() << LHS.get()->getSourceRange() 10901 << RHS.get()->getSourceRange(); 10902 } 10903 10904 /// Return the resulting type when a vector is shifted 10905 /// by a scalar or vector shift amount. 10906 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10907 SourceLocation Loc, bool IsCompAssign) { 10908 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10909 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10910 !LHS.get()->getType()->isVectorType()) { 10911 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10912 << RHS.get()->getType() << LHS.get()->getType() 10913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10914 return QualType(); 10915 } 10916 10917 if (!IsCompAssign) { 10918 LHS = S.UsualUnaryConversions(LHS.get()); 10919 if (LHS.isInvalid()) return QualType(); 10920 } 10921 10922 RHS = S.UsualUnaryConversions(RHS.get()); 10923 if (RHS.isInvalid()) return QualType(); 10924 10925 QualType LHSType = LHS.get()->getType(); 10926 // Note that LHS might be a scalar because the routine calls not only in 10927 // OpenCL case. 10928 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10929 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10930 10931 // Note that RHS might not be a vector. 10932 QualType RHSType = RHS.get()->getType(); 10933 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10934 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10935 10936 // The operands need to be integers. 10937 if (!LHSEleType->isIntegerType()) { 10938 S.Diag(Loc, diag::err_typecheck_expect_int) 10939 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10940 return QualType(); 10941 } 10942 10943 if (!RHSEleType->isIntegerType()) { 10944 S.Diag(Loc, diag::err_typecheck_expect_int) 10945 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10946 return QualType(); 10947 } 10948 10949 if (!LHSVecTy) { 10950 assert(RHSVecTy); 10951 if (IsCompAssign) 10952 return RHSType; 10953 if (LHSEleType != RHSEleType) { 10954 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10955 LHSEleType = RHSEleType; 10956 } 10957 QualType VecTy = 10958 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10959 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10960 LHSType = VecTy; 10961 } else if (RHSVecTy) { 10962 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10963 // are applied component-wise. So if RHS is a vector, then ensure 10964 // that the number of elements is the same as LHS... 10965 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10966 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10967 << LHS.get()->getType() << RHS.get()->getType() 10968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10969 return QualType(); 10970 } 10971 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10972 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10973 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10974 if (LHSBT != RHSBT && 10975 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10976 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10977 << LHS.get()->getType() << RHS.get()->getType() 10978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10979 } 10980 } 10981 } else { 10982 // ...else expand RHS to match the number of elements in LHS. 10983 QualType VecTy = 10984 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10985 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10986 } 10987 10988 return LHSType; 10989 } 10990 10991 // C99 6.5.7 10992 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10993 SourceLocation Loc, BinaryOperatorKind Opc, 10994 bool IsCompAssign) { 10995 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10996 10997 // Vector shifts promote their scalar inputs to vector type. 10998 if (LHS.get()->getType()->isVectorType() || 10999 RHS.get()->getType()->isVectorType()) { 11000 if (LangOpts.ZVector) { 11001 // The shift operators for the z vector extensions work basically 11002 // like general shifts, except that neither the LHS nor the RHS is 11003 // allowed to be a "vector bool". 11004 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11005 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11006 return InvalidOperands(Loc, LHS, RHS); 11007 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11008 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11009 return InvalidOperands(Loc, LHS, RHS); 11010 } 11011 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11012 } 11013 11014 // Shifts don't perform usual arithmetic conversions, they just do integer 11015 // promotions on each operand. C99 6.5.7p3 11016 11017 // For the LHS, do usual unary conversions, but then reset them away 11018 // if this is a compound assignment. 11019 ExprResult OldLHS = LHS; 11020 LHS = UsualUnaryConversions(LHS.get()); 11021 if (LHS.isInvalid()) 11022 return QualType(); 11023 QualType LHSType = LHS.get()->getType(); 11024 if (IsCompAssign) LHS = OldLHS; 11025 11026 // The RHS is simpler. 11027 RHS = UsualUnaryConversions(RHS.get()); 11028 if (RHS.isInvalid()) 11029 return QualType(); 11030 QualType RHSType = RHS.get()->getType(); 11031 11032 // C99 6.5.7p2: Each of the operands shall have integer type. 11033 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11034 if ((!LHSType->isFixedPointOrIntegerType() && 11035 !LHSType->hasIntegerRepresentation()) || 11036 !RHSType->hasIntegerRepresentation()) 11037 return InvalidOperands(Loc, LHS, RHS); 11038 11039 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11040 // hasIntegerRepresentation() above instead of this. 11041 if (isScopedEnumerationType(LHSType) || 11042 isScopedEnumerationType(RHSType)) { 11043 return InvalidOperands(Loc, LHS, RHS); 11044 } 11045 // Sanity-check shift operands 11046 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11047 11048 // "The type of the result is that of the promoted left operand." 11049 return LHSType; 11050 } 11051 11052 /// Diagnose bad pointer comparisons. 11053 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11054 ExprResult &LHS, ExprResult &RHS, 11055 bool IsError) { 11056 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11057 : diag::ext_typecheck_comparison_of_distinct_pointers) 11058 << LHS.get()->getType() << RHS.get()->getType() 11059 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11060 } 11061 11062 /// Returns false if the pointers are converted to a composite type, 11063 /// true otherwise. 11064 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11065 ExprResult &LHS, ExprResult &RHS) { 11066 // C++ [expr.rel]p2: 11067 // [...] Pointer conversions (4.10) and qualification 11068 // conversions (4.4) are performed on pointer operands (or on 11069 // a pointer operand and a null pointer constant) to bring 11070 // them to their composite pointer type. [...] 11071 // 11072 // C++ [expr.eq]p1 uses the same notion for (in)equality 11073 // comparisons of pointers. 11074 11075 QualType LHSType = LHS.get()->getType(); 11076 QualType RHSType = RHS.get()->getType(); 11077 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11078 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11079 11080 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11081 if (T.isNull()) { 11082 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11083 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11084 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11085 else 11086 S.InvalidOperands(Loc, LHS, RHS); 11087 return true; 11088 } 11089 11090 return false; 11091 } 11092 11093 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11094 ExprResult &LHS, 11095 ExprResult &RHS, 11096 bool IsError) { 11097 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11098 : diag::ext_typecheck_comparison_of_fptr_to_void) 11099 << LHS.get()->getType() << RHS.get()->getType() 11100 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11101 } 11102 11103 static bool isObjCObjectLiteral(ExprResult &E) { 11104 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11105 case Stmt::ObjCArrayLiteralClass: 11106 case Stmt::ObjCDictionaryLiteralClass: 11107 case Stmt::ObjCStringLiteralClass: 11108 case Stmt::ObjCBoxedExprClass: 11109 return true; 11110 default: 11111 // Note that ObjCBoolLiteral is NOT an object literal! 11112 return false; 11113 } 11114 } 11115 11116 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11117 const ObjCObjectPointerType *Type = 11118 LHS->getType()->getAs<ObjCObjectPointerType>(); 11119 11120 // If this is not actually an Objective-C object, bail out. 11121 if (!Type) 11122 return false; 11123 11124 // Get the LHS object's interface type. 11125 QualType InterfaceType = Type->getPointeeType(); 11126 11127 // If the RHS isn't an Objective-C object, bail out. 11128 if (!RHS->getType()->isObjCObjectPointerType()) 11129 return false; 11130 11131 // Try to find the -isEqual: method. 11132 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11133 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11134 InterfaceType, 11135 /*IsInstance=*/true); 11136 if (!Method) { 11137 if (Type->isObjCIdType()) { 11138 // For 'id', just check the global pool. 11139 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11140 /*receiverId=*/true); 11141 } else { 11142 // Check protocols. 11143 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11144 /*IsInstance=*/true); 11145 } 11146 } 11147 11148 if (!Method) 11149 return false; 11150 11151 QualType T = Method->parameters()[0]->getType(); 11152 if (!T->isObjCObjectPointerType()) 11153 return false; 11154 11155 QualType R = Method->getReturnType(); 11156 if (!R->isScalarType()) 11157 return false; 11158 11159 return true; 11160 } 11161 11162 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11163 FromE = FromE->IgnoreParenImpCasts(); 11164 switch (FromE->getStmtClass()) { 11165 default: 11166 break; 11167 case Stmt::ObjCStringLiteralClass: 11168 // "string literal" 11169 return LK_String; 11170 case Stmt::ObjCArrayLiteralClass: 11171 // "array literal" 11172 return LK_Array; 11173 case Stmt::ObjCDictionaryLiteralClass: 11174 // "dictionary literal" 11175 return LK_Dictionary; 11176 case Stmt::BlockExprClass: 11177 return LK_Block; 11178 case Stmt::ObjCBoxedExprClass: { 11179 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11180 switch (Inner->getStmtClass()) { 11181 case Stmt::IntegerLiteralClass: 11182 case Stmt::FloatingLiteralClass: 11183 case Stmt::CharacterLiteralClass: 11184 case Stmt::ObjCBoolLiteralExprClass: 11185 case Stmt::CXXBoolLiteralExprClass: 11186 // "numeric literal" 11187 return LK_Numeric; 11188 case Stmt::ImplicitCastExprClass: { 11189 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11190 // Boolean literals can be represented by implicit casts. 11191 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11192 return LK_Numeric; 11193 break; 11194 } 11195 default: 11196 break; 11197 } 11198 return LK_Boxed; 11199 } 11200 } 11201 return LK_None; 11202 } 11203 11204 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11205 ExprResult &LHS, ExprResult &RHS, 11206 BinaryOperator::Opcode Opc){ 11207 Expr *Literal; 11208 Expr *Other; 11209 if (isObjCObjectLiteral(LHS)) { 11210 Literal = LHS.get(); 11211 Other = RHS.get(); 11212 } else { 11213 Literal = RHS.get(); 11214 Other = LHS.get(); 11215 } 11216 11217 // Don't warn on comparisons against nil. 11218 Other = Other->IgnoreParenCasts(); 11219 if (Other->isNullPointerConstant(S.getASTContext(), 11220 Expr::NPC_ValueDependentIsNotNull)) 11221 return; 11222 11223 // This should be kept in sync with warn_objc_literal_comparison. 11224 // LK_String should always be after the other literals, since it has its own 11225 // warning flag. 11226 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11227 assert(LiteralKind != Sema::LK_Block); 11228 if (LiteralKind == Sema::LK_None) { 11229 llvm_unreachable("Unknown Objective-C object literal kind"); 11230 } 11231 11232 if (LiteralKind == Sema::LK_String) 11233 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11234 << Literal->getSourceRange(); 11235 else 11236 S.Diag(Loc, diag::warn_objc_literal_comparison) 11237 << LiteralKind << Literal->getSourceRange(); 11238 11239 if (BinaryOperator::isEqualityOp(Opc) && 11240 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11241 SourceLocation Start = LHS.get()->getBeginLoc(); 11242 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11243 CharSourceRange OpRange = 11244 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11245 11246 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11247 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11248 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11249 << FixItHint::CreateInsertion(End, "]"); 11250 } 11251 } 11252 11253 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11254 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11255 ExprResult &RHS, SourceLocation Loc, 11256 BinaryOperatorKind Opc) { 11257 // Check that left hand side is !something. 11258 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11259 if (!UO || UO->getOpcode() != UO_LNot) return; 11260 11261 // Only check if the right hand side is non-bool arithmetic type. 11262 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11263 11264 // Make sure that the something in !something is not bool. 11265 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11266 if (SubExpr->isKnownToHaveBooleanValue()) return; 11267 11268 // Emit warning. 11269 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11270 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11271 << Loc << IsBitwiseOp; 11272 11273 // First note suggest !(x < y) 11274 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11275 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11276 FirstClose = S.getLocForEndOfToken(FirstClose); 11277 if (FirstClose.isInvalid()) 11278 FirstOpen = SourceLocation(); 11279 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11280 << IsBitwiseOp 11281 << FixItHint::CreateInsertion(FirstOpen, "(") 11282 << FixItHint::CreateInsertion(FirstClose, ")"); 11283 11284 // Second note suggests (!x) < y 11285 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11286 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11287 SecondClose = S.getLocForEndOfToken(SecondClose); 11288 if (SecondClose.isInvalid()) 11289 SecondOpen = SourceLocation(); 11290 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11291 << FixItHint::CreateInsertion(SecondOpen, "(") 11292 << FixItHint::CreateInsertion(SecondClose, ")"); 11293 } 11294 11295 // Returns true if E refers to a non-weak array. 11296 static bool checkForArray(const Expr *E) { 11297 const ValueDecl *D = nullptr; 11298 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11299 D = DR->getDecl(); 11300 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11301 if (Mem->isImplicitAccess()) 11302 D = Mem->getMemberDecl(); 11303 } 11304 if (!D) 11305 return false; 11306 return D->getType()->isArrayType() && !D->isWeak(); 11307 } 11308 11309 /// Diagnose some forms of syntactically-obvious tautological comparison. 11310 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11311 Expr *LHS, Expr *RHS, 11312 BinaryOperatorKind Opc) { 11313 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11314 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11315 11316 QualType LHSType = LHS->getType(); 11317 QualType RHSType = RHS->getType(); 11318 if (LHSType->hasFloatingRepresentation() || 11319 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11320 S.inTemplateInstantiation()) 11321 return; 11322 11323 // Comparisons between two array types are ill-formed for operator<=>, so 11324 // we shouldn't emit any additional warnings about it. 11325 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11326 return; 11327 11328 // For non-floating point types, check for self-comparisons of the form 11329 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11330 // often indicate logic errors in the program. 11331 // 11332 // NOTE: Don't warn about comparison expressions resulting from macro 11333 // expansion. Also don't warn about comparisons which are only self 11334 // comparisons within a template instantiation. The warnings should catch 11335 // obvious cases in the definition of the template anyways. The idea is to 11336 // warn when the typed comparison operator will always evaluate to the same 11337 // result. 11338 11339 // Used for indexing into %select in warn_comparison_always 11340 enum { 11341 AlwaysConstant, 11342 AlwaysTrue, 11343 AlwaysFalse, 11344 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11345 }; 11346 11347 // C++2a [depr.array.comp]: 11348 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11349 // operands of array type are deprecated. 11350 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11351 RHSStripped->getType()->isArrayType()) { 11352 S.Diag(Loc, diag::warn_depr_array_comparison) 11353 << LHS->getSourceRange() << RHS->getSourceRange() 11354 << LHSStripped->getType() << RHSStripped->getType(); 11355 // Carry on to produce the tautological comparison warning, if this 11356 // expression is potentially-evaluated, we can resolve the array to a 11357 // non-weak declaration, and so on. 11358 } 11359 11360 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11361 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11362 unsigned Result; 11363 switch (Opc) { 11364 case BO_EQ: 11365 case BO_LE: 11366 case BO_GE: 11367 Result = AlwaysTrue; 11368 break; 11369 case BO_NE: 11370 case BO_LT: 11371 case BO_GT: 11372 Result = AlwaysFalse; 11373 break; 11374 case BO_Cmp: 11375 Result = AlwaysEqual; 11376 break; 11377 default: 11378 Result = AlwaysConstant; 11379 break; 11380 } 11381 S.DiagRuntimeBehavior(Loc, nullptr, 11382 S.PDiag(diag::warn_comparison_always) 11383 << 0 /*self-comparison*/ 11384 << Result); 11385 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11386 // What is it always going to evaluate to? 11387 unsigned Result; 11388 switch (Opc) { 11389 case BO_EQ: // e.g. array1 == array2 11390 Result = AlwaysFalse; 11391 break; 11392 case BO_NE: // e.g. array1 != array2 11393 Result = AlwaysTrue; 11394 break; 11395 default: // e.g. array1 <= array2 11396 // The best we can say is 'a constant' 11397 Result = AlwaysConstant; 11398 break; 11399 } 11400 S.DiagRuntimeBehavior(Loc, nullptr, 11401 S.PDiag(diag::warn_comparison_always) 11402 << 1 /*array comparison*/ 11403 << Result); 11404 } 11405 } 11406 11407 if (isa<CastExpr>(LHSStripped)) 11408 LHSStripped = LHSStripped->IgnoreParenCasts(); 11409 if (isa<CastExpr>(RHSStripped)) 11410 RHSStripped = RHSStripped->IgnoreParenCasts(); 11411 11412 // Warn about comparisons against a string constant (unless the other 11413 // operand is null); the user probably wants string comparison function. 11414 Expr *LiteralString = nullptr; 11415 Expr *LiteralStringStripped = nullptr; 11416 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11417 !RHSStripped->isNullPointerConstant(S.Context, 11418 Expr::NPC_ValueDependentIsNull)) { 11419 LiteralString = LHS; 11420 LiteralStringStripped = LHSStripped; 11421 } else if ((isa<StringLiteral>(RHSStripped) || 11422 isa<ObjCEncodeExpr>(RHSStripped)) && 11423 !LHSStripped->isNullPointerConstant(S.Context, 11424 Expr::NPC_ValueDependentIsNull)) { 11425 LiteralString = RHS; 11426 LiteralStringStripped = RHSStripped; 11427 } 11428 11429 if (LiteralString) { 11430 S.DiagRuntimeBehavior(Loc, nullptr, 11431 S.PDiag(diag::warn_stringcompare) 11432 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11433 << LiteralString->getSourceRange()); 11434 } 11435 } 11436 11437 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11438 switch (CK) { 11439 default: { 11440 #ifndef NDEBUG 11441 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11442 << "\n"; 11443 #endif 11444 llvm_unreachable("unhandled cast kind"); 11445 } 11446 case CK_UserDefinedConversion: 11447 return ICK_Identity; 11448 case CK_LValueToRValue: 11449 return ICK_Lvalue_To_Rvalue; 11450 case CK_ArrayToPointerDecay: 11451 return ICK_Array_To_Pointer; 11452 case CK_FunctionToPointerDecay: 11453 return ICK_Function_To_Pointer; 11454 case CK_IntegralCast: 11455 return ICK_Integral_Conversion; 11456 case CK_FloatingCast: 11457 return ICK_Floating_Conversion; 11458 case CK_IntegralToFloating: 11459 case CK_FloatingToIntegral: 11460 return ICK_Floating_Integral; 11461 case CK_IntegralComplexCast: 11462 case CK_FloatingComplexCast: 11463 case CK_FloatingComplexToIntegralComplex: 11464 case CK_IntegralComplexToFloatingComplex: 11465 return ICK_Complex_Conversion; 11466 case CK_FloatingComplexToReal: 11467 case CK_FloatingRealToComplex: 11468 case CK_IntegralComplexToReal: 11469 case CK_IntegralRealToComplex: 11470 return ICK_Complex_Real; 11471 } 11472 } 11473 11474 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11475 QualType FromType, 11476 SourceLocation Loc) { 11477 // Check for a narrowing implicit conversion. 11478 StandardConversionSequence SCS; 11479 SCS.setAsIdentityConversion(); 11480 SCS.setToType(0, FromType); 11481 SCS.setToType(1, ToType); 11482 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11483 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11484 11485 APValue PreNarrowingValue; 11486 QualType PreNarrowingType; 11487 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11488 PreNarrowingType, 11489 /*IgnoreFloatToIntegralConversion*/ true)) { 11490 case NK_Dependent_Narrowing: 11491 // Implicit conversion to a narrower type, but the expression is 11492 // value-dependent so we can't tell whether it's actually narrowing. 11493 case NK_Not_Narrowing: 11494 return false; 11495 11496 case NK_Constant_Narrowing: 11497 // Implicit conversion to a narrower type, and the value is not a constant 11498 // expression. 11499 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11500 << /*Constant*/ 1 11501 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11502 return true; 11503 11504 case NK_Variable_Narrowing: 11505 // Implicit conversion to a narrower type, and the value is not a constant 11506 // expression. 11507 case NK_Type_Narrowing: 11508 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11509 << /*Constant*/ 0 << FromType << ToType; 11510 // TODO: It's not a constant expression, but what if the user intended it 11511 // to be? Can we produce notes to help them figure out why it isn't? 11512 return true; 11513 } 11514 llvm_unreachable("unhandled case in switch"); 11515 } 11516 11517 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11518 ExprResult &LHS, 11519 ExprResult &RHS, 11520 SourceLocation Loc) { 11521 QualType LHSType = LHS.get()->getType(); 11522 QualType RHSType = RHS.get()->getType(); 11523 // Dig out the original argument type and expression before implicit casts 11524 // were applied. These are the types/expressions we need to check the 11525 // [expr.spaceship] requirements against. 11526 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11527 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11528 QualType LHSStrippedType = LHSStripped.get()->getType(); 11529 QualType RHSStrippedType = RHSStripped.get()->getType(); 11530 11531 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11532 // other is not, the program is ill-formed. 11533 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11534 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11535 return QualType(); 11536 } 11537 11538 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11539 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11540 RHSStrippedType->isEnumeralType(); 11541 if (NumEnumArgs == 1) { 11542 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11543 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11544 if (OtherTy->hasFloatingRepresentation()) { 11545 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11546 return QualType(); 11547 } 11548 } 11549 if (NumEnumArgs == 2) { 11550 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11551 // type E, the operator yields the result of converting the operands 11552 // to the underlying type of E and applying <=> to the converted operands. 11553 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11554 S.InvalidOperands(Loc, LHS, RHS); 11555 return QualType(); 11556 } 11557 QualType IntType = 11558 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11559 assert(IntType->isArithmeticType()); 11560 11561 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11562 // promote the boolean type, and all other promotable integer types, to 11563 // avoid this. 11564 if (IntType->isPromotableIntegerType()) 11565 IntType = S.Context.getPromotedIntegerType(IntType); 11566 11567 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11568 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11569 LHSType = RHSType = IntType; 11570 } 11571 11572 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11573 // usual arithmetic conversions are applied to the operands. 11574 QualType Type = 11575 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11576 if (LHS.isInvalid() || RHS.isInvalid()) 11577 return QualType(); 11578 if (Type.isNull()) 11579 return S.InvalidOperands(Loc, LHS, RHS); 11580 11581 Optional<ComparisonCategoryType> CCT = 11582 getComparisonCategoryForBuiltinCmp(Type); 11583 if (!CCT) 11584 return S.InvalidOperands(Loc, LHS, RHS); 11585 11586 bool HasNarrowing = checkThreeWayNarrowingConversion( 11587 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11588 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11589 RHS.get()->getBeginLoc()); 11590 if (HasNarrowing) 11591 return QualType(); 11592 11593 assert(!Type.isNull() && "composite type for <=> has not been set"); 11594 11595 return S.CheckComparisonCategoryType( 11596 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11597 } 11598 11599 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11600 ExprResult &RHS, 11601 SourceLocation Loc, 11602 BinaryOperatorKind Opc) { 11603 if (Opc == BO_Cmp) 11604 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11605 11606 // C99 6.5.8p3 / C99 6.5.9p4 11607 QualType Type = 11608 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11609 if (LHS.isInvalid() || RHS.isInvalid()) 11610 return QualType(); 11611 if (Type.isNull()) 11612 return S.InvalidOperands(Loc, LHS, RHS); 11613 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11614 11615 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11616 return S.InvalidOperands(Loc, LHS, RHS); 11617 11618 // Check for comparisons of floating point operands using != and ==. 11619 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11620 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11621 11622 // The result of comparisons is 'bool' in C++, 'int' in C. 11623 return S.Context.getLogicalOperationType(); 11624 } 11625 11626 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11627 if (!NullE.get()->getType()->isAnyPointerType()) 11628 return; 11629 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11630 if (!E.get()->getType()->isAnyPointerType() && 11631 E.get()->isNullPointerConstant(Context, 11632 Expr::NPC_ValueDependentIsNotNull) == 11633 Expr::NPCK_ZeroExpression) { 11634 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11635 if (CL->getValue() == 0) 11636 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11637 << NullValue 11638 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11639 NullValue ? "NULL" : "(void *)0"); 11640 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11641 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11642 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11643 if (T == Context.CharTy) 11644 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11645 << NullValue 11646 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11647 NullValue ? "NULL" : "(void *)0"); 11648 } 11649 } 11650 } 11651 11652 // C99 6.5.8, C++ [expr.rel] 11653 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11654 SourceLocation Loc, 11655 BinaryOperatorKind Opc) { 11656 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11657 bool IsThreeWay = Opc == BO_Cmp; 11658 bool IsOrdered = IsRelational || IsThreeWay; 11659 auto IsAnyPointerType = [](ExprResult E) { 11660 QualType Ty = E.get()->getType(); 11661 return Ty->isPointerType() || Ty->isMemberPointerType(); 11662 }; 11663 11664 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11665 // type, array-to-pointer, ..., conversions are performed on both operands to 11666 // bring them to their composite type. 11667 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11668 // any type-related checks. 11669 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11670 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11671 if (LHS.isInvalid()) 11672 return QualType(); 11673 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11674 if (RHS.isInvalid()) 11675 return QualType(); 11676 } else { 11677 LHS = DefaultLvalueConversion(LHS.get()); 11678 if (LHS.isInvalid()) 11679 return QualType(); 11680 RHS = DefaultLvalueConversion(RHS.get()); 11681 if (RHS.isInvalid()) 11682 return QualType(); 11683 } 11684 11685 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11686 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11687 CheckPtrComparisonWithNullChar(LHS, RHS); 11688 CheckPtrComparisonWithNullChar(RHS, LHS); 11689 } 11690 11691 // Handle vector comparisons separately. 11692 if (LHS.get()->getType()->isVectorType() || 11693 RHS.get()->getType()->isVectorType()) 11694 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11695 11696 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11697 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11698 11699 QualType LHSType = LHS.get()->getType(); 11700 QualType RHSType = RHS.get()->getType(); 11701 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11702 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11703 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11704 11705 const Expr::NullPointerConstantKind LHSNullKind = 11706 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11707 const Expr::NullPointerConstantKind RHSNullKind = 11708 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11709 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11710 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11711 11712 auto computeResultTy = [&]() { 11713 if (Opc != BO_Cmp) 11714 return Context.getLogicalOperationType(); 11715 assert(getLangOpts().CPlusPlus); 11716 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11717 11718 QualType CompositeTy = LHS.get()->getType(); 11719 assert(!CompositeTy->isReferenceType()); 11720 11721 Optional<ComparisonCategoryType> CCT = 11722 getComparisonCategoryForBuiltinCmp(CompositeTy); 11723 if (!CCT) 11724 return InvalidOperands(Loc, LHS, RHS); 11725 11726 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11727 // P0946R0: Comparisons between a null pointer constant and an object 11728 // pointer result in std::strong_equality, which is ill-formed under 11729 // P1959R0. 11730 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11731 << (LHSIsNull ? LHS.get()->getSourceRange() 11732 : RHS.get()->getSourceRange()); 11733 return QualType(); 11734 } 11735 11736 return CheckComparisonCategoryType( 11737 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11738 }; 11739 11740 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11741 bool IsEquality = Opc == BO_EQ; 11742 if (RHSIsNull) 11743 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11744 RHS.get()->getSourceRange()); 11745 else 11746 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11747 LHS.get()->getSourceRange()); 11748 } 11749 11750 if ((LHSType->isIntegerType() && !LHSIsNull) || 11751 (RHSType->isIntegerType() && !RHSIsNull)) { 11752 // Skip normal pointer conversion checks in this case; we have better 11753 // diagnostics for this below. 11754 } else if (getLangOpts().CPlusPlus) { 11755 // Equality comparison of a function pointer to a void pointer is invalid, 11756 // but we allow it as an extension. 11757 // FIXME: If we really want to allow this, should it be part of composite 11758 // pointer type computation so it works in conditionals too? 11759 if (!IsOrdered && 11760 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11761 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11762 // This is a gcc extension compatibility comparison. 11763 // In a SFINAE context, we treat this as a hard error to maintain 11764 // conformance with the C++ standard. 11765 diagnoseFunctionPointerToVoidComparison( 11766 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11767 11768 if (isSFINAEContext()) 11769 return QualType(); 11770 11771 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11772 return computeResultTy(); 11773 } 11774 11775 // C++ [expr.eq]p2: 11776 // If at least one operand is a pointer [...] bring them to their 11777 // composite pointer type. 11778 // C++ [expr.spaceship]p6 11779 // If at least one of the operands is of pointer type, [...] bring them 11780 // to their composite pointer type. 11781 // C++ [expr.rel]p2: 11782 // If both operands are pointers, [...] bring them to their composite 11783 // pointer type. 11784 // For <=>, the only valid non-pointer types are arrays and functions, and 11785 // we already decayed those, so this is really the same as the relational 11786 // comparison rule. 11787 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11788 (IsOrdered ? 2 : 1) && 11789 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11790 RHSType->isObjCObjectPointerType()))) { 11791 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11792 return QualType(); 11793 return computeResultTy(); 11794 } 11795 } else if (LHSType->isPointerType() && 11796 RHSType->isPointerType()) { // C99 6.5.8p2 11797 // All of the following pointer-related warnings are GCC extensions, except 11798 // when handling null pointer constants. 11799 QualType LCanPointeeTy = 11800 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11801 QualType RCanPointeeTy = 11802 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11803 11804 // C99 6.5.9p2 and C99 6.5.8p2 11805 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11806 RCanPointeeTy.getUnqualifiedType())) { 11807 if (IsRelational) { 11808 // Pointers both need to point to complete or incomplete types 11809 if ((LCanPointeeTy->isIncompleteType() != 11810 RCanPointeeTy->isIncompleteType()) && 11811 !getLangOpts().C11) { 11812 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11813 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11814 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11815 << RCanPointeeTy->isIncompleteType(); 11816 } 11817 if (LCanPointeeTy->isFunctionType()) { 11818 // Valid unless a relational comparison of function pointers 11819 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11820 << LHSType << RHSType << LHS.get()->getSourceRange() 11821 << RHS.get()->getSourceRange(); 11822 } 11823 } 11824 } else if (!IsRelational && 11825 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11826 // Valid unless comparison between non-null pointer and function pointer 11827 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11828 && !LHSIsNull && !RHSIsNull) 11829 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11830 /*isError*/false); 11831 } else { 11832 // Invalid 11833 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11834 } 11835 if (LCanPointeeTy != RCanPointeeTy) { 11836 // Treat NULL constant as a special case in OpenCL. 11837 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11838 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11839 Diag(Loc, 11840 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11841 << LHSType << RHSType << 0 /* comparison */ 11842 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11843 } 11844 } 11845 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11846 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11847 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11848 : CK_BitCast; 11849 if (LHSIsNull && !RHSIsNull) 11850 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11851 else 11852 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11853 } 11854 return computeResultTy(); 11855 } 11856 11857 if (getLangOpts().CPlusPlus) { 11858 // C++ [expr.eq]p4: 11859 // Two operands of type std::nullptr_t or one operand of type 11860 // std::nullptr_t and the other a null pointer constant compare equal. 11861 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11862 if (LHSType->isNullPtrType()) { 11863 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11864 return computeResultTy(); 11865 } 11866 if (RHSType->isNullPtrType()) { 11867 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11868 return computeResultTy(); 11869 } 11870 } 11871 11872 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11873 // These aren't covered by the composite pointer type rules. 11874 if (!IsOrdered && RHSType->isNullPtrType() && 11875 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11876 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11877 return computeResultTy(); 11878 } 11879 if (!IsOrdered && LHSType->isNullPtrType() && 11880 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11881 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11882 return computeResultTy(); 11883 } 11884 11885 if (IsRelational && 11886 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11887 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11888 // HACK: Relational comparison of nullptr_t against a pointer type is 11889 // invalid per DR583, but we allow it within std::less<> and friends, 11890 // since otherwise common uses of it break. 11891 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11892 // friends to have std::nullptr_t overload candidates. 11893 DeclContext *DC = CurContext; 11894 if (isa<FunctionDecl>(DC)) 11895 DC = DC->getParent(); 11896 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11897 if (CTSD->isInStdNamespace() && 11898 llvm::StringSwitch<bool>(CTSD->getName()) 11899 .Cases("less", "less_equal", "greater", "greater_equal", true) 11900 .Default(false)) { 11901 if (RHSType->isNullPtrType()) 11902 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11903 else 11904 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11905 return computeResultTy(); 11906 } 11907 } 11908 } 11909 11910 // C++ [expr.eq]p2: 11911 // If at least one operand is a pointer to member, [...] bring them to 11912 // their composite pointer type. 11913 if (!IsOrdered && 11914 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11915 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11916 return QualType(); 11917 else 11918 return computeResultTy(); 11919 } 11920 } 11921 11922 // Handle block pointer types. 11923 if (!IsOrdered && LHSType->isBlockPointerType() && 11924 RHSType->isBlockPointerType()) { 11925 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11926 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11927 11928 if (!LHSIsNull && !RHSIsNull && 11929 !Context.typesAreCompatible(lpointee, rpointee)) { 11930 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11931 << LHSType << RHSType << LHS.get()->getSourceRange() 11932 << RHS.get()->getSourceRange(); 11933 } 11934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11935 return computeResultTy(); 11936 } 11937 11938 // Allow block pointers to be compared with null pointer constants. 11939 if (!IsOrdered 11940 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11941 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11942 if (!LHSIsNull && !RHSIsNull) { 11943 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11944 ->getPointeeType()->isVoidType()) 11945 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11946 ->getPointeeType()->isVoidType()))) 11947 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11948 << LHSType << RHSType << LHS.get()->getSourceRange() 11949 << RHS.get()->getSourceRange(); 11950 } 11951 if (LHSIsNull && !RHSIsNull) 11952 LHS = ImpCastExprToType(LHS.get(), RHSType, 11953 RHSType->isPointerType() ? CK_BitCast 11954 : CK_AnyPointerToBlockPointerCast); 11955 else 11956 RHS = ImpCastExprToType(RHS.get(), LHSType, 11957 LHSType->isPointerType() ? CK_BitCast 11958 : CK_AnyPointerToBlockPointerCast); 11959 return computeResultTy(); 11960 } 11961 11962 if (LHSType->isObjCObjectPointerType() || 11963 RHSType->isObjCObjectPointerType()) { 11964 const PointerType *LPT = LHSType->getAs<PointerType>(); 11965 const PointerType *RPT = RHSType->getAs<PointerType>(); 11966 if (LPT || RPT) { 11967 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11968 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11969 11970 if (!LPtrToVoid && !RPtrToVoid && 11971 !Context.typesAreCompatible(LHSType, RHSType)) { 11972 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11973 /*isError*/false); 11974 } 11975 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11976 // the RHS, but we have test coverage for this behavior. 11977 // FIXME: Consider using convertPointersToCompositeType in C++. 11978 if (LHSIsNull && !RHSIsNull) { 11979 Expr *E = LHS.get(); 11980 if (getLangOpts().ObjCAutoRefCount) 11981 CheckObjCConversion(SourceRange(), RHSType, E, 11982 CCK_ImplicitConversion); 11983 LHS = ImpCastExprToType(E, RHSType, 11984 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11985 } 11986 else { 11987 Expr *E = RHS.get(); 11988 if (getLangOpts().ObjCAutoRefCount) 11989 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11990 /*Diagnose=*/true, 11991 /*DiagnoseCFAudited=*/false, Opc); 11992 RHS = ImpCastExprToType(E, LHSType, 11993 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11994 } 11995 return computeResultTy(); 11996 } 11997 if (LHSType->isObjCObjectPointerType() && 11998 RHSType->isObjCObjectPointerType()) { 11999 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12000 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12001 /*isError*/false); 12002 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12003 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12004 12005 if (LHSIsNull && !RHSIsNull) 12006 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12007 else 12008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12009 return computeResultTy(); 12010 } 12011 12012 if (!IsOrdered && LHSType->isBlockPointerType() && 12013 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12014 LHS = ImpCastExprToType(LHS.get(), RHSType, 12015 CK_BlockPointerToObjCPointerCast); 12016 return computeResultTy(); 12017 } else if (!IsOrdered && 12018 LHSType->isBlockCompatibleObjCPointerType(Context) && 12019 RHSType->isBlockPointerType()) { 12020 RHS = ImpCastExprToType(RHS.get(), LHSType, 12021 CK_BlockPointerToObjCPointerCast); 12022 return computeResultTy(); 12023 } 12024 } 12025 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12026 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12027 unsigned DiagID = 0; 12028 bool isError = false; 12029 if (LangOpts.DebuggerSupport) { 12030 // Under a debugger, allow the comparison of pointers to integers, 12031 // since users tend to want to compare addresses. 12032 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12033 (RHSIsNull && RHSType->isIntegerType())) { 12034 if (IsOrdered) { 12035 isError = getLangOpts().CPlusPlus; 12036 DiagID = 12037 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12038 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12039 } 12040 } else if (getLangOpts().CPlusPlus) { 12041 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12042 isError = true; 12043 } else if (IsOrdered) 12044 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12045 else 12046 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12047 12048 if (DiagID) { 12049 Diag(Loc, DiagID) 12050 << LHSType << RHSType << LHS.get()->getSourceRange() 12051 << RHS.get()->getSourceRange(); 12052 if (isError) 12053 return QualType(); 12054 } 12055 12056 if (LHSType->isIntegerType()) 12057 LHS = ImpCastExprToType(LHS.get(), RHSType, 12058 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12059 else 12060 RHS = ImpCastExprToType(RHS.get(), LHSType, 12061 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12062 return computeResultTy(); 12063 } 12064 12065 // Handle block pointers. 12066 if (!IsOrdered && RHSIsNull 12067 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12068 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12069 return computeResultTy(); 12070 } 12071 if (!IsOrdered && LHSIsNull 12072 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12073 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12074 return computeResultTy(); 12075 } 12076 12077 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12078 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12079 return computeResultTy(); 12080 } 12081 12082 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12083 return computeResultTy(); 12084 } 12085 12086 if (LHSIsNull && RHSType->isQueueT()) { 12087 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12088 return computeResultTy(); 12089 } 12090 12091 if (LHSType->isQueueT() && RHSIsNull) { 12092 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12093 return computeResultTy(); 12094 } 12095 } 12096 12097 return InvalidOperands(Loc, LHS, RHS); 12098 } 12099 12100 // Return a signed ext_vector_type that is of identical size and number of 12101 // elements. For floating point vectors, return an integer type of identical 12102 // size and number of elements. In the non ext_vector_type case, search from 12103 // the largest type to the smallest type to avoid cases where long long == long, 12104 // where long gets picked over long long. 12105 QualType Sema::GetSignedVectorType(QualType V) { 12106 const VectorType *VTy = V->castAs<VectorType>(); 12107 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12108 12109 if (isa<ExtVectorType>(VTy)) { 12110 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12111 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12112 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12113 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12114 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12115 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12116 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12117 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12118 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12119 "Unhandled vector element size in vector compare"); 12120 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12121 } 12122 12123 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12124 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12125 VectorType::GenericVector); 12126 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12127 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12128 VectorType::GenericVector); 12129 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12130 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12131 VectorType::GenericVector); 12132 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12133 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12134 VectorType::GenericVector); 12135 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12136 "Unhandled vector element size in vector compare"); 12137 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12138 VectorType::GenericVector); 12139 } 12140 12141 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12142 /// operates on extended vector types. Instead of producing an IntTy result, 12143 /// like a scalar comparison, a vector comparison produces a vector of integer 12144 /// types. 12145 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12146 SourceLocation Loc, 12147 BinaryOperatorKind Opc) { 12148 if (Opc == BO_Cmp) { 12149 Diag(Loc, diag::err_three_way_vector_comparison); 12150 return QualType(); 12151 } 12152 12153 // Check to make sure we're operating on vectors of the same type and width, 12154 // Allowing one side to be a scalar of element type. 12155 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12156 /*AllowBothBool*/true, 12157 /*AllowBoolConversions*/getLangOpts().ZVector); 12158 if (vType.isNull()) 12159 return vType; 12160 12161 QualType LHSType = LHS.get()->getType(); 12162 12163 // If AltiVec, the comparison results in a numeric type, i.e. 12164 // bool for C++, int for C 12165 if (getLangOpts().AltiVec && 12166 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12167 return Context.getLogicalOperationType(); 12168 12169 // For non-floating point types, check for self-comparisons of the form 12170 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12171 // often indicate logic errors in the program. 12172 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12173 12174 // Check for comparisons of floating point operands using != and ==. 12175 if (BinaryOperator::isEqualityOp(Opc) && 12176 LHSType->hasFloatingRepresentation()) { 12177 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12178 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12179 } 12180 12181 // Return a signed type for the vector. 12182 return GetSignedVectorType(vType); 12183 } 12184 12185 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12186 const ExprResult &XorRHS, 12187 const SourceLocation Loc) { 12188 // Do not diagnose macros. 12189 if (Loc.isMacroID()) 12190 return; 12191 12192 // Do not diagnose if both LHS and RHS are macros. 12193 if (XorLHS.get()->getExprLoc().isMacroID() && 12194 XorRHS.get()->getExprLoc().isMacroID()) 12195 return; 12196 12197 bool Negative = false; 12198 bool ExplicitPlus = false; 12199 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12200 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12201 12202 if (!LHSInt) 12203 return; 12204 if (!RHSInt) { 12205 // Check negative literals. 12206 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12207 UnaryOperatorKind Opc = UO->getOpcode(); 12208 if (Opc != UO_Minus && Opc != UO_Plus) 12209 return; 12210 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12211 if (!RHSInt) 12212 return; 12213 Negative = (Opc == UO_Minus); 12214 ExplicitPlus = !Negative; 12215 } else { 12216 return; 12217 } 12218 } 12219 12220 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12221 llvm::APInt RightSideValue = RHSInt->getValue(); 12222 if (LeftSideValue != 2 && LeftSideValue != 10) 12223 return; 12224 12225 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12226 return; 12227 12228 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12229 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12230 llvm::StringRef ExprStr = 12231 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12232 12233 CharSourceRange XorRange = 12234 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12235 llvm::StringRef XorStr = 12236 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12237 // Do not diagnose if xor keyword/macro is used. 12238 if (XorStr == "xor") 12239 return; 12240 12241 std::string LHSStr = std::string(Lexer::getSourceText( 12242 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12243 S.getSourceManager(), S.getLangOpts())); 12244 std::string RHSStr = std::string(Lexer::getSourceText( 12245 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12246 S.getSourceManager(), S.getLangOpts())); 12247 12248 if (Negative) { 12249 RightSideValue = -RightSideValue; 12250 RHSStr = "-" + RHSStr; 12251 } else if (ExplicitPlus) { 12252 RHSStr = "+" + RHSStr; 12253 } 12254 12255 StringRef LHSStrRef = LHSStr; 12256 StringRef RHSStrRef = RHSStr; 12257 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12258 // literals. 12259 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12260 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12261 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12262 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12263 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12264 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12265 LHSStrRef.find('\'') != StringRef::npos || 12266 RHSStrRef.find('\'') != StringRef::npos) 12267 return; 12268 12269 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12270 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12271 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12272 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12273 std::string SuggestedExpr = "1 << " + RHSStr; 12274 bool Overflow = false; 12275 llvm::APInt One = (LeftSideValue - 1); 12276 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12277 if (Overflow) { 12278 if (RightSideIntValue < 64) 12279 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12280 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12281 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12282 else if (RightSideIntValue == 64) 12283 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12284 else 12285 return; 12286 } else { 12287 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12288 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12289 << PowValue.toString(10, true) 12290 << FixItHint::CreateReplacement( 12291 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12292 } 12293 12294 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12295 } else if (LeftSideValue == 10) { 12296 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12297 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12298 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12299 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12300 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12301 } 12302 } 12303 12304 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12305 SourceLocation Loc) { 12306 // Ensure that either both operands are of the same vector type, or 12307 // one operand is of a vector type and the other is of its element type. 12308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12309 /*AllowBothBool*/true, 12310 /*AllowBoolConversions*/false); 12311 if (vType.isNull()) 12312 return InvalidOperands(Loc, LHS, RHS); 12313 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12314 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12315 return InvalidOperands(Loc, LHS, RHS); 12316 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12317 // usage of the logical operators && and || with vectors in C. This 12318 // check could be notionally dropped. 12319 if (!getLangOpts().CPlusPlus && 12320 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12321 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12322 12323 return GetSignedVectorType(LHS.get()->getType()); 12324 } 12325 12326 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12327 SourceLocation Loc, 12328 bool IsCompAssign) { 12329 if (!IsCompAssign) { 12330 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12331 if (LHS.isInvalid()) 12332 return QualType(); 12333 } 12334 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12335 if (RHS.isInvalid()) 12336 return QualType(); 12337 12338 // For conversion purposes, we ignore any qualifiers. 12339 // For example, "const float" and "float" are equivalent. 12340 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12341 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12342 12343 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12344 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12345 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12346 12347 if (Context.hasSameType(LHSType, RHSType)) 12348 return LHSType; 12349 12350 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12351 // case we have to return InvalidOperands. 12352 ExprResult OriginalLHS = LHS; 12353 ExprResult OriginalRHS = RHS; 12354 if (LHSMatType && !RHSMatType) { 12355 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12356 if (!RHS.isInvalid()) 12357 return LHSType; 12358 12359 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12360 } 12361 12362 if (!LHSMatType && RHSMatType) { 12363 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12364 if (!LHS.isInvalid()) 12365 return RHSType; 12366 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12367 } 12368 12369 return InvalidOperands(Loc, LHS, RHS); 12370 } 12371 12372 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12373 SourceLocation Loc, 12374 bool IsCompAssign) { 12375 if (!IsCompAssign) { 12376 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12377 if (LHS.isInvalid()) 12378 return QualType(); 12379 } 12380 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12381 if (RHS.isInvalid()) 12382 return QualType(); 12383 12384 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12385 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12386 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12387 12388 if (LHSMatType && RHSMatType) { 12389 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12390 return InvalidOperands(Loc, LHS, RHS); 12391 12392 if (!Context.hasSameType(LHSMatType->getElementType(), 12393 RHSMatType->getElementType())) 12394 return InvalidOperands(Loc, LHS, RHS); 12395 12396 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12397 LHSMatType->getNumRows(), 12398 RHSMatType->getNumColumns()); 12399 } 12400 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12401 } 12402 12403 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12404 SourceLocation Loc, 12405 BinaryOperatorKind Opc) { 12406 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12407 12408 bool IsCompAssign = 12409 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12410 12411 if (LHS.get()->getType()->isVectorType() || 12412 RHS.get()->getType()->isVectorType()) { 12413 if (LHS.get()->getType()->hasIntegerRepresentation() && 12414 RHS.get()->getType()->hasIntegerRepresentation()) 12415 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12416 /*AllowBothBool*/true, 12417 /*AllowBoolConversions*/getLangOpts().ZVector); 12418 return InvalidOperands(Loc, LHS, RHS); 12419 } 12420 12421 if (Opc == BO_And) 12422 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12423 12424 if (LHS.get()->getType()->hasFloatingRepresentation() || 12425 RHS.get()->getType()->hasFloatingRepresentation()) 12426 return InvalidOperands(Loc, LHS, RHS); 12427 12428 ExprResult LHSResult = LHS, RHSResult = RHS; 12429 QualType compType = UsualArithmeticConversions( 12430 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12431 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12432 return QualType(); 12433 LHS = LHSResult.get(); 12434 RHS = RHSResult.get(); 12435 12436 if (Opc == BO_Xor) 12437 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12438 12439 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12440 return compType; 12441 return InvalidOperands(Loc, LHS, RHS); 12442 } 12443 12444 // C99 6.5.[13,14] 12445 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12446 SourceLocation Loc, 12447 BinaryOperatorKind Opc) { 12448 // Check vector operands differently. 12449 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12450 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12451 12452 bool EnumConstantInBoolContext = false; 12453 for (const ExprResult &HS : {LHS, RHS}) { 12454 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12455 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12456 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12457 EnumConstantInBoolContext = true; 12458 } 12459 } 12460 12461 if (EnumConstantInBoolContext) 12462 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12463 12464 // Diagnose cases where the user write a logical and/or but probably meant a 12465 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12466 // is a constant. 12467 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12468 !LHS.get()->getType()->isBooleanType() && 12469 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12470 // Don't warn in macros or template instantiations. 12471 !Loc.isMacroID() && !inTemplateInstantiation()) { 12472 // If the RHS can be constant folded, and if it constant folds to something 12473 // that isn't 0 or 1 (which indicate a potential logical operation that 12474 // happened to fold to true/false) then warn. 12475 // Parens on the RHS are ignored. 12476 Expr::EvalResult EVResult; 12477 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12478 llvm::APSInt Result = EVResult.Val.getInt(); 12479 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12480 !RHS.get()->getExprLoc().isMacroID()) || 12481 (Result != 0 && Result != 1)) { 12482 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12483 << RHS.get()->getSourceRange() 12484 << (Opc == BO_LAnd ? "&&" : "||"); 12485 // Suggest replacing the logical operator with the bitwise version 12486 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12487 << (Opc == BO_LAnd ? "&" : "|") 12488 << FixItHint::CreateReplacement(SourceRange( 12489 Loc, getLocForEndOfToken(Loc)), 12490 Opc == BO_LAnd ? "&" : "|"); 12491 if (Opc == BO_LAnd) 12492 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12493 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12494 << FixItHint::CreateRemoval( 12495 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12496 RHS.get()->getEndLoc())); 12497 } 12498 } 12499 } 12500 12501 if (!Context.getLangOpts().CPlusPlus) { 12502 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12503 // not operate on the built-in scalar and vector float types. 12504 if (Context.getLangOpts().OpenCL && 12505 Context.getLangOpts().OpenCLVersion < 120) { 12506 if (LHS.get()->getType()->isFloatingType() || 12507 RHS.get()->getType()->isFloatingType()) 12508 return InvalidOperands(Loc, LHS, RHS); 12509 } 12510 12511 LHS = UsualUnaryConversions(LHS.get()); 12512 if (LHS.isInvalid()) 12513 return QualType(); 12514 12515 RHS = UsualUnaryConversions(RHS.get()); 12516 if (RHS.isInvalid()) 12517 return QualType(); 12518 12519 if (!LHS.get()->getType()->isScalarType() || 12520 !RHS.get()->getType()->isScalarType()) 12521 return InvalidOperands(Loc, LHS, RHS); 12522 12523 return Context.IntTy; 12524 } 12525 12526 // The following is safe because we only use this method for 12527 // non-overloadable operands. 12528 12529 // C++ [expr.log.and]p1 12530 // C++ [expr.log.or]p1 12531 // The operands are both contextually converted to type bool. 12532 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12533 if (LHSRes.isInvalid()) 12534 return InvalidOperands(Loc, LHS, RHS); 12535 LHS = LHSRes; 12536 12537 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12538 if (RHSRes.isInvalid()) 12539 return InvalidOperands(Loc, LHS, RHS); 12540 RHS = RHSRes; 12541 12542 // C++ [expr.log.and]p2 12543 // C++ [expr.log.or]p2 12544 // The result is a bool. 12545 return Context.BoolTy; 12546 } 12547 12548 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12549 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12550 if (!ME) return false; 12551 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12552 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12553 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12554 if (!Base) return false; 12555 return Base->getMethodDecl() != nullptr; 12556 } 12557 12558 /// Is the given expression (which must be 'const') a reference to a 12559 /// variable which was originally non-const, but which has become 12560 /// 'const' due to being captured within a block? 12561 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12562 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12563 assert(E->isLValue() && E->getType().isConstQualified()); 12564 E = E->IgnoreParens(); 12565 12566 // Must be a reference to a declaration from an enclosing scope. 12567 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12568 if (!DRE) return NCCK_None; 12569 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12570 12571 // The declaration must be a variable which is not declared 'const'. 12572 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12573 if (!var) return NCCK_None; 12574 if (var->getType().isConstQualified()) return NCCK_None; 12575 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12576 12577 // Decide whether the first capture was for a block or a lambda. 12578 DeclContext *DC = S.CurContext, *Prev = nullptr; 12579 // Decide whether the first capture was for a block or a lambda. 12580 while (DC) { 12581 // For init-capture, it is possible that the variable belongs to the 12582 // template pattern of the current context. 12583 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12584 if (var->isInitCapture() && 12585 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12586 break; 12587 if (DC == var->getDeclContext()) 12588 break; 12589 Prev = DC; 12590 DC = DC->getParent(); 12591 } 12592 // Unless we have an init-capture, we've gone one step too far. 12593 if (!var->isInitCapture()) 12594 DC = Prev; 12595 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12596 } 12597 12598 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12599 Ty = Ty.getNonReferenceType(); 12600 if (IsDereference && Ty->isPointerType()) 12601 Ty = Ty->getPointeeType(); 12602 return !Ty.isConstQualified(); 12603 } 12604 12605 // Update err_typecheck_assign_const and note_typecheck_assign_const 12606 // when this enum is changed. 12607 enum { 12608 ConstFunction, 12609 ConstVariable, 12610 ConstMember, 12611 ConstMethod, 12612 NestedConstMember, 12613 ConstUnknown, // Keep as last element 12614 }; 12615 12616 /// Emit the "read-only variable not assignable" error and print notes to give 12617 /// more information about why the variable is not assignable, such as pointing 12618 /// to the declaration of a const variable, showing that a method is const, or 12619 /// that the function is returning a const reference. 12620 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12621 SourceLocation Loc) { 12622 SourceRange ExprRange = E->getSourceRange(); 12623 12624 // Only emit one error on the first const found. All other consts will emit 12625 // a note to the error. 12626 bool DiagnosticEmitted = false; 12627 12628 // Track if the current expression is the result of a dereference, and if the 12629 // next checked expression is the result of a dereference. 12630 bool IsDereference = false; 12631 bool NextIsDereference = false; 12632 12633 // Loop to process MemberExpr chains. 12634 while (true) { 12635 IsDereference = NextIsDereference; 12636 12637 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12638 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12639 NextIsDereference = ME->isArrow(); 12640 const ValueDecl *VD = ME->getMemberDecl(); 12641 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12642 // Mutable fields can be modified even if the class is const. 12643 if (Field->isMutable()) { 12644 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12645 break; 12646 } 12647 12648 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12649 if (!DiagnosticEmitted) { 12650 S.Diag(Loc, diag::err_typecheck_assign_const) 12651 << ExprRange << ConstMember << false /*static*/ << Field 12652 << Field->getType(); 12653 DiagnosticEmitted = true; 12654 } 12655 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12656 << ConstMember << false /*static*/ << Field << Field->getType() 12657 << Field->getSourceRange(); 12658 } 12659 E = ME->getBase(); 12660 continue; 12661 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12662 if (VDecl->getType().isConstQualified()) { 12663 if (!DiagnosticEmitted) { 12664 S.Diag(Loc, diag::err_typecheck_assign_const) 12665 << ExprRange << ConstMember << true /*static*/ << VDecl 12666 << VDecl->getType(); 12667 DiagnosticEmitted = true; 12668 } 12669 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12670 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12671 << VDecl->getSourceRange(); 12672 } 12673 // Static fields do not inherit constness from parents. 12674 break; 12675 } 12676 break; // End MemberExpr 12677 } else if (const ArraySubscriptExpr *ASE = 12678 dyn_cast<ArraySubscriptExpr>(E)) { 12679 E = ASE->getBase()->IgnoreParenImpCasts(); 12680 continue; 12681 } else if (const ExtVectorElementExpr *EVE = 12682 dyn_cast<ExtVectorElementExpr>(E)) { 12683 E = EVE->getBase()->IgnoreParenImpCasts(); 12684 continue; 12685 } 12686 break; 12687 } 12688 12689 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12690 // Function calls 12691 const FunctionDecl *FD = CE->getDirectCallee(); 12692 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12693 if (!DiagnosticEmitted) { 12694 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12695 << ConstFunction << FD; 12696 DiagnosticEmitted = true; 12697 } 12698 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12699 diag::note_typecheck_assign_const) 12700 << ConstFunction << FD << FD->getReturnType() 12701 << FD->getReturnTypeSourceRange(); 12702 } 12703 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12704 // Point to variable declaration. 12705 if (const ValueDecl *VD = DRE->getDecl()) { 12706 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12707 if (!DiagnosticEmitted) { 12708 S.Diag(Loc, diag::err_typecheck_assign_const) 12709 << ExprRange << ConstVariable << VD << VD->getType(); 12710 DiagnosticEmitted = true; 12711 } 12712 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12713 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12714 } 12715 } 12716 } else if (isa<CXXThisExpr>(E)) { 12717 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12719 if (MD->isConst()) { 12720 if (!DiagnosticEmitted) { 12721 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12722 << ConstMethod << MD; 12723 DiagnosticEmitted = true; 12724 } 12725 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12726 << ConstMethod << MD << MD->getSourceRange(); 12727 } 12728 } 12729 } 12730 } 12731 12732 if (DiagnosticEmitted) 12733 return; 12734 12735 // Can't determine a more specific message, so display the generic error. 12736 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12737 } 12738 12739 enum OriginalExprKind { 12740 OEK_Variable, 12741 OEK_Member, 12742 OEK_LValue 12743 }; 12744 12745 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12746 const RecordType *Ty, 12747 SourceLocation Loc, SourceRange Range, 12748 OriginalExprKind OEK, 12749 bool &DiagnosticEmitted) { 12750 std::vector<const RecordType *> RecordTypeList; 12751 RecordTypeList.push_back(Ty); 12752 unsigned NextToCheckIndex = 0; 12753 // We walk the record hierarchy breadth-first to ensure that we print 12754 // diagnostics in field nesting order. 12755 while (RecordTypeList.size() > NextToCheckIndex) { 12756 bool IsNested = NextToCheckIndex > 0; 12757 for (const FieldDecl *Field : 12758 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12759 // First, check every field for constness. 12760 QualType FieldTy = Field->getType(); 12761 if (FieldTy.isConstQualified()) { 12762 if (!DiagnosticEmitted) { 12763 S.Diag(Loc, diag::err_typecheck_assign_const) 12764 << Range << NestedConstMember << OEK << VD 12765 << IsNested << Field; 12766 DiagnosticEmitted = true; 12767 } 12768 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12769 << NestedConstMember << IsNested << Field 12770 << FieldTy << Field->getSourceRange(); 12771 } 12772 12773 // Then we append it to the list to check next in order. 12774 FieldTy = FieldTy.getCanonicalType(); 12775 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12776 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12777 RecordTypeList.push_back(FieldRecTy); 12778 } 12779 } 12780 ++NextToCheckIndex; 12781 } 12782 } 12783 12784 /// Emit an error for the case where a record we are trying to assign to has a 12785 /// const-qualified field somewhere in its hierarchy. 12786 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12787 SourceLocation Loc) { 12788 QualType Ty = E->getType(); 12789 assert(Ty->isRecordType() && "lvalue was not record?"); 12790 SourceRange Range = E->getSourceRange(); 12791 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12792 bool DiagEmitted = false; 12793 12794 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12795 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12796 Range, OEK_Member, DiagEmitted); 12797 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12798 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12799 Range, OEK_Variable, DiagEmitted); 12800 else 12801 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12802 Range, OEK_LValue, DiagEmitted); 12803 if (!DiagEmitted) 12804 DiagnoseConstAssignment(S, E, Loc); 12805 } 12806 12807 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12808 /// emit an error and return true. If so, return false. 12809 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12810 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12811 12812 S.CheckShadowingDeclModification(E, Loc); 12813 12814 SourceLocation OrigLoc = Loc; 12815 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12816 &Loc); 12817 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12818 IsLV = Expr::MLV_InvalidMessageExpression; 12819 if (IsLV == Expr::MLV_Valid) 12820 return false; 12821 12822 unsigned DiagID = 0; 12823 bool NeedType = false; 12824 switch (IsLV) { // C99 6.5.16p2 12825 case Expr::MLV_ConstQualified: 12826 // Use a specialized diagnostic when we're assigning to an object 12827 // from an enclosing function or block. 12828 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12829 if (NCCK == NCCK_Block) 12830 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12831 else 12832 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12833 break; 12834 } 12835 12836 // In ARC, use some specialized diagnostics for occasions where we 12837 // infer 'const'. These are always pseudo-strong variables. 12838 if (S.getLangOpts().ObjCAutoRefCount) { 12839 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12840 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12841 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12842 12843 // Use the normal diagnostic if it's pseudo-__strong but the 12844 // user actually wrote 'const'. 12845 if (var->isARCPseudoStrong() && 12846 (!var->getTypeSourceInfo() || 12847 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12848 // There are three pseudo-strong cases: 12849 // - self 12850 ObjCMethodDecl *method = S.getCurMethodDecl(); 12851 if (method && var == method->getSelfDecl()) { 12852 DiagID = method->isClassMethod() 12853 ? diag::err_typecheck_arc_assign_self_class_method 12854 : diag::err_typecheck_arc_assign_self; 12855 12856 // - Objective-C externally_retained attribute. 12857 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12858 isa<ParmVarDecl>(var)) { 12859 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12860 12861 // - fast enumeration variables 12862 } else { 12863 DiagID = diag::err_typecheck_arr_assign_enumeration; 12864 } 12865 12866 SourceRange Assign; 12867 if (Loc != OrigLoc) 12868 Assign = SourceRange(OrigLoc, OrigLoc); 12869 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12870 // We need to preserve the AST regardless, so migration tool 12871 // can do its job. 12872 return false; 12873 } 12874 } 12875 } 12876 12877 // If none of the special cases above are triggered, then this is a 12878 // simple const assignment. 12879 if (DiagID == 0) { 12880 DiagnoseConstAssignment(S, E, Loc); 12881 return true; 12882 } 12883 12884 break; 12885 case Expr::MLV_ConstAddrSpace: 12886 DiagnoseConstAssignment(S, E, Loc); 12887 return true; 12888 case Expr::MLV_ConstQualifiedField: 12889 DiagnoseRecursiveConstFields(S, E, Loc); 12890 return true; 12891 case Expr::MLV_ArrayType: 12892 case Expr::MLV_ArrayTemporary: 12893 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12894 NeedType = true; 12895 break; 12896 case Expr::MLV_NotObjectType: 12897 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12898 NeedType = true; 12899 break; 12900 case Expr::MLV_LValueCast: 12901 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12902 break; 12903 case Expr::MLV_Valid: 12904 llvm_unreachable("did not take early return for MLV_Valid"); 12905 case Expr::MLV_InvalidExpression: 12906 case Expr::MLV_MemberFunction: 12907 case Expr::MLV_ClassTemporary: 12908 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12909 break; 12910 case Expr::MLV_IncompleteType: 12911 case Expr::MLV_IncompleteVoidType: 12912 return S.RequireCompleteType(Loc, E->getType(), 12913 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12914 case Expr::MLV_DuplicateVectorComponents: 12915 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12916 break; 12917 case Expr::MLV_NoSetterProperty: 12918 llvm_unreachable("readonly properties should be processed differently"); 12919 case Expr::MLV_InvalidMessageExpression: 12920 DiagID = diag::err_readonly_message_assignment; 12921 break; 12922 case Expr::MLV_SubObjCPropertySetting: 12923 DiagID = diag::err_no_subobject_property_setting; 12924 break; 12925 } 12926 12927 SourceRange Assign; 12928 if (Loc != OrigLoc) 12929 Assign = SourceRange(OrigLoc, OrigLoc); 12930 if (NeedType) 12931 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12932 else 12933 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12934 return true; 12935 } 12936 12937 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12938 SourceLocation Loc, 12939 Sema &Sema) { 12940 if (Sema.inTemplateInstantiation()) 12941 return; 12942 if (Sema.isUnevaluatedContext()) 12943 return; 12944 if (Loc.isInvalid() || Loc.isMacroID()) 12945 return; 12946 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12947 return; 12948 12949 // C / C++ fields 12950 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12951 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12952 if (ML && MR) { 12953 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12954 return; 12955 const ValueDecl *LHSDecl = 12956 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12957 const ValueDecl *RHSDecl = 12958 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12959 if (LHSDecl != RHSDecl) 12960 return; 12961 if (LHSDecl->getType().isVolatileQualified()) 12962 return; 12963 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12964 if (RefTy->getPointeeType().isVolatileQualified()) 12965 return; 12966 12967 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12968 } 12969 12970 // Objective-C instance variables 12971 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12972 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12973 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12974 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12975 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12976 if (RL && RR && RL->getDecl() == RR->getDecl()) 12977 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12978 } 12979 } 12980 12981 // C99 6.5.16.1 12982 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12983 SourceLocation Loc, 12984 QualType CompoundType) { 12985 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12986 12987 // Verify that LHS is a modifiable lvalue, and emit error if not. 12988 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12989 return QualType(); 12990 12991 QualType LHSType = LHSExpr->getType(); 12992 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12993 CompoundType; 12994 // OpenCL v1.2 s6.1.1.1 p2: 12995 // The half data type can only be used to declare a pointer to a buffer that 12996 // contains half values 12997 if (getLangOpts().OpenCL && 12998 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 12999 LHSType->isHalfType()) { 13000 Diag(Loc, diag::err_opencl_half_load_store) << 1 13001 << LHSType.getUnqualifiedType(); 13002 return QualType(); 13003 } 13004 13005 AssignConvertType ConvTy; 13006 if (CompoundType.isNull()) { 13007 Expr *RHSCheck = RHS.get(); 13008 13009 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13010 13011 QualType LHSTy(LHSType); 13012 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13013 if (RHS.isInvalid()) 13014 return QualType(); 13015 // Special case of NSObject attributes on c-style pointer types. 13016 if (ConvTy == IncompatiblePointer && 13017 ((Context.isObjCNSObjectType(LHSType) && 13018 RHSType->isObjCObjectPointerType()) || 13019 (Context.isObjCNSObjectType(RHSType) && 13020 LHSType->isObjCObjectPointerType()))) 13021 ConvTy = Compatible; 13022 13023 if (ConvTy == Compatible && 13024 LHSType->isObjCObjectType()) 13025 Diag(Loc, diag::err_objc_object_assignment) 13026 << LHSType; 13027 13028 // If the RHS is a unary plus or minus, check to see if they = and + are 13029 // right next to each other. If so, the user may have typo'd "x =+ 4" 13030 // instead of "x += 4". 13031 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13032 RHSCheck = ICE->getSubExpr(); 13033 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13034 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13035 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13036 // Only if the two operators are exactly adjacent. 13037 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13038 // And there is a space or other character before the subexpr of the 13039 // unary +/-. We don't want to warn on "x=-1". 13040 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13041 UO->getSubExpr()->getBeginLoc().isFileID()) { 13042 Diag(Loc, diag::warn_not_compound_assign) 13043 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13044 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13045 } 13046 } 13047 13048 if (ConvTy == Compatible) { 13049 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13050 // Warn about retain cycles where a block captures the LHS, but 13051 // not if the LHS is a simple variable into which the block is 13052 // being stored...unless that variable can be captured by reference! 13053 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13054 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13055 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13056 checkRetainCycles(LHSExpr, RHS.get()); 13057 } 13058 13059 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13060 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13061 // It is safe to assign a weak reference into a strong variable. 13062 // Although this code can still have problems: 13063 // id x = self.weakProp; 13064 // id y = self.weakProp; 13065 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13066 // paths through the function. This should be revisited if 13067 // -Wrepeated-use-of-weak is made flow-sensitive. 13068 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13069 // variable, which will be valid for the current autorelease scope. 13070 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13071 RHS.get()->getBeginLoc())) 13072 getCurFunction()->markSafeWeakUse(RHS.get()); 13073 13074 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13075 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13076 } 13077 } 13078 } else { 13079 // Compound assignment "x += y" 13080 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13081 } 13082 13083 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13084 RHS.get(), AA_Assigning)) 13085 return QualType(); 13086 13087 CheckForNullPointerDereference(*this, LHSExpr); 13088 13089 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13090 if (CompoundType.isNull()) { 13091 // C++2a [expr.ass]p5: 13092 // A simple-assignment whose left operand is of a volatile-qualified 13093 // type is deprecated unless the assignment is either a discarded-value 13094 // expression or an unevaluated operand 13095 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13096 } else { 13097 // C++2a [expr.ass]p6: 13098 // [Compound-assignment] expressions are deprecated if E1 has 13099 // volatile-qualified type 13100 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13101 } 13102 } 13103 13104 // C99 6.5.16p3: The type of an assignment expression is the type of the 13105 // left operand unless the left operand has qualified type, in which case 13106 // it is the unqualified version of the type of the left operand. 13107 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13108 // is converted to the type of the assignment expression (above). 13109 // C++ 5.17p1: the type of the assignment expression is that of its left 13110 // operand. 13111 return (getLangOpts().CPlusPlus 13112 ? LHSType : LHSType.getUnqualifiedType()); 13113 } 13114 13115 // Only ignore explicit casts to void. 13116 static bool IgnoreCommaOperand(const Expr *E) { 13117 E = E->IgnoreParens(); 13118 13119 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13120 if (CE->getCastKind() == CK_ToVoid) { 13121 return true; 13122 } 13123 13124 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13125 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13126 CE->getSubExpr()->getType()->isDependentType()) { 13127 return true; 13128 } 13129 } 13130 13131 return false; 13132 } 13133 13134 // Look for instances where it is likely the comma operator is confused with 13135 // another operator. There is an explicit list of acceptable expressions for 13136 // the left hand side of the comma operator, otherwise emit a warning. 13137 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13138 // No warnings in macros 13139 if (Loc.isMacroID()) 13140 return; 13141 13142 // Don't warn in template instantiations. 13143 if (inTemplateInstantiation()) 13144 return; 13145 13146 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13147 // instead, skip more than needed, then call back into here with the 13148 // CommaVisitor in SemaStmt.cpp. 13149 // The listed locations are the initialization and increment portions 13150 // of a for loop. The additional checks are on the condition of 13151 // if statements, do/while loops, and for loops. 13152 // Differences in scope flags for C89 mode requires the extra logic. 13153 const unsigned ForIncrementFlags = 13154 getLangOpts().C99 || getLangOpts().CPlusPlus 13155 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13156 : Scope::ContinueScope | Scope::BreakScope; 13157 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13158 const unsigned ScopeFlags = getCurScope()->getFlags(); 13159 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13160 (ScopeFlags & ForInitFlags) == ForInitFlags) 13161 return; 13162 13163 // If there are multiple comma operators used together, get the RHS of the 13164 // of the comma operator as the LHS. 13165 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13166 if (BO->getOpcode() != BO_Comma) 13167 break; 13168 LHS = BO->getRHS(); 13169 } 13170 13171 // Only allow some expressions on LHS to not warn. 13172 if (IgnoreCommaOperand(LHS)) 13173 return; 13174 13175 Diag(Loc, diag::warn_comma_operator); 13176 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13177 << LHS->getSourceRange() 13178 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13179 LangOpts.CPlusPlus ? "static_cast<void>(" 13180 : "(void)(") 13181 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13182 ")"); 13183 } 13184 13185 // C99 6.5.17 13186 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13187 SourceLocation Loc) { 13188 LHS = S.CheckPlaceholderExpr(LHS.get()); 13189 RHS = S.CheckPlaceholderExpr(RHS.get()); 13190 if (LHS.isInvalid() || RHS.isInvalid()) 13191 return QualType(); 13192 13193 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13194 // operands, but not unary promotions. 13195 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13196 13197 // So we treat the LHS as a ignored value, and in C++ we allow the 13198 // containing site to determine what should be done with the RHS. 13199 LHS = S.IgnoredValueConversions(LHS.get()); 13200 if (LHS.isInvalid()) 13201 return QualType(); 13202 13203 S.DiagnoseUnusedExprResult(LHS.get()); 13204 13205 if (!S.getLangOpts().CPlusPlus) { 13206 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13207 if (RHS.isInvalid()) 13208 return QualType(); 13209 if (!RHS.get()->getType()->isVoidType()) 13210 S.RequireCompleteType(Loc, RHS.get()->getType(), 13211 diag::err_incomplete_type); 13212 } 13213 13214 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13215 S.DiagnoseCommaOperator(LHS.get(), Loc); 13216 13217 return RHS.get()->getType(); 13218 } 13219 13220 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13221 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13222 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13223 ExprValueKind &VK, 13224 ExprObjectKind &OK, 13225 SourceLocation OpLoc, 13226 bool IsInc, bool IsPrefix) { 13227 if (Op->isTypeDependent()) 13228 return S.Context.DependentTy; 13229 13230 QualType ResType = Op->getType(); 13231 // Atomic types can be used for increment / decrement where the non-atomic 13232 // versions can, so ignore the _Atomic() specifier for the purpose of 13233 // checking. 13234 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13235 ResType = ResAtomicType->getValueType(); 13236 13237 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13238 13239 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13240 // Decrement of bool is not allowed. 13241 if (!IsInc) { 13242 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13243 return QualType(); 13244 } 13245 // Increment of bool sets it to true, but is deprecated. 13246 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13247 : diag::warn_increment_bool) 13248 << Op->getSourceRange(); 13249 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13250 // Error on enum increments and decrements in C++ mode 13251 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13252 return QualType(); 13253 } else if (ResType->isRealType()) { 13254 // OK! 13255 } else if (ResType->isPointerType()) { 13256 // C99 6.5.2.4p2, 6.5.6p2 13257 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13258 return QualType(); 13259 } else if (ResType->isObjCObjectPointerType()) { 13260 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13261 // Otherwise, we just need a complete type. 13262 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13263 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13264 return QualType(); 13265 } else if (ResType->isAnyComplexType()) { 13266 // C99 does not support ++/-- on complex types, we allow as an extension. 13267 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13268 << ResType << Op->getSourceRange(); 13269 } else if (ResType->isPlaceholderType()) { 13270 ExprResult PR = S.CheckPlaceholderExpr(Op); 13271 if (PR.isInvalid()) return QualType(); 13272 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13273 IsInc, IsPrefix); 13274 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13275 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13276 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13277 (ResType->castAs<VectorType>()->getVectorKind() != 13278 VectorType::AltiVecBool)) { 13279 // The z vector extensions allow ++ and -- for non-bool vectors. 13280 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13281 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13282 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13283 } else { 13284 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13285 << ResType << int(IsInc) << Op->getSourceRange(); 13286 return QualType(); 13287 } 13288 // At this point, we know we have a real, complex or pointer type. 13289 // Now make sure the operand is a modifiable lvalue. 13290 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13291 return QualType(); 13292 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13293 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13294 // An operand with volatile-qualified type is deprecated 13295 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13296 << IsInc << ResType; 13297 } 13298 // In C++, a prefix increment is the same type as the operand. Otherwise 13299 // (in C or with postfix), the increment is the unqualified type of the 13300 // operand. 13301 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13302 VK = VK_LValue; 13303 OK = Op->getObjectKind(); 13304 return ResType; 13305 } else { 13306 VK = VK_RValue; 13307 return ResType.getUnqualifiedType(); 13308 } 13309 } 13310 13311 13312 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13313 /// This routine allows us to typecheck complex/recursive expressions 13314 /// where the declaration is needed for type checking. We only need to 13315 /// handle cases when the expression references a function designator 13316 /// or is an lvalue. Here are some examples: 13317 /// - &(x) => x 13318 /// - &*****f => f for f a function designator. 13319 /// - &s.xx => s 13320 /// - &s.zz[1].yy -> s, if zz is an array 13321 /// - *(x + 1) -> x, if x is an array 13322 /// - &"123"[2] -> 0 13323 /// - & __real__ x -> x 13324 /// 13325 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13326 /// members. 13327 static ValueDecl *getPrimaryDecl(Expr *E) { 13328 switch (E->getStmtClass()) { 13329 case Stmt::DeclRefExprClass: 13330 return cast<DeclRefExpr>(E)->getDecl(); 13331 case Stmt::MemberExprClass: 13332 // If this is an arrow operator, the address is an offset from 13333 // the base's value, so the object the base refers to is 13334 // irrelevant. 13335 if (cast<MemberExpr>(E)->isArrow()) 13336 return nullptr; 13337 // Otherwise, the expression refers to a part of the base 13338 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13339 case Stmt::ArraySubscriptExprClass: { 13340 // FIXME: This code shouldn't be necessary! We should catch the implicit 13341 // promotion of register arrays earlier. 13342 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13343 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13344 if (ICE->getSubExpr()->getType()->isArrayType()) 13345 return getPrimaryDecl(ICE->getSubExpr()); 13346 } 13347 return nullptr; 13348 } 13349 case Stmt::UnaryOperatorClass: { 13350 UnaryOperator *UO = cast<UnaryOperator>(E); 13351 13352 switch(UO->getOpcode()) { 13353 case UO_Real: 13354 case UO_Imag: 13355 case UO_Extension: 13356 return getPrimaryDecl(UO->getSubExpr()); 13357 default: 13358 return nullptr; 13359 } 13360 } 13361 case Stmt::ParenExprClass: 13362 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13363 case Stmt::ImplicitCastExprClass: 13364 // If the result of an implicit cast is an l-value, we care about 13365 // the sub-expression; otherwise, the result here doesn't matter. 13366 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13367 case Stmt::CXXUuidofExprClass: 13368 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13369 default: 13370 return nullptr; 13371 } 13372 } 13373 13374 namespace { 13375 enum { 13376 AO_Bit_Field = 0, 13377 AO_Vector_Element = 1, 13378 AO_Property_Expansion = 2, 13379 AO_Register_Variable = 3, 13380 AO_Matrix_Element = 4, 13381 AO_No_Error = 5 13382 }; 13383 } 13384 /// Diagnose invalid operand for address of operations. 13385 /// 13386 /// \param Type The type of operand which cannot have its address taken. 13387 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13388 Expr *E, unsigned Type) { 13389 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13390 } 13391 13392 /// CheckAddressOfOperand - The operand of & must be either a function 13393 /// designator or an lvalue designating an object. If it is an lvalue, the 13394 /// object cannot be declared with storage class register or be a bit field. 13395 /// Note: The usual conversions are *not* applied to the operand of the & 13396 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13397 /// In C++, the operand might be an overloaded function name, in which case 13398 /// we allow the '&' but retain the overloaded-function type. 13399 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13400 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13401 if (PTy->getKind() == BuiltinType::Overload) { 13402 Expr *E = OrigOp.get()->IgnoreParens(); 13403 if (!isa<OverloadExpr>(E)) { 13404 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13405 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13406 << OrigOp.get()->getSourceRange(); 13407 return QualType(); 13408 } 13409 13410 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13411 if (isa<UnresolvedMemberExpr>(Ovl)) 13412 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13413 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13414 << OrigOp.get()->getSourceRange(); 13415 return QualType(); 13416 } 13417 13418 return Context.OverloadTy; 13419 } 13420 13421 if (PTy->getKind() == BuiltinType::UnknownAny) 13422 return Context.UnknownAnyTy; 13423 13424 if (PTy->getKind() == BuiltinType::BoundMember) { 13425 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13426 << OrigOp.get()->getSourceRange(); 13427 return QualType(); 13428 } 13429 13430 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13431 if (OrigOp.isInvalid()) return QualType(); 13432 } 13433 13434 if (OrigOp.get()->isTypeDependent()) 13435 return Context.DependentTy; 13436 13437 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13438 13439 // Make sure to ignore parentheses in subsequent checks 13440 Expr *op = OrigOp.get()->IgnoreParens(); 13441 13442 // In OpenCL captures for blocks called as lambda functions 13443 // are located in the private address space. Blocks used in 13444 // enqueue_kernel can be located in a different address space 13445 // depending on a vendor implementation. Thus preventing 13446 // taking an address of the capture to avoid invalid AS casts. 13447 if (LangOpts.OpenCL) { 13448 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13449 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13450 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13451 return QualType(); 13452 } 13453 } 13454 13455 if (getLangOpts().C99) { 13456 // Implement C99-only parts of addressof rules. 13457 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13458 if (uOp->getOpcode() == UO_Deref) 13459 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13460 // (assuming the deref expression is valid). 13461 return uOp->getSubExpr()->getType(); 13462 } 13463 // Technically, there should be a check for array subscript 13464 // expressions here, but the result of one is always an lvalue anyway. 13465 } 13466 ValueDecl *dcl = getPrimaryDecl(op); 13467 13468 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13469 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13470 op->getBeginLoc())) 13471 return QualType(); 13472 13473 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13474 unsigned AddressOfError = AO_No_Error; 13475 13476 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13477 bool sfinae = (bool)isSFINAEContext(); 13478 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13479 : diag::ext_typecheck_addrof_temporary) 13480 << op->getType() << op->getSourceRange(); 13481 if (sfinae) 13482 return QualType(); 13483 // Materialize the temporary as an lvalue so that we can take its address. 13484 OrigOp = op = 13485 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13486 } else if (isa<ObjCSelectorExpr>(op)) { 13487 return Context.getPointerType(op->getType()); 13488 } else if (lval == Expr::LV_MemberFunction) { 13489 // If it's an instance method, make a member pointer. 13490 // The expression must have exactly the form &A::foo. 13491 13492 // If the underlying expression isn't a decl ref, give up. 13493 if (!isa<DeclRefExpr>(op)) { 13494 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13495 << OrigOp.get()->getSourceRange(); 13496 return QualType(); 13497 } 13498 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13499 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13500 13501 // The id-expression was parenthesized. 13502 if (OrigOp.get() != DRE) { 13503 Diag(OpLoc, diag::err_parens_pointer_member_function) 13504 << OrigOp.get()->getSourceRange(); 13505 13506 // The method was named without a qualifier. 13507 } else if (!DRE->getQualifier()) { 13508 if (MD->getParent()->getName().empty()) 13509 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13510 << op->getSourceRange(); 13511 else { 13512 SmallString<32> Str; 13513 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13514 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13515 << op->getSourceRange() 13516 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13517 } 13518 } 13519 13520 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13521 if (isa<CXXDestructorDecl>(MD)) 13522 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13523 13524 QualType MPTy = Context.getMemberPointerType( 13525 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13526 // Under the MS ABI, lock down the inheritance model now. 13527 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13528 (void)isCompleteType(OpLoc, MPTy); 13529 return MPTy; 13530 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13531 // C99 6.5.3.2p1 13532 // The operand must be either an l-value or a function designator 13533 if (!op->getType()->isFunctionType()) { 13534 // Use a special diagnostic for loads from property references. 13535 if (isa<PseudoObjectExpr>(op)) { 13536 AddressOfError = AO_Property_Expansion; 13537 } else { 13538 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13539 << op->getType() << op->getSourceRange(); 13540 return QualType(); 13541 } 13542 } 13543 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13544 // The operand cannot be a bit-field 13545 AddressOfError = AO_Bit_Field; 13546 } else if (op->getObjectKind() == OK_VectorComponent) { 13547 // The operand cannot be an element of a vector 13548 AddressOfError = AO_Vector_Element; 13549 } else if (op->getObjectKind() == OK_MatrixComponent) { 13550 // The operand cannot be an element of a matrix. 13551 AddressOfError = AO_Matrix_Element; 13552 } else if (dcl) { // C99 6.5.3.2p1 13553 // We have an lvalue with a decl. Make sure the decl is not declared 13554 // with the register storage-class specifier. 13555 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13556 // in C++ it is not error to take address of a register 13557 // variable (c++03 7.1.1P3) 13558 if (vd->getStorageClass() == SC_Register && 13559 !getLangOpts().CPlusPlus) { 13560 AddressOfError = AO_Register_Variable; 13561 } 13562 } else if (isa<MSPropertyDecl>(dcl)) { 13563 AddressOfError = AO_Property_Expansion; 13564 } else if (isa<FunctionTemplateDecl>(dcl)) { 13565 return Context.OverloadTy; 13566 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13567 // Okay: we can take the address of a field. 13568 // Could be a pointer to member, though, if there is an explicit 13569 // scope qualifier for the class. 13570 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13571 DeclContext *Ctx = dcl->getDeclContext(); 13572 if (Ctx && Ctx->isRecord()) { 13573 if (dcl->getType()->isReferenceType()) { 13574 Diag(OpLoc, 13575 diag::err_cannot_form_pointer_to_member_of_reference_type) 13576 << dcl->getDeclName() << dcl->getType(); 13577 return QualType(); 13578 } 13579 13580 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13581 Ctx = Ctx->getParent(); 13582 13583 QualType MPTy = Context.getMemberPointerType( 13584 op->getType(), 13585 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13586 // Under the MS ABI, lock down the inheritance model now. 13587 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13588 (void)isCompleteType(OpLoc, MPTy); 13589 return MPTy; 13590 } 13591 } 13592 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13593 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13594 llvm_unreachable("Unknown/unexpected decl type"); 13595 } 13596 13597 if (AddressOfError != AO_No_Error) { 13598 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13599 return QualType(); 13600 } 13601 13602 if (lval == Expr::LV_IncompleteVoidType) { 13603 // Taking the address of a void variable is technically illegal, but we 13604 // allow it in cases which are otherwise valid. 13605 // Example: "extern void x; void* y = &x;". 13606 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13607 } 13608 13609 // If the operand has type "type", the result has type "pointer to type". 13610 if (op->getType()->isObjCObjectType()) 13611 return Context.getObjCObjectPointerType(op->getType()); 13612 13613 CheckAddressOfPackedMember(op); 13614 13615 return Context.getPointerType(op->getType()); 13616 } 13617 13618 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13619 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13620 if (!DRE) 13621 return; 13622 const Decl *D = DRE->getDecl(); 13623 if (!D) 13624 return; 13625 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13626 if (!Param) 13627 return; 13628 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13629 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13630 return; 13631 if (FunctionScopeInfo *FD = S.getCurFunction()) 13632 if (!FD->ModifiedNonNullParams.count(Param)) 13633 FD->ModifiedNonNullParams.insert(Param); 13634 } 13635 13636 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13637 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13638 SourceLocation OpLoc) { 13639 if (Op->isTypeDependent()) 13640 return S.Context.DependentTy; 13641 13642 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13643 if (ConvResult.isInvalid()) 13644 return QualType(); 13645 Op = ConvResult.get(); 13646 QualType OpTy = Op->getType(); 13647 QualType Result; 13648 13649 if (isa<CXXReinterpretCastExpr>(Op)) { 13650 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13651 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13652 Op->getSourceRange()); 13653 } 13654 13655 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13656 { 13657 Result = PT->getPointeeType(); 13658 } 13659 else if (const ObjCObjectPointerType *OPT = 13660 OpTy->getAs<ObjCObjectPointerType>()) 13661 Result = OPT->getPointeeType(); 13662 else { 13663 ExprResult PR = S.CheckPlaceholderExpr(Op); 13664 if (PR.isInvalid()) return QualType(); 13665 if (PR.get() != Op) 13666 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13667 } 13668 13669 if (Result.isNull()) { 13670 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13671 << OpTy << Op->getSourceRange(); 13672 return QualType(); 13673 } 13674 13675 // Note that per both C89 and C99, indirection is always legal, even if Result 13676 // is an incomplete type or void. It would be possible to warn about 13677 // dereferencing a void pointer, but it's completely well-defined, and such a 13678 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13679 // for pointers to 'void' but is fine for any other pointer type: 13680 // 13681 // C++ [expr.unary.op]p1: 13682 // [...] the expression to which [the unary * operator] is applied shall 13683 // be a pointer to an object type, or a pointer to a function type 13684 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13685 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13686 << OpTy << Op->getSourceRange(); 13687 13688 // Dereferences are usually l-values... 13689 VK = VK_LValue; 13690 13691 // ...except that certain expressions are never l-values in C. 13692 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13693 VK = VK_RValue; 13694 13695 return Result; 13696 } 13697 13698 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13699 BinaryOperatorKind Opc; 13700 switch (Kind) { 13701 default: llvm_unreachable("Unknown binop!"); 13702 case tok::periodstar: Opc = BO_PtrMemD; break; 13703 case tok::arrowstar: Opc = BO_PtrMemI; break; 13704 case tok::star: Opc = BO_Mul; break; 13705 case tok::slash: Opc = BO_Div; break; 13706 case tok::percent: Opc = BO_Rem; break; 13707 case tok::plus: Opc = BO_Add; break; 13708 case tok::minus: Opc = BO_Sub; break; 13709 case tok::lessless: Opc = BO_Shl; break; 13710 case tok::greatergreater: Opc = BO_Shr; break; 13711 case tok::lessequal: Opc = BO_LE; break; 13712 case tok::less: Opc = BO_LT; break; 13713 case tok::greaterequal: Opc = BO_GE; break; 13714 case tok::greater: Opc = BO_GT; break; 13715 case tok::exclaimequal: Opc = BO_NE; break; 13716 case tok::equalequal: Opc = BO_EQ; break; 13717 case tok::spaceship: Opc = BO_Cmp; break; 13718 case tok::amp: Opc = BO_And; break; 13719 case tok::caret: Opc = BO_Xor; break; 13720 case tok::pipe: Opc = BO_Or; break; 13721 case tok::ampamp: Opc = BO_LAnd; break; 13722 case tok::pipepipe: Opc = BO_LOr; break; 13723 case tok::equal: Opc = BO_Assign; break; 13724 case tok::starequal: Opc = BO_MulAssign; break; 13725 case tok::slashequal: Opc = BO_DivAssign; break; 13726 case tok::percentequal: Opc = BO_RemAssign; break; 13727 case tok::plusequal: Opc = BO_AddAssign; break; 13728 case tok::minusequal: Opc = BO_SubAssign; break; 13729 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13730 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13731 case tok::ampequal: Opc = BO_AndAssign; break; 13732 case tok::caretequal: Opc = BO_XorAssign; break; 13733 case tok::pipeequal: Opc = BO_OrAssign; break; 13734 case tok::comma: Opc = BO_Comma; break; 13735 } 13736 return Opc; 13737 } 13738 13739 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13740 tok::TokenKind Kind) { 13741 UnaryOperatorKind Opc; 13742 switch (Kind) { 13743 default: llvm_unreachable("Unknown unary op!"); 13744 case tok::plusplus: Opc = UO_PreInc; break; 13745 case tok::minusminus: Opc = UO_PreDec; break; 13746 case tok::amp: Opc = UO_AddrOf; break; 13747 case tok::star: Opc = UO_Deref; break; 13748 case tok::plus: Opc = UO_Plus; break; 13749 case tok::minus: Opc = UO_Minus; break; 13750 case tok::tilde: Opc = UO_Not; break; 13751 case tok::exclaim: Opc = UO_LNot; break; 13752 case tok::kw___real: Opc = UO_Real; break; 13753 case tok::kw___imag: Opc = UO_Imag; break; 13754 case tok::kw___extension__: Opc = UO_Extension; break; 13755 } 13756 return Opc; 13757 } 13758 13759 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13760 /// This warning suppressed in the event of macro expansions. 13761 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13762 SourceLocation OpLoc, bool IsBuiltin) { 13763 if (S.inTemplateInstantiation()) 13764 return; 13765 if (S.isUnevaluatedContext()) 13766 return; 13767 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13768 return; 13769 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13770 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13771 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13772 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13773 if (!LHSDeclRef || !RHSDeclRef || 13774 LHSDeclRef->getLocation().isMacroID() || 13775 RHSDeclRef->getLocation().isMacroID()) 13776 return; 13777 const ValueDecl *LHSDecl = 13778 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13779 const ValueDecl *RHSDecl = 13780 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13781 if (LHSDecl != RHSDecl) 13782 return; 13783 if (LHSDecl->getType().isVolatileQualified()) 13784 return; 13785 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13786 if (RefTy->getPointeeType().isVolatileQualified()) 13787 return; 13788 13789 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13790 : diag::warn_self_assignment_overloaded) 13791 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13792 << RHSExpr->getSourceRange(); 13793 } 13794 13795 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13796 /// is usually indicative of introspection within the Objective-C pointer. 13797 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13798 SourceLocation OpLoc) { 13799 if (!S.getLangOpts().ObjC) 13800 return; 13801 13802 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13803 const Expr *LHS = L.get(); 13804 const Expr *RHS = R.get(); 13805 13806 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13807 ObjCPointerExpr = LHS; 13808 OtherExpr = RHS; 13809 } 13810 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13811 ObjCPointerExpr = RHS; 13812 OtherExpr = LHS; 13813 } 13814 13815 // This warning is deliberately made very specific to reduce false 13816 // positives with logic that uses '&' for hashing. This logic mainly 13817 // looks for code trying to introspect into tagged pointers, which 13818 // code should generally never do. 13819 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13820 unsigned Diag = diag::warn_objc_pointer_masking; 13821 // Determine if we are introspecting the result of performSelectorXXX. 13822 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13823 // Special case messages to -performSelector and friends, which 13824 // can return non-pointer values boxed in a pointer value. 13825 // Some clients may wish to silence warnings in this subcase. 13826 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13827 Selector S = ME->getSelector(); 13828 StringRef SelArg0 = S.getNameForSlot(0); 13829 if (SelArg0.startswith("performSelector")) 13830 Diag = diag::warn_objc_pointer_masking_performSelector; 13831 } 13832 13833 S.Diag(OpLoc, Diag) 13834 << ObjCPointerExpr->getSourceRange(); 13835 } 13836 } 13837 13838 static NamedDecl *getDeclFromExpr(Expr *E) { 13839 if (!E) 13840 return nullptr; 13841 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13842 return DRE->getDecl(); 13843 if (auto *ME = dyn_cast<MemberExpr>(E)) 13844 return ME->getMemberDecl(); 13845 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13846 return IRE->getDecl(); 13847 return nullptr; 13848 } 13849 13850 // This helper function promotes a binary operator's operands (which are of a 13851 // half vector type) to a vector of floats and then truncates the result to 13852 // a vector of either half or short. 13853 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13854 BinaryOperatorKind Opc, QualType ResultTy, 13855 ExprValueKind VK, ExprObjectKind OK, 13856 bool IsCompAssign, SourceLocation OpLoc, 13857 FPOptionsOverride FPFeatures) { 13858 auto &Context = S.getASTContext(); 13859 assert((isVector(ResultTy, Context.HalfTy) || 13860 isVector(ResultTy, Context.ShortTy)) && 13861 "Result must be a vector of half or short"); 13862 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13863 isVector(RHS.get()->getType(), Context.HalfTy) && 13864 "both operands expected to be a half vector"); 13865 13866 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13867 QualType BinOpResTy = RHS.get()->getType(); 13868 13869 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13870 // change BinOpResTy to a vector of ints. 13871 if (isVector(ResultTy, Context.ShortTy)) 13872 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13873 13874 if (IsCompAssign) 13875 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13876 ResultTy, VK, OK, OpLoc, FPFeatures, 13877 BinOpResTy, BinOpResTy); 13878 13879 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13880 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13881 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13882 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13883 } 13884 13885 static std::pair<ExprResult, ExprResult> 13886 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13887 Expr *RHSExpr) { 13888 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13889 if (!S.Context.isDependenceAllowed()) { 13890 // C cannot handle TypoExpr nodes on either side of a binop because it 13891 // doesn't handle dependent types properly, so make sure any TypoExprs have 13892 // been dealt with before checking the operands. 13893 LHS = S.CorrectDelayedTyposInExpr(LHS); 13894 RHS = S.CorrectDelayedTyposInExpr( 13895 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13896 [Opc, LHS](Expr *E) { 13897 if (Opc != BO_Assign) 13898 return ExprResult(E); 13899 // Avoid correcting the RHS to the same Expr as the LHS. 13900 Decl *D = getDeclFromExpr(E); 13901 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13902 }); 13903 } 13904 return std::make_pair(LHS, RHS); 13905 } 13906 13907 /// Returns true if conversion between vectors of halfs and vectors of floats 13908 /// is needed. 13909 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13910 Expr *E0, Expr *E1 = nullptr) { 13911 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13912 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13913 return false; 13914 13915 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13916 QualType Ty = E->IgnoreImplicit()->getType(); 13917 13918 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13919 // to vectors of floats. Although the element type of the vectors is __fp16, 13920 // the vectors shouldn't be treated as storage-only types. See the 13921 // discussion here: https://reviews.llvm.org/rG825235c140e7 13922 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13923 if (VT->getVectorKind() == VectorType::NeonVector) 13924 return false; 13925 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13926 } 13927 return false; 13928 }; 13929 13930 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13931 } 13932 13933 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13934 /// operator @p Opc at location @c TokLoc. This routine only supports 13935 /// built-in operations; ActOnBinOp handles overloaded operators. 13936 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13937 BinaryOperatorKind Opc, 13938 Expr *LHSExpr, Expr *RHSExpr) { 13939 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13940 // The syntax only allows initializer lists on the RHS of assignment, 13941 // so we don't need to worry about accepting invalid code for 13942 // non-assignment operators. 13943 // C++11 5.17p9: 13944 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13945 // of x = {} is x = T(). 13946 InitializationKind Kind = InitializationKind::CreateDirectList( 13947 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13948 InitializedEntity Entity = 13949 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13950 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13951 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13952 if (Init.isInvalid()) 13953 return Init; 13954 RHSExpr = Init.get(); 13955 } 13956 13957 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13958 QualType ResultTy; // Result type of the binary operator. 13959 // The following two variables are used for compound assignment operators 13960 QualType CompLHSTy; // Type of LHS after promotions for computation 13961 QualType CompResultTy; // Type of computation result 13962 ExprValueKind VK = VK_RValue; 13963 ExprObjectKind OK = OK_Ordinary; 13964 bool ConvertHalfVec = false; 13965 13966 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13967 if (!LHS.isUsable() || !RHS.isUsable()) 13968 return ExprError(); 13969 13970 if (getLangOpts().OpenCL) { 13971 QualType LHSTy = LHSExpr->getType(); 13972 QualType RHSTy = RHSExpr->getType(); 13973 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13974 // the ATOMIC_VAR_INIT macro. 13975 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13976 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13977 if (BO_Assign == Opc) 13978 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13979 else 13980 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13981 return ExprError(); 13982 } 13983 13984 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13985 // only with a builtin functions and therefore should be disallowed here. 13986 if (LHSTy->isImageType() || RHSTy->isImageType() || 13987 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13988 LHSTy->isPipeType() || RHSTy->isPipeType() || 13989 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13990 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13991 return ExprError(); 13992 } 13993 } 13994 13995 switch (Opc) { 13996 case BO_Assign: 13997 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13998 if (getLangOpts().CPlusPlus && 13999 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14000 VK = LHS.get()->getValueKind(); 14001 OK = LHS.get()->getObjectKind(); 14002 } 14003 if (!ResultTy.isNull()) { 14004 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14005 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14006 14007 // Avoid copying a block to the heap if the block is assigned to a local 14008 // auto variable that is declared in the same scope as the block. This 14009 // optimization is unsafe if the local variable is declared in an outer 14010 // scope. For example: 14011 // 14012 // BlockTy b; 14013 // { 14014 // b = ^{...}; 14015 // } 14016 // // It is unsafe to invoke the block here if it wasn't copied to the 14017 // // heap. 14018 // b(); 14019 14020 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14021 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14022 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14023 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14024 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14025 14026 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14027 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14028 NTCUC_Assignment, NTCUK_Copy); 14029 } 14030 RecordModifiableNonNullParam(*this, LHS.get()); 14031 break; 14032 case BO_PtrMemD: 14033 case BO_PtrMemI: 14034 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14035 Opc == BO_PtrMemI); 14036 break; 14037 case BO_Mul: 14038 case BO_Div: 14039 ConvertHalfVec = true; 14040 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14041 Opc == BO_Div); 14042 break; 14043 case BO_Rem: 14044 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14045 break; 14046 case BO_Add: 14047 ConvertHalfVec = true; 14048 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14049 break; 14050 case BO_Sub: 14051 ConvertHalfVec = true; 14052 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14053 break; 14054 case BO_Shl: 14055 case BO_Shr: 14056 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14057 break; 14058 case BO_LE: 14059 case BO_LT: 14060 case BO_GE: 14061 case BO_GT: 14062 ConvertHalfVec = true; 14063 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14064 break; 14065 case BO_EQ: 14066 case BO_NE: 14067 ConvertHalfVec = true; 14068 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14069 break; 14070 case BO_Cmp: 14071 ConvertHalfVec = true; 14072 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14073 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14074 break; 14075 case BO_And: 14076 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14077 LLVM_FALLTHROUGH; 14078 case BO_Xor: 14079 case BO_Or: 14080 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14081 break; 14082 case BO_LAnd: 14083 case BO_LOr: 14084 ConvertHalfVec = true; 14085 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14086 break; 14087 case BO_MulAssign: 14088 case BO_DivAssign: 14089 ConvertHalfVec = true; 14090 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14091 Opc == BO_DivAssign); 14092 CompLHSTy = CompResultTy; 14093 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14094 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14095 break; 14096 case BO_RemAssign: 14097 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14098 CompLHSTy = CompResultTy; 14099 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14100 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14101 break; 14102 case BO_AddAssign: 14103 ConvertHalfVec = true; 14104 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14105 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14106 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14107 break; 14108 case BO_SubAssign: 14109 ConvertHalfVec = true; 14110 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14111 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14112 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14113 break; 14114 case BO_ShlAssign: 14115 case BO_ShrAssign: 14116 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14117 CompLHSTy = CompResultTy; 14118 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14119 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14120 break; 14121 case BO_AndAssign: 14122 case BO_OrAssign: // fallthrough 14123 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14124 LLVM_FALLTHROUGH; 14125 case BO_XorAssign: 14126 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14127 CompLHSTy = CompResultTy; 14128 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14130 break; 14131 case BO_Comma: 14132 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14133 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14134 VK = RHS.get()->getValueKind(); 14135 OK = RHS.get()->getObjectKind(); 14136 } 14137 break; 14138 } 14139 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14140 return ExprError(); 14141 14142 // Some of the binary operations require promoting operands of half vector to 14143 // float vectors and truncating the result back to half vector. For now, we do 14144 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14145 // arm64). 14146 assert( 14147 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14148 isVector(LHS.get()->getType(), Context.HalfTy)) && 14149 "both sides are half vectors or neither sides are"); 14150 ConvertHalfVec = 14151 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14152 14153 // Check for array bounds violations for both sides of the BinaryOperator 14154 CheckArrayAccess(LHS.get()); 14155 CheckArrayAccess(RHS.get()); 14156 14157 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14158 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14159 &Context.Idents.get("object_setClass"), 14160 SourceLocation(), LookupOrdinaryName); 14161 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14162 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14163 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14164 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14165 "object_setClass(") 14166 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14167 ",") 14168 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14169 } 14170 else 14171 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14172 } 14173 else if (const ObjCIvarRefExpr *OIRE = 14174 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14175 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14176 14177 // Opc is not a compound assignment if CompResultTy is null. 14178 if (CompResultTy.isNull()) { 14179 if (ConvertHalfVec) 14180 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14181 OpLoc, CurFPFeatureOverrides()); 14182 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14183 VK, OK, OpLoc, CurFPFeatureOverrides()); 14184 } 14185 14186 // Handle compound assignments. 14187 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14188 OK_ObjCProperty) { 14189 VK = VK_LValue; 14190 OK = LHS.get()->getObjectKind(); 14191 } 14192 14193 // The LHS is not converted to the result type for fixed-point compound 14194 // assignment as the common type is computed on demand. Reset the CompLHSTy 14195 // to the LHS type we would have gotten after unary conversions. 14196 if (CompResultTy->isFixedPointType()) 14197 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14198 14199 if (ConvertHalfVec) 14200 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14201 OpLoc, CurFPFeatureOverrides()); 14202 14203 return CompoundAssignOperator::Create( 14204 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14205 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14206 } 14207 14208 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14209 /// operators are mixed in a way that suggests that the programmer forgot that 14210 /// comparison operators have higher precedence. The most typical example of 14211 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14212 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14213 SourceLocation OpLoc, Expr *LHSExpr, 14214 Expr *RHSExpr) { 14215 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14216 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14217 14218 // Check that one of the sides is a comparison operator and the other isn't. 14219 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14220 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14221 if (isLeftComp == isRightComp) 14222 return; 14223 14224 // Bitwise operations are sometimes used as eager logical ops. 14225 // Don't diagnose this. 14226 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14227 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14228 if (isLeftBitwise || isRightBitwise) 14229 return; 14230 14231 SourceRange DiagRange = isLeftComp 14232 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14233 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14234 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14235 SourceRange ParensRange = 14236 isLeftComp 14237 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14238 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14239 14240 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14241 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14242 SuggestParentheses(Self, OpLoc, 14243 Self.PDiag(diag::note_precedence_silence) << OpStr, 14244 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14245 SuggestParentheses(Self, OpLoc, 14246 Self.PDiag(diag::note_precedence_bitwise_first) 14247 << BinaryOperator::getOpcodeStr(Opc), 14248 ParensRange); 14249 } 14250 14251 /// It accepts a '&&' expr that is inside a '||' one. 14252 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14253 /// in parentheses. 14254 static void 14255 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14256 BinaryOperator *Bop) { 14257 assert(Bop->getOpcode() == BO_LAnd); 14258 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14259 << Bop->getSourceRange() << OpLoc; 14260 SuggestParentheses(Self, Bop->getOperatorLoc(), 14261 Self.PDiag(diag::note_precedence_silence) 14262 << Bop->getOpcodeStr(), 14263 Bop->getSourceRange()); 14264 } 14265 14266 /// Returns true if the given expression can be evaluated as a constant 14267 /// 'true'. 14268 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14269 bool Res; 14270 return !E->isValueDependent() && 14271 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14272 } 14273 14274 /// Returns true if the given expression can be evaluated as a constant 14275 /// 'false'. 14276 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14277 bool Res; 14278 return !E->isValueDependent() && 14279 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14280 } 14281 14282 /// Look for '&&' in the left hand of a '||' expr. 14283 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14284 Expr *LHSExpr, Expr *RHSExpr) { 14285 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14286 if (Bop->getOpcode() == BO_LAnd) { 14287 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14288 if (EvaluatesAsFalse(S, RHSExpr)) 14289 return; 14290 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14291 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14292 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14293 } else if (Bop->getOpcode() == BO_LOr) { 14294 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14295 // If it's "a || b && 1 || c" we didn't warn earlier for 14296 // "a || b && 1", but warn now. 14297 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14298 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14299 } 14300 } 14301 } 14302 } 14303 14304 /// Look for '&&' in the right hand of a '||' expr. 14305 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14306 Expr *LHSExpr, Expr *RHSExpr) { 14307 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14308 if (Bop->getOpcode() == BO_LAnd) { 14309 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14310 if (EvaluatesAsFalse(S, LHSExpr)) 14311 return; 14312 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14313 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14314 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14315 } 14316 } 14317 } 14318 14319 /// Look for bitwise op in the left or right hand of a bitwise op with 14320 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14321 /// the '&' expression in parentheses. 14322 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14323 SourceLocation OpLoc, Expr *SubExpr) { 14324 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14325 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14326 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14327 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14328 << Bop->getSourceRange() << OpLoc; 14329 SuggestParentheses(S, Bop->getOperatorLoc(), 14330 S.PDiag(diag::note_precedence_silence) 14331 << Bop->getOpcodeStr(), 14332 Bop->getSourceRange()); 14333 } 14334 } 14335 } 14336 14337 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14338 Expr *SubExpr, StringRef Shift) { 14339 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14340 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14341 StringRef Op = Bop->getOpcodeStr(); 14342 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14343 << Bop->getSourceRange() << OpLoc << Shift << Op; 14344 SuggestParentheses(S, Bop->getOperatorLoc(), 14345 S.PDiag(diag::note_precedence_silence) << Op, 14346 Bop->getSourceRange()); 14347 } 14348 } 14349 } 14350 14351 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14352 Expr *LHSExpr, Expr *RHSExpr) { 14353 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14354 if (!OCE) 14355 return; 14356 14357 FunctionDecl *FD = OCE->getDirectCallee(); 14358 if (!FD || !FD->isOverloadedOperator()) 14359 return; 14360 14361 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14362 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14363 return; 14364 14365 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14366 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14367 << (Kind == OO_LessLess); 14368 SuggestParentheses(S, OCE->getOperatorLoc(), 14369 S.PDiag(diag::note_precedence_silence) 14370 << (Kind == OO_LessLess ? "<<" : ">>"), 14371 OCE->getSourceRange()); 14372 SuggestParentheses( 14373 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14374 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14375 } 14376 14377 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14378 /// precedence. 14379 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14380 SourceLocation OpLoc, Expr *LHSExpr, 14381 Expr *RHSExpr){ 14382 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14383 if (BinaryOperator::isBitwiseOp(Opc)) 14384 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14385 14386 // Diagnose "arg1 & arg2 | arg3" 14387 if ((Opc == BO_Or || Opc == BO_Xor) && 14388 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14389 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14390 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14391 } 14392 14393 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14394 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14395 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14396 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14397 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14398 } 14399 14400 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14401 || Opc == BO_Shr) { 14402 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14403 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14404 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14405 } 14406 14407 // Warn on overloaded shift operators and comparisons, such as: 14408 // cout << 5 == 4; 14409 if (BinaryOperator::isComparisonOp(Opc)) 14410 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14411 } 14412 14413 // Binary Operators. 'Tok' is the token for the operator. 14414 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14415 tok::TokenKind Kind, 14416 Expr *LHSExpr, Expr *RHSExpr) { 14417 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14418 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14419 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14420 14421 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14422 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14423 14424 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14425 } 14426 14427 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14428 UnresolvedSetImpl &Functions) { 14429 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14430 if (OverOp != OO_None && OverOp != OO_Equal) 14431 LookupOverloadedOperatorName(OverOp, S, Functions); 14432 14433 // In C++20 onwards, we may have a second operator to look up. 14434 if (getLangOpts().CPlusPlus20) { 14435 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14436 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14437 } 14438 } 14439 14440 /// Build an overloaded binary operator expression in the given scope. 14441 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14442 BinaryOperatorKind Opc, 14443 Expr *LHS, Expr *RHS) { 14444 switch (Opc) { 14445 case BO_Assign: 14446 case BO_DivAssign: 14447 case BO_RemAssign: 14448 case BO_SubAssign: 14449 case BO_AndAssign: 14450 case BO_OrAssign: 14451 case BO_XorAssign: 14452 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14453 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14454 break; 14455 default: 14456 break; 14457 } 14458 14459 // Find all of the overloaded operators visible from this point. 14460 UnresolvedSet<16> Functions; 14461 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14462 14463 // Build the (potentially-overloaded, potentially-dependent) 14464 // binary operation. 14465 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14466 } 14467 14468 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14469 BinaryOperatorKind Opc, 14470 Expr *LHSExpr, Expr *RHSExpr) { 14471 ExprResult LHS, RHS; 14472 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14473 if (!LHS.isUsable() || !RHS.isUsable()) 14474 return ExprError(); 14475 LHSExpr = LHS.get(); 14476 RHSExpr = RHS.get(); 14477 14478 // We want to end up calling one of checkPseudoObjectAssignment 14479 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14480 // both expressions are overloadable or either is type-dependent), 14481 // or CreateBuiltinBinOp (in any other case). We also want to get 14482 // any placeholder types out of the way. 14483 14484 // Handle pseudo-objects in the LHS. 14485 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14486 // Assignments with a pseudo-object l-value need special analysis. 14487 if (pty->getKind() == BuiltinType::PseudoObject && 14488 BinaryOperator::isAssignmentOp(Opc)) 14489 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14490 14491 // Don't resolve overloads if the other type is overloadable. 14492 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14493 // We can't actually test that if we still have a placeholder, 14494 // though. Fortunately, none of the exceptions we see in that 14495 // code below are valid when the LHS is an overload set. Note 14496 // that an overload set can be dependently-typed, but it never 14497 // instantiates to having an overloadable type. 14498 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14499 if (resolvedRHS.isInvalid()) return ExprError(); 14500 RHSExpr = resolvedRHS.get(); 14501 14502 if (RHSExpr->isTypeDependent() || 14503 RHSExpr->getType()->isOverloadableType()) 14504 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14505 } 14506 14507 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14508 // template, diagnose the missing 'template' keyword instead of diagnosing 14509 // an invalid use of a bound member function. 14510 // 14511 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14512 // to C++1z [over.over]/1.4, but we already checked for that case above. 14513 if (Opc == BO_LT && inTemplateInstantiation() && 14514 (pty->getKind() == BuiltinType::BoundMember || 14515 pty->getKind() == BuiltinType::Overload)) { 14516 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14517 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14518 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14519 return isa<FunctionTemplateDecl>(ND); 14520 })) { 14521 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14522 : OE->getNameLoc(), 14523 diag::err_template_kw_missing) 14524 << OE->getName().getAsString() << ""; 14525 return ExprError(); 14526 } 14527 } 14528 14529 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14530 if (LHS.isInvalid()) return ExprError(); 14531 LHSExpr = LHS.get(); 14532 } 14533 14534 // Handle pseudo-objects in the RHS. 14535 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14536 // An overload in the RHS can potentially be resolved by the type 14537 // being assigned to. 14538 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14539 if (getLangOpts().CPlusPlus && 14540 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14541 LHSExpr->getType()->isOverloadableType())) 14542 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14543 14544 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14545 } 14546 14547 // Don't resolve overloads if the other type is overloadable. 14548 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14549 LHSExpr->getType()->isOverloadableType()) 14550 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14551 14552 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14553 if (!resolvedRHS.isUsable()) return ExprError(); 14554 RHSExpr = resolvedRHS.get(); 14555 } 14556 14557 if (getLangOpts().CPlusPlus) { 14558 // If either expression is type-dependent, always build an 14559 // overloaded op. 14560 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14561 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14562 14563 // Otherwise, build an overloaded op if either expression has an 14564 // overloadable type. 14565 if (LHSExpr->getType()->isOverloadableType() || 14566 RHSExpr->getType()->isOverloadableType()) 14567 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14568 } 14569 14570 if (getLangOpts().RecoveryAST && 14571 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14572 assert(!getLangOpts().CPlusPlus); 14573 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14574 "Should only occur in error-recovery path."); 14575 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14576 // C [6.15.16] p3: 14577 // An assignment expression has the value of the left operand after the 14578 // assignment, but is not an lvalue. 14579 return CompoundAssignOperator::Create( 14580 Context, LHSExpr, RHSExpr, Opc, 14581 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14582 OpLoc, CurFPFeatureOverrides()); 14583 QualType ResultType; 14584 switch (Opc) { 14585 case BO_Assign: 14586 ResultType = LHSExpr->getType().getUnqualifiedType(); 14587 break; 14588 case BO_LT: 14589 case BO_GT: 14590 case BO_LE: 14591 case BO_GE: 14592 case BO_EQ: 14593 case BO_NE: 14594 case BO_LAnd: 14595 case BO_LOr: 14596 // These operators have a fixed result type regardless of operands. 14597 ResultType = Context.IntTy; 14598 break; 14599 case BO_Comma: 14600 ResultType = RHSExpr->getType(); 14601 break; 14602 default: 14603 ResultType = Context.DependentTy; 14604 break; 14605 } 14606 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14607 VK_RValue, OK_Ordinary, OpLoc, 14608 CurFPFeatureOverrides()); 14609 } 14610 14611 // Build a built-in binary operation. 14612 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14613 } 14614 14615 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14616 if (T.isNull() || T->isDependentType()) 14617 return false; 14618 14619 if (!T->isPromotableIntegerType()) 14620 return true; 14621 14622 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14623 } 14624 14625 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14626 UnaryOperatorKind Opc, 14627 Expr *InputExpr) { 14628 ExprResult Input = InputExpr; 14629 ExprValueKind VK = VK_RValue; 14630 ExprObjectKind OK = OK_Ordinary; 14631 QualType resultType; 14632 bool CanOverflow = false; 14633 14634 bool ConvertHalfVec = false; 14635 if (getLangOpts().OpenCL) { 14636 QualType Ty = InputExpr->getType(); 14637 // The only legal unary operation for atomics is '&'. 14638 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14639 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14640 // only with a builtin functions and therefore should be disallowed here. 14641 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14642 || Ty->isBlockPointerType())) { 14643 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14644 << InputExpr->getType() 14645 << Input.get()->getSourceRange()); 14646 } 14647 } 14648 14649 switch (Opc) { 14650 case UO_PreInc: 14651 case UO_PreDec: 14652 case UO_PostInc: 14653 case UO_PostDec: 14654 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14655 OpLoc, 14656 Opc == UO_PreInc || 14657 Opc == UO_PostInc, 14658 Opc == UO_PreInc || 14659 Opc == UO_PreDec); 14660 CanOverflow = isOverflowingIntegerType(Context, resultType); 14661 break; 14662 case UO_AddrOf: 14663 resultType = CheckAddressOfOperand(Input, OpLoc); 14664 CheckAddressOfNoDeref(InputExpr); 14665 RecordModifiableNonNullParam(*this, InputExpr); 14666 break; 14667 case UO_Deref: { 14668 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14669 if (Input.isInvalid()) return ExprError(); 14670 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14671 break; 14672 } 14673 case UO_Plus: 14674 case UO_Minus: 14675 CanOverflow = Opc == UO_Minus && 14676 isOverflowingIntegerType(Context, Input.get()->getType()); 14677 Input = UsualUnaryConversions(Input.get()); 14678 if (Input.isInvalid()) return ExprError(); 14679 // Unary plus and minus require promoting an operand of half vector to a 14680 // float vector and truncating the result back to a half vector. For now, we 14681 // do this only when HalfArgsAndReturns is set (that is, when the target is 14682 // arm or arm64). 14683 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14684 14685 // If the operand is a half vector, promote it to a float vector. 14686 if (ConvertHalfVec) 14687 Input = convertVector(Input.get(), Context.FloatTy, *this); 14688 resultType = Input.get()->getType(); 14689 if (resultType->isDependentType()) 14690 break; 14691 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14692 break; 14693 else if (resultType->isVectorType() && 14694 // The z vector extensions don't allow + or - with bool vectors. 14695 (!Context.getLangOpts().ZVector || 14696 resultType->castAs<VectorType>()->getVectorKind() != 14697 VectorType::AltiVecBool)) 14698 break; 14699 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14700 Opc == UO_Plus && 14701 resultType->isPointerType()) 14702 break; 14703 14704 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14705 << resultType << Input.get()->getSourceRange()); 14706 14707 case UO_Not: // bitwise complement 14708 Input = UsualUnaryConversions(Input.get()); 14709 if (Input.isInvalid()) 14710 return ExprError(); 14711 resultType = Input.get()->getType(); 14712 if (resultType->isDependentType()) 14713 break; 14714 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14715 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14716 // C99 does not support '~' for complex conjugation. 14717 Diag(OpLoc, diag::ext_integer_complement_complex) 14718 << resultType << Input.get()->getSourceRange(); 14719 else if (resultType->hasIntegerRepresentation()) 14720 break; 14721 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14722 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14723 // on vector float types. 14724 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14725 if (!T->isIntegerType()) 14726 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14727 << resultType << Input.get()->getSourceRange()); 14728 } else { 14729 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14730 << resultType << Input.get()->getSourceRange()); 14731 } 14732 break; 14733 14734 case UO_LNot: // logical negation 14735 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14736 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14737 if (Input.isInvalid()) return ExprError(); 14738 resultType = Input.get()->getType(); 14739 14740 // Though we still have to promote half FP to float... 14741 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14742 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14743 resultType = Context.FloatTy; 14744 } 14745 14746 if (resultType->isDependentType()) 14747 break; 14748 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14749 // C99 6.5.3.3p1: ok, fallthrough; 14750 if (Context.getLangOpts().CPlusPlus) { 14751 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14752 // operand contextually converted to bool. 14753 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14754 ScalarTypeToBooleanCastKind(resultType)); 14755 } else if (Context.getLangOpts().OpenCL && 14756 Context.getLangOpts().OpenCLVersion < 120) { 14757 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14758 // operate on scalar float types. 14759 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14760 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14761 << resultType << Input.get()->getSourceRange()); 14762 } 14763 } else if (resultType->isExtVectorType()) { 14764 if (Context.getLangOpts().OpenCL && 14765 Context.getLangOpts().OpenCLVersion < 120 && 14766 !Context.getLangOpts().OpenCLCPlusPlus) { 14767 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14768 // operate on vector float types. 14769 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14770 if (!T->isIntegerType()) 14771 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14772 << resultType << Input.get()->getSourceRange()); 14773 } 14774 // Vector logical not returns the signed variant of the operand type. 14775 resultType = GetSignedVectorType(resultType); 14776 break; 14777 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14778 const VectorType *VTy = resultType->castAs<VectorType>(); 14779 if (VTy->getVectorKind() != VectorType::GenericVector) 14780 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14781 << resultType << Input.get()->getSourceRange()); 14782 14783 // Vector logical not returns the signed variant of the operand type. 14784 resultType = GetSignedVectorType(resultType); 14785 break; 14786 } else { 14787 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14788 << resultType << Input.get()->getSourceRange()); 14789 } 14790 14791 // LNot always has type int. C99 6.5.3.3p5. 14792 // In C++, it's bool. C++ 5.3.1p8 14793 resultType = Context.getLogicalOperationType(); 14794 break; 14795 case UO_Real: 14796 case UO_Imag: 14797 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14798 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14799 // complex l-values to ordinary l-values and all other values to r-values. 14800 if (Input.isInvalid()) return ExprError(); 14801 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14802 if (Input.get()->getValueKind() != VK_RValue && 14803 Input.get()->getObjectKind() == OK_Ordinary) 14804 VK = Input.get()->getValueKind(); 14805 } else if (!getLangOpts().CPlusPlus) { 14806 // In C, a volatile scalar is read by __imag. In C++, it is not. 14807 Input = DefaultLvalueConversion(Input.get()); 14808 } 14809 break; 14810 case UO_Extension: 14811 resultType = Input.get()->getType(); 14812 VK = Input.get()->getValueKind(); 14813 OK = Input.get()->getObjectKind(); 14814 break; 14815 case UO_Coawait: 14816 // It's unnecessary to represent the pass-through operator co_await in the 14817 // AST; just return the input expression instead. 14818 assert(!Input.get()->getType()->isDependentType() && 14819 "the co_await expression must be non-dependant before " 14820 "building operator co_await"); 14821 return Input; 14822 } 14823 if (resultType.isNull() || Input.isInvalid()) 14824 return ExprError(); 14825 14826 // Check for array bounds violations in the operand of the UnaryOperator, 14827 // except for the '*' and '&' operators that have to be handled specially 14828 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14829 // that are explicitly defined as valid by the standard). 14830 if (Opc != UO_AddrOf && Opc != UO_Deref) 14831 CheckArrayAccess(Input.get()); 14832 14833 auto *UO = 14834 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14835 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14836 14837 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14838 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14839 !isUnevaluatedContext()) 14840 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14841 14842 // Convert the result back to a half vector. 14843 if (ConvertHalfVec) 14844 return convertVector(UO, Context.HalfTy, *this); 14845 return UO; 14846 } 14847 14848 /// Determine whether the given expression is a qualified member 14849 /// access expression, of a form that could be turned into a pointer to member 14850 /// with the address-of operator. 14851 bool Sema::isQualifiedMemberAccess(Expr *E) { 14852 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14853 if (!DRE->getQualifier()) 14854 return false; 14855 14856 ValueDecl *VD = DRE->getDecl(); 14857 if (!VD->isCXXClassMember()) 14858 return false; 14859 14860 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14861 return true; 14862 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14863 return Method->isInstance(); 14864 14865 return false; 14866 } 14867 14868 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14869 if (!ULE->getQualifier()) 14870 return false; 14871 14872 for (NamedDecl *D : ULE->decls()) { 14873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14874 if (Method->isInstance()) 14875 return true; 14876 } else { 14877 // Overload set does not contain methods. 14878 break; 14879 } 14880 } 14881 14882 return false; 14883 } 14884 14885 return false; 14886 } 14887 14888 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14889 UnaryOperatorKind Opc, Expr *Input) { 14890 // First things first: handle placeholders so that the 14891 // overloaded-operator check considers the right type. 14892 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14893 // Increment and decrement of pseudo-object references. 14894 if (pty->getKind() == BuiltinType::PseudoObject && 14895 UnaryOperator::isIncrementDecrementOp(Opc)) 14896 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14897 14898 // extension is always a builtin operator. 14899 if (Opc == UO_Extension) 14900 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14901 14902 // & gets special logic for several kinds of placeholder. 14903 // The builtin code knows what to do. 14904 if (Opc == UO_AddrOf && 14905 (pty->getKind() == BuiltinType::Overload || 14906 pty->getKind() == BuiltinType::UnknownAny || 14907 pty->getKind() == BuiltinType::BoundMember)) 14908 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14909 14910 // Anything else needs to be handled now. 14911 ExprResult Result = CheckPlaceholderExpr(Input); 14912 if (Result.isInvalid()) return ExprError(); 14913 Input = Result.get(); 14914 } 14915 14916 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14917 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14918 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14919 // Find all of the overloaded operators visible from this point. 14920 UnresolvedSet<16> Functions; 14921 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14922 if (S && OverOp != OO_None) 14923 LookupOverloadedOperatorName(OverOp, S, Functions); 14924 14925 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14926 } 14927 14928 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14929 } 14930 14931 // Unary Operators. 'Tok' is the token for the operator. 14932 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14933 tok::TokenKind Op, Expr *Input) { 14934 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14935 } 14936 14937 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14938 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14939 LabelDecl *TheDecl) { 14940 TheDecl->markUsed(Context); 14941 // Create the AST node. The address of a label always has type 'void*'. 14942 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14943 Context.getPointerType(Context.VoidTy)); 14944 } 14945 14946 void Sema::ActOnStartStmtExpr() { 14947 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14948 } 14949 14950 void Sema::ActOnStmtExprError() { 14951 // Note that function is also called by TreeTransform when leaving a 14952 // StmtExpr scope without rebuilding anything. 14953 14954 DiscardCleanupsInEvaluationContext(); 14955 PopExpressionEvaluationContext(); 14956 } 14957 14958 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14959 SourceLocation RPLoc) { 14960 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14961 } 14962 14963 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14964 SourceLocation RPLoc, unsigned TemplateDepth) { 14965 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14966 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14967 14968 if (hasAnyUnrecoverableErrorsInThisFunction()) 14969 DiscardCleanupsInEvaluationContext(); 14970 assert(!Cleanup.exprNeedsCleanups() && 14971 "cleanups within StmtExpr not correctly bound!"); 14972 PopExpressionEvaluationContext(); 14973 14974 // FIXME: there are a variety of strange constraints to enforce here, for 14975 // example, it is not possible to goto into a stmt expression apparently. 14976 // More semantic analysis is needed. 14977 14978 // If there are sub-stmts in the compound stmt, take the type of the last one 14979 // as the type of the stmtexpr. 14980 QualType Ty = Context.VoidTy; 14981 bool StmtExprMayBindToTemp = false; 14982 if (!Compound->body_empty()) { 14983 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14984 if (const auto *LastStmt = 14985 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14986 if (const Expr *Value = LastStmt->getExprStmt()) { 14987 StmtExprMayBindToTemp = true; 14988 Ty = Value->getType(); 14989 } 14990 } 14991 } 14992 14993 // FIXME: Check that expression type is complete/non-abstract; statement 14994 // expressions are not lvalues. 14995 Expr *ResStmtExpr = 14996 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14997 if (StmtExprMayBindToTemp) 14998 return MaybeBindToTemporary(ResStmtExpr); 14999 return ResStmtExpr; 15000 } 15001 15002 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15003 if (ER.isInvalid()) 15004 return ExprError(); 15005 15006 // Do function/array conversion on the last expression, but not 15007 // lvalue-to-rvalue. However, initialize an unqualified type. 15008 ER = DefaultFunctionArrayConversion(ER.get()); 15009 if (ER.isInvalid()) 15010 return ExprError(); 15011 Expr *E = ER.get(); 15012 15013 if (E->isTypeDependent()) 15014 return E; 15015 15016 // In ARC, if the final expression ends in a consume, splice 15017 // the consume out and bind it later. In the alternate case 15018 // (when dealing with a retainable type), the result 15019 // initialization will create a produce. In both cases the 15020 // result will be +1, and we'll need to balance that out with 15021 // a bind. 15022 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15023 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15024 return Cast->getSubExpr(); 15025 15026 // FIXME: Provide a better location for the initialization. 15027 return PerformCopyInitialization( 15028 InitializedEntity::InitializeStmtExprResult( 15029 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15030 SourceLocation(), E); 15031 } 15032 15033 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15034 TypeSourceInfo *TInfo, 15035 ArrayRef<OffsetOfComponent> Components, 15036 SourceLocation RParenLoc) { 15037 QualType ArgTy = TInfo->getType(); 15038 bool Dependent = ArgTy->isDependentType(); 15039 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15040 15041 // We must have at least one component that refers to the type, and the first 15042 // one is known to be a field designator. Verify that the ArgTy represents 15043 // a struct/union/class. 15044 if (!Dependent && !ArgTy->isRecordType()) 15045 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15046 << ArgTy << TypeRange); 15047 15048 // Type must be complete per C99 7.17p3 because a declaring a variable 15049 // with an incomplete type would be ill-formed. 15050 if (!Dependent 15051 && RequireCompleteType(BuiltinLoc, ArgTy, 15052 diag::err_offsetof_incomplete_type, TypeRange)) 15053 return ExprError(); 15054 15055 bool DidWarnAboutNonPOD = false; 15056 QualType CurrentType = ArgTy; 15057 SmallVector<OffsetOfNode, 4> Comps; 15058 SmallVector<Expr*, 4> Exprs; 15059 for (const OffsetOfComponent &OC : Components) { 15060 if (OC.isBrackets) { 15061 // Offset of an array sub-field. TODO: Should we allow vector elements? 15062 if (!CurrentType->isDependentType()) { 15063 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15064 if(!AT) 15065 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15066 << CurrentType); 15067 CurrentType = AT->getElementType(); 15068 } else 15069 CurrentType = Context.DependentTy; 15070 15071 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15072 if (IdxRval.isInvalid()) 15073 return ExprError(); 15074 Expr *Idx = IdxRval.get(); 15075 15076 // The expression must be an integral expression. 15077 // FIXME: An integral constant expression? 15078 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15079 !Idx->getType()->isIntegerType()) 15080 return ExprError( 15081 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15082 << Idx->getSourceRange()); 15083 15084 // Record this array index. 15085 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15086 Exprs.push_back(Idx); 15087 continue; 15088 } 15089 15090 // Offset of a field. 15091 if (CurrentType->isDependentType()) { 15092 // We have the offset of a field, but we can't look into the dependent 15093 // type. Just record the identifier of the field. 15094 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15095 CurrentType = Context.DependentTy; 15096 continue; 15097 } 15098 15099 // We need to have a complete type to look into. 15100 if (RequireCompleteType(OC.LocStart, CurrentType, 15101 diag::err_offsetof_incomplete_type)) 15102 return ExprError(); 15103 15104 // Look for the designated field. 15105 const RecordType *RC = CurrentType->getAs<RecordType>(); 15106 if (!RC) 15107 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15108 << CurrentType); 15109 RecordDecl *RD = RC->getDecl(); 15110 15111 // C++ [lib.support.types]p5: 15112 // The macro offsetof accepts a restricted set of type arguments in this 15113 // International Standard. type shall be a POD structure or a POD union 15114 // (clause 9). 15115 // C++11 [support.types]p4: 15116 // If type is not a standard-layout class (Clause 9), the results are 15117 // undefined. 15118 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15119 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15120 unsigned DiagID = 15121 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15122 : diag::ext_offsetof_non_pod_type; 15123 15124 if (!IsSafe && !DidWarnAboutNonPOD && 15125 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15126 PDiag(DiagID) 15127 << SourceRange(Components[0].LocStart, OC.LocEnd) 15128 << CurrentType)) 15129 DidWarnAboutNonPOD = true; 15130 } 15131 15132 // Look for the field. 15133 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15134 LookupQualifiedName(R, RD); 15135 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15136 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15137 if (!MemberDecl) { 15138 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15139 MemberDecl = IndirectMemberDecl->getAnonField(); 15140 } 15141 15142 if (!MemberDecl) 15143 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15144 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15145 OC.LocEnd)); 15146 15147 // C99 7.17p3: 15148 // (If the specified member is a bit-field, the behavior is undefined.) 15149 // 15150 // We diagnose this as an error. 15151 if (MemberDecl->isBitField()) { 15152 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15153 << MemberDecl->getDeclName() 15154 << SourceRange(BuiltinLoc, RParenLoc); 15155 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15156 return ExprError(); 15157 } 15158 15159 RecordDecl *Parent = MemberDecl->getParent(); 15160 if (IndirectMemberDecl) 15161 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15162 15163 // If the member was found in a base class, introduce OffsetOfNodes for 15164 // the base class indirections. 15165 CXXBasePaths Paths; 15166 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15167 Paths)) { 15168 if (Paths.getDetectedVirtual()) { 15169 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15170 << MemberDecl->getDeclName() 15171 << SourceRange(BuiltinLoc, RParenLoc); 15172 return ExprError(); 15173 } 15174 15175 CXXBasePath &Path = Paths.front(); 15176 for (const CXXBasePathElement &B : Path) 15177 Comps.push_back(OffsetOfNode(B.Base)); 15178 } 15179 15180 if (IndirectMemberDecl) { 15181 for (auto *FI : IndirectMemberDecl->chain()) { 15182 assert(isa<FieldDecl>(FI)); 15183 Comps.push_back(OffsetOfNode(OC.LocStart, 15184 cast<FieldDecl>(FI), OC.LocEnd)); 15185 } 15186 } else 15187 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15188 15189 CurrentType = MemberDecl->getType().getNonReferenceType(); 15190 } 15191 15192 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15193 Comps, Exprs, RParenLoc); 15194 } 15195 15196 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15197 SourceLocation BuiltinLoc, 15198 SourceLocation TypeLoc, 15199 ParsedType ParsedArgTy, 15200 ArrayRef<OffsetOfComponent> Components, 15201 SourceLocation RParenLoc) { 15202 15203 TypeSourceInfo *ArgTInfo; 15204 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15205 if (ArgTy.isNull()) 15206 return ExprError(); 15207 15208 if (!ArgTInfo) 15209 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15210 15211 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15212 } 15213 15214 15215 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15216 Expr *CondExpr, 15217 Expr *LHSExpr, Expr *RHSExpr, 15218 SourceLocation RPLoc) { 15219 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15220 15221 ExprValueKind VK = VK_RValue; 15222 ExprObjectKind OK = OK_Ordinary; 15223 QualType resType; 15224 bool CondIsTrue = false; 15225 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15226 resType = Context.DependentTy; 15227 } else { 15228 // The conditional expression is required to be a constant expression. 15229 llvm::APSInt condEval(32); 15230 ExprResult CondICE = VerifyIntegerConstantExpression( 15231 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15232 if (CondICE.isInvalid()) 15233 return ExprError(); 15234 CondExpr = CondICE.get(); 15235 CondIsTrue = condEval.getZExtValue(); 15236 15237 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15238 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15239 15240 resType = ActiveExpr->getType(); 15241 VK = ActiveExpr->getValueKind(); 15242 OK = ActiveExpr->getObjectKind(); 15243 } 15244 15245 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15246 resType, VK, OK, RPLoc, CondIsTrue); 15247 } 15248 15249 //===----------------------------------------------------------------------===// 15250 // Clang Extensions. 15251 //===----------------------------------------------------------------------===// 15252 15253 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15254 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15255 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15256 15257 if (LangOpts.CPlusPlus) { 15258 MangleNumberingContext *MCtx; 15259 Decl *ManglingContextDecl; 15260 std::tie(MCtx, ManglingContextDecl) = 15261 getCurrentMangleNumberContext(Block->getDeclContext()); 15262 if (MCtx) { 15263 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15264 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15265 } 15266 } 15267 15268 PushBlockScope(CurScope, Block); 15269 CurContext->addDecl(Block); 15270 if (CurScope) 15271 PushDeclContext(CurScope, Block); 15272 else 15273 CurContext = Block; 15274 15275 getCurBlock()->HasImplicitReturnType = true; 15276 15277 // Enter a new evaluation context to insulate the block from any 15278 // cleanups from the enclosing full-expression. 15279 PushExpressionEvaluationContext( 15280 ExpressionEvaluationContext::PotentiallyEvaluated); 15281 } 15282 15283 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15284 Scope *CurScope) { 15285 assert(ParamInfo.getIdentifier() == nullptr && 15286 "block-id should have no identifier!"); 15287 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15288 BlockScopeInfo *CurBlock = getCurBlock(); 15289 15290 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15291 QualType T = Sig->getType(); 15292 15293 // FIXME: We should allow unexpanded parameter packs here, but that would, 15294 // in turn, make the block expression contain unexpanded parameter packs. 15295 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15296 // Drop the parameters. 15297 FunctionProtoType::ExtProtoInfo EPI; 15298 EPI.HasTrailingReturn = false; 15299 EPI.TypeQuals.addConst(); 15300 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15301 Sig = Context.getTrivialTypeSourceInfo(T); 15302 } 15303 15304 // GetTypeForDeclarator always produces a function type for a block 15305 // literal signature. Furthermore, it is always a FunctionProtoType 15306 // unless the function was written with a typedef. 15307 assert(T->isFunctionType() && 15308 "GetTypeForDeclarator made a non-function block signature"); 15309 15310 // Look for an explicit signature in that function type. 15311 FunctionProtoTypeLoc ExplicitSignature; 15312 15313 if ((ExplicitSignature = Sig->getTypeLoc() 15314 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15315 15316 // Check whether that explicit signature was synthesized by 15317 // GetTypeForDeclarator. If so, don't save that as part of the 15318 // written signature. 15319 if (ExplicitSignature.getLocalRangeBegin() == 15320 ExplicitSignature.getLocalRangeEnd()) { 15321 // This would be much cheaper if we stored TypeLocs instead of 15322 // TypeSourceInfos. 15323 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15324 unsigned Size = Result.getFullDataSize(); 15325 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15326 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15327 15328 ExplicitSignature = FunctionProtoTypeLoc(); 15329 } 15330 } 15331 15332 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15333 CurBlock->FunctionType = T; 15334 15335 const auto *Fn = T->castAs<FunctionType>(); 15336 QualType RetTy = Fn->getReturnType(); 15337 bool isVariadic = 15338 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15339 15340 CurBlock->TheDecl->setIsVariadic(isVariadic); 15341 15342 // Context.DependentTy is used as a placeholder for a missing block 15343 // return type. TODO: what should we do with declarators like: 15344 // ^ * { ... } 15345 // If the answer is "apply template argument deduction".... 15346 if (RetTy != Context.DependentTy) { 15347 CurBlock->ReturnType = RetTy; 15348 CurBlock->TheDecl->setBlockMissingReturnType(false); 15349 CurBlock->HasImplicitReturnType = false; 15350 } 15351 15352 // Push block parameters from the declarator if we had them. 15353 SmallVector<ParmVarDecl*, 8> Params; 15354 if (ExplicitSignature) { 15355 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15356 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15357 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15358 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15359 // Diagnose this as an extension in C17 and earlier. 15360 if (!getLangOpts().C2x) 15361 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15362 } 15363 Params.push_back(Param); 15364 } 15365 15366 // Fake up parameter variables if we have a typedef, like 15367 // ^ fntype { ... } 15368 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15369 for (const auto &I : Fn->param_types()) { 15370 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15371 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15372 Params.push_back(Param); 15373 } 15374 } 15375 15376 // Set the parameters on the block decl. 15377 if (!Params.empty()) { 15378 CurBlock->TheDecl->setParams(Params); 15379 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15380 /*CheckParameterNames=*/false); 15381 } 15382 15383 // Finally we can process decl attributes. 15384 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15385 15386 // Put the parameter variables in scope. 15387 for (auto AI : CurBlock->TheDecl->parameters()) { 15388 AI->setOwningFunction(CurBlock->TheDecl); 15389 15390 // If this has an identifier, add it to the scope stack. 15391 if (AI->getIdentifier()) { 15392 CheckShadow(CurBlock->TheScope, AI); 15393 15394 PushOnScopeChains(AI, CurBlock->TheScope); 15395 } 15396 } 15397 } 15398 15399 /// ActOnBlockError - If there is an error parsing a block, this callback 15400 /// is invoked to pop the information about the block from the action impl. 15401 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15402 // Leave the expression-evaluation context. 15403 DiscardCleanupsInEvaluationContext(); 15404 PopExpressionEvaluationContext(); 15405 15406 // Pop off CurBlock, handle nested blocks. 15407 PopDeclContext(); 15408 PopFunctionScopeInfo(); 15409 } 15410 15411 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15412 /// literal was successfully completed. ^(int x){...} 15413 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15414 Stmt *Body, Scope *CurScope) { 15415 // If blocks are disabled, emit an error. 15416 if (!LangOpts.Blocks) 15417 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15418 15419 // Leave the expression-evaluation context. 15420 if (hasAnyUnrecoverableErrorsInThisFunction()) 15421 DiscardCleanupsInEvaluationContext(); 15422 assert(!Cleanup.exprNeedsCleanups() && 15423 "cleanups within block not correctly bound!"); 15424 PopExpressionEvaluationContext(); 15425 15426 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15427 BlockDecl *BD = BSI->TheDecl; 15428 15429 if (BSI->HasImplicitReturnType) 15430 deduceClosureReturnType(*BSI); 15431 15432 QualType RetTy = Context.VoidTy; 15433 if (!BSI->ReturnType.isNull()) 15434 RetTy = BSI->ReturnType; 15435 15436 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15437 QualType BlockTy; 15438 15439 // If the user wrote a function type in some form, try to use that. 15440 if (!BSI->FunctionType.isNull()) { 15441 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15442 15443 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15444 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15445 15446 // Turn protoless block types into nullary block types. 15447 if (isa<FunctionNoProtoType>(FTy)) { 15448 FunctionProtoType::ExtProtoInfo EPI; 15449 EPI.ExtInfo = Ext; 15450 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15451 15452 // Otherwise, if we don't need to change anything about the function type, 15453 // preserve its sugar structure. 15454 } else if (FTy->getReturnType() == RetTy && 15455 (!NoReturn || FTy->getNoReturnAttr())) { 15456 BlockTy = BSI->FunctionType; 15457 15458 // Otherwise, make the minimal modifications to the function type. 15459 } else { 15460 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15461 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15462 EPI.TypeQuals = Qualifiers(); 15463 EPI.ExtInfo = Ext; 15464 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15465 } 15466 15467 // If we don't have a function type, just build one from nothing. 15468 } else { 15469 FunctionProtoType::ExtProtoInfo EPI; 15470 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15471 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15472 } 15473 15474 DiagnoseUnusedParameters(BD->parameters()); 15475 BlockTy = Context.getBlockPointerType(BlockTy); 15476 15477 // If needed, diagnose invalid gotos and switches in the block. 15478 if (getCurFunction()->NeedsScopeChecking() && 15479 !PP.isCodeCompletionEnabled()) 15480 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15481 15482 BD->setBody(cast<CompoundStmt>(Body)); 15483 15484 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15485 DiagnoseUnguardedAvailabilityViolations(BD); 15486 15487 // Try to apply the named return value optimization. We have to check again 15488 // if we can do this, though, because blocks keep return statements around 15489 // to deduce an implicit return type. 15490 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15491 !BD->isDependentContext()) 15492 computeNRVO(Body, BSI); 15493 15494 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15495 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15496 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15497 NTCUK_Destruct|NTCUK_Copy); 15498 15499 PopDeclContext(); 15500 15501 // Set the captured variables on the block. 15502 SmallVector<BlockDecl::Capture, 4> Captures; 15503 for (Capture &Cap : BSI->Captures) { 15504 if (Cap.isInvalid() || Cap.isThisCapture()) 15505 continue; 15506 15507 VarDecl *Var = Cap.getVariable(); 15508 Expr *CopyExpr = nullptr; 15509 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15510 if (const RecordType *Record = 15511 Cap.getCaptureType()->getAs<RecordType>()) { 15512 // The capture logic needs the destructor, so make sure we mark it. 15513 // Usually this is unnecessary because most local variables have 15514 // their destructors marked at declaration time, but parameters are 15515 // an exception because it's technically only the call site that 15516 // actually requires the destructor. 15517 if (isa<ParmVarDecl>(Var)) 15518 FinalizeVarWithDestructor(Var, Record); 15519 15520 // Enter a separate potentially-evaluated context while building block 15521 // initializers to isolate their cleanups from those of the block 15522 // itself. 15523 // FIXME: Is this appropriate even when the block itself occurs in an 15524 // unevaluated operand? 15525 EnterExpressionEvaluationContext EvalContext( 15526 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15527 15528 SourceLocation Loc = Cap.getLocation(); 15529 15530 ExprResult Result = BuildDeclarationNameExpr( 15531 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15532 15533 // According to the blocks spec, the capture of a variable from 15534 // the stack requires a const copy constructor. This is not true 15535 // of the copy/move done to move a __block variable to the heap. 15536 if (!Result.isInvalid() && 15537 !Result.get()->getType().isConstQualified()) { 15538 Result = ImpCastExprToType(Result.get(), 15539 Result.get()->getType().withConst(), 15540 CK_NoOp, VK_LValue); 15541 } 15542 15543 if (!Result.isInvalid()) { 15544 Result = PerformCopyInitialization( 15545 InitializedEntity::InitializeBlock(Var->getLocation(), 15546 Cap.getCaptureType(), false), 15547 Loc, Result.get()); 15548 } 15549 15550 // Build a full-expression copy expression if initialization 15551 // succeeded and used a non-trivial constructor. Recover from 15552 // errors by pretending that the copy isn't necessary. 15553 if (!Result.isInvalid() && 15554 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15555 ->isTrivial()) { 15556 Result = MaybeCreateExprWithCleanups(Result); 15557 CopyExpr = Result.get(); 15558 } 15559 } 15560 } 15561 15562 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15563 CopyExpr); 15564 Captures.push_back(NewCap); 15565 } 15566 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15567 15568 // Pop the block scope now but keep it alive to the end of this function. 15569 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15570 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15571 15572 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15573 15574 // If the block isn't obviously global, i.e. it captures anything at 15575 // all, then we need to do a few things in the surrounding context: 15576 if (Result->getBlockDecl()->hasCaptures()) { 15577 // First, this expression has a new cleanup object. 15578 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15579 Cleanup.setExprNeedsCleanups(true); 15580 15581 // It also gets a branch-protected scope if any of the captured 15582 // variables needs destruction. 15583 for (const auto &CI : Result->getBlockDecl()->captures()) { 15584 const VarDecl *var = CI.getVariable(); 15585 if (var->getType().isDestructedType() != QualType::DK_none) { 15586 setFunctionHasBranchProtectedScope(); 15587 break; 15588 } 15589 } 15590 } 15591 15592 if (getCurFunction()) 15593 getCurFunction()->addBlock(BD); 15594 15595 return Result; 15596 } 15597 15598 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15599 SourceLocation RPLoc) { 15600 TypeSourceInfo *TInfo; 15601 GetTypeFromParser(Ty, &TInfo); 15602 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15603 } 15604 15605 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15606 Expr *E, TypeSourceInfo *TInfo, 15607 SourceLocation RPLoc) { 15608 Expr *OrigExpr = E; 15609 bool IsMS = false; 15610 15611 // CUDA device code does not support varargs. 15612 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15613 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15614 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15615 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15616 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15617 } 15618 } 15619 15620 // NVPTX does not support va_arg expression. 15621 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15622 Context.getTargetInfo().getTriple().isNVPTX()) 15623 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15624 15625 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15626 // as Microsoft ABI on an actual Microsoft platform, where 15627 // __builtin_ms_va_list and __builtin_va_list are the same.) 15628 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15629 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15630 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15631 if (Context.hasSameType(MSVaListType, E->getType())) { 15632 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15633 return ExprError(); 15634 IsMS = true; 15635 } 15636 } 15637 15638 // Get the va_list type 15639 QualType VaListType = Context.getBuiltinVaListType(); 15640 if (!IsMS) { 15641 if (VaListType->isArrayType()) { 15642 // Deal with implicit array decay; for example, on x86-64, 15643 // va_list is an array, but it's supposed to decay to 15644 // a pointer for va_arg. 15645 VaListType = Context.getArrayDecayedType(VaListType); 15646 // Make sure the input expression also decays appropriately. 15647 ExprResult Result = UsualUnaryConversions(E); 15648 if (Result.isInvalid()) 15649 return ExprError(); 15650 E = Result.get(); 15651 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15652 // If va_list is a record type and we are compiling in C++ mode, 15653 // check the argument using reference binding. 15654 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15655 Context, Context.getLValueReferenceType(VaListType), false); 15656 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15657 if (Init.isInvalid()) 15658 return ExprError(); 15659 E = Init.getAs<Expr>(); 15660 } else { 15661 // Otherwise, the va_list argument must be an l-value because 15662 // it is modified by va_arg. 15663 if (!E->isTypeDependent() && 15664 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15665 return ExprError(); 15666 } 15667 } 15668 15669 if (!IsMS && !E->isTypeDependent() && 15670 !Context.hasSameType(VaListType, E->getType())) 15671 return ExprError( 15672 Diag(E->getBeginLoc(), 15673 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15674 << OrigExpr->getType() << E->getSourceRange()); 15675 15676 if (!TInfo->getType()->isDependentType()) { 15677 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15678 diag::err_second_parameter_to_va_arg_incomplete, 15679 TInfo->getTypeLoc())) 15680 return ExprError(); 15681 15682 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15683 TInfo->getType(), 15684 diag::err_second_parameter_to_va_arg_abstract, 15685 TInfo->getTypeLoc())) 15686 return ExprError(); 15687 15688 if (!TInfo->getType().isPODType(Context)) { 15689 Diag(TInfo->getTypeLoc().getBeginLoc(), 15690 TInfo->getType()->isObjCLifetimeType() 15691 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15692 : diag::warn_second_parameter_to_va_arg_not_pod) 15693 << TInfo->getType() 15694 << TInfo->getTypeLoc().getSourceRange(); 15695 } 15696 15697 // Check for va_arg where arguments of the given type will be promoted 15698 // (i.e. this va_arg is guaranteed to have undefined behavior). 15699 QualType PromoteType; 15700 if (TInfo->getType()->isPromotableIntegerType()) { 15701 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15702 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15703 PromoteType = QualType(); 15704 } 15705 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15706 PromoteType = Context.DoubleTy; 15707 if (!PromoteType.isNull()) 15708 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15709 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15710 << TInfo->getType() 15711 << PromoteType 15712 << TInfo->getTypeLoc().getSourceRange()); 15713 } 15714 15715 QualType T = TInfo->getType().getNonLValueExprType(Context); 15716 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15717 } 15718 15719 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15720 // The type of __null will be int or long, depending on the size of 15721 // pointers on the target. 15722 QualType Ty; 15723 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15724 if (pw == Context.getTargetInfo().getIntWidth()) 15725 Ty = Context.IntTy; 15726 else if (pw == Context.getTargetInfo().getLongWidth()) 15727 Ty = Context.LongTy; 15728 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15729 Ty = Context.LongLongTy; 15730 else { 15731 llvm_unreachable("I don't know size of pointer!"); 15732 } 15733 15734 return new (Context) GNUNullExpr(Ty, TokenLoc); 15735 } 15736 15737 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15738 SourceLocation BuiltinLoc, 15739 SourceLocation RPLoc) { 15740 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15741 } 15742 15743 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15744 SourceLocation BuiltinLoc, 15745 SourceLocation RPLoc, 15746 DeclContext *ParentContext) { 15747 return new (Context) 15748 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15749 } 15750 15751 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15752 bool Diagnose) { 15753 if (!getLangOpts().ObjC) 15754 return false; 15755 15756 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15757 if (!PT) 15758 return false; 15759 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15760 15761 // Ignore any parens, implicit casts (should only be 15762 // array-to-pointer decays), and not-so-opaque values. The last is 15763 // important for making this trigger for property assignments. 15764 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15765 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15766 if (OV->getSourceExpr()) 15767 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15768 15769 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15770 if (!PT->isObjCIdType() && 15771 !(ID && ID->getIdentifier()->isStr("NSString"))) 15772 return false; 15773 if (!SL->isAscii()) 15774 return false; 15775 15776 if (Diagnose) { 15777 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15778 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15779 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15780 } 15781 return true; 15782 } 15783 15784 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15785 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15786 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15787 !SrcExpr->isNullPointerConstant( 15788 getASTContext(), Expr::NPC_NeverValueDependent)) { 15789 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15790 return false; 15791 if (Diagnose) { 15792 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15793 << /*number*/1 15794 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15795 Expr *NumLit = 15796 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15797 if (NumLit) 15798 Exp = NumLit; 15799 } 15800 return true; 15801 } 15802 15803 return false; 15804 } 15805 15806 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15807 const Expr *SrcExpr) { 15808 if (!DstType->isFunctionPointerType() || 15809 !SrcExpr->getType()->isFunctionType()) 15810 return false; 15811 15812 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15813 if (!DRE) 15814 return false; 15815 15816 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15817 if (!FD) 15818 return false; 15819 15820 return !S.checkAddressOfFunctionIsAvailable(FD, 15821 /*Complain=*/true, 15822 SrcExpr->getBeginLoc()); 15823 } 15824 15825 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15826 SourceLocation Loc, 15827 QualType DstType, QualType SrcType, 15828 Expr *SrcExpr, AssignmentAction Action, 15829 bool *Complained) { 15830 if (Complained) 15831 *Complained = false; 15832 15833 // Decode the result (notice that AST's are still created for extensions). 15834 bool CheckInferredResultType = false; 15835 bool isInvalid = false; 15836 unsigned DiagKind = 0; 15837 ConversionFixItGenerator ConvHints; 15838 bool MayHaveConvFixit = false; 15839 bool MayHaveFunctionDiff = false; 15840 const ObjCInterfaceDecl *IFace = nullptr; 15841 const ObjCProtocolDecl *PDecl = nullptr; 15842 15843 switch (ConvTy) { 15844 case Compatible: 15845 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15846 return false; 15847 15848 case PointerToInt: 15849 if (getLangOpts().CPlusPlus) { 15850 DiagKind = diag::err_typecheck_convert_pointer_int; 15851 isInvalid = true; 15852 } else { 15853 DiagKind = diag::ext_typecheck_convert_pointer_int; 15854 } 15855 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15856 MayHaveConvFixit = true; 15857 break; 15858 case IntToPointer: 15859 if (getLangOpts().CPlusPlus) { 15860 DiagKind = diag::err_typecheck_convert_int_pointer; 15861 isInvalid = true; 15862 } else { 15863 DiagKind = diag::ext_typecheck_convert_int_pointer; 15864 } 15865 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15866 MayHaveConvFixit = true; 15867 break; 15868 case IncompatibleFunctionPointer: 15869 if (getLangOpts().CPlusPlus) { 15870 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15871 isInvalid = true; 15872 } else { 15873 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15874 } 15875 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15876 MayHaveConvFixit = true; 15877 break; 15878 case IncompatiblePointer: 15879 if (Action == AA_Passing_CFAudited) { 15880 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15881 } else if (getLangOpts().CPlusPlus) { 15882 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15883 isInvalid = true; 15884 } else { 15885 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15886 } 15887 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15888 SrcType->isObjCObjectPointerType(); 15889 if (!CheckInferredResultType) { 15890 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15891 } else if (CheckInferredResultType) { 15892 SrcType = SrcType.getUnqualifiedType(); 15893 DstType = DstType.getUnqualifiedType(); 15894 } 15895 MayHaveConvFixit = true; 15896 break; 15897 case IncompatiblePointerSign: 15898 if (getLangOpts().CPlusPlus) { 15899 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15900 isInvalid = true; 15901 } else { 15902 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15903 } 15904 break; 15905 case FunctionVoidPointer: 15906 if (getLangOpts().CPlusPlus) { 15907 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15908 isInvalid = true; 15909 } else { 15910 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15911 } 15912 break; 15913 case IncompatiblePointerDiscardsQualifiers: { 15914 // Perform array-to-pointer decay if necessary. 15915 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15916 15917 isInvalid = true; 15918 15919 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15920 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15921 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15922 DiagKind = diag::err_typecheck_incompatible_address_space; 15923 break; 15924 15925 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15926 DiagKind = diag::err_typecheck_incompatible_ownership; 15927 break; 15928 } 15929 15930 llvm_unreachable("unknown error case for discarding qualifiers!"); 15931 // fallthrough 15932 } 15933 case CompatiblePointerDiscardsQualifiers: 15934 // If the qualifiers lost were because we were applying the 15935 // (deprecated) C++ conversion from a string literal to a char* 15936 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15937 // Ideally, this check would be performed in 15938 // checkPointerTypesForAssignment. However, that would require a 15939 // bit of refactoring (so that the second argument is an 15940 // expression, rather than a type), which should be done as part 15941 // of a larger effort to fix checkPointerTypesForAssignment for 15942 // C++ semantics. 15943 if (getLangOpts().CPlusPlus && 15944 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15945 return false; 15946 if (getLangOpts().CPlusPlus) { 15947 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15948 isInvalid = true; 15949 } else { 15950 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15951 } 15952 15953 break; 15954 case IncompatibleNestedPointerQualifiers: 15955 if (getLangOpts().CPlusPlus) { 15956 isInvalid = true; 15957 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15958 } else { 15959 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15960 } 15961 break; 15962 case IncompatibleNestedPointerAddressSpaceMismatch: 15963 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15964 isInvalid = true; 15965 break; 15966 case IntToBlockPointer: 15967 DiagKind = diag::err_int_to_block_pointer; 15968 isInvalid = true; 15969 break; 15970 case IncompatibleBlockPointer: 15971 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15972 isInvalid = true; 15973 break; 15974 case IncompatibleObjCQualifiedId: { 15975 if (SrcType->isObjCQualifiedIdType()) { 15976 const ObjCObjectPointerType *srcOPT = 15977 SrcType->castAs<ObjCObjectPointerType>(); 15978 for (auto *srcProto : srcOPT->quals()) { 15979 PDecl = srcProto; 15980 break; 15981 } 15982 if (const ObjCInterfaceType *IFaceT = 15983 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15984 IFace = IFaceT->getDecl(); 15985 } 15986 else if (DstType->isObjCQualifiedIdType()) { 15987 const ObjCObjectPointerType *dstOPT = 15988 DstType->castAs<ObjCObjectPointerType>(); 15989 for (auto *dstProto : dstOPT->quals()) { 15990 PDecl = dstProto; 15991 break; 15992 } 15993 if (const ObjCInterfaceType *IFaceT = 15994 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15995 IFace = IFaceT->getDecl(); 15996 } 15997 if (getLangOpts().CPlusPlus) { 15998 DiagKind = diag::err_incompatible_qualified_id; 15999 isInvalid = true; 16000 } else { 16001 DiagKind = diag::warn_incompatible_qualified_id; 16002 } 16003 break; 16004 } 16005 case IncompatibleVectors: 16006 if (getLangOpts().CPlusPlus) { 16007 DiagKind = diag::err_incompatible_vectors; 16008 isInvalid = true; 16009 } else { 16010 DiagKind = diag::warn_incompatible_vectors; 16011 } 16012 break; 16013 case IncompatibleObjCWeakRef: 16014 DiagKind = diag::err_arc_weak_unavailable_assign; 16015 isInvalid = true; 16016 break; 16017 case Incompatible: 16018 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16019 if (Complained) 16020 *Complained = true; 16021 return true; 16022 } 16023 16024 DiagKind = diag::err_typecheck_convert_incompatible; 16025 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16026 MayHaveConvFixit = true; 16027 isInvalid = true; 16028 MayHaveFunctionDiff = true; 16029 break; 16030 } 16031 16032 QualType FirstType, SecondType; 16033 switch (Action) { 16034 case AA_Assigning: 16035 case AA_Initializing: 16036 // The destination type comes first. 16037 FirstType = DstType; 16038 SecondType = SrcType; 16039 break; 16040 16041 case AA_Returning: 16042 case AA_Passing: 16043 case AA_Passing_CFAudited: 16044 case AA_Converting: 16045 case AA_Sending: 16046 case AA_Casting: 16047 // The source type comes first. 16048 FirstType = SrcType; 16049 SecondType = DstType; 16050 break; 16051 } 16052 16053 PartialDiagnostic FDiag = PDiag(DiagKind); 16054 if (Action == AA_Passing_CFAudited) 16055 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16056 else 16057 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16058 16059 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16060 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16061 auto isPlainChar = [](const clang::Type *Type) { 16062 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16063 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16064 }; 16065 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16066 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16067 } 16068 16069 // If we can fix the conversion, suggest the FixIts. 16070 if (!ConvHints.isNull()) { 16071 for (FixItHint &H : ConvHints.Hints) 16072 FDiag << H; 16073 } 16074 16075 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16076 16077 if (MayHaveFunctionDiff) 16078 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16079 16080 Diag(Loc, FDiag); 16081 if ((DiagKind == diag::warn_incompatible_qualified_id || 16082 DiagKind == diag::err_incompatible_qualified_id) && 16083 PDecl && IFace && !IFace->hasDefinition()) 16084 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16085 << IFace << PDecl; 16086 16087 if (SecondType == Context.OverloadTy) 16088 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16089 FirstType, /*TakingAddress=*/true); 16090 16091 if (CheckInferredResultType) 16092 EmitRelatedResultTypeNote(SrcExpr); 16093 16094 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16095 EmitRelatedResultTypeNoteForReturn(DstType); 16096 16097 if (Complained) 16098 *Complained = true; 16099 return isInvalid; 16100 } 16101 16102 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16103 llvm::APSInt *Result, 16104 AllowFoldKind CanFold) { 16105 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16106 public: 16107 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16108 QualType T) override { 16109 return S.Diag(Loc, diag::err_ice_not_integral) 16110 << T << S.LangOpts.CPlusPlus; 16111 } 16112 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16113 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16114 } 16115 } Diagnoser; 16116 16117 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16118 } 16119 16120 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16121 llvm::APSInt *Result, 16122 unsigned DiagID, 16123 AllowFoldKind CanFold) { 16124 class IDDiagnoser : public VerifyICEDiagnoser { 16125 unsigned DiagID; 16126 16127 public: 16128 IDDiagnoser(unsigned DiagID) 16129 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16130 16131 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16132 return S.Diag(Loc, DiagID); 16133 } 16134 } Diagnoser(DiagID); 16135 16136 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16137 } 16138 16139 Sema::SemaDiagnosticBuilder 16140 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16141 QualType T) { 16142 return diagnoseNotICE(S, Loc); 16143 } 16144 16145 Sema::SemaDiagnosticBuilder 16146 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16147 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16148 } 16149 16150 ExprResult 16151 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16152 VerifyICEDiagnoser &Diagnoser, 16153 AllowFoldKind CanFold) { 16154 SourceLocation DiagLoc = E->getBeginLoc(); 16155 16156 if (getLangOpts().CPlusPlus11) { 16157 // C++11 [expr.const]p5: 16158 // If an expression of literal class type is used in a context where an 16159 // integral constant expression is required, then that class type shall 16160 // have a single non-explicit conversion function to an integral or 16161 // unscoped enumeration type 16162 ExprResult Converted; 16163 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16164 VerifyICEDiagnoser &BaseDiagnoser; 16165 public: 16166 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16167 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16168 BaseDiagnoser.Suppress, true), 16169 BaseDiagnoser(BaseDiagnoser) {} 16170 16171 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16172 QualType T) override { 16173 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16174 } 16175 16176 SemaDiagnosticBuilder diagnoseIncomplete( 16177 Sema &S, SourceLocation Loc, QualType T) override { 16178 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16179 } 16180 16181 SemaDiagnosticBuilder diagnoseExplicitConv( 16182 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16183 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16184 } 16185 16186 SemaDiagnosticBuilder noteExplicitConv( 16187 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16188 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16189 << ConvTy->isEnumeralType() << ConvTy; 16190 } 16191 16192 SemaDiagnosticBuilder diagnoseAmbiguous( 16193 Sema &S, SourceLocation Loc, QualType T) override { 16194 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16195 } 16196 16197 SemaDiagnosticBuilder noteAmbiguous( 16198 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16199 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16200 << ConvTy->isEnumeralType() << ConvTy; 16201 } 16202 16203 SemaDiagnosticBuilder diagnoseConversion( 16204 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16205 llvm_unreachable("conversion functions are permitted"); 16206 } 16207 } ConvertDiagnoser(Diagnoser); 16208 16209 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16210 ConvertDiagnoser); 16211 if (Converted.isInvalid()) 16212 return Converted; 16213 E = Converted.get(); 16214 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16215 return ExprError(); 16216 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16217 // An ICE must be of integral or unscoped enumeration type. 16218 if (!Diagnoser.Suppress) 16219 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16220 << E->getSourceRange(); 16221 return ExprError(); 16222 } 16223 16224 ExprResult RValueExpr = DefaultLvalueConversion(E); 16225 if (RValueExpr.isInvalid()) 16226 return ExprError(); 16227 16228 E = RValueExpr.get(); 16229 16230 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16231 // in the non-ICE case. 16232 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16233 if (Result) 16234 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16235 if (!isa<ConstantExpr>(E)) 16236 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16237 : ConstantExpr::Create(Context, E); 16238 return E; 16239 } 16240 16241 Expr::EvalResult EvalResult; 16242 SmallVector<PartialDiagnosticAt, 8> Notes; 16243 EvalResult.Diag = &Notes; 16244 16245 // Try to evaluate the expression, and produce diagnostics explaining why it's 16246 // not a constant expression as a side-effect. 16247 bool Folded = 16248 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16249 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16250 16251 if (!isa<ConstantExpr>(E)) 16252 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16253 16254 // In C++11, we can rely on diagnostics being produced for any expression 16255 // which is not a constant expression. If no diagnostics were produced, then 16256 // this is a constant expression. 16257 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16258 if (Result) 16259 *Result = EvalResult.Val.getInt(); 16260 return E; 16261 } 16262 16263 // If our only note is the usual "invalid subexpression" note, just point 16264 // the caret at its location rather than producing an essentially 16265 // redundant note. 16266 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16267 diag::note_invalid_subexpr_in_const_expr) { 16268 DiagLoc = Notes[0].first; 16269 Notes.clear(); 16270 } 16271 16272 if (!Folded || !CanFold) { 16273 if (!Diagnoser.Suppress) { 16274 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16275 for (const PartialDiagnosticAt &Note : Notes) 16276 Diag(Note.first, Note.second); 16277 } 16278 16279 return ExprError(); 16280 } 16281 16282 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16283 for (const PartialDiagnosticAt &Note : Notes) 16284 Diag(Note.first, Note.second); 16285 16286 if (Result) 16287 *Result = EvalResult.Val.getInt(); 16288 return E; 16289 } 16290 16291 namespace { 16292 // Handle the case where we conclude a expression which we speculatively 16293 // considered to be unevaluated is actually evaluated. 16294 class TransformToPE : public TreeTransform<TransformToPE> { 16295 typedef TreeTransform<TransformToPE> BaseTransform; 16296 16297 public: 16298 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16299 16300 // Make sure we redo semantic analysis 16301 bool AlwaysRebuild() { return true; } 16302 bool ReplacingOriginal() { return true; } 16303 16304 // We need to special-case DeclRefExprs referring to FieldDecls which 16305 // are not part of a member pointer formation; normal TreeTransforming 16306 // doesn't catch this case because of the way we represent them in the AST. 16307 // FIXME: This is a bit ugly; is it really the best way to handle this 16308 // case? 16309 // 16310 // Error on DeclRefExprs referring to FieldDecls. 16311 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16312 if (isa<FieldDecl>(E->getDecl()) && 16313 !SemaRef.isUnevaluatedContext()) 16314 return SemaRef.Diag(E->getLocation(), 16315 diag::err_invalid_non_static_member_use) 16316 << E->getDecl() << E->getSourceRange(); 16317 16318 return BaseTransform::TransformDeclRefExpr(E); 16319 } 16320 16321 // Exception: filter out member pointer formation 16322 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16323 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16324 return E; 16325 16326 return BaseTransform::TransformUnaryOperator(E); 16327 } 16328 16329 // The body of a lambda-expression is in a separate expression evaluation 16330 // context so never needs to be transformed. 16331 // FIXME: Ideally we wouldn't transform the closure type either, and would 16332 // just recreate the capture expressions and lambda expression. 16333 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16334 return SkipLambdaBody(E, Body); 16335 } 16336 }; 16337 } 16338 16339 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16340 assert(isUnevaluatedContext() && 16341 "Should only transform unevaluated expressions"); 16342 ExprEvalContexts.back().Context = 16343 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16344 if (isUnevaluatedContext()) 16345 return E; 16346 return TransformToPE(*this).TransformExpr(E); 16347 } 16348 16349 void 16350 Sema::PushExpressionEvaluationContext( 16351 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16352 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16353 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16354 LambdaContextDecl, ExprContext); 16355 Cleanup.reset(); 16356 if (!MaybeODRUseExprs.empty()) 16357 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16358 } 16359 16360 void 16361 Sema::PushExpressionEvaluationContext( 16362 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16363 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16364 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16365 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16366 } 16367 16368 namespace { 16369 16370 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16371 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16372 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16373 if (E->getOpcode() == UO_Deref) 16374 return CheckPossibleDeref(S, E->getSubExpr()); 16375 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16376 return CheckPossibleDeref(S, E->getBase()); 16377 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16378 return CheckPossibleDeref(S, E->getBase()); 16379 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16380 QualType Inner; 16381 QualType Ty = E->getType(); 16382 if (const auto *Ptr = Ty->getAs<PointerType>()) 16383 Inner = Ptr->getPointeeType(); 16384 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16385 Inner = Arr->getElementType(); 16386 else 16387 return nullptr; 16388 16389 if (Inner->hasAttr(attr::NoDeref)) 16390 return E; 16391 } 16392 return nullptr; 16393 } 16394 16395 } // namespace 16396 16397 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16398 for (const Expr *E : Rec.PossibleDerefs) { 16399 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16400 if (DeclRef) { 16401 const ValueDecl *Decl = DeclRef->getDecl(); 16402 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16403 << Decl->getName() << E->getSourceRange(); 16404 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16405 } else { 16406 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16407 << E->getSourceRange(); 16408 } 16409 } 16410 Rec.PossibleDerefs.clear(); 16411 } 16412 16413 /// Check whether E, which is either a discarded-value expression or an 16414 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16415 /// and if so, remove it from the list of volatile-qualified assignments that 16416 /// we are going to warn are deprecated. 16417 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16418 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16419 return; 16420 16421 // Note: ignoring parens here is not justified by the standard rules, but 16422 // ignoring parentheses seems like a more reasonable approach, and this only 16423 // drives a deprecation warning so doesn't affect conformance. 16424 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16425 if (BO->getOpcode() == BO_Assign) { 16426 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16427 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16428 LHSs.end()); 16429 } 16430 } 16431 } 16432 16433 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16434 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16435 RebuildingImmediateInvocation) 16436 return E; 16437 16438 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16439 /// It's OK if this fails; we'll also remove this in 16440 /// HandleImmediateInvocations, but catching it here allows us to avoid 16441 /// walking the AST looking for it in simple cases. 16442 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16443 if (auto *DeclRef = 16444 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16445 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16446 16447 E = MaybeCreateExprWithCleanups(E); 16448 16449 ConstantExpr *Res = ConstantExpr::Create( 16450 getASTContext(), E.get(), 16451 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16452 getASTContext()), 16453 /*IsImmediateInvocation*/ true); 16454 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16455 return Res; 16456 } 16457 16458 static void EvaluateAndDiagnoseImmediateInvocation( 16459 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16460 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16461 Expr::EvalResult Eval; 16462 Eval.Diag = &Notes; 16463 ConstantExpr *CE = Candidate.getPointer(); 16464 bool Result = CE->EvaluateAsConstantExpr( 16465 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16466 if (!Result || !Notes.empty()) { 16467 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16468 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16469 InnerExpr = FunctionalCast->getSubExpr(); 16470 FunctionDecl *FD = nullptr; 16471 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16472 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16473 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16474 FD = Call->getConstructor(); 16475 else 16476 llvm_unreachable("unhandled decl kind"); 16477 assert(FD->isConsteval()); 16478 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16479 for (auto &Note : Notes) 16480 SemaRef.Diag(Note.first, Note.second); 16481 return; 16482 } 16483 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16484 } 16485 16486 static void RemoveNestedImmediateInvocation( 16487 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16488 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16489 struct ComplexRemove : TreeTransform<ComplexRemove> { 16490 using Base = TreeTransform<ComplexRemove>; 16491 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16492 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16493 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16494 CurrentII; 16495 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16496 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16497 SmallVector<Sema::ImmediateInvocationCandidate, 16498 4>::reverse_iterator Current) 16499 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16500 void RemoveImmediateInvocation(ConstantExpr* E) { 16501 auto It = std::find_if(CurrentII, IISet.rend(), 16502 [E](Sema::ImmediateInvocationCandidate Elem) { 16503 return Elem.getPointer() == E; 16504 }); 16505 assert(It != IISet.rend() && 16506 "ConstantExpr marked IsImmediateInvocation should " 16507 "be present"); 16508 It->setInt(1); // Mark as deleted 16509 } 16510 ExprResult TransformConstantExpr(ConstantExpr *E) { 16511 if (!E->isImmediateInvocation()) 16512 return Base::TransformConstantExpr(E); 16513 RemoveImmediateInvocation(E); 16514 return Base::TransformExpr(E->getSubExpr()); 16515 } 16516 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16517 /// we need to remove its DeclRefExpr from the DRSet. 16518 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16519 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16520 return Base::TransformCXXOperatorCallExpr(E); 16521 } 16522 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16523 /// here. 16524 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16525 if (!Init) 16526 return Init; 16527 /// ConstantExpr are the first layer of implicit node to be removed so if 16528 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16529 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16530 if (CE->isImmediateInvocation()) 16531 RemoveImmediateInvocation(CE); 16532 return Base::TransformInitializer(Init, NotCopyInit); 16533 } 16534 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16535 DRSet.erase(E); 16536 return E; 16537 } 16538 bool AlwaysRebuild() { return false; } 16539 bool ReplacingOriginal() { return true; } 16540 bool AllowSkippingCXXConstructExpr() { 16541 bool Res = AllowSkippingFirstCXXConstructExpr; 16542 AllowSkippingFirstCXXConstructExpr = true; 16543 return Res; 16544 } 16545 bool AllowSkippingFirstCXXConstructExpr = true; 16546 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16547 Rec.ImmediateInvocationCandidates, It); 16548 16549 /// CXXConstructExpr with a single argument are getting skipped by 16550 /// TreeTransform in some situtation because they could be implicit. This 16551 /// can only occur for the top-level CXXConstructExpr because it is used 16552 /// nowhere in the expression being transformed therefore will not be rebuilt. 16553 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16554 /// skipping the first CXXConstructExpr. 16555 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16556 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16557 16558 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16559 assert(Res.isUsable()); 16560 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16561 It->getPointer()->setSubExpr(Res.get()); 16562 } 16563 16564 static void 16565 HandleImmediateInvocations(Sema &SemaRef, 16566 Sema::ExpressionEvaluationContextRecord &Rec) { 16567 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16568 Rec.ReferenceToConsteval.size() == 0) || 16569 SemaRef.RebuildingImmediateInvocation) 16570 return; 16571 16572 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16573 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16574 /// need to remove ReferenceToConsteval in the immediate invocation. 16575 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16576 16577 /// Prevent sema calls during the tree transform from adding pointers that 16578 /// are already in the sets. 16579 llvm::SaveAndRestore<bool> DisableIITracking( 16580 SemaRef.RebuildingImmediateInvocation, true); 16581 16582 /// Prevent diagnostic during tree transfrom as they are duplicates 16583 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16584 16585 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16586 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16587 if (!It->getInt()) 16588 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16589 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16590 Rec.ReferenceToConsteval.size()) { 16591 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16592 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16593 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16594 bool VisitDeclRefExpr(DeclRefExpr *E) { 16595 DRSet.erase(E); 16596 return DRSet.size(); 16597 } 16598 } Visitor(Rec.ReferenceToConsteval); 16599 Visitor.TraverseStmt( 16600 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16601 } 16602 for (auto CE : Rec.ImmediateInvocationCandidates) 16603 if (!CE.getInt()) 16604 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16605 for (auto DR : Rec.ReferenceToConsteval) { 16606 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16607 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16608 << FD; 16609 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16610 } 16611 } 16612 16613 void Sema::PopExpressionEvaluationContext() { 16614 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16615 unsigned NumTypos = Rec.NumTypos; 16616 16617 if (!Rec.Lambdas.empty()) { 16618 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16619 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16620 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16621 unsigned D; 16622 if (Rec.isUnevaluated()) { 16623 // C++11 [expr.prim.lambda]p2: 16624 // A lambda-expression shall not appear in an unevaluated operand 16625 // (Clause 5). 16626 D = diag::err_lambda_unevaluated_operand; 16627 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16628 // C++1y [expr.const]p2: 16629 // A conditional-expression e is a core constant expression unless the 16630 // evaluation of e, following the rules of the abstract machine, would 16631 // evaluate [...] a lambda-expression. 16632 D = diag::err_lambda_in_constant_expression; 16633 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16634 // C++17 [expr.prim.lamda]p2: 16635 // A lambda-expression shall not appear [...] in a template-argument. 16636 D = diag::err_lambda_in_invalid_context; 16637 } else 16638 llvm_unreachable("Couldn't infer lambda error message."); 16639 16640 for (const auto *L : Rec.Lambdas) 16641 Diag(L->getBeginLoc(), D); 16642 } 16643 } 16644 16645 WarnOnPendingNoDerefs(Rec); 16646 HandleImmediateInvocations(*this, Rec); 16647 16648 // Warn on any volatile-qualified simple-assignments that are not discarded- 16649 // value expressions nor unevaluated operands (those cases get removed from 16650 // this list by CheckUnusedVolatileAssignment). 16651 for (auto *BO : Rec.VolatileAssignmentLHSs) 16652 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16653 << BO->getType(); 16654 16655 // When are coming out of an unevaluated context, clear out any 16656 // temporaries that we may have created as part of the evaluation of 16657 // the expression in that context: they aren't relevant because they 16658 // will never be constructed. 16659 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16660 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16661 ExprCleanupObjects.end()); 16662 Cleanup = Rec.ParentCleanup; 16663 CleanupVarDeclMarking(); 16664 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16665 // Otherwise, merge the contexts together. 16666 } else { 16667 Cleanup.mergeFrom(Rec.ParentCleanup); 16668 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16669 Rec.SavedMaybeODRUseExprs.end()); 16670 } 16671 16672 // Pop the current expression evaluation context off the stack. 16673 ExprEvalContexts.pop_back(); 16674 16675 // The global expression evaluation context record is never popped. 16676 ExprEvalContexts.back().NumTypos += NumTypos; 16677 } 16678 16679 void Sema::DiscardCleanupsInEvaluationContext() { 16680 ExprCleanupObjects.erase( 16681 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16682 ExprCleanupObjects.end()); 16683 Cleanup.reset(); 16684 MaybeODRUseExprs.clear(); 16685 } 16686 16687 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16688 ExprResult Result = CheckPlaceholderExpr(E); 16689 if (Result.isInvalid()) 16690 return ExprError(); 16691 E = Result.get(); 16692 if (!E->getType()->isVariablyModifiedType()) 16693 return E; 16694 return TransformToPotentiallyEvaluated(E); 16695 } 16696 16697 /// Are we in a context that is potentially constant evaluated per C++20 16698 /// [expr.const]p12? 16699 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16700 /// C++2a [expr.const]p12: 16701 // An expression or conversion is potentially constant evaluated if it is 16702 switch (SemaRef.ExprEvalContexts.back().Context) { 16703 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16704 // -- a manifestly constant-evaluated expression, 16705 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16706 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16707 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16708 // -- a potentially-evaluated expression, 16709 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16710 // -- an immediate subexpression of a braced-init-list, 16711 16712 // -- [FIXME] an expression of the form & cast-expression that occurs 16713 // within a templated entity 16714 // -- a subexpression of one of the above that is not a subexpression of 16715 // a nested unevaluated operand. 16716 return true; 16717 16718 case Sema::ExpressionEvaluationContext::Unevaluated: 16719 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16720 // Expressions in this context are never evaluated. 16721 return false; 16722 } 16723 llvm_unreachable("Invalid context"); 16724 } 16725 16726 /// Return true if this function has a calling convention that requires mangling 16727 /// in the size of the parameter pack. 16728 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16729 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16730 // we don't need parameter type sizes. 16731 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16732 if (!TT.isOSWindows() || !TT.isX86()) 16733 return false; 16734 16735 // If this is C++ and this isn't an extern "C" function, parameters do not 16736 // need to be complete. In this case, C++ mangling will apply, which doesn't 16737 // use the size of the parameters. 16738 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16739 return false; 16740 16741 // Stdcall, fastcall, and vectorcall need this special treatment. 16742 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16743 switch (CC) { 16744 case CC_X86StdCall: 16745 case CC_X86FastCall: 16746 case CC_X86VectorCall: 16747 return true; 16748 default: 16749 break; 16750 } 16751 return false; 16752 } 16753 16754 /// Require that all of the parameter types of function be complete. Normally, 16755 /// parameter types are only required to be complete when a function is called 16756 /// or defined, but to mangle functions with certain calling conventions, the 16757 /// mangler needs to know the size of the parameter list. In this situation, 16758 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16759 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16760 /// result in a linker error. Clang doesn't implement this behavior, and instead 16761 /// attempts to error at compile time. 16762 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16763 SourceLocation Loc) { 16764 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16765 FunctionDecl *FD; 16766 ParmVarDecl *Param; 16767 16768 public: 16769 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16770 : FD(FD), Param(Param) {} 16771 16772 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16773 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16774 StringRef CCName; 16775 switch (CC) { 16776 case CC_X86StdCall: 16777 CCName = "stdcall"; 16778 break; 16779 case CC_X86FastCall: 16780 CCName = "fastcall"; 16781 break; 16782 case CC_X86VectorCall: 16783 CCName = "vectorcall"; 16784 break; 16785 default: 16786 llvm_unreachable("CC does not need mangling"); 16787 } 16788 16789 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16790 << Param->getDeclName() << FD->getDeclName() << CCName; 16791 } 16792 }; 16793 16794 for (ParmVarDecl *Param : FD->parameters()) { 16795 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16796 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16797 } 16798 } 16799 16800 namespace { 16801 enum class OdrUseContext { 16802 /// Declarations in this context are not odr-used. 16803 None, 16804 /// Declarations in this context are formally odr-used, but this is a 16805 /// dependent context. 16806 Dependent, 16807 /// Declarations in this context are odr-used but not actually used (yet). 16808 FormallyOdrUsed, 16809 /// Declarations in this context are used. 16810 Used 16811 }; 16812 } 16813 16814 /// Are we within a context in which references to resolved functions or to 16815 /// variables result in odr-use? 16816 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16817 OdrUseContext Result; 16818 16819 switch (SemaRef.ExprEvalContexts.back().Context) { 16820 case Sema::ExpressionEvaluationContext::Unevaluated: 16821 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16822 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16823 return OdrUseContext::None; 16824 16825 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16826 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16827 Result = OdrUseContext::Used; 16828 break; 16829 16830 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16831 Result = OdrUseContext::FormallyOdrUsed; 16832 break; 16833 16834 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16835 // A default argument formally results in odr-use, but doesn't actually 16836 // result in a use in any real sense until it itself is used. 16837 Result = OdrUseContext::FormallyOdrUsed; 16838 break; 16839 } 16840 16841 if (SemaRef.CurContext->isDependentContext()) 16842 return OdrUseContext::Dependent; 16843 16844 return Result; 16845 } 16846 16847 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16848 if (!Func->isConstexpr()) 16849 return false; 16850 16851 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16852 return true; 16853 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16854 return CCD && CCD->getInheritedConstructor(); 16855 } 16856 16857 /// Mark a function referenced, and check whether it is odr-used 16858 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16859 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16860 bool MightBeOdrUse) { 16861 assert(Func && "No function?"); 16862 16863 Func->setReferenced(); 16864 16865 // Recursive functions aren't really used until they're used from some other 16866 // context. 16867 bool IsRecursiveCall = CurContext == Func; 16868 16869 // C++11 [basic.def.odr]p3: 16870 // A function whose name appears as a potentially-evaluated expression is 16871 // odr-used if it is the unique lookup result or the selected member of a 16872 // set of overloaded functions [...]. 16873 // 16874 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16875 // can just check that here. 16876 OdrUseContext OdrUse = 16877 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16878 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16879 OdrUse = OdrUseContext::FormallyOdrUsed; 16880 16881 // Trivial default constructors and destructors are never actually used. 16882 // FIXME: What about other special members? 16883 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16884 OdrUse == OdrUseContext::Used) { 16885 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16886 if (Constructor->isDefaultConstructor()) 16887 OdrUse = OdrUseContext::FormallyOdrUsed; 16888 if (isa<CXXDestructorDecl>(Func)) 16889 OdrUse = OdrUseContext::FormallyOdrUsed; 16890 } 16891 16892 // C++20 [expr.const]p12: 16893 // A function [...] is needed for constant evaluation if it is [...] a 16894 // constexpr function that is named by an expression that is potentially 16895 // constant evaluated 16896 bool NeededForConstantEvaluation = 16897 isPotentiallyConstantEvaluatedContext(*this) && 16898 isImplicitlyDefinableConstexprFunction(Func); 16899 16900 // Determine whether we require a function definition to exist, per 16901 // C++11 [temp.inst]p3: 16902 // Unless a function template specialization has been explicitly 16903 // instantiated or explicitly specialized, the function template 16904 // specialization is implicitly instantiated when the specialization is 16905 // referenced in a context that requires a function definition to exist. 16906 // C++20 [temp.inst]p7: 16907 // The existence of a definition of a [...] function is considered to 16908 // affect the semantics of the program if the [...] function is needed for 16909 // constant evaluation by an expression 16910 // C++20 [basic.def.odr]p10: 16911 // Every program shall contain exactly one definition of every non-inline 16912 // function or variable that is odr-used in that program outside of a 16913 // discarded statement 16914 // C++20 [special]p1: 16915 // The implementation will implicitly define [defaulted special members] 16916 // if they are odr-used or needed for constant evaluation. 16917 // 16918 // Note that we skip the implicit instantiation of templates that are only 16919 // used in unused default arguments or by recursive calls to themselves. 16920 // This is formally non-conforming, but seems reasonable in practice. 16921 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16922 NeededForConstantEvaluation); 16923 16924 // C++14 [temp.expl.spec]p6: 16925 // If a template [...] is explicitly specialized then that specialization 16926 // shall be declared before the first use of that specialization that would 16927 // cause an implicit instantiation to take place, in every translation unit 16928 // in which such a use occurs 16929 if (NeedDefinition && 16930 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16931 Func->getMemberSpecializationInfo())) 16932 checkSpecializationVisibility(Loc, Func); 16933 16934 if (getLangOpts().CUDA) 16935 CheckCUDACall(Loc, Func); 16936 16937 if (getLangOpts().SYCLIsDevice) 16938 checkSYCLDeviceFunction(Loc, Func); 16939 16940 // If we need a definition, try to create one. 16941 if (NeedDefinition && !Func->getBody()) { 16942 runWithSufficientStackSpace(Loc, [&] { 16943 if (CXXConstructorDecl *Constructor = 16944 dyn_cast<CXXConstructorDecl>(Func)) { 16945 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16946 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16947 if (Constructor->isDefaultConstructor()) { 16948 if (Constructor->isTrivial() && 16949 !Constructor->hasAttr<DLLExportAttr>()) 16950 return; 16951 DefineImplicitDefaultConstructor(Loc, Constructor); 16952 } else if (Constructor->isCopyConstructor()) { 16953 DefineImplicitCopyConstructor(Loc, Constructor); 16954 } else if (Constructor->isMoveConstructor()) { 16955 DefineImplicitMoveConstructor(Loc, Constructor); 16956 } 16957 } else if (Constructor->getInheritedConstructor()) { 16958 DefineInheritingConstructor(Loc, Constructor); 16959 } 16960 } else if (CXXDestructorDecl *Destructor = 16961 dyn_cast<CXXDestructorDecl>(Func)) { 16962 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16963 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16964 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16965 return; 16966 DefineImplicitDestructor(Loc, Destructor); 16967 } 16968 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16969 MarkVTableUsed(Loc, Destructor->getParent()); 16970 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16971 if (MethodDecl->isOverloadedOperator() && 16972 MethodDecl->getOverloadedOperator() == OO_Equal) { 16973 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16974 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16975 if (MethodDecl->isCopyAssignmentOperator()) 16976 DefineImplicitCopyAssignment(Loc, MethodDecl); 16977 else if (MethodDecl->isMoveAssignmentOperator()) 16978 DefineImplicitMoveAssignment(Loc, MethodDecl); 16979 } 16980 } else if (isa<CXXConversionDecl>(MethodDecl) && 16981 MethodDecl->getParent()->isLambda()) { 16982 CXXConversionDecl *Conversion = 16983 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16984 if (Conversion->isLambdaToBlockPointerConversion()) 16985 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16986 else 16987 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16988 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16989 MarkVTableUsed(Loc, MethodDecl->getParent()); 16990 } 16991 16992 if (Func->isDefaulted() && !Func->isDeleted()) { 16993 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16994 if (DCK != DefaultedComparisonKind::None) 16995 DefineDefaultedComparison(Loc, Func, DCK); 16996 } 16997 16998 // Implicit instantiation of function templates and member functions of 16999 // class templates. 17000 if (Func->isImplicitlyInstantiable()) { 17001 TemplateSpecializationKind TSK = 17002 Func->getTemplateSpecializationKindForInstantiation(); 17003 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17004 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17005 if (FirstInstantiation) { 17006 PointOfInstantiation = Loc; 17007 if (auto *MSI = Func->getMemberSpecializationInfo()) 17008 MSI->setPointOfInstantiation(Loc); 17009 // FIXME: Notify listener. 17010 else 17011 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17012 } else if (TSK != TSK_ImplicitInstantiation) { 17013 // Use the point of use as the point of instantiation, instead of the 17014 // point of explicit instantiation (which we track as the actual point 17015 // of instantiation). This gives better backtraces in diagnostics. 17016 PointOfInstantiation = Loc; 17017 } 17018 17019 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17020 Func->isConstexpr()) { 17021 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17022 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17023 CodeSynthesisContexts.size()) 17024 PendingLocalImplicitInstantiations.push_back( 17025 std::make_pair(Func, PointOfInstantiation)); 17026 else if (Func->isConstexpr()) 17027 // Do not defer instantiations of constexpr functions, to avoid the 17028 // expression evaluator needing to call back into Sema if it sees a 17029 // call to such a function. 17030 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17031 else { 17032 Func->setInstantiationIsPending(true); 17033 PendingInstantiations.push_back( 17034 std::make_pair(Func, PointOfInstantiation)); 17035 // Notify the consumer that a function was implicitly instantiated. 17036 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17037 } 17038 } 17039 } else { 17040 // Walk redefinitions, as some of them may be instantiable. 17041 for (auto i : Func->redecls()) { 17042 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17043 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17044 } 17045 } 17046 }); 17047 } 17048 17049 // C++14 [except.spec]p17: 17050 // An exception-specification is considered to be needed when: 17051 // - the function is odr-used or, if it appears in an unevaluated operand, 17052 // would be odr-used if the expression were potentially-evaluated; 17053 // 17054 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17055 // function is a pure virtual function we're calling, and in that case the 17056 // function was selected by overload resolution and we need to resolve its 17057 // exception specification for a different reason. 17058 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17059 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17060 ResolveExceptionSpec(Loc, FPT); 17061 17062 // If this is the first "real" use, act on that. 17063 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17064 // Keep track of used but undefined functions. 17065 if (!Func->isDefined()) { 17066 if (mightHaveNonExternalLinkage(Func)) 17067 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17068 else if (Func->getMostRecentDecl()->isInlined() && 17069 !LangOpts.GNUInline && 17070 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17071 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17072 else if (isExternalWithNoLinkageType(Func)) 17073 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17074 } 17075 17076 // Some x86 Windows calling conventions mangle the size of the parameter 17077 // pack into the name. Computing the size of the parameters requires the 17078 // parameter types to be complete. Check that now. 17079 if (funcHasParameterSizeMangling(*this, Func)) 17080 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17081 17082 // In the MS C++ ABI, the compiler emits destructor variants where they are 17083 // used. If the destructor is used here but defined elsewhere, mark the 17084 // virtual base destructors referenced. If those virtual base destructors 17085 // are inline, this will ensure they are defined when emitting the complete 17086 // destructor variant. This checking may be redundant if the destructor is 17087 // provided later in this TU. 17088 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17089 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17090 CXXRecordDecl *Parent = Dtor->getParent(); 17091 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17092 CheckCompleteDestructorVariant(Loc, Dtor); 17093 } 17094 } 17095 17096 Func->markUsed(Context); 17097 } 17098 } 17099 17100 /// Directly mark a variable odr-used. Given a choice, prefer to use 17101 /// MarkVariableReferenced since it does additional checks and then 17102 /// calls MarkVarDeclODRUsed. 17103 /// If the variable must be captured: 17104 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17105 /// - else capture it in the DeclContext that maps to the 17106 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17107 static void 17108 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17109 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17110 // Keep track of used but undefined variables. 17111 // FIXME: We shouldn't suppress this warning for static data members. 17112 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17113 (!Var->isExternallyVisible() || Var->isInline() || 17114 SemaRef.isExternalWithNoLinkageType(Var)) && 17115 !(Var->isStaticDataMember() && Var->hasInit())) { 17116 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17117 if (old.isInvalid()) 17118 old = Loc; 17119 } 17120 QualType CaptureType, DeclRefType; 17121 if (SemaRef.LangOpts.OpenMP) 17122 SemaRef.tryCaptureOpenMPLambdas(Var); 17123 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17124 /*EllipsisLoc*/ SourceLocation(), 17125 /*BuildAndDiagnose*/ true, 17126 CaptureType, DeclRefType, 17127 FunctionScopeIndexToStopAt); 17128 17129 // Diagnose ODR-use of host global variables in device functions. Reference 17130 // of device global variables in host functions is allowed through shadow 17131 // variables therefore it is not diagnosed. 17132 if (SemaRef.LangOpts.CUDA && SemaRef.LangOpts.CUDAIsDevice) { 17133 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17134 auto Target = SemaRef.IdentifyCUDATarget(FD); 17135 auto IsEmittedOnDeviceSide = [](VarDecl *Var) { 17136 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() || 17137 Var->hasAttr<CUDASharedAttr>() || 17138 Var->getType()->isCUDADeviceBuiltinSurfaceType() || 17139 Var->getType()->isCUDADeviceBuiltinTextureType()) 17140 return true; 17141 // Function-scope static variable in device functions or kernels are 17142 // emitted on device side. 17143 if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) { 17144 return FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>(); 17145 } 17146 return false; 17147 }; 17148 if (Var && Var->hasGlobalStorage() && !IsEmittedOnDeviceSide(Var)) { 17149 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17150 << /*host*/ 2 << /*variable*/ 1 << Var << Target; 17151 } 17152 } 17153 17154 Var->markUsed(SemaRef.Context); 17155 } 17156 17157 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17158 SourceLocation Loc, 17159 unsigned CapturingScopeIndex) { 17160 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17161 } 17162 17163 static void 17164 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17165 ValueDecl *var, DeclContext *DC) { 17166 DeclContext *VarDC = var->getDeclContext(); 17167 17168 // If the parameter still belongs to the translation unit, then 17169 // we're actually just using one parameter in the declaration of 17170 // the next. 17171 if (isa<ParmVarDecl>(var) && 17172 isa<TranslationUnitDecl>(VarDC)) 17173 return; 17174 17175 // For C code, don't diagnose about capture if we're not actually in code 17176 // right now; it's impossible to write a non-constant expression outside of 17177 // function context, so we'll get other (more useful) diagnostics later. 17178 // 17179 // For C++, things get a bit more nasty... it would be nice to suppress this 17180 // diagnostic for certain cases like using a local variable in an array bound 17181 // for a member of a local class, but the correct predicate is not obvious. 17182 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17183 return; 17184 17185 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17186 unsigned ContextKind = 3; // unknown 17187 if (isa<CXXMethodDecl>(VarDC) && 17188 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17189 ContextKind = 2; 17190 } else if (isa<FunctionDecl>(VarDC)) { 17191 ContextKind = 0; 17192 } else if (isa<BlockDecl>(VarDC)) { 17193 ContextKind = 1; 17194 } 17195 17196 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17197 << var << ValueKind << ContextKind << VarDC; 17198 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17199 << var; 17200 17201 // FIXME: Add additional diagnostic info about class etc. which prevents 17202 // capture. 17203 } 17204 17205 17206 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17207 bool &SubCapturesAreNested, 17208 QualType &CaptureType, 17209 QualType &DeclRefType) { 17210 // Check whether we've already captured it. 17211 if (CSI->CaptureMap.count(Var)) { 17212 // If we found a capture, any subcaptures are nested. 17213 SubCapturesAreNested = true; 17214 17215 // Retrieve the capture type for this variable. 17216 CaptureType = CSI->getCapture(Var).getCaptureType(); 17217 17218 // Compute the type of an expression that refers to this variable. 17219 DeclRefType = CaptureType.getNonReferenceType(); 17220 17221 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17222 // are mutable in the sense that user can change their value - they are 17223 // private instances of the captured declarations. 17224 const Capture &Cap = CSI->getCapture(Var); 17225 if (Cap.isCopyCapture() && 17226 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17227 !(isa<CapturedRegionScopeInfo>(CSI) && 17228 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17229 DeclRefType.addConst(); 17230 return true; 17231 } 17232 return false; 17233 } 17234 17235 // Only block literals, captured statements, and lambda expressions can 17236 // capture; other scopes don't work. 17237 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17238 SourceLocation Loc, 17239 const bool Diagnose, Sema &S) { 17240 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17241 return getLambdaAwareParentOfDeclContext(DC); 17242 else if (Var->hasLocalStorage()) { 17243 if (Diagnose) 17244 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17245 } 17246 return nullptr; 17247 } 17248 17249 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17250 // certain types of variables (unnamed, variably modified types etc.) 17251 // so check for eligibility. 17252 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17253 SourceLocation Loc, 17254 const bool Diagnose, Sema &S) { 17255 17256 bool IsBlock = isa<BlockScopeInfo>(CSI); 17257 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17258 17259 // Lambdas are not allowed to capture unnamed variables 17260 // (e.g. anonymous unions). 17261 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17262 // assuming that's the intent. 17263 if (IsLambda && !Var->getDeclName()) { 17264 if (Diagnose) { 17265 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17266 S.Diag(Var->getLocation(), diag::note_declared_at); 17267 } 17268 return false; 17269 } 17270 17271 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17272 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17273 if (Diagnose) { 17274 S.Diag(Loc, diag::err_ref_vm_type); 17275 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17276 } 17277 return false; 17278 } 17279 // Prohibit structs with flexible array members too. 17280 // We cannot capture what is in the tail end of the struct. 17281 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17282 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17283 if (Diagnose) { 17284 if (IsBlock) 17285 S.Diag(Loc, diag::err_ref_flexarray_type); 17286 else 17287 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17288 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17289 } 17290 return false; 17291 } 17292 } 17293 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17294 // Lambdas and captured statements are not allowed to capture __block 17295 // variables; they don't support the expected semantics. 17296 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17297 if (Diagnose) { 17298 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17299 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17300 } 17301 return false; 17302 } 17303 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17304 if (S.getLangOpts().OpenCL && IsBlock && 17305 Var->getType()->isBlockPointerType()) { 17306 if (Diagnose) 17307 S.Diag(Loc, diag::err_opencl_block_ref_block); 17308 return false; 17309 } 17310 17311 return true; 17312 } 17313 17314 // Returns true if the capture by block was successful. 17315 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17316 SourceLocation Loc, 17317 const bool BuildAndDiagnose, 17318 QualType &CaptureType, 17319 QualType &DeclRefType, 17320 const bool Nested, 17321 Sema &S, bool Invalid) { 17322 bool ByRef = false; 17323 17324 // Blocks are not allowed to capture arrays, excepting OpenCL. 17325 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17326 // (decayed to pointers). 17327 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17328 if (BuildAndDiagnose) { 17329 S.Diag(Loc, diag::err_ref_array_type); 17330 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17331 Invalid = true; 17332 } else { 17333 return false; 17334 } 17335 } 17336 17337 // Forbid the block-capture of autoreleasing variables. 17338 if (!Invalid && 17339 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17340 if (BuildAndDiagnose) { 17341 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17342 << /*block*/ 0; 17343 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17344 Invalid = true; 17345 } else { 17346 return false; 17347 } 17348 } 17349 17350 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17351 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17352 QualType PointeeTy = PT->getPointeeType(); 17353 17354 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17355 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17356 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17357 if (BuildAndDiagnose) { 17358 SourceLocation VarLoc = Var->getLocation(); 17359 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17360 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17361 } 17362 } 17363 } 17364 17365 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17366 if (HasBlocksAttr || CaptureType->isReferenceType() || 17367 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17368 // Block capture by reference does not change the capture or 17369 // declaration reference types. 17370 ByRef = true; 17371 } else { 17372 // Block capture by copy introduces 'const'. 17373 CaptureType = CaptureType.getNonReferenceType().withConst(); 17374 DeclRefType = CaptureType; 17375 } 17376 17377 // Actually capture the variable. 17378 if (BuildAndDiagnose) 17379 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17380 CaptureType, Invalid); 17381 17382 return !Invalid; 17383 } 17384 17385 17386 /// Capture the given variable in the captured region. 17387 static bool captureInCapturedRegion( 17388 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17389 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17390 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17391 bool IsTopScope, Sema &S, bool Invalid) { 17392 // By default, capture variables by reference. 17393 bool ByRef = true; 17394 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17395 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17396 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17397 // Using an LValue reference type is consistent with Lambdas (see below). 17398 if (S.isOpenMPCapturedDecl(Var)) { 17399 bool HasConst = DeclRefType.isConstQualified(); 17400 DeclRefType = DeclRefType.getUnqualifiedType(); 17401 // Don't lose diagnostics about assignments to const. 17402 if (HasConst) 17403 DeclRefType.addConst(); 17404 } 17405 // Do not capture firstprivates in tasks. 17406 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17407 OMPC_unknown) 17408 return true; 17409 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17410 RSI->OpenMPCaptureLevel); 17411 } 17412 17413 if (ByRef) 17414 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17415 else 17416 CaptureType = DeclRefType; 17417 17418 // Actually capture the variable. 17419 if (BuildAndDiagnose) 17420 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17421 Loc, SourceLocation(), CaptureType, Invalid); 17422 17423 return !Invalid; 17424 } 17425 17426 /// Capture the given variable in the lambda. 17427 static bool captureInLambda(LambdaScopeInfo *LSI, 17428 VarDecl *Var, 17429 SourceLocation Loc, 17430 const bool BuildAndDiagnose, 17431 QualType &CaptureType, 17432 QualType &DeclRefType, 17433 const bool RefersToCapturedVariable, 17434 const Sema::TryCaptureKind Kind, 17435 SourceLocation EllipsisLoc, 17436 const bool IsTopScope, 17437 Sema &S, bool Invalid) { 17438 // Determine whether we are capturing by reference or by value. 17439 bool ByRef = false; 17440 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17441 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17442 } else { 17443 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17444 } 17445 17446 // Compute the type of the field that will capture this variable. 17447 if (ByRef) { 17448 // C++11 [expr.prim.lambda]p15: 17449 // An entity is captured by reference if it is implicitly or 17450 // explicitly captured but not captured by copy. It is 17451 // unspecified whether additional unnamed non-static data 17452 // members are declared in the closure type for entities 17453 // captured by reference. 17454 // 17455 // FIXME: It is not clear whether we want to build an lvalue reference 17456 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17457 // to do the former, while EDG does the latter. Core issue 1249 will 17458 // clarify, but for now we follow GCC because it's a more permissive and 17459 // easily defensible position. 17460 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17461 } else { 17462 // C++11 [expr.prim.lambda]p14: 17463 // For each entity captured by copy, an unnamed non-static 17464 // data member is declared in the closure type. The 17465 // declaration order of these members is unspecified. The type 17466 // of such a data member is the type of the corresponding 17467 // captured entity if the entity is not a reference to an 17468 // object, or the referenced type otherwise. [Note: If the 17469 // captured entity is a reference to a function, the 17470 // corresponding data member is also a reference to a 17471 // function. - end note ] 17472 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17473 if (!RefType->getPointeeType()->isFunctionType()) 17474 CaptureType = RefType->getPointeeType(); 17475 } 17476 17477 // Forbid the lambda copy-capture of autoreleasing variables. 17478 if (!Invalid && 17479 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17480 if (BuildAndDiagnose) { 17481 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17482 S.Diag(Var->getLocation(), diag::note_previous_decl) 17483 << Var->getDeclName(); 17484 Invalid = true; 17485 } else { 17486 return false; 17487 } 17488 } 17489 17490 // Make sure that by-copy captures are of a complete and non-abstract type. 17491 if (!Invalid && BuildAndDiagnose) { 17492 if (!CaptureType->isDependentType() && 17493 S.RequireCompleteSizedType( 17494 Loc, CaptureType, 17495 diag::err_capture_of_incomplete_or_sizeless_type, 17496 Var->getDeclName())) 17497 Invalid = true; 17498 else if (S.RequireNonAbstractType(Loc, CaptureType, 17499 diag::err_capture_of_abstract_type)) 17500 Invalid = true; 17501 } 17502 } 17503 17504 // Compute the type of a reference to this captured variable. 17505 if (ByRef) 17506 DeclRefType = CaptureType.getNonReferenceType(); 17507 else { 17508 // C++ [expr.prim.lambda]p5: 17509 // The closure type for a lambda-expression has a public inline 17510 // function call operator [...]. This function call operator is 17511 // declared const (9.3.1) if and only if the lambda-expression's 17512 // parameter-declaration-clause is not followed by mutable. 17513 DeclRefType = CaptureType.getNonReferenceType(); 17514 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17515 DeclRefType.addConst(); 17516 } 17517 17518 // Add the capture. 17519 if (BuildAndDiagnose) 17520 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17521 Loc, EllipsisLoc, CaptureType, Invalid); 17522 17523 return !Invalid; 17524 } 17525 17526 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17527 // Offer a Copy fix even if the type is dependent. 17528 if (Var->getType()->isDependentType()) 17529 return true; 17530 QualType T = Var->getType().getNonReferenceType(); 17531 if (T.isTriviallyCopyableType(Context)) 17532 return true; 17533 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17534 17535 if (!(RD = RD->getDefinition())) 17536 return false; 17537 if (RD->hasSimpleCopyConstructor()) 17538 return true; 17539 if (RD->hasUserDeclaredCopyConstructor()) 17540 for (CXXConstructorDecl *Ctor : RD->ctors()) 17541 if (Ctor->isCopyConstructor()) 17542 return !Ctor->isDeleted(); 17543 } 17544 return false; 17545 } 17546 17547 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17548 /// default capture. Fixes may be omitted if they aren't allowed by the 17549 /// standard, for example we can't emit a default copy capture fix-it if we 17550 /// already explicitly copy capture capture another variable. 17551 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17552 VarDecl *Var) { 17553 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17554 // Don't offer Capture by copy of default capture by copy fixes if Var is 17555 // known not to be copy constructible. 17556 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17557 17558 SmallString<32> FixBuffer; 17559 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17560 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17561 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17562 if (ShouldOfferCopyFix) { 17563 // Offer fixes to insert an explicit capture for the variable. 17564 // [] -> [VarName] 17565 // [OtherCapture] -> [OtherCapture, VarName] 17566 FixBuffer.assign({Separator, Var->getName()}); 17567 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17568 << Var << /*value*/ 0 17569 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17570 } 17571 // As above but capture by reference. 17572 FixBuffer.assign({Separator, "&", Var->getName()}); 17573 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17574 << Var << /*reference*/ 1 17575 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17576 } 17577 17578 // Only try to offer default capture if there are no captures excluding this 17579 // and init captures. 17580 // [this]: OK. 17581 // [X = Y]: OK. 17582 // [&A, &B]: Don't offer. 17583 // [A, B]: Don't offer. 17584 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17585 return !C.isThisCapture() && !C.isInitCapture(); 17586 })) 17587 return; 17588 17589 // The default capture specifiers, '=' or '&', must appear first in the 17590 // capture body. 17591 SourceLocation DefaultInsertLoc = 17592 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17593 17594 if (ShouldOfferCopyFix) { 17595 bool CanDefaultCopyCapture = true; 17596 // [=, *this] OK since c++17 17597 // [=, this] OK since c++20 17598 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17599 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17600 ? LSI->getCXXThisCapture().isCopyCapture() 17601 : false; 17602 // We can't use default capture by copy if any captures already specified 17603 // capture by copy. 17604 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17605 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17606 })) { 17607 FixBuffer.assign({"=", Separator}); 17608 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17609 << /*value*/ 0 17610 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17611 } 17612 } 17613 17614 // We can't use default capture by reference if any captures already specified 17615 // capture by reference. 17616 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17617 return !C.isInitCapture() && C.isReferenceCapture() && 17618 !C.isThisCapture(); 17619 })) { 17620 FixBuffer.assign({"&", Separator}); 17621 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17622 << /*reference*/ 1 17623 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17624 } 17625 } 17626 17627 bool Sema::tryCaptureVariable( 17628 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17629 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17630 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17631 // An init-capture is notionally from the context surrounding its 17632 // declaration, but its parent DC is the lambda class. 17633 DeclContext *VarDC = Var->getDeclContext(); 17634 if (Var->isInitCapture()) 17635 VarDC = VarDC->getParent(); 17636 17637 DeclContext *DC = CurContext; 17638 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17639 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17640 // We need to sync up the Declaration Context with the 17641 // FunctionScopeIndexToStopAt 17642 if (FunctionScopeIndexToStopAt) { 17643 unsigned FSIndex = FunctionScopes.size() - 1; 17644 while (FSIndex != MaxFunctionScopesIndex) { 17645 DC = getLambdaAwareParentOfDeclContext(DC); 17646 --FSIndex; 17647 } 17648 } 17649 17650 17651 // If the variable is declared in the current context, there is no need to 17652 // capture it. 17653 if (VarDC == DC) return true; 17654 17655 // Capture global variables if it is required to use private copy of this 17656 // variable. 17657 bool IsGlobal = !Var->hasLocalStorage(); 17658 if (IsGlobal && 17659 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17660 MaxFunctionScopesIndex))) 17661 return true; 17662 Var = Var->getCanonicalDecl(); 17663 17664 // Walk up the stack to determine whether we can capture the variable, 17665 // performing the "simple" checks that don't depend on type. We stop when 17666 // we've either hit the declared scope of the variable or find an existing 17667 // capture of that variable. We start from the innermost capturing-entity 17668 // (the DC) and ensure that all intervening capturing-entities 17669 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17670 // declcontext can either capture the variable or have already captured 17671 // the variable. 17672 CaptureType = Var->getType(); 17673 DeclRefType = CaptureType.getNonReferenceType(); 17674 bool Nested = false; 17675 bool Explicit = (Kind != TryCapture_Implicit); 17676 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17677 do { 17678 // Only block literals, captured statements, and lambda expressions can 17679 // capture; other scopes don't work. 17680 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17681 ExprLoc, 17682 BuildAndDiagnose, 17683 *this); 17684 // We need to check for the parent *first* because, if we *have* 17685 // private-captured a global variable, we need to recursively capture it in 17686 // intermediate blocks, lambdas, etc. 17687 if (!ParentDC) { 17688 if (IsGlobal) { 17689 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17690 break; 17691 } 17692 return true; 17693 } 17694 17695 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17696 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17697 17698 17699 // Check whether we've already captured it. 17700 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17701 DeclRefType)) { 17702 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17703 break; 17704 } 17705 // If we are instantiating a generic lambda call operator body, 17706 // we do not want to capture new variables. What was captured 17707 // during either a lambdas transformation or initial parsing 17708 // should be used. 17709 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17710 if (BuildAndDiagnose) { 17711 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17712 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17713 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17714 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17715 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17716 buildLambdaCaptureFixit(*this, LSI, Var); 17717 } else 17718 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17719 } 17720 return true; 17721 } 17722 17723 // Try to capture variable-length arrays types. 17724 if (Var->getType()->isVariablyModifiedType()) { 17725 // We're going to walk down into the type and look for VLA 17726 // expressions. 17727 QualType QTy = Var->getType(); 17728 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17729 QTy = PVD->getOriginalType(); 17730 captureVariablyModifiedType(Context, QTy, CSI); 17731 } 17732 17733 if (getLangOpts().OpenMP) { 17734 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17735 // OpenMP private variables should not be captured in outer scope, so 17736 // just break here. Similarly, global variables that are captured in a 17737 // target region should not be captured outside the scope of the region. 17738 if (RSI->CapRegionKind == CR_OpenMP) { 17739 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17740 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17741 // If the variable is private (i.e. not captured) and has variably 17742 // modified type, we still need to capture the type for correct 17743 // codegen in all regions, associated with the construct. Currently, 17744 // it is captured in the innermost captured region only. 17745 if (IsOpenMPPrivateDecl != OMPC_unknown && 17746 Var->getType()->isVariablyModifiedType()) { 17747 QualType QTy = Var->getType(); 17748 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17749 QTy = PVD->getOriginalType(); 17750 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17751 I < E; ++I) { 17752 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17753 FunctionScopes[FunctionScopesIndex - I]); 17754 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17755 "Wrong number of captured regions associated with the " 17756 "OpenMP construct."); 17757 captureVariablyModifiedType(Context, QTy, OuterRSI); 17758 } 17759 } 17760 bool IsTargetCap = 17761 IsOpenMPPrivateDecl != OMPC_private && 17762 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17763 RSI->OpenMPCaptureLevel); 17764 // Do not capture global if it is not privatized in outer regions. 17765 bool IsGlobalCap = 17766 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17767 RSI->OpenMPCaptureLevel); 17768 17769 // When we detect target captures we are looking from inside the 17770 // target region, therefore we need to propagate the capture from the 17771 // enclosing region. Therefore, the capture is not initially nested. 17772 if (IsTargetCap) 17773 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17774 17775 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17776 (IsGlobal && !IsGlobalCap)) { 17777 Nested = !IsTargetCap; 17778 bool HasConst = DeclRefType.isConstQualified(); 17779 DeclRefType = DeclRefType.getUnqualifiedType(); 17780 // Don't lose diagnostics about assignments to const. 17781 if (HasConst) 17782 DeclRefType.addConst(); 17783 CaptureType = Context.getLValueReferenceType(DeclRefType); 17784 break; 17785 } 17786 } 17787 } 17788 } 17789 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17790 // No capture-default, and this is not an explicit capture 17791 // so cannot capture this variable. 17792 if (BuildAndDiagnose) { 17793 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17794 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17795 auto *LSI = cast<LambdaScopeInfo>(CSI); 17796 if (LSI->Lambda) { 17797 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17798 buildLambdaCaptureFixit(*this, LSI, Var); 17799 } 17800 // FIXME: If we error out because an outer lambda can not implicitly 17801 // capture a variable that an inner lambda explicitly captures, we 17802 // should have the inner lambda do the explicit capture - because 17803 // it makes for cleaner diagnostics later. This would purely be done 17804 // so that the diagnostic does not misleadingly claim that a variable 17805 // can not be captured by a lambda implicitly even though it is captured 17806 // explicitly. Suggestion: 17807 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17808 // at the function head 17809 // - cache the StartingDeclContext - this must be a lambda 17810 // - captureInLambda in the innermost lambda the variable. 17811 } 17812 return true; 17813 } 17814 17815 FunctionScopesIndex--; 17816 DC = ParentDC; 17817 Explicit = false; 17818 } while (!VarDC->Equals(DC)); 17819 17820 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17821 // computing the type of the capture at each step, checking type-specific 17822 // requirements, and adding captures if requested. 17823 // If the variable had already been captured previously, we start capturing 17824 // at the lambda nested within that one. 17825 bool Invalid = false; 17826 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17827 ++I) { 17828 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17829 17830 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17831 // certain types of variables (unnamed, variably modified types etc.) 17832 // so check for eligibility. 17833 if (!Invalid) 17834 Invalid = 17835 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17836 17837 // After encountering an error, if we're actually supposed to capture, keep 17838 // capturing in nested contexts to suppress any follow-on diagnostics. 17839 if (Invalid && !BuildAndDiagnose) 17840 return true; 17841 17842 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17843 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17844 DeclRefType, Nested, *this, Invalid); 17845 Nested = true; 17846 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17847 Invalid = !captureInCapturedRegion( 17848 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17849 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17850 Nested = true; 17851 } else { 17852 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17853 Invalid = 17854 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17855 DeclRefType, Nested, Kind, EllipsisLoc, 17856 /*IsTopScope*/ I == N - 1, *this, Invalid); 17857 Nested = true; 17858 } 17859 17860 if (Invalid && !BuildAndDiagnose) 17861 return true; 17862 } 17863 return Invalid; 17864 } 17865 17866 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17867 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17868 QualType CaptureType; 17869 QualType DeclRefType; 17870 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17871 /*BuildAndDiagnose=*/true, CaptureType, 17872 DeclRefType, nullptr); 17873 } 17874 17875 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17876 QualType CaptureType; 17877 QualType DeclRefType; 17878 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17879 /*BuildAndDiagnose=*/false, CaptureType, 17880 DeclRefType, nullptr); 17881 } 17882 17883 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17884 QualType CaptureType; 17885 QualType DeclRefType; 17886 17887 // Determine whether we can capture this variable. 17888 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17889 /*BuildAndDiagnose=*/false, CaptureType, 17890 DeclRefType, nullptr)) 17891 return QualType(); 17892 17893 return DeclRefType; 17894 } 17895 17896 namespace { 17897 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17898 // The produced TemplateArgumentListInfo* points to data stored within this 17899 // object, so should only be used in contexts where the pointer will not be 17900 // used after the CopiedTemplateArgs object is destroyed. 17901 class CopiedTemplateArgs { 17902 bool HasArgs; 17903 TemplateArgumentListInfo TemplateArgStorage; 17904 public: 17905 template<typename RefExpr> 17906 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17907 if (HasArgs) 17908 E->copyTemplateArgumentsInto(TemplateArgStorage); 17909 } 17910 operator TemplateArgumentListInfo*() 17911 #ifdef __has_cpp_attribute 17912 #if __has_cpp_attribute(clang::lifetimebound) 17913 [[clang::lifetimebound]] 17914 #endif 17915 #endif 17916 { 17917 return HasArgs ? &TemplateArgStorage : nullptr; 17918 } 17919 }; 17920 } 17921 17922 /// Walk the set of potential results of an expression and mark them all as 17923 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17924 /// 17925 /// \return A new expression if we found any potential results, ExprEmpty() if 17926 /// not, and ExprError() if we diagnosed an error. 17927 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17928 NonOdrUseReason NOUR) { 17929 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17930 // an object that satisfies the requirements for appearing in a 17931 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17932 // is immediately applied." This function handles the lvalue-to-rvalue 17933 // conversion part. 17934 // 17935 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17936 // transform it into the relevant kind of non-odr-use node and rebuild the 17937 // tree of nodes leading to it. 17938 // 17939 // This is a mini-TreeTransform that only transforms a restricted subset of 17940 // nodes (and only certain operands of them). 17941 17942 // Rebuild a subexpression. 17943 auto Rebuild = [&](Expr *Sub) { 17944 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17945 }; 17946 17947 // Check whether a potential result satisfies the requirements of NOUR. 17948 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17949 // Any entity other than a VarDecl is always odr-used whenever it's named 17950 // in a potentially-evaluated expression. 17951 auto *VD = dyn_cast<VarDecl>(D); 17952 if (!VD) 17953 return true; 17954 17955 // C++2a [basic.def.odr]p4: 17956 // A variable x whose name appears as a potentially-evalauted expression 17957 // e is odr-used by e unless 17958 // -- x is a reference that is usable in constant expressions, or 17959 // -- x is a variable of non-reference type that is usable in constant 17960 // expressions and has no mutable subobjects, and e is an element of 17961 // the set of potential results of an expression of 17962 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17963 // conversion is applied, or 17964 // -- x is a variable of non-reference type, and e is an element of the 17965 // set of potential results of a discarded-value expression to which 17966 // the lvalue-to-rvalue conversion is not applied 17967 // 17968 // We check the first bullet and the "potentially-evaluated" condition in 17969 // BuildDeclRefExpr. We check the type requirements in the second bullet 17970 // in CheckLValueToRValueConversionOperand below. 17971 switch (NOUR) { 17972 case NOUR_None: 17973 case NOUR_Unevaluated: 17974 llvm_unreachable("unexpected non-odr-use-reason"); 17975 17976 case NOUR_Constant: 17977 // Constant references were handled when they were built. 17978 if (VD->getType()->isReferenceType()) 17979 return true; 17980 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17981 if (RD->hasMutableFields()) 17982 return true; 17983 if (!VD->isUsableInConstantExpressions(S.Context)) 17984 return true; 17985 break; 17986 17987 case NOUR_Discarded: 17988 if (VD->getType()->isReferenceType()) 17989 return true; 17990 break; 17991 } 17992 return false; 17993 }; 17994 17995 // Mark that this expression does not constitute an odr-use. 17996 auto MarkNotOdrUsed = [&] { 17997 S.MaybeODRUseExprs.remove(E); 17998 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17999 LSI->markVariableExprAsNonODRUsed(E); 18000 }; 18001 18002 // C++2a [basic.def.odr]p2: 18003 // The set of potential results of an expression e is defined as follows: 18004 switch (E->getStmtClass()) { 18005 // -- If e is an id-expression, ... 18006 case Expr::DeclRefExprClass: { 18007 auto *DRE = cast<DeclRefExpr>(E); 18008 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18009 break; 18010 18011 // Rebuild as a non-odr-use DeclRefExpr. 18012 MarkNotOdrUsed(); 18013 return DeclRefExpr::Create( 18014 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18015 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18016 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18017 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18018 } 18019 18020 case Expr::FunctionParmPackExprClass: { 18021 auto *FPPE = cast<FunctionParmPackExpr>(E); 18022 // If any of the declarations in the pack is odr-used, then the expression 18023 // as a whole constitutes an odr-use. 18024 for (VarDecl *D : *FPPE) 18025 if (IsPotentialResultOdrUsed(D)) 18026 return ExprEmpty(); 18027 18028 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18029 // nothing cares about whether we marked this as an odr-use, but it might 18030 // be useful for non-compiler tools. 18031 MarkNotOdrUsed(); 18032 break; 18033 } 18034 18035 // -- If e is a subscripting operation with an array operand... 18036 case Expr::ArraySubscriptExprClass: { 18037 auto *ASE = cast<ArraySubscriptExpr>(E); 18038 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18039 if (!OldBase->getType()->isArrayType()) 18040 break; 18041 ExprResult Base = Rebuild(OldBase); 18042 if (!Base.isUsable()) 18043 return Base; 18044 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18045 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18046 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18047 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18048 ASE->getRBracketLoc()); 18049 } 18050 18051 case Expr::MemberExprClass: { 18052 auto *ME = cast<MemberExpr>(E); 18053 // -- If e is a class member access expression [...] naming a non-static 18054 // data member... 18055 if (isa<FieldDecl>(ME->getMemberDecl())) { 18056 ExprResult Base = Rebuild(ME->getBase()); 18057 if (!Base.isUsable()) 18058 return Base; 18059 return MemberExpr::Create( 18060 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18061 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18062 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18063 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18064 ME->getObjectKind(), ME->isNonOdrUse()); 18065 } 18066 18067 if (ME->getMemberDecl()->isCXXInstanceMember()) 18068 break; 18069 18070 // -- If e is a class member access expression naming a static data member, 18071 // ... 18072 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18073 break; 18074 18075 // Rebuild as a non-odr-use MemberExpr. 18076 MarkNotOdrUsed(); 18077 return MemberExpr::Create( 18078 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18079 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18080 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18081 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18082 return ExprEmpty(); 18083 } 18084 18085 case Expr::BinaryOperatorClass: { 18086 auto *BO = cast<BinaryOperator>(E); 18087 Expr *LHS = BO->getLHS(); 18088 Expr *RHS = BO->getRHS(); 18089 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18090 if (BO->getOpcode() == BO_PtrMemD) { 18091 ExprResult Sub = Rebuild(LHS); 18092 if (!Sub.isUsable()) 18093 return Sub; 18094 LHS = Sub.get(); 18095 // -- If e is a comma expression, ... 18096 } else if (BO->getOpcode() == BO_Comma) { 18097 ExprResult Sub = Rebuild(RHS); 18098 if (!Sub.isUsable()) 18099 return Sub; 18100 RHS = Sub.get(); 18101 } else { 18102 break; 18103 } 18104 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18105 LHS, RHS); 18106 } 18107 18108 // -- If e has the form (e1)... 18109 case Expr::ParenExprClass: { 18110 auto *PE = cast<ParenExpr>(E); 18111 ExprResult Sub = Rebuild(PE->getSubExpr()); 18112 if (!Sub.isUsable()) 18113 return Sub; 18114 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18115 } 18116 18117 // -- If e is a glvalue conditional expression, ... 18118 // We don't apply this to a binary conditional operator. FIXME: Should we? 18119 case Expr::ConditionalOperatorClass: { 18120 auto *CO = cast<ConditionalOperator>(E); 18121 ExprResult LHS = Rebuild(CO->getLHS()); 18122 if (LHS.isInvalid()) 18123 return ExprError(); 18124 ExprResult RHS = Rebuild(CO->getRHS()); 18125 if (RHS.isInvalid()) 18126 return ExprError(); 18127 if (!LHS.isUsable() && !RHS.isUsable()) 18128 return ExprEmpty(); 18129 if (!LHS.isUsable()) 18130 LHS = CO->getLHS(); 18131 if (!RHS.isUsable()) 18132 RHS = CO->getRHS(); 18133 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18134 CO->getCond(), LHS.get(), RHS.get()); 18135 } 18136 18137 // [Clang extension] 18138 // -- If e has the form __extension__ e1... 18139 case Expr::UnaryOperatorClass: { 18140 auto *UO = cast<UnaryOperator>(E); 18141 if (UO->getOpcode() != UO_Extension) 18142 break; 18143 ExprResult Sub = Rebuild(UO->getSubExpr()); 18144 if (!Sub.isUsable()) 18145 return Sub; 18146 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18147 Sub.get()); 18148 } 18149 18150 // [Clang extension] 18151 // -- If e has the form _Generic(...), the set of potential results is the 18152 // union of the sets of potential results of the associated expressions. 18153 case Expr::GenericSelectionExprClass: { 18154 auto *GSE = cast<GenericSelectionExpr>(E); 18155 18156 SmallVector<Expr *, 4> AssocExprs; 18157 bool AnyChanged = false; 18158 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18159 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18160 if (AssocExpr.isInvalid()) 18161 return ExprError(); 18162 if (AssocExpr.isUsable()) { 18163 AssocExprs.push_back(AssocExpr.get()); 18164 AnyChanged = true; 18165 } else { 18166 AssocExprs.push_back(OrigAssocExpr); 18167 } 18168 } 18169 18170 return AnyChanged ? S.CreateGenericSelectionExpr( 18171 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18172 GSE->getRParenLoc(), GSE->getControllingExpr(), 18173 GSE->getAssocTypeSourceInfos(), AssocExprs) 18174 : ExprEmpty(); 18175 } 18176 18177 // [Clang extension] 18178 // -- If e has the form __builtin_choose_expr(...), the set of potential 18179 // results is the union of the sets of potential results of the 18180 // second and third subexpressions. 18181 case Expr::ChooseExprClass: { 18182 auto *CE = cast<ChooseExpr>(E); 18183 18184 ExprResult LHS = Rebuild(CE->getLHS()); 18185 if (LHS.isInvalid()) 18186 return ExprError(); 18187 18188 ExprResult RHS = Rebuild(CE->getLHS()); 18189 if (RHS.isInvalid()) 18190 return ExprError(); 18191 18192 if (!LHS.get() && !RHS.get()) 18193 return ExprEmpty(); 18194 if (!LHS.isUsable()) 18195 LHS = CE->getLHS(); 18196 if (!RHS.isUsable()) 18197 RHS = CE->getRHS(); 18198 18199 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18200 RHS.get(), CE->getRParenLoc()); 18201 } 18202 18203 // Step through non-syntactic nodes. 18204 case Expr::ConstantExprClass: { 18205 auto *CE = cast<ConstantExpr>(E); 18206 ExprResult Sub = Rebuild(CE->getSubExpr()); 18207 if (!Sub.isUsable()) 18208 return Sub; 18209 return ConstantExpr::Create(S.Context, Sub.get()); 18210 } 18211 18212 // We could mostly rely on the recursive rebuilding to rebuild implicit 18213 // casts, but not at the top level, so rebuild them here. 18214 case Expr::ImplicitCastExprClass: { 18215 auto *ICE = cast<ImplicitCastExpr>(E); 18216 // Only step through the narrow set of cast kinds we expect to encounter. 18217 // Anything else suggests we've left the region in which potential results 18218 // can be found. 18219 switch (ICE->getCastKind()) { 18220 case CK_NoOp: 18221 case CK_DerivedToBase: 18222 case CK_UncheckedDerivedToBase: { 18223 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18224 if (!Sub.isUsable()) 18225 return Sub; 18226 CXXCastPath Path(ICE->path()); 18227 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18228 ICE->getValueKind(), &Path); 18229 } 18230 18231 default: 18232 break; 18233 } 18234 break; 18235 } 18236 18237 default: 18238 break; 18239 } 18240 18241 // Can't traverse through this node. Nothing to do. 18242 return ExprEmpty(); 18243 } 18244 18245 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18246 // Check whether the operand is or contains an object of non-trivial C union 18247 // type. 18248 if (E->getType().isVolatileQualified() && 18249 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18250 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18251 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18252 Sema::NTCUC_LValueToRValueVolatile, 18253 NTCUK_Destruct|NTCUK_Copy); 18254 18255 // C++2a [basic.def.odr]p4: 18256 // [...] an expression of non-volatile-qualified non-class type to which 18257 // the lvalue-to-rvalue conversion is applied [...] 18258 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18259 return E; 18260 18261 ExprResult Result = 18262 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18263 if (Result.isInvalid()) 18264 return ExprError(); 18265 return Result.get() ? Result : E; 18266 } 18267 18268 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18269 Res = CorrectDelayedTyposInExpr(Res); 18270 18271 if (!Res.isUsable()) 18272 return Res; 18273 18274 // If a constant-expression is a reference to a variable where we delay 18275 // deciding whether it is an odr-use, just assume we will apply the 18276 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18277 // (a non-type template argument), we have special handling anyway. 18278 return CheckLValueToRValueConversionOperand(Res.get()); 18279 } 18280 18281 void Sema::CleanupVarDeclMarking() { 18282 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18283 // call. 18284 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18285 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18286 18287 for (Expr *E : LocalMaybeODRUseExprs) { 18288 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18289 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18290 DRE->getLocation(), *this); 18291 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18292 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18293 *this); 18294 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18295 for (VarDecl *VD : *FP) 18296 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18297 } else { 18298 llvm_unreachable("Unexpected expression"); 18299 } 18300 } 18301 18302 assert(MaybeODRUseExprs.empty() && 18303 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18304 } 18305 18306 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18307 VarDecl *Var, Expr *E) { 18308 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18309 isa<FunctionParmPackExpr>(E)) && 18310 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18311 Var->setReferenced(); 18312 18313 if (Var->isInvalidDecl()) 18314 return; 18315 18316 // Record a CUDA/HIP static device/constant variable if it is referenced 18317 // by host code. This is done conservatively, when the variable is referenced 18318 // in any of the following contexts: 18319 // - a non-function context 18320 // - a host function 18321 // - a host device function 18322 // This also requires the reference of the static device/constant variable by 18323 // host code to be visible in the device compilation for the compiler to be 18324 // able to externalize the static device/constant variable. 18325 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18326 auto *CurContext = SemaRef.CurContext; 18327 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18328 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18329 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18330 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18331 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18332 } 18333 18334 auto *MSI = Var->getMemberSpecializationInfo(); 18335 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18336 : Var->getTemplateSpecializationKind(); 18337 18338 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18339 bool UsableInConstantExpr = 18340 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18341 18342 // C++20 [expr.const]p12: 18343 // A variable [...] is needed for constant evaluation if it is [...] a 18344 // variable whose name appears as a potentially constant evaluated 18345 // expression that is either a contexpr variable or is of non-volatile 18346 // const-qualified integral type or of reference type 18347 bool NeededForConstantEvaluation = 18348 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18349 18350 bool NeedDefinition = 18351 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18352 18353 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18354 "Can't instantiate a partial template specialization."); 18355 18356 // If this might be a member specialization of a static data member, check 18357 // the specialization is visible. We already did the checks for variable 18358 // template specializations when we created them. 18359 if (NeedDefinition && TSK != TSK_Undeclared && 18360 !isa<VarTemplateSpecializationDecl>(Var)) 18361 SemaRef.checkSpecializationVisibility(Loc, Var); 18362 18363 // Perform implicit instantiation of static data members, static data member 18364 // templates of class templates, and variable template specializations. Delay 18365 // instantiations of variable templates, except for those that could be used 18366 // in a constant expression. 18367 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18368 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18369 // instantiation declaration if a variable is usable in a constant 18370 // expression (among other cases). 18371 bool TryInstantiating = 18372 TSK == TSK_ImplicitInstantiation || 18373 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18374 18375 if (TryInstantiating) { 18376 SourceLocation PointOfInstantiation = 18377 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18378 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18379 if (FirstInstantiation) { 18380 PointOfInstantiation = Loc; 18381 if (MSI) 18382 MSI->setPointOfInstantiation(PointOfInstantiation); 18383 // FIXME: Notify listener. 18384 else 18385 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18386 } 18387 18388 if (UsableInConstantExpr) { 18389 // Do not defer instantiations of variables that could be used in a 18390 // constant expression. 18391 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18392 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18393 }); 18394 18395 // Re-set the member to trigger a recomputation of the dependence bits 18396 // for the expression. 18397 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18398 DRE->setDecl(DRE->getDecl()); 18399 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18400 ME->setMemberDecl(ME->getMemberDecl()); 18401 } else if (FirstInstantiation || 18402 isa<VarTemplateSpecializationDecl>(Var)) { 18403 // FIXME: For a specialization of a variable template, we don't 18404 // distinguish between "declaration and type implicitly instantiated" 18405 // and "implicit instantiation of definition requested", so we have 18406 // no direct way to avoid enqueueing the pending instantiation 18407 // multiple times. 18408 SemaRef.PendingInstantiations 18409 .push_back(std::make_pair(Var, PointOfInstantiation)); 18410 } 18411 } 18412 } 18413 18414 // C++2a [basic.def.odr]p4: 18415 // A variable x whose name appears as a potentially-evaluated expression e 18416 // is odr-used by e unless 18417 // -- x is a reference that is usable in constant expressions 18418 // -- x is a variable of non-reference type that is usable in constant 18419 // expressions and has no mutable subobjects [FIXME], and e is an 18420 // element of the set of potential results of an expression of 18421 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18422 // conversion is applied 18423 // -- x is a variable of non-reference type, and e is an element of the set 18424 // of potential results of a discarded-value expression to which the 18425 // lvalue-to-rvalue conversion is not applied [FIXME] 18426 // 18427 // We check the first part of the second bullet here, and 18428 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18429 // FIXME: To get the third bullet right, we need to delay this even for 18430 // variables that are not usable in constant expressions. 18431 18432 // If we already know this isn't an odr-use, there's nothing more to do. 18433 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18434 if (DRE->isNonOdrUse()) 18435 return; 18436 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18437 if (ME->isNonOdrUse()) 18438 return; 18439 18440 switch (OdrUse) { 18441 case OdrUseContext::None: 18442 assert((!E || isa<FunctionParmPackExpr>(E)) && 18443 "missing non-odr-use marking for unevaluated decl ref"); 18444 break; 18445 18446 case OdrUseContext::FormallyOdrUsed: 18447 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18448 // behavior. 18449 break; 18450 18451 case OdrUseContext::Used: 18452 // If we might later find that this expression isn't actually an odr-use, 18453 // delay the marking. 18454 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18455 SemaRef.MaybeODRUseExprs.insert(E); 18456 else 18457 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18458 break; 18459 18460 case OdrUseContext::Dependent: 18461 // If this is a dependent context, we don't need to mark variables as 18462 // odr-used, but we may still need to track them for lambda capture. 18463 // FIXME: Do we also need to do this inside dependent typeid expressions 18464 // (which are modeled as unevaluated at this point)? 18465 const bool RefersToEnclosingScope = 18466 (SemaRef.CurContext != Var->getDeclContext() && 18467 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18468 if (RefersToEnclosingScope) { 18469 LambdaScopeInfo *const LSI = 18470 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18471 if (LSI && (!LSI->CallOperator || 18472 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18473 // If a variable could potentially be odr-used, defer marking it so 18474 // until we finish analyzing the full expression for any 18475 // lvalue-to-rvalue 18476 // or discarded value conversions that would obviate odr-use. 18477 // Add it to the list of potential captures that will be analyzed 18478 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18479 // unless the variable is a reference that was initialized by a constant 18480 // expression (this will never need to be captured or odr-used). 18481 // 18482 // FIXME: We can simplify this a lot after implementing P0588R1. 18483 assert(E && "Capture variable should be used in an expression."); 18484 if (!Var->getType()->isReferenceType() || 18485 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18486 LSI->addPotentialCapture(E->IgnoreParens()); 18487 } 18488 } 18489 break; 18490 } 18491 } 18492 18493 /// Mark a variable referenced, and check whether it is odr-used 18494 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18495 /// used directly for normal expressions referring to VarDecl. 18496 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18497 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18498 } 18499 18500 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18501 Decl *D, Expr *E, bool MightBeOdrUse) { 18502 if (SemaRef.isInOpenMPDeclareTargetContext()) 18503 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18504 18505 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18506 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18507 return; 18508 } 18509 18510 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18511 18512 // If this is a call to a method via a cast, also mark the method in the 18513 // derived class used in case codegen can devirtualize the call. 18514 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18515 if (!ME) 18516 return; 18517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18518 if (!MD) 18519 return; 18520 // Only attempt to devirtualize if this is truly a virtual call. 18521 bool IsVirtualCall = MD->isVirtual() && 18522 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18523 if (!IsVirtualCall) 18524 return; 18525 18526 // If it's possible to devirtualize the call, mark the called function 18527 // referenced. 18528 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18529 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18530 if (DM) 18531 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18532 } 18533 18534 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18535 /// 18536 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18537 /// handled with care if the DeclRefExpr is not newly-created. 18538 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18539 // TODO: update this with DR# once a defect report is filed. 18540 // C++11 defect. The address of a pure member should not be an ODR use, even 18541 // if it's a qualified reference. 18542 bool OdrUse = true; 18543 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18544 if (Method->isVirtual() && 18545 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18546 OdrUse = false; 18547 18548 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18549 if (!isConstantEvaluated() && FD->isConsteval() && 18550 !RebuildingImmediateInvocation) 18551 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18552 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18553 } 18554 18555 /// Perform reference-marking and odr-use handling for a MemberExpr. 18556 void Sema::MarkMemberReferenced(MemberExpr *E) { 18557 // C++11 [basic.def.odr]p2: 18558 // A non-overloaded function whose name appears as a potentially-evaluated 18559 // expression or a member of a set of candidate functions, if selected by 18560 // overload resolution when referred to from a potentially-evaluated 18561 // expression, is odr-used, unless it is a pure virtual function and its 18562 // name is not explicitly qualified. 18563 bool MightBeOdrUse = true; 18564 if (E->performsVirtualDispatch(getLangOpts())) { 18565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18566 if (Method->isPure()) 18567 MightBeOdrUse = false; 18568 } 18569 SourceLocation Loc = 18570 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18571 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18572 } 18573 18574 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18575 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18576 for (VarDecl *VD : *E) 18577 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18578 } 18579 18580 /// Perform marking for a reference to an arbitrary declaration. It 18581 /// marks the declaration referenced, and performs odr-use checking for 18582 /// functions and variables. This method should not be used when building a 18583 /// normal expression which refers to a variable. 18584 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18585 bool MightBeOdrUse) { 18586 if (MightBeOdrUse) { 18587 if (auto *VD = dyn_cast<VarDecl>(D)) { 18588 MarkVariableReferenced(Loc, VD); 18589 return; 18590 } 18591 } 18592 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18593 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18594 return; 18595 } 18596 D->setReferenced(); 18597 } 18598 18599 namespace { 18600 // Mark all of the declarations used by a type as referenced. 18601 // FIXME: Not fully implemented yet! We need to have a better understanding 18602 // of when we're entering a context we should not recurse into. 18603 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18604 // TreeTransforms rebuilding the type in a new context. Rather than 18605 // duplicating the TreeTransform logic, we should consider reusing it here. 18606 // Currently that causes problems when rebuilding LambdaExprs. 18607 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18608 Sema &S; 18609 SourceLocation Loc; 18610 18611 public: 18612 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18613 18614 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18615 18616 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18617 }; 18618 } 18619 18620 bool MarkReferencedDecls::TraverseTemplateArgument( 18621 const TemplateArgument &Arg) { 18622 { 18623 // A non-type template argument is a constant-evaluated context. 18624 EnterExpressionEvaluationContext Evaluated( 18625 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18626 if (Arg.getKind() == TemplateArgument::Declaration) { 18627 if (Decl *D = Arg.getAsDecl()) 18628 S.MarkAnyDeclReferenced(Loc, D, true); 18629 } else if (Arg.getKind() == TemplateArgument::Expression) { 18630 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18631 } 18632 } 18633 18634 return Inherited::TraverseTemplateArgument(Arg); 18635 } 18636 18637 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18638 MarkReferencedDecls Marker(*this, Loc); 18639 Marker.TraverseType(T); 18640 } 18641 18642 namespace { 18643 /// Helper class that marks all of the declarations referenced by 18644 /// potentially-evaluated subexpressions as "referenced". 18645 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18646 public: 18647 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18648 bool SkipLocalVariables; 18649 18650 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18651 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18652 18653 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18654 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18655 } 18656 18657 void VisitDeclRefExpr(DeclRefExpr *E) { 18658 // If we were asked not to visit local variables, don't. 18659 if (SkipLocalVariables) { 18660 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18661 if (VD->hasLocalStorage()) 18662 return; 18663 } 18664 18665 // FIXME: This can trigger the instantiation of the initializer of a 18666 // variable, which can cause the expression to become value-dependent 18667 // or error-dependent. Do we need to propagate the new dependence bits? 18668 S.MarkDeclRefReferenced(E); 18669 } 18670 18671 void VisitMemberExpr(MemberExpr *E) { 18672 S.MarkMemberReferenced(E); 18673 Visit(E->getBase()); 18674 } 18675 }; 18676 } // namespace 18677 18678 /// Mark any declarations that appear within this expression or any 18679 /// potentially-evaluated subexpressions as "referenced". 18680 /// 18681 /// \param SkipLocalVariables If true, don't mark local variables as 18682 /// 'referenced'. 18683 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18684 bool SkipLocalVariables) { 18685 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18686 } 18687 18688 /// Emit a diagnostic that describes an effect on the run-time behavior 18689 /// of the program being compiled. 18690 /// 18691 /// This routine emits the given diagnostic when the code currently being 18692 /// type-checked is "potentially evaluated", meaning that there is a 18693 /// possibility that the code will actually be executable. Code in sizeof() 18694 /// expressions, code used only during overload resolution, etc., are not 18695 /// potentially evaluated. This routine will suppress such diagnostics or, 18696 /// in the absolutely nutty case of potentially potentially evaluated 18697 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18698 /// later. 18699 /// 18700 /// This routine should be used for all diagnostics that describe the run-time 18701 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18702 /// Failure to do so will likely result in spurious diagnostics or failures 18703 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18704 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18705 const PartialDiagnostic &PD) { 18706 switch (ExprEvalContexts.back().Context) { 18707 case ExpressionEvaluationContext::Unevaluated: 18708 case ExpressionEvaluationContext::UnevaluatedList: 18709 case ExpressionEvaluationContext::UnevaluatedAbstract: 18710 case ExpressionEvaluationContext::DiscardedStatement: 18711 // The argument will never be evaluated, so don't complain. 18712 break; 18713 18714 case ExpressionEvaluationContext::ConstantEvaluated: 18715 // Relevant diagnostics should be produced by constant evaluation. 18716 break; 18717 18718 case ExpressionEvaluationContext::PotentiallyEvaluated: 18719 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18720 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18721 FunctionScopes.back()->PossiblyUnreachableDiags. 18722 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18723 return true; 18724 } 18725 18726 // The initializer of a constexpr variable or of the first declaration of a 18727 // static data member is not syntactically a constant evaluated constant, 18728 // but nonetheless is always required to be a constant expression, so we 18729 // can skip diagnosing. 18730 // FIXME: Using the mangling context here is a hack. 18731 if (auto *VD = dyn_cast_or_null<VarDecl>( 18732 ExprEvalContexts.back().ManglingContextDecl)) { 18733 if (VD->isConstexpr() || 18734 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18735 break; 18736 // FIXME: For any other kind of variable, we should build a CFG for its 18737 // initializer and check whether the context in question is reachable. 18738 } 18739 18740 Diag(Loc, PD); 18741 return true; 18742 } 18743 18744 return false; 18745 } 18746 18747 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18748 const PartialDiagnostic &PD) { 18749 return DiagRuntimeBehavior( 18750 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18751 } 18752 18753 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18754 CallExpr *CE, FunctionDecl *FD) { 18755 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18756 return false; 18757 18758 // If we're inside a decltype's expression, don't check for a valid return 18759 // type or construct temporaries until we know whether this is the last call. 18760 if (ExprEvalContexts.back().ExprContext == 18761 ExpressionEvaluationContextRecord::EK_Decltype) { 18762 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18763 return false; 18764 } 18765 18766 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18767 FunctionDecl *FD; 18768 CallExpr *CE; 18769 18770 public: 18771 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18772 : FD(FD), CE(CE) { } 18773 18774 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18775 if (!FD) { 18776 S.Diag(Loc, diag::err_call_incomplete_return) 18777 << T << CE->getSourceRange(); 18778 return; 18779 } 18780 18781 S.Diag(Loc, diag::err_call_function_incomplete_return) 18782 << CE->getSourceRange() << FD << T; 18783 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18784 << FD->getDeclName(); 18785 } 18786 } Diagnoser(FD, CE); 18787 18788 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18789 return true; 18790 18791 return false; 18792 } 18793 18794 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18795 // will prevent this condition from triggering, which is what we want. 18796 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18797 SourceLocation Loc; 18798 18799 unsigned diagnostic = diag::warn_condition_is_assignment; 18800 bool IsOrAssign = false; 18801 18802 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18803 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18804 return; 18805 18806 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18807 18808 // Greylist some idioms by putting them into a warning subcategory. 18809 if (ObjCMessageExpr *ME 18810 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18811 Selector Sel = ME->getSelector(); 18812 18813 // self = [<foo> init...] 18814 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18815 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18816 18817 // <foo> = [<bar> nextObject] 18818 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18819 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18820 } 18821 18822 Loc = Op->getOperatorLoc(); 18823 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18824 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18825 return; 18826 18827 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18828 Loc = Op->getOperatorLoc(); 18829 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18830 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18831 else { 18832 // Not an assignment. 18833 return; 18834 } 18835 18836 Diag(Loc, diagnostic) << E->getSourceRange(); 18837 18838 SourceLocation Open = E->getBeginLoc(); 18839 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18840 Diag(Loc, diag::note_condition_assign_silence) 18841 << FixItHint::CreateInsertion(Open, "(") 18842 << FixItHint::CreateInsertion(Close, ")"); 18843 18844 if (IsOrAssign) 18845 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18846 << FixItHint::CreateReplacement(Loc, "!="); 18847 else 18848 Diag(Loc, diag::note_condition_assign_to_comparison) 18849 << FixItHint::CreateReplacement(Loc, "=="); 18850 } 18851 18852 /// Redundant parentheses over an equality comparison can indicate 18853 /// that the user intended an assignment used as condition. 18854 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18855 // Don't warn if the parens came from a macro. 18856 SourceLocation parenLoc = ParenE->getBeginLoc(); 18857 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18858 return; 18859 // Don't warn for dependent expressions. 18860 if (ParenE->isTypeDependent()) 18861 return; 18862 18863 Expr *E = ParenE->IgnoreParens(); 18864 18865 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18866 if (opE->getOpcode() == BO_EQ && 18867 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18868 == Expr::MLV_Valid) { 18869 SourceLocation Loc = opE->getOperatorLoc(); 18870 18871 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18872 SourceRange ParenERange = ParenE->getSourceRange(); 18873 Diag(Loc, diag::note_equality_comparison_silence) 18874 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18875 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18876 Diag(Loc, diag::note_equality_comparison_to_assign) 18877 << FixItHint::CreateReplacement(Loc, "="); 18878 } 18879 } 18880 18881 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18882 bool IsConstexpr) { 18883 DiagnoseAssignmentAsCondition(E); 18884 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18885 DiagnoseEqualityWithExtraParens(parenE); 18886 18887 ExprResult result = CheckPlaceholderExpr(E); 18888 if (result.isInvalid()) return ExprError(); 18889 E = result.get(); 18890 18891 if (!E->isTypeDependent()) { 18892 if (getLangOpts().CPlusPlus) 18893 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18894 18895 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18896 if (ERes.isInvalid()) 18897 return ExprError(); 18898 E = ERes.get(); 18899 18900 QualType T = E->getType(); 18901 if (!T->isScalarType()) { // C99 6.8.4.1p1 18902 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18903 << T << E->getSourceRange(); 18904 return ExprError(); 18905 } 18906 CheckBoolLikeConversion(E, Loc); 18907 } 18908 18909 return E; 18910 } 18911 18912 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18913 Expr *SubExpr, ConditionKind CK) { 18914 // Empty conditions are valid in for-statements. 18915 if (!SubExpr) 18916 return ConditionResult(); 18917 18918 ExprResult Cond; 18919 switch (CK) { 18920 case ConditionKind::Boolean: 18921 Cond = CheckBooleanCondition(Loc, SubExpr); 18922 break; 18923 18924 case ConditionKind::ConstexprIf: 18925 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18926 break; 18927 18928 case ConditionKind::Switch: 18929 Cond = CheckSwitchCondition(Loc, SubExpr); 18930 break; 18931 } 18932 if (Cond.isInvalid()) { 18933 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18934 {SubExpr}); 18935 if (!Cond.get()) 18936 return ConditionError(); 18937 } 18938 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18939 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18940 if (!FullExpr.get()) 18941 return ConditionError(); 18942 18943 return ConditionResult(*this, nullptr, FullExpr, 18944 CK == ConditionKind::ConstexprIf); 18945 } 18946 18947 namespace { 18948 /// A visitor for rebuilding a call to an __unknown_any expression 18949 /// to have an appropriate type. 18950 struct RebuildUnknownAnyFunction 18951 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18952 18953 Sema &S; 18954 18955 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18956 18957 ExprResult VisitStmt(Stmt *S) { 18958 llvm_unreachable("unexpected statement!"); 18959 } 18960 18961 ExprResult VisitExpr(Expr *E) { 18962 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18963 << E->getSourceRange(); 18964 return ExprError(); 18965 } 18966 18967 /// Rebuild an expression which simply semantically wraps another 18968 /// expression which it shares the type and value kind of. 18969 template <class T> ExprResult rebuildSugarExpr(T *E) { 18970 ExprResult SubResult = Visit(E->getSubExpr()); 18971 if (SubResult.isInvalid()) return ExprError(); 18972 18973 Expr *SubExpr = SubResult.get(); 18974 E->setSubExpr(SubExpr); 18975 E->setType(SubExpr->getType()); 18976 E->setValueKind(SubExpr->getValueKind()); 18977 assert(E->getObjectKind() == OK_Ordinary); 18978 return E; 18979 } 18980 18981 ExprResult VisitParenExpr(ParenExpr *E) { 18982 return rebuildSugarExpr(E); 18983 } 18984 18985 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18986 return rebuildSugarExpr(E); 18987 } 18988 18989 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18990 ExprResult SubResult = Visit(E->getSubExpr()); 18991 if (SubResult.isInvalid()) return ExprError(); 18992 18993 Expr *SubExpr = SubResult.get(); 18994 E->setSubExpr(SubExpr); 18995 E->setType(S.Context.getPointerType(SubExpr->getType())); 18996 assert(E->getValueKind() == VK_RValue); 18997 assert(E->getObjectKind() == OK_Ordinary); 18998 return E; 18999 } 19000 19001 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19002 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19003 19004 E->setType(VD->getType()); 19005 19006 assert(E->getValueKind() == VK_RValue); 19007 if (S.getLangOpts().CPlusPlus && 19008 !(isa<CXXMethodDecl>(VD) && 19009 cast<CXXMethodDecl>(VD)->isInstance())) 19010 E->setValueKind(VK_LValue); 19011 19012 return E; 19013 } 19014 19015 ExprResult VisitMemberExpr(MemberExpr *E) { 19016 return resolveDecl(E, E->getMemberDecl()); 19017 } 19018 19019 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19020 return resolveDecl(E, E->getDecl()); 19021 } 19022 }; 19023 } 19024 19025 /// Given a function expression of unknown-any type, try to rebuild it 19026 /// to have a function type. 19027 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19028 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19029 if (Result.isInvalid()) return ExprError(); 19030 return S.DefaultFunctionArrayConversion(Result.get()); 19031 } 19032 19033 namespace { 19034 /// A visitor for rebuilding an expression of type __unknown_anytype 19035 /// into one which resolves the type directly on the referring 19036 /// expression. Strict preservation of the original source 19037 /// structure is not a goal. 19038 struct RebuildUnknownAnyExpr 19039 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19040 19041 Sema &S; 19042 19043 /// The current destination type. 19044 QualType DestType; 19045 19046 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19047 : S(S), DestType(CastType) {} 19048 19049 ExprResult VisitStmt(Stmt *S) { 19050 llvm_unreachable("unexpected statement!"); 19051 } 19052 19053 ExprResult VisitExpr(Expr *E) { 19054 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19055 << E->getSourceRange(); 19056 return ExprError(); 19057 } 19058 19059 ExprResult VisitCallExpr(CallExpr *E); 19060 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19061 19062 /// Rebuild an expression which simply semantically wraps another 19063 /// expression which it shares the type and value kind of. 19064 template <class T> ExprResult rebuildSugarExpr(T *E) { 19065 ExprResult SubResult = Visit(E->getSubExpr()); 19066 if (SubResult.isInvalid()) return ExprError(); 19067 Expr *SubExpr = SubResult.get(); 19068 E->setSubExpr(SubExpr); 19069 E->setType(SubExpr->getType()); 19070 E->setValueKind(SubExpr->getValueKind()); 19071 assert(E->getObjectKind() == OK_Ordinary); 19072 return E; 19073 } 19074 19075 ExprResult VisitParenExpr(ParenExpr *E) { 19076 return rebuildSugarExpr(E); 19077 } 19078 19079 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19080 return rebuildSugarExpr(E); 19081 } 19082 19083 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19084 const PointerType *Ptr = DestType->getAs<PointerType>(); 19085 if (!Ptr) { 19086 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19087 << E->getSourceRange(); 19088 return ExprError(); 19089 } 19090 19091 if (isa<CallExpr>(E->getSubExpr())) { 19092 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19093 << E->getSourceRange(); 19094 return ExprError(); 19095 } 19096 19097 assert(E->getValueKind() == VK_RValue); 19098 assert(E->getObjectKind() == OK_Ordinary); 19099 E->setType(DestType); 19100 19101 // Build the sub-expression as if it were an object of the pointee type. 19102 DestType = Ptr->getPointeeType(); 19103 ExprResult SubResult = Visit(E->getSubExpr()); 19104 if (SubResult.isInvalid()) return ExprError(); 19105 E->setSubExpr(SubResult.get()); 19106 return E; 19107 } 19108 19109 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19110 19111 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19112 19113 ExprResult VisitMemberExpr(MemberExpr *E) { 19114 return resolveDecl(E, E->getMemberDecl()); 19115 } 19116 19117 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19118 return resolveDecl(E, E->getDecl()); 19119 } 19120 }; 19121 } 19122 19123 /// Rebuilds a call expression which yielded __unknown_anytype. 19124 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19125 Expr *CalleeExpr = E->getCallee(); 19126 19127 enum FnKind { 19128 FK_MemberFunction, 19129 FK_FunctionPointer, 19130 FK_BlockPointer 19131 }; 19132 19133 FnKind Kind; 19134 QualType CalleeType = CalleeExpr->getType(); 19135 if (CalleeType == S.Context.BoundMemberTy) { 19136 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19137 Kind = FK_MemberFunction; 19138 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19139 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19140 CalleeType = Ptr->getPointeeType(); 19141 Kind = FK_FunctionPointer; 19142 } else { 19143 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19144 Kind = FK_BlockPointer; 19145 } 19146 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19147 19148 // Verify that this is a legal result type of a function. 19149 if (DestType->isArrayType() || DestType->isFunctionType()) { 19150 unsigned diagID = diag::err_func_returning_array_function; 19151 if (Kind == FK_BlockPointer) 19152 diagID = diag::err_block_returning_array_function; 19153 19154 S.Diag(E->getExprLoc(), diagID) 19155 << DestType->isFunctionType() << DestType; 19156 return ExprError(); 19157 } 19158 19159 // Otherwise, go ahead and set DestType as the call's result. 19160 E->setType(DestType.getNonLValueExprType(S.Context)); 19161 E->setValueKind(Expr::getValueKindForType(DestType)); 19162 assert(E->getObjectKind() == OK_Ordinary); 19163 19164 // Rebuild the function type, replacing the result type with DestType. 19165 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19166 if (Proto) { 19167 // __unknown_anytype(...) is a special case used by the debugger when 19168 // it has no idea what a function's signature is. 19169 // 19170 // We want to build this call essentially under the K&R 19171 // unprototyped rules, but making a FunctionNoProtoType in C++ 19172 // would foul up all sorts of assumptions. However, we cannot 19173 // simply pass all arguments as variadic arguments, nor can we 19174 // portably just call the function under a non-variadic type; see 19175 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19176 // However, it turns out that in practice it is generally safe to 19177 // call a function declared as "A foo(B,C,D);" under the prototype 19178 // "A foo(B,C,D,...);". The only known exception is with the 19179 // Windows ABI, where any variadic function is implicitly cdecl 19180 // regardless of its normal CC. Therefore we change the parameter 19181 // types to match the types of the arguments. 19182 // 19183 // This is a hack, but it is far superior to moving the 19184 // corresponding target-specific code from IR-gen to Sema/AST. 19185 19186 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19187 SmallVector<QualType, 8> ArgTypes; 19188 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19189 ArgTypes.reserve(E->getNumArgs()); 19190 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19191 Expr *Arg = E->getArg(i); 19192 QualType ArgType = Arg->getType(); 19193 if (E->isLValue()) { 19194 ArgType = S.Context.getLValueReferenceType(ArgType); 19195 } else if (E->isXValue()) { 19196 ArgType = S.Context.getRValueReferenceType(ArgType); 19197 } 19198 ArgTypes.push_back(ArgType); 19199 } 19200 ParamTypes = ArgTypes; 19201 } 19202 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19203 Proto->getExtProtoInfo()); 19204 } else { 19205 DestType = S.Context.getFunctionNoProtoType(DestType, 19206 FnType->getExtInfo()); 19207 } 19208 19209 // Rebuild the appropriate pointer-to-function type. 19210 switch (Kind) { 19211 case FK_MemberFunction: 19212 // Nothing to do. 19213 break; 19214 19215 case FK_FunctionPointer: 19216 DestType = S.Context.getPointerType(DestType); 19217 break; 19218 19219 case FK_BlockPointer: 19220 DestType = S.Context.getBlockPointerType(DestType); 19221 break; 19222 } 19223 19224 // Finally, we can recurse. 19225 ExprResult CalleeResult = Visit(CalleeExpr); 19226 if (!CalleeResult.isUsable()) return ExprError(); 19227 E->setCallee(CalleeResult.get()); 19228 19229 // Bind a temporary if necessary. 19230 return S.MaybeBindToTemporary(E); 19231 } 19232 19233 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19234 // Verify that this is a legal result type of a call. 19235 if (DestType->isArrayType() || DestType->isFunctionType()) { 19236 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19237 << DestType->isFunctionType() << DestType; 19238 return ExprError(); 19239 } 19240 19241 // Rewrite the method result type if available. 19242 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19243 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19244 Method->setReturnType(DestType); 19245 } 19246 19247 // Change the type of the message. 19248 E->setType(DestType.getNonReferenceType()); 19249 E->setValueKind(Expr::getValueKindForType(DestType)); 19250 19251 return S.MaybeBindToTemporary(E); 19252 } 19253 19254 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19255 // The only case we should ever see here is a function-to-pointer decay. 19256 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19257 assert(E->getValueKind() == VK_RValue); 19258 assert(E->getObjectKind() == OK_Ordinary); 19259 19260 E->setType(DestType); 19261 19262 // Rebuild the sub-expression as the pointee (function) type. 19263 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19264 19265 ExprResult Result = Visit(E->getSubExpr()); 19266 if (!Result.isUsable()) return ExprError(); 19267 19268 E->setSubExpr(Result.get()); 19269 return E; 19270 } else if (E->getCastKind() == CK_LValueToRValue) { 19271 assert(E->getValueKind() == VK_RValue); 19272 assert(E->getObjectKind() == OK_Ordinary); 19273 19274 assert(isa<BlockPointerType>(E->getType())); 19275 19276 E->setType(DestType); 19277 19278 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19279 DestType = S.Context.getLValueReferenceType(DestType); 19280 19281 ExprResult Result = Visit(E->getSubExpr()); 19282 if (!Result.isUsable()) return ExprError(); 19283 19284 E->setSubExpr(Result.get()); 19285 return E; 19286 } else { 19287 llvm_unreachable("Unhandled cast type!"); 19288 } 19289 } 19290 19291 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19292 ExprValueKind ValueKind = VK_LValue; 19293 QualType Type = DestType; 19294 19295 // We know how to make this work for certain kinds of decls: 19296 19297 // - functions 19298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19299 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19300 DestType = Ptr->getPointeeType(); 19301 ExprResult Result = resolveDecl(E, VD); 19302 if (Result.isInvalid()) return ExprError(); 19303 return S.ImpCastExprToType(Result.get(), Type, 19304 CK_FunctionToPointerDecay, VK_RValue); 19305 } 19306 19307 if (!Type->isFunctionType()) { 19308 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19309 << VD << E->getSourceRange(); 19310 return ExprError(); 19311 } 19312 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19313 // We must match the FunctionDecl's type to the hack introduced in 19314 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19315 // type. See the lengthy commentary in that routine. 19316 QualType FDT = FD->getType(); 19317 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19318 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19319 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19320 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19321 SourceLocation Loc = FD->getLocation(); 19322 FunctionDecl *NewFD = FunctionDecl::Create( 19323 S.Context, FD->getDeclContext(), Loc, Loc, 19324 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19325 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19326 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19327 19328 if (FD->getQualifier()) 19329 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19330 19331 SmallVector<ParmVarDecl*, 16> Params; 19332 for (const auto &AI : FT->param_types()) { 19333 ParmVarDecl *Param = 19334 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19335 Param->setScopeInfo(0, Params.size()); 19336 Params.push_back(Param); 19337 } 19338 NewFD->setParams(Params); 19339 DRE->setDecl(NewFD); 19340 VD = DRE->getDecl(); 19341 } 19342 } 19343 19344 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19345 if (MD->isInstance()) { 19346 ValueKind = VK_RValue; 19347 Type = S.Context.BoundMemberTy; 19348 } 19349 19350 // Function references aren't l-values in C. 19351 if (!S.getLangOpts().CPlusPlus) 19352 ValueKind = VK_RValue; 19353 19354 // - variables 19355 } else if (isa<VarDecl>(VD)) { 19356 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19357 Type = RefTy->getPointeeType(); 19358 } else if (Type->isFunctionType()) { 19359 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19360 << VD << E->getSourceRange(); 19361 return ExprError(); 19362 } 19363 19364 // - nothing else 19365 } else { 19366 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19367 << VD << E->getSourceRange(); 19368 return ExprError(); 19369 } 19370 19371 // Modifying the declaration like this is friendly to IR-gen but 19372 // also really dangerous. 19373 VD->setType(DestType); 19374 E->setType(Type); 19375 E->setValueKind(ValueKind); 19376 return E; 19377 } 19378 19379 /// Check a cast of an unknown-any type. We intentionally only 19380 /// trigger this for C-style casts. 19381 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19382 Expr *CastExpr, CastKind &CastKind, 19383 ExprValueKind &VK, CXXCastPath &Path) { 19384 // The type we're casting to must be either void or complete. 19385 if (!CastType->isVoidType() && 19386 RequireCompleteType(TypeRange.getBegin(), CastType, 19387 diag::err_typecheck_cast_to_incomplete)) 19388 return ExprError(); 19389 19390 // Rewrite the casted expression from scratch. 19391 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19392 if (!result.isUsable()) return ExprError(); 19393 19394 CastExpr = result.get(); 19395 VK = CastExpr->getValueKind(); 19396 CastKind = CK_NoOp; 19397 19398 return CastExpr; 19399 } 19400 19401 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19402 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19403 } 19404 19405 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19406 Expr *arg, QualType ¶mType) { 19407 // If the syntactic form of the argument is not an explicit cast of 19408 // any sort, just do default argument promotion. 19409 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19410 if (!castArg) { 19411 ExprResult result = DefaultArgumentPromotion(arg); 19412 if (result.isInvalid()) return ExprError(); 19413 paramType = result.get()->getType(); 19414 return result; 19415 } 19416 19417 // Otherwise, use the type that was written in the explicit cast. 19418 assert(!arg->hasPlaceholderType()); 19419 paramType = castArg->getTypeAsWritten(); 19420 19421 // Copy-initialize a parameter of that type. 19422 InitializedEntity entity = 19423 InitializedEntity::InitializeParameter(Context, paramType, 19424 /*consumed*/ false); 19425 return PerformCopyInitialization(entity, callLoc, arg); 19426 } 19427 19428 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19429 Expr *orig = E; 19430 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19431 while (true) { 19432 E = E->IgnoreParenImpCasts(); 19433 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19434 E = call->getCallee(); 19435 diagID = diag::err_uncasted_call_of_unknown_any; 19436 } else { 19437 break; 19438 } 19439 } 19440 19441 SourceLocation loc; 19442 NamedDecl *d; 19443 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19444 loc = ref->getLocation(); 19445 d = ref->getDecl(); 19446 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19447 loc = mem->getMemberLoc(); 19448 d = mem->getMemberDecl(); 19449 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19450 diagID = diag::err_uncasted_call_of_unknown_any; 19451 loc = msg->getSelectorStartLoc(); 19452 d = msg->getMethodDecl(); 19453 if (!d) { 19454 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19455 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19456 << orig->getSourceRange(); 19457 return ExprError(); 19458 } 19459 } else { 19460 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19461 << E->getSourceRange(); 19462 return ExprError(); 19463 } 19464 19465 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19466 19467 // Never recoverable. 19468 return ExprError(); 19469 } 19470 19471 /// Check for operands with placeholder types and complain if found. 19472 /// Returns ExprError() if there was an error and no recovery was possible. 19473 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19474 if (!Context.isDependenceAllowed()) { 19475 // C cannot handle TypoExpr nodes on either side of a binop because it 19476 // doesn't handle dependent types properly, so make sure any TypoExprs have 19477 // been dealt with before checking the operands. 19478 ExprResult Result = CorrectDelayedTyposInExpr(E); 19479 if (!Result.isUsable()) return ExprError(); 19480 E = Result.get(); 19481 } 19482 19483 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19484 if (!placeholderType) return E; 19485 19486 switch (placeholderType->getKind()) { 19487 19488 // Overloaded expressions. 19489 case BuiltinType::Overload: { 19490 // Try to resolve a single function template specialization. 19491 // This is obligatory. 19492 ExprResult Result = E; 19493 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19494 return Result; 19495 19496 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19497 // leaves Result unchanged on failure. 19498 Result = E; 19499 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19500 return Result; 19501 19502 // If that failed, try to recover with a call. 19503 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19504 /*complain*/ true); 19505 return Result; 19506 } 19507 19508 // Bound member functions. 19509 case BuiltinType::BoundMember: { 19510 ExprResult result = E; 19511 const Expr *BME = E->IgnoreParens(); 19512 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19513 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19514 if (isa<CXXPseudoDestructorExpr>(BME)) { 19515 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19516 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19517 if (ME->getMemberNameInfo().getName().getNameKind() == 19518 DeclarationName::CXXDestructorName) 19519 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19520 } 19521 tryToRecoverWithCall(result, PD, 19522 /*complain*/ true); 19523 return result; 19524 } 19525 19526 // ARC unbridged casts. 19527 case BuiltinType::ARCUnbridgedCast: { 19528 Expr *realCast = stripARCUnbridgedCast(E); 19529 diagnoseARCUnbridgedCast(realCast); 19530 return realCast; 19531 } 19532 19533 // Expressions of unknown type. 19534 case BuiltinType::UnknownAny: 19535 return diagnoseUnknownAnyExpr(*this, E); 19536 19537 // Pseudo-objects. 19538 case BuiltinType::PseudoObject: 19539 return checkPseudoObjectRValue(E); 19540 19541 case BuiltinType::BuiltinFn: { 19542 // Accept __noop without parens by implicitly converting it to a call expr. 19543 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19544 if (DRE) { 19545 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19546 if (FD->getBuiltinID() == Builtin::BI__noop) { 19547 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19548 CK_BuiltinFnToFnPtr) 19549 .get(); 19550 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19551 VK_RValue, SourceLocation(), 19552 FPOptionsOverride()); 19553 } 19554 } 19555 19556 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19557 return ExprError(); 19558 } 19559 19560 case BuiltinType::IncompleteMatrixIdx: 19561 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19562 ->getRowIdx() 19563 ->getBeginLoc(), 19564 diag::err_matrix_incomplete_index); 19565 return ExprError(); 19566 19567 // Expressions of unknown type. 19568 case BuiltinType::OMPArraySection: 19569 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19570 return ExprError(); 19571 19572 // Expressions of unknown type. 19573 case BuiltinType::OMPArrayShaping: 19574 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19575 19576 case BuiltinType::OMPIterator: 19577 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19578 19579 // Everything else should be impossible. 19580 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19581 case BuiltinType::Id: 19582 #include "clang/Basic/OpenCLImageTypes.def" 19583 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19584 case BuiltinType::Id: 19585 #include "clang/Basic/OpenCLExtensionTypes.def" 19586 #define SVE_TYPE(Name, Id, SingletonId) \ 19587 case BuiltinType::Id: 19588 #include "clang/Basic/AArch64SVEACLETypes.def" 19589 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19590 case BuiltinType::Id: 19591 #include "clang/Basic/PPCTypes.def" 19592 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19593 #include "clang/Basic/RISCVVTypes.def" 19594 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19595 #define PLACEHOLDER_TYPE(Id, SingletonId) 19596 #include "clang/AST/BuiltinTypes.def" 19597 break; 19598 } 19599 19600 llvm_unreachable("invalid placeholder type!"); 19601 } 19602 19603 bool Sema::CheckCaseExpression(Expr *E) { 19604 if (E->isTypeDependent()) 19605 return true; 19606 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19607 return E->getType()->isIntegralOrEnumerationType(); 19608 return false; 19609 } 19610 19611 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19612 ExprResult 19613 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19614 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19615 "Unknown Objective-C Boolean value!"); 19616 QualType BoolT = Context.ObjCBuiltinBoolTy; 19617 if (!Context.getBOOLDecl()) { 19618 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19619 Sema::LookupOrdinaryName); 19620 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19621 NamedDecl *ND = Result.getFoundDecl(); 19622 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19623 Context.setBOOLDecl(TD); 19624 } 19625 } 19626 if (Context.getBOOLDecl()) 19627 BoolT = Context.getBOOLType(); 19628 return new (Context) 19629 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19630 } 19631 19632 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19633 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19634 SourceLocation RParen) { 19635 19636 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19637 19638 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19639 return Spec.getPlatform() == Platform; 19640 }); 19641 19642 VersionTuple Version; 19643 if (Spec != AvailSpecs.end()) 19644 Version = Spec->getVersion(); 19645 19646 // The use of `@available` in the enclosing function should be analyzed to 19647 // warn when it's used inappropriately (i.e. not if(@available)). 19648 if (getCurFunctionOrMethodDecl()) 19649 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19650 else if (getCurBlock() || getCurLambda()) 19651 getCurFunction()->HasPotentialAvailabilityViolations = true; 19652 19653 return new (Context) 19654 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19655 } 19656 19657 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19658 ArrayRef<Expr *> SubExprs, QualType T) { 19659 if (!Context.getLangOpts().RecoveryAST) 19660 return ExprError(); 19661 19662 if (isSFINAEContext()) 19663 return ExprError(); 19664 19665 if (T.isNull() || T->isUndeducedType() || 19666 !Context.getLangOpts().RecoveryASTType) 19667 // We don't know the concrete type, fallback to dependent type. 19668 T = Context.DependentTy; 19669 19670 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19671 } 19672