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 "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 70 // See if this is an aligned allocation/deallocation function that is 71 // unavailable. 72 if (TreatUnavailableAsInvalid && 73 isUnavailableAlignedAllocationFunction(*FD)) 74 return false; 75 } 76 77 // See if this function is unavailable. 78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 80 return false; 81 82 return true; 83 } 84 85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 86 // Warn if this is used but marked unused. 87 if (const auto *A = D->getAttr<UnusedAttr>()) { 88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 89 // should diagnose them. 90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 93 if (DC && !DC->hasAttr<UnusedAttr>()) 94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 95 } 96 } 97 } 98 99 /// Emit a note explaining that this function is deleted. 100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 101 assert(Decl && Decl->isDeleted()); 102 103 if (Decl->isDefaulted()) { 104 // If the method was explicitly defaulted, point at that declaration. 105 if (!Decl->isImplicit()) 106 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 107 108 // Try to diagnose why this special member function was implicitly 109 // deleted. This might fail, if that reason no longer applies. 110 DiagnoseDeletedDefaultedFunction(Decl); 111 return; 112 } 113 114 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 115 if (Ctor && Ctor->isInheritingConstructor()) 116 return NoteDeletedInheritingConstructor(Ctor); 117 118 Diag(Decl->getLocation(), diag::note_availability_specified_here) 119 << Decl << 1; 120 } 121 122 /// Determine whether a FunctionDecl was ever declared with an 123 /// explicit storage class. 124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 125 for (auto I : D->redecls()) { 126 if (I->getStorageClass() != SC_None) 127 return true; 128 } 129 return false; 130 } 131 132 /// Check whether we're in an extern inline function and referring to a 133 /// variable or function with internal linkage (C11 6.7.4p3). 134 /// 135 /// This is only a warning because we used to silently accept this code, but 136 /// in many cases it will not behave correctly. This is not enabled in C++ mode 137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 138 /// and so while there may still be user mistakes, most of the time we can't 139 /// prove that there are errors. 140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 141 const NamedDecl *D, 142 SourceLocation Loc) { 143 // This is disabled under C++; there are too many ways for this to fire in 144 // contexts where the warning is a false positive, or where it is technically 145 // correct but benign. 146 if (S.getLangOpts().CPlusPlus) 147 return; 148 149 // Check if this is an inlined function or method. 150 FunctionDecl *Current = S.getCurFunctionDecl(); 151 if (!Current) 152 return; 153 if (!Current->isInlined()) 154 return; 155 if (!Current->isExternallyVisible()) 156 return; 157 158 // Check if the decl has internal linkage. 159 if (D->getFormalLinkage() != InternalLinkage) 160 return; 161 162 // Downgrade from ExtWarn to Extension if 163 // (1) the supposedly external inline function is in the main file, 164 // and probably won't be included anywhere else. 165 // (2) the thing we're referencing is a pure function. 166 // (3) the thing we're referencing is another inline function. 167 // This last can give us false negatives, but it's better than warning on 168 // wrappers for simple C library functions. 169 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 170 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 171 if (!DowngradeWarning && UsedFn) 172 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 173 174 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 175 : diag::ext_internal_in_extern_inline) 176 << /*IsVar=*/!UsedFn << D; 177 178 S.MaybeSuggestAddingStaticToDecl(Current); 179 180 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 181 << D; 182 } 183 184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 185 const FunctionDecl *First = Cur->getFirstDecl(); 186 187 // Suggest "static" on the function, if possible. 188 if (!hasAnyExplicitStorageClass(First)) { 189 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 190 Diag(DeclBegin, diag::note_convert_inline_to_static) 191 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 192 } 193 } 194 195 /// Determine whether the use of this declaration is valid, and 196 /// emit any corresponding diagnostics. 197 /// 198 /// This routine diagnoses various problems with referencing 199 /// declarations that can occur when using a declaration. For example, 200 /// it might warn if a deprecated or unavailable declaration is being 201 /// used, or produce an error (and return true) if a C++0x deleted 202 /// function is being used. 203 /// 204 /// \returns true if there was an error (this declaration cannot be 205 /// referenced), false otherwise. 206 /// 207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 208 const ObjCInterfaceDecl *UnknownObjCClass, 209 bool ObjCPropertyAccess, 210 bool AvoidPartialAvailabilityChecks, 211 ObjCInterfaceDecl *ClassReceiver) { 212 SourceLocation Loc = Locs.front(); 213 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 214 // If there were any diagnostics suppressed by template argument deduction, 215 // emit them now. 216 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 217 if (Pos != SuppressedDiagnostics.end()) { 218 for (const PartialDiagnosticAt &Suppressed : Pos->second) 219 Diag(Suppressed.first, Suppressed.second); 220 221 // Clear out the list of suppressed diagnostics, so that we don't emit 222 // them again for this specialization. However, we don't obsolete this 223 // entry from the table, because we want to avoid ever emitting these 224 // diagnostics again. 225 Pos->second.clear(); 226 } 227 228 // C++ [basic.start.main]p3: 229 // The function 'main' shall not be used within a program. 230 if (cast<FunctionDecl>(D)->isMain()) 231 Diag(Loc, diag::ext_main_used); 232 233 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 234 } 235 236 // See if this is an auto-typed variable whose initializer we are parsing. 237 if (ParsingInitForAutoVars.count(D)) { 238 if (isa<BindingDecl>(D)) { 239 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 240 << D->getDeclName(); 241 } else { 242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 243 << D->getDeclName() << cast<VarDecl>(D)->getType(); 244 } 245 return true; 246 } 247 248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 249 // See if this is a deleted function. 250 if (FD->isDeleted()) { 251 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 252 if (Ctor && Ctor->isInheritingConstructor()) 253 Diag(Loc, diag::err_deleted_inherited_ctor_use) 254 << Ctor->getParent() 255 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 256 else 257 Diag(Loc, diag::err_deleted_function_use); 258 NoteDeletedFunction(FD); 259 return true; 260 } 261 262 // [expr.prim.id]p4 263 // A program that refers explicitly or implicitly to a function with a 264 // trailing requires-clause whose constraint-expression is not satisfied, 265 // other than to declare it, is ill-formed. [...] 266 // 267 // See if this is a function with constraints that need to be satisfied. 268 // Check this before deducing the return type, as it might instantiate the 269 // definition. 270 if (FD->getTrailingRequiresClause()) { 271 ConstraintSatisfaction Satisfaction; 272 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 273 // A diagnostic will have already been generated (non-constant 274 // constraint expression, for example) 275 return true; 276 if (!Satisfaction.IsSatisfied) { 277 Diag(Loc, 278 diag::err_reference_to_function_with_unsatisfied_constraints) 279 << D; 280 DiagnoseUnsatisfiedConstraint(Satisfaction); 281 return true; 282 } 283 } 284 285 // If the function has a deduced return type, and we can't deduce it, 286 // then we can't use it either. 287 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 288 DeduceReturnType(FD, Loc)) 289 return true; 290 291 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 292 return true; 293 } 294 295 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 296 // Lambdas are only default-constructible or assignable in C++2a onwards. 297 if (MD->getParent()->isLambda() && 298 ((isa<CXXConstructorDecl>(MD) && 299 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 300 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 301 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 302 << !isa<CXXConstructorDecl>(MD); 303 } 304 } 305 306 auto getReferencedObjCProp = [](const NamedDecl *D) -> 307 const ObjCPropertyDecl * { 308 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 309 return MD->findPropertyDecl(); 310 return nullptr; 311 }; 312 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 313 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 314 return true; 315 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 316 return true; 317 } 318 319 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 320 // Only the variables omp_in and omp_out are allowed in the combiner. 321 // Only the variables omp_priv and omp_orig are allowed in the 322 // initializer-clause. 323 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 324 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 325 isa<VarDecl>(D)) { 326 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 327 << getCurFunction()->HasOMPDeclareReductionCombiner; 328 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 329 return true; 330 } 331 332 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 333 // List-items in map clauses on this construct may only refer to the declared 334 // variable var and entities that could be referenced by a procedure defined 335 // at the same location 336 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 337 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 338 isa<VarDecl>(D)) { 339 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 340 << DMD->getVarName().getAsString(); 341 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 342 return true; 343 } 344 345 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 346 AvoidPartialAvailabilityChecks, ClassReceiver); 347 348 DiagnoseUnusedOfDecl(*this, D, Loc); 349 350 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 351 352 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 353 !isUnevaluatedContext()) { 354 // C++ [expr.prim.req.nested] p3 355 // A local parameter shall only appear as an unevaluated operand 356 // (Clause 8) within the constraint-expression. 357 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 358 << D; 359 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 360 return true; 361 } 362 363 return false; 364 } 365 366 /// DiagnoseSentinelCalls - This routine checks whether a call or 367 /// message-send is to a declaration with the sentinel attribute, and 368 /// if so, it checks that the requirements of the sentinel are 369 /// satisfied. 370 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 371 ArrayRef<Expr *> Args) { 372 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 373 if (!attr) 374 return; 375 376 // The number of formal parameters of the declaration. 377 unsigned numFormalParams; 378 379 // The kind of declaration. This is also an index into a %select in 380 // the diagnostic. 381 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 382 383 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 384 numFormalParams = MD->param_size(); 385 calleeType = CT_Method; 386 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 387 numFormalParams = FD->param_size(); 388 calleeType = CT_Function; 389 } else if (isa<VarDecl>(D)) { 390 QualType type = cast<ValueDecl>(D)->getType(); 391 const FunctionType *fn = nullptr; 392 if (const PointerType *ptr = type->getAs<PointerType>()) { 393 fn = ptr->getPointeeType()->getAs<FunctionType>(); 394 if (!fn) return; 395 calleeType = CT_Function; 396 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 397 fn = ptr->getPointeeType()->castAs<FunctionType>(); 398 calleeType = CT_Block; 399 } else { 400 return; 401 } 402 403 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 404 numFormalParams = proto->getNumParams(); 405 } else { 406 numFormalParams = 0; 407 } 408 } else { 409 return; 410 } 411 412 // "nullPos" is the number of formal parameters at the end which 413 // effectively count as part of the variadic arguments. This is 414 // useful if you would prefer to not have *any* formal parameters, 415 // but the language forces you to have at least one. 416 unsigned nullPos = attr->getNullPos(); 417 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 418 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 419 420 // The number of arguments which should follow the sentinel. 421 unsigned numArgsAfterSentinel = attr->getSentinel(); 422 423 // If there aren't enough arguments for all the formal parameters, 424 // the sentinel, and the args after the sentinel, complain. 425 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 426 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 427 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 428 return; 429 } 430 431 // Otherwise, find the sentinel expression. 432 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 433 if (!sentinelExpr) return; 434 if (sentinelExpr->isValueDependent()) return; 435 if (Context.isSentinelNullExpr(sentinelExpr)) return; 436 437 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 438 // or 'NULL' if those are actually defined in the context. Only use 439 // 'nil' for ObjC methods, where it's much more likely that the 440 // variadic arguments form a list of object pointers. 441 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 442 std::string NullValue; 443 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 444 NullValue = "nil"; 445 else if (getLangOpts().CPlusPlus11) 446 NullValue = "nullptr"; 447 else if (PP.isMacroDefined("NULL")) 448 NullValue = "NULL"; 449 else 450 NullValue = "(void*) 0"; 451 452 if (MissingNilLoc.isInvalid()) 453 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 454 else 455 Diag(MissingNilLoc, diag::warn_missing_sentinel) 456 << int(calleeType) 457 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 458 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 459 } 460 461 SourceRange Sema::getExprRange(Expr *E) const { 462 return E ? E->getSourceRange() : SourceRange(); 463 } 464 465 //===----------------------------------------------------------------------===// 466 // Standard Promotions and Conversions 467 //===----------------------------------------------------------------------===// 468 469 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 470 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 471 // Handle any placeholder expressions which made it here. 472 if (E->getType()->isPlaceholderType()) { 473 ExprResult result = CheckPlaceholderExpr(E); 474 if (result.isInvalid()) return ExprError(); 475 E = result.get(); 476 } 477 478 QualType Ty = E->getType(); 479 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 480 481 if (Ty->isFunctionType()) { 482 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 483 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 484 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 485 return ExprError(); 486 487 E = ImpCastExprToType(E, Context.getPointerType(Ty), 488 CK_FunctionToPointerDecay).get(); 489 } else if (Ty->isArrayType()) { 490 // In C90 mode, arrays only promote to pointers if the array expression is 491 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 492 // type 'array of type' is converted to an expression that has type 'pointer 493 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 494 // that has type 'array of type' ...". The relevant change is "an lvalue" 495 // (C90) to "an expression" (C99). 496 // 497 // C++ 4.2p1: 498 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 499 // T" can be converted to an rvalue of type "pointer to T". 500 // 501 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 502 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 503 CK_ArrayToPointerDecay).get(); 504 } 505 return E; 506 } 507 508 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 509 // Check to see if we are dereferencing a null pointer. If so, 510 // and if not volatile-qualified, this is undefined behavior that the 511 // optimizer will delete, so warn about it. People sometimes try to use this 512 // to get a deterministic trap and are surprised by clang's behavior. This 513 // only handles the pattern "*null", which is a very syntactic check. 514 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 515 if (UO && UO->getOpcode() == UO_Deref && 516 UO->getSubExpr()->getType()->isPointerType()) { 517 const LangAS AS = 518 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 519 if ((!isTargetAddressSpace(AS) || 520 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 521 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 522 S.Context, Expr::NPC_ValueDependentIsNotNull) && 523 !UO->getType().isVolatileQualified()) { 524 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 525 S.PDiag(diag::warn_indirection_through_null) 526 << UO->getSubExpr()->getSourceRange()); 527 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 528 S.PDiag(diag::note_indirection_through_null)); 529 } 530 } 531 } 532 533 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 534 SourceLocation AssignLoc, 535 const Expr* RHS) { 536 const ObjCIvarDecl *IV = OIRE->getDecl(); 537 if (!IV) 538 return; 539 540 DeclarationName MemberName = IV->getDeclName(); 541 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 542 if (!Member || !Member->isStr("isa")) 543 return; 544 545 const Expr *Base = OIRE->getBase(); 546 QualType BaseType = Base->getType(); 547 if (OIRE->isArrow()) 548 BaseType = BaseType->getPointeeType(); 549 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 550 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 551 ObjCInterfaceDecl *ClassDeclared = nullptr; 552 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 553 if (!ClassDeclared->getSuperClass() 554 && (*ClassDeclared->ivar_begin()) == IV) { 555 if (RHS) { 556 NamedDecl *ObjectSetClass = 557 S.LookupSingleName(S.TUScope, 558 &S.Context.Idents.get("object_setClass"), 559 SourceLocation(), S.LookupOrdinaryName); 560 if (ObjectSetClass) { 561 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 562 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 563 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 564 "object_setClass(") 565 << FixItHint::CreateReplacement( 566 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 567 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 568 } 569 else 570 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 571 } else { 572 NamedDecl *ObjectGetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_getClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectGetClass) 577 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 578 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 579 "object_getClass(") 580 << FixItHint::CreateReplacement( 581 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 582 else 583 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 584 } 585 S.Diag(IV->getLocation(), diag::note_ivar_decl); 586 } 587 } 588 } 589 590 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 591 // Handle any placeholder expressions which made it here. 592 if (E->getType()->isPlaceholderType()) { 593 ExprResult result = CheckPlaceholderExpr(E); 594 if (result.isInvalid()) return ExprError(); 595 E = result.get(); 596 } 597 598 // C++ [conv.lval]p1: 599 // A glvalue of a non-function, non-array type T can be 600 // converted to a prvalue. 601 if (!E->isGLValue()) return E; 602 603 QualType T = E->getType(); 604 assert(!T.isNull() && "r-value conversion on typeless expression?"); 605 606 // We don't want to throw lvalue-to-rvalue casts on top of 607 // expressions of certain types in C++. 608 if (getLangOpts().CPlusPlus && 609 (E->getType() == Context.OverloadTy || 610 T->isDependentType() || 611 T->isRecordType())) 612 return E; 613 614 // The C standard is actually really unclear on this point, and 615 // DR106 tells us what the result should be but not why. It's 616 // generally best to say that void types just doesn't undergo 617 // lvalue-to-rvalue at all. Note that expressions of unqualified 618 // 'void' type are never l-values, but qualified void can be. 619 if (T->isVoidType()) 620 return E; 621 622 // OpenCL usually rejects direct accesses to values of 'half' type. 623 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 624 T->isHalfType()) { 625 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 626 << 0 << T; 627 return ExprError(); 628 } 629 630 CheckForNullPointerDereference(*this, E); 631 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 632 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 633 &Context.Idents.get("object_getClass"), 634 SourceLocation(), LookupOrdinaryName); 635 if (ObjectGetClass) 636 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 637 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 638 << FixItHint::CreateReplacement( 639 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 640 else 641 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 642 } 643 else if (const ObjCIvarRefExpr *OIRE = 644 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 645 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 646 647 // C++ [conv.lval]p1: 648 // [...] If T is a non-class type, the type of the prvalue is the 649 // cv-unqualified version of T. Otherwise, the type of the 650 // rvalue is T. 651 // 652 // C99 6.3.2.1p2: 653 // If the lvalue has qualified type, the value has the unqualified 654 // version of the type of the lvalue; otherwise, the value has the 655 // type of the lvalue. 656 if (T.hasQualifiers()) 657 T = T.getUnqualifiedType(); 658 659 // Under the MS ABI, lock down the inheritance model now. 660 if (T->isMemberPointerType() && 661 Context.getTargetInfo().getCXXABI().isMicrosoft()) 662 (void)isCompleteType(E->getExprLoc(), T); 663 664 ExprResult Res = CheckLValueToRValueConversionOperand(E); 665 if (Res.isInvalid()) 666 return Res; 667 E = Res.get(); 668 669 // Loading a __weak object implicitly retains the value, so we need a cleanup to 670 // balance that. 671 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 672 Cleanup.setExprNeedsCleanups(true); 673 674 // C++ [conv.lval]p3: 675 // If T is cv std::nullptr_t, the result is a null pointer constant. 676 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 677 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 678 679 // C11 6.3.2.1p2: 680 // ... if the lvalue has atomic type, the value has the non-atomic version 681 // of the type of the lvalue ... 682 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 683 T = Atomic->getValueType().getUnqualifiedType(); 684 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 685 nullptr, VK_RValue); 686 } 687 688 return Res; 689 } 690 691 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 692 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 693 if (Res.isInvalid()) 694 return ExprError(); 695 Res = DefaultLvalueConversion(Res.get()); 696 if (Res.isInvalid()) 697 return ExprError(); 698 return Res; 699 } 700 701 /// CallExprUnaryConversions - a special case of an unary conversion 702 /// performed on a function designator of a call expression. 703 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 704 QualType Ty = E->getType(); 705 ExprResult Res = E; 706 // Only do implicit cast for a function type, but not for a pointer 707 // to function type. 708 if (Ty->isFunctionType()) { 709 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 710 CK_FunctionToPointerDecay).get(); 711 if (Res.isInvalid()) 712 return ExprError(); 713 } 714 Res = DefaultLvalueConversion(Res.get()); 715 if (Res.isInvalid()) 716 return ExprError(); 717 return Res.get(); 718 } 719 720 /// UsualUnaryConversions - Performs various conversions that are common to most 721 /// operators (C99 6.3). The conversions of array and function types are 722 /// sometimes suppressed. For example, the array->pointer conversion doesn't 723 /// apply if the array is an argument to the sizeof or address (&) operators. 724 /// In these instances, this routine should *not* be called. 725 ExprResult Sema::UsualUnaryConversions(Expr *E) { 726 // First, convert to an r-value. 727 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 728 if (Res.isInvalid()) 729 return ExprError(); 730 E = Res.get(); 731 732 QualType Ty = E->getType(); 733 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 734 735 // Half FP have to be promoted to float unless it is natively supported 736 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 737 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 738 739 // Try to perform integral promotions if the object has a theoretically 740 // promotable type. 741 if (Ty->isIntegralOrUnscopedEnumerationType()) { 742 // C99 6.3.1.1p2: 743 // 744 // The following may be used in an expression wherever an int or 745 // unsigned int may be used: 746 // - an object or expression with an integer type whose integer 747 // conversion rank is less than or equal to the rank of int 748 // and unsigned int. 749 // - A bit-field of type _Bool, int, signed int, or unsigned int. 750 // 751 // If an int can represent all values of the original type, the 752 // value is converted to an int; otherwise, it is converted to an 753 // unsigned int. These are called the integer promotions. All 754 // other types are unchanged by the integer promotions. 755 756 QualType PTy = Context.isPromotableBitField(E); 757 if (!PTy.isNull()) { 758 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 759 return E; 760 } 761 if (Ty->isPromotableIntegerType()) { 762 QualType PT = Context.getPromotedIntegerType(Ty); 763 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 764 return E; 765 } 766 } 767 return E; 768 } 769 770 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 771 /// do not have a prototype. Arguments that have type float or __fp16 772 /// are promoted to double. All other argument types are converted by 773 /// UsualUnaryConversions(). 774 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 775 QualType Ty = E->getType(); 776 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 777 778 ExprResult Res = UsualUnaryConversions(E); 779 if (Res.isInvalid()) 780 return ExprError(); 781 E = Res.get(); 782 783 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 784 // promote to double. 785 // Note that default argument promotion applies only to float (and 786 // half/fp16); it does not apply to _Float16. 787 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 788 if (BTy && (BTy->getKind() == BuiltinType::Half || 789 BTy->getKind() == BuiltinType::Float)) { 790 if (getLangOpts().OpenCL && 791 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 792 if (BTy->getKind() == BuiltinType::Half) { 793 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 794 } 795 } else { 796 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 797 } 798 } 799 800 // C++ performs lvalue-to-rvalue conversion as a default argument 801 // promotion, even on class types, but note: 802 // C++11 [conv.lval]p2: 803 // When an lvalue-to-rvalue conversion occurs in an unevaluated 804 // operand or a subexpression thereof the value contained in the 805 // referenced object is not accessed. Otherwise, if the glvalue 806 // has a class type, the conversion copy-initializes a temporary 807 // of type T from the glvalue and the result of the conversion 808 // is a prvalue for the temporary. 809 // FIXME: add some way to gate this entire thing for correctness in 810 // potentially potentially evaluated contexts. 811 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 812 ExprResult Temp = PerformCopyInitialization( 813 InitializedEntity::InitializeTemporary(E->getType()), 814 E->getExprLoc(), E); 815 if (Temp.isInvalid()) 816 return ExprError(); 817 E = Temp.get(); 818 } 819 820 return E; 821 } 822 823 /// Determine the degree of POD-ness for an expression. 824 /// Incomplete types are considered POD, since this check can be performed 825 /// when we're in an unevaluated context. 826 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 827 if (Ty->isIncompleteType()) { 828 // C++11 [expr.call]p7: 829 // After these conversions, if the argument does not have arithmetic, 830 // enumeration, pointer, pointer to member, or class type, the program 831 // is ill-formed. 832 // 833 // Since we've already performed array-to-pointer and function-to-pointer 834 // decay, the only such type in C++ is cv void. This also handles 835 // initializer lists as variadic arguments. 836 if (Ty->isVoidType()) 837 return VAK_Invalid; 838 839 if (Ty->isObjCObjectType()) 840 return VAK_Invalid; 841 return VAK_Valid; 842 } 843 844 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 845 return VAK_Invalid; 846 847 if (Ty.isCXX98PODType(Context)) 848 return VAK_Valid; 849 850 // C++11 [expr.call]p7: 851 // Passing a potentially-evaluated argument of class type (Clause 9) 852 // having a non-trivial copy constructor, a non-trivial move constructor, 853 // or a non-trivial destructor, with no corresponding parameter, 854 // is conditionally-supported with implementation-defined semantics. 855 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 856 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 857 if (!Record->hasNonTrivialCopyConstructor() && 858 !Record->hasNonTrivialMoveConstructor() && 859 !Record->hasNonTrivialDestructor()) 860 return VAK_ValidInCXX11; 861 862 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 863 return VAK_Valid; 864 865 if (Ty->isObjCObjectType()) 866 return VAK_Invalid; 867 868 if (getLangOpts().MSVCCompat) 869 return VAK_MSVCUndefined; 870 871 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 872 // permitted to reject them. We should consider doing so. 873 return VAK_Undefined; 874 } 875 876 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 877 // Don't allow one to pass an Objective-C interface to a vararg. 878 const QualType &Ty = E->getType(); 879 VarArgKind VAK = isValidVarArgType(Ty); 880 881 // Complain about passing non-POD types through varargs. 882 switch (VAK) { 883 case VAK_ValidInCXX11: 884 DiagRuntimeBehavior( 885 E->getBeginLoc(), nullptr, 886 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 887 LLVM_FALLTHROUGH; 888 case VAK_Valid: 889 if (Ty->isRecordType()) { 890 // This is unlikely to be what the user intended. If the class has a 891 // 'c_str' member function, the user probably meant to call that. 892 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 893 PDiag(diag::warn_pass_class_arg_to_vararg) 894 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 895 } 896 break; 897 898 case VAK_Undefined: 899 case VAK_MSVCUndefined: 900 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 901 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 902 << getLangOpts().CPlusPlus11 << Ty << CT); 903 break; 904 905 case VAK_Invalid: 906 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 907 Diag(E->getBeginLoc(), 908 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 909 << Ty << CT; 910 else if (Ty->isObjCObjectType()) 911 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 912 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 913 << Ty << CT); 914 else 915 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 916 << isa<InitListExpr>(E) << Ty << CT; 917 break; 918 } 919 } 920 921 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 922 /// will create a trap if the resulting type is not a POD type. 923 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 924 FunctionDecl *FDecl) { 925 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 926 // Strip the unbridged-cast placeholder expression off, if applicable. 927 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 928 (CT == VariadicMethod || 929 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 930 E = stripARCUnbridgedCast(E); 931 932 // Otherwise, do normal placeholder checking. 933 } else { 934 ExprResult ExprRes = CheckPlaceholderExpr(E); 935 if (ExprRes.isInvalid()) 936 return ExprError(); 937 E = ExprRes.get(); 938 } 939 } 940 941 ExprResult ExprRes = DefaultArgumentPromotion(E); 942 if (ExprRes.isInvalid()) 943 return ExprError(); 944 E = ExprRes.get(); 945 946 // Diagnostics regarding non-POD argument types are 947 // emitted along with format string checking in Sema::CheckFunctionCall(). 948 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 949 // Turn this into a trap. 950 CXXScopeSpec SS; 951 SourceLocation TemplateKWLoc; 952 UnqualifiedId Name; 953 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 954 E->getBeginLoc()); 955 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 956 /*HasTrailingLParen=*/true, 957 /*IsAddressOfOperand=*/false); 958 if (TrapFn.isInvalid()) 959 return ExprError(); 960 961 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 962 None, E->getEndLoc()); 963 if (Call.isInvalid()) 964 return ExprError(); 965 966 ExprResult Comma = 967 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 968 if (Comma.isInvalid()) 969 return ExprError(); 970 return Comma.get(); 971 } 972 973 if (!getLangOpts().CPlusPlus && 974 RequireCompleteType(E->getExprLoc(), E->getType(), 975 diag::err_call_incomplete_argument)) 976 return ExprError(); 977 978 return E; 979 } 980 981 /// Converts an integer to complex float type. Helper function of 982 /// UsualArithmeticConversions() 983 /// 984 /// \return false if the integer expression is an integer type and is 985 /// successfully converted to the complex type. 986 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 987 ExprResult &ComplexExpr, 988 QualType IntTy, 989 QualType ComplexTy, 990 bool SkipCast) { 991 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 992 if (SkipCast) return false; 993 if (IntTy->isIntegerType()) { 994 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 995 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 996 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 997 CK_FloatingRealToComplex); 998 } else { 999 assert(IntTy->isComplexIntegerType()); 1000 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1001 CK_IntegralComplexToFloatingComplex); 1002 } 1003 return false; 1004 } 1005 1006 /// Handle arithmetic conversion with complex types. Helper function of 1007 /// UsualArithmeticConversions() 1008 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1009 ExprResult &RHS, QualType LHSType, 1010 QualType RHSType, 1011 bool IsCompAssign) { 1012 // if we have an integer operand, the result is the complex type. 1013 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1014 /*skipCast*/false)) 1015 return LHSType; 1016 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1017 /*skipCast*/IsCompAssign)) 1018 return RHSType; 1019 1020 // This handles complex/complex, complex/float, or float/complex. 1021 // When both operands are complex, the shorter operand is converted to the 1022 // type of the longer, and that is the type of the result. This corresponds 1023 // to what is done when combining two real floating-point operands. 1024 // The fun begins when size promotion occur across type domains. 1025 // From H&S 6.3.4: When one operand is complex and the other is a real 1026 // floating-point type, the less precise type is converted, within it's 1027 // real or complex domain, to the precision of the other type. For example, 1028 // when combining a "long double" with a "double _Complex", the 1029 // "double _Complex" is promoted to "long double _Complex". 1030 1031 // Compute the rank of the two types, regardless of whether they are complex. 1032 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1033 1034 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1035 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1036 QualType LHSElementType = 1037 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1038 QualType RHSElementType = 1039 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1040 1041 QualType ResultType = S.Context.getComplexType(LHSElementType); 1042 if (Order < 0) { 1043 // Promote the precision of the LHS if not an assignment. 1044 ResultType = S.Context.getComplexType(RHSElementType); 1045 if (!IsCompAssign) { 1046 if (LHSComplexType) 1047 LHS = 1048 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1049 else 1050 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1051 } 1052 } else if (Order > 0) { 1053 // Promote the precision of the RHS. 1054 if (RHSComplexType) 1055 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1056 else 1057 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1058 } 1059 return ResultType; 1060 } 1061 1062 /// Handle arithmetic conversion from integer to float. Helper function 1063 /// of UsualArithmeticConversions() 1064 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1065 ExprResult &IntExpr, 1066 QualType FloatTy, QualType IntTy, 1067 bool ConvertFloat, bool ConvertInt) { 1068 if (IntTy->isIntegerType()) { 1069 if (ConvertInt) 1070 // Convert intExpr to the lhs floating point type. 1071 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1072 CK_IntegralToFloating); 1073 return FloatTy; 1074 } 1075 1076 // Convert both sides to the appropriate complex float. 1077 assert(IntTy->isComplexIntegerType()); 1078 QualType result = S.Context.getComplexType(FloatTy); 1079 1080 // _Complex int -> _Complex float 1081 if (ConvertInt) 1082 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1083 CK_IntegralComplexToFloatingComplex); 1084 1085 // float -> _Complex float 1086 if (ConvertFloat) 1087 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1088 CK_FloatingRealToComplex); 1089 1090 return result; 1091 } 1092 1093 /// Handle arithmethic conversion with floating point types. Helper 1094 /// function of UsualArithmeticConversions() 1095 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1096 ExprResult &RHS, QualType LHSType, 1097 QualType RHSType, bool IsCompAssign) { 1098 bool LHSFloat = LHSType->isRealFloatingType(); 1099 bool RHSFloat = RHSType->isRealFloatingType(); 1100 1101 // If we have two real floating types, convert the smaller operand 1102 // to the bigger result. 1103 if (LHSFloat && RHSFloat) { 1104 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1105 if (order > 0) { 1106 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1107 return LHSType; 1108 } 1109 1110 assert(order < 0 && "illegal float comparison"); 1111 if (!IsCompAssign) 1112 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1113 return RHSType; 1114 } 1115 1116 if (LHSFloat) { 1117 // Half FP has to be promoted to float unless it is natively supported 1118 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1119 LHSType = S.Context.FloatTy; 1120 1121 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1122 /*ConvertFloat=*/!IsCompAssign, 1123 /*ConvertInt=*/ true); 1124 } 1125 assert(RHSFloat); 1126 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1127 /*convertInt=*/ true, 1128 /*convertFloat=*/!IsCompAssign); 1129 } 1130 1131 /// Diagnose attempts to convert between __float128 and long double if 1132 /// there is no support for such conversion. Helper function of 1133 /// UsualArithmeticConversions(). 1134 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1135 QualType RHSType) { 1136 /* No issue converting if at least one of the types is not a floating point 1137 type or the two types have the same rank. 1138 */ 1139 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1140 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1141 return false; 1142 1143 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1144 "The remaining types must be floating point types."); 1145 1146 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1147 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1148 1149 QualType LHSElemType = LHSComplex ? 1150 LHSComplex->getElementType() : LHSType; 1151 QualType RHSElemType = RHSComplex ? 1152 RHSComplex->getElementType() : RHSType; 1153 1154 // No issue if the two types have the same representation 1155 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1156 &S.Context.getFloatTypeSemantics(RHSElemType)) 1157 return false; 1158 1159 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1160 RHSElemType == S.Context.LongDoubleTy); 1161 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1162 RHSElemType == S.Context.Float128Ty); 1163 1164 // We've handled the situation where __float128 and long double have the same 1165 // representation. We allow all conversions for all possible long double types 1166 // except PPC's double double. 1167 return Float128AndLongDouble && 1168 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1169 &llvm::APFloat::PPCDoubleDouble()); 1170 } 1171 1172 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1173 1174 namespace { 1175 /// These helper callbacks are placed in an anonymous namespace to 1176 /// permit their use as function template parameters. 1177 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1178 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1179 } 1180 1181 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1182 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1183 CK_IntegralComplexCast); 1184 } 1185 } 1186 1187 /// Handle integer arithmetic conversions. Helper function of 1188 /// UsualArithmeticConversions() 1189 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1190 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1191 ExprResult &RHS, QualType LHSType, 1192 QualType RHSType, bool IsCompAssign) { 1193 // The rules for this case are in C99 6.3.1.8 1194 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1195 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1196 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1197 if (LHSSigned == RHSSigned) { 1198 // Same signedness; use the higher-ranked type 1199 if (order >= 0) { 1200 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1201 return LHSType; 1202 } else if (!IsCompAssign) 1203 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1204 return RHSType; 1205 } else if (order != (LHSSigned ? 1 : -1)) { 1206 // The unsigned type has greater than or equal rank to the 1207 // signed type, so use the unsigned type 1208 if (RHSSigned) { 1209 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1210 return LHSType; 1211 } else if (!IsCompAssign) 1212 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1213 return RHSType; 1214 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1215 // The two types are different widths; if we are here, that 1216 // means the signed type is larger than the unsigned type, so 1217 // use the signed type. 1218 if (LHSSigned) { 1219 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1220 return LHSType; 1221 } else if (!IsCompAssign) 1222 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1223 return RHSType; 1224 } else { 1225 // The signed type is higher-ranked than the unsigned type, 1226 // but isn't actually any bigger (like unsigned int and long 1227 // on most 32-bit systems). Use the unsigned type corresponding 1228 // to the signed type. 1229 QualType result = 1230 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1231 RHS = (*doRHSCast)(S, RHS.get(), result); 1232 if (!IsCompAssign) 1233 LHS = (*doLHSCast)(S, LHS.get(), result); 1234 return result; 1235 } 1236 } 1237 1238 /// Handle conversions with GCC complex int extension. Helper function 1239 /// of UsualArithmeticConversions() 1240 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1241 ExprResult &RHS, QualType LHSType, 1242 QualType RHSType, 1243 bool IsCompAssign) { 1244 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1245 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1246 1247 if (LHSComplexInt && RHSComplexInt) { 1248 QualType LHSEltType = LHSComplexInt->getElementType(); 1249 QualType RHSEltType = RHSComplexInt->getElementType(); 1250 QualType ScalarType = 1251 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1252 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1253 1254 return S.Context.getComplexType(ScalarType); 1255 } 1256 1257 if (LHSComplexInt) { 1258 QualType LHSEltType = LHSComplexInt->getElementType(); 1259 QualType ScalarType = 1260 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1261 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1262 QualType ComplexType = S.Context.getComplexType(ScalarType); 1263 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1264 CK_IntegralRealToComplex); 1265 1266 return ComplexType; 1267 } 1268 1269 assert(RHSComplexInt); 1270 1271 QualType RHSEltType = RHSComplexInt->getElementType(); 1272 QualType ScalarType = 1273 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1274 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1275 QualType ComplexType = S.Context.getComplexType(ScalarType); 1276 1277 if (!IsCompAssign) 1278 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1279 CK_IntegralRealToComplex); 1280 return ComplexType; 1281 } 1282 1283 /// Return the rank of a given fixed point or integer type. The value itself 1284 /// doesn't matter, but the values must be increasing with proper increasing 1285 /// rank as described in N1169 4.1.1. 1286 static unsigned GetFixedPointRank(QualType Ty) { 1287 const auto *BTy = Ty->getAs<BuiltinType>(); 1288 assert(BTy && "Expected a builtin type."); 1289 1290 switch (BTy->getKind()) { 1291 case BuiltinType::ShortFract: 1292 case BuiltinType::UShortFract: 1293 case BuiltinType::SatShortFract: 1294 case BuiltinType::SatUShortFract: 1295 return 1; 1296 case BuiltinType::Fract: 1297 case BuiltinType::UFract: 1298 case BuiltinType::SatFract: 1299 case BuiltinType::SatUFract: 1300 return 2; 1301 case BuiltinType::LongFract: 1302 case BuiltinType::ULongFract: 1303 case BuiltinType::SatLongFract: 1304 case BuiltinType::SatULongFract: 1305 return 3; 1306 case BuiltinType::ShortAccum: 1307 case BuiltinType::UShortAccum: 1308 case BuiltinType::SatShortAccum: 1309 case BuiltinType::SatUShortAccum: 1310 return 4; 1311 case BuiltinType::Accum: 1312 case BuiltinType::UAccum: 1313 case BuiltinType::SatAccum: 1314 case BuiltinType::SatUAccum: 1315 return 5; 1316 case BuiltinType::LongAccum: 1317 case BuiltinType::ULongAccum: 1318 case BuiltinType::SatLongAccum: 1319 case BuiltinType::SatULongAccum: 1320 return 6; 1321 default: 1322 if (BTy->isInteger()) 1323 return 0; 1324 llvm_unreachable("Unexpected fixed point or integer type"); 1325 } 1326 } 1327 1328 /// handleFixedPointConversion - Fixed point operations between fixed 1329 /// point types and integers or other fixed point types do not fall under 1330 /// usual arithmetic conversion since these conversions could result in loss 1331 /// of precsision (N1169 4.1.4). These operations should be calculated with 1332 /// the full precision of their result type (N1169 4.1.6.2.1). 1333 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1334 QualType RHSTy) { 1335 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1336 "Expected at least one of the operands to be a fixed point type"); 1337 assert((LHSTy->isFixedPointOrIntegerType() || 1338 RHSTy->isFixedPointOrIntegerType()) && 1339 "Special fixed point arithmetic operation conversions are only " 1340 "applied to ints or other fixed point types"); 1341 1342 // If one operand has signed fixed-point type and the other operand has 1343 // unsigned fixed-point type, then the unsigned fixed-point operand is 1344 // converted to its corresponding signed fixed-point type and the resulting 1345 // type is the type of the converted operand. 1346 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1347 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1348 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1349 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1350 1351 // The result type is the type with the highest rank, whereby a fixed-point 1352 // conversion rank is always greater than an integer conversion rank; if the 1353 // type of either of the operands is a saturating fixedpoint type, the result 1354 // type shall be the saturating fixed-point type corresponding to the type 1355 // with the highest rank; the resulting value is converted (taking into 1356 // account rounding and overflow) to the precision of the resulting type. 1357 // Same ranks between signed and unsigned types are resolved earlier, so both 1358 // types are either signed or both unsigned at this point. 1359 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1360 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1361 1362 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1363 1364 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1365 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1366 1367 return ResultTy; 1368 } 1369 1370 /// Check that the usual arithmetic conversions can be performed on this pair of 1371 /// expressions that might be of enumeration type. 1372 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1373 SourceLocation Loc, 1374 Sema::ArithConvKind ACK) { 1375 // C++2a [expr.arith.conv]p1: 1376 // If one operand is of enumeration type and the other operand is of a 1377 // different enumeration type or a floating-point type, this behavior is 1378 // deprecated ([depr.arith.conv.enum]). 1379 // 1380 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1381 // Eventually we will presumably reject these cases (in C++23 onwards?). 1382 QualType L = LHS->getType(), R = RHS->getType(); 1383 bool LEnum = L->isUnscopedEnumerationType(), 1384 REnum = R->isUnscopedEnumerationType(); 1385 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1386 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1387 (REnum && L->isFloatingType())) { 1388 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1389 ? diag::warn_arith_conv_enum_float_cxx2a 1390 : diag::warn_arith_conv_enum_float) 1391 << LHS->getSourceRange() << RHS->getSourceRange() 1392 << (int)ACK << LEnum << L << R; 1393 } else if (!IsCompAssign && LEnum && REnum && 1394 !S.Context.hasSameUnqualifiedType(L, R)) { 1395 unsigned DiagID; 1396 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1397 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1398 // If either enumeration type is unnamed, it's less likely that the 1399 // user cares about this, but this situation is still deprecated in 1400 // C++2a. Use a different warning group. 1401 DiagID = S.getLangOpts().CPlusPlus2a 1402 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1403 : diag::warn_arith_conv_mixed_anon_enum_types; 1404 } else if (ACK == Sema::ACK_Conditional) { 1405 // Conditional expressions are separated out because they have 1406 // historically had a different warning flag. 1407 DiagID = S.getLangOpts().CPlusPlus2a 1408 ? diag::warn_conditional_mixed_enum_types_cxx2a 1409 : diag::warn_conditional_mixed_enum_types; 1410 } else if (ACK == Sema::ACK_Comparison) { 1411 // Comparison expressions are separated out because they have 1412 // historically had a different warning flag. 1413 DiagID = S.getLangOpts().CPlusPlus2a 1414 ? diag::warn_comparison_mixed_enum_types_cxx2a 1415 : diag::warn_comparison_mixed_enum_types; 1416 } else { 1417 DiagID = S.getLangOpts().CPlusPlus2a 1418 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1419 : diag::warn_arith_conv_mixed_enum_types; 1420 } 1421 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1422 << (int)ACK << L << R; 1423 } 1424 } 1425 1426 /// UsualArithmeticConversions - Performs various conversions that are common to 1427 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1428 /// routine returns the first non-arithmetic type found. The client is 1429 /// responsible for emitting appropriate error diagnostics. 1430 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1431 SourceLocation Loc, 1432 ArithConvKind ACK) { 1433 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1434 1435 if (ACK != ACK_CompAssign) { 1436 LHS = UsualUnaryConversions(LHS.get()); 1437 if (LHS.isInvalid()) 1438 return QualType(); 1439 } 1440 1441 RHS = UsualUnaryConversions(RHS.get()); 1442 if (RHS.isInvalid()) 1443 return QualType(); 1444 1445 // For conversion purposes, we ignore any qualifiers. 1446 // For example, "const float" and "float" are equivalent. 1447 QualType LHSType = 1448 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1449 QualType RHSType = 1450 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1451 1452 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1453 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1454 LHSType = AtomicLHS->getValueType(); 1455 1456 // If both types are identical, no conversion is needed. 1457 if (LHSType == RHSType) 1458 return LHSType; 1459 1460 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1461 // The caller can deal with this (e.g. pointer + int). 1462 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1463 return QualType(); 1464 1465 // Apply unary and bitfield promotions to the LHS's type. 1466 QualType LHSUnpromotedType = LHSType; 1467 if (LHSType->isPromotableIntegerType()) 1468 LHSType = Context.getPromotedIntegerType(LHSType); 1469 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1470 if (!LHSBitfieldPromoteTy.isNull()) 1471 LHSType = LHSBitfieldPromoteTy; 1472 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1473 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1474 1475 // If both types are identical, no conversion is needed. 1476 if (LHSType == RHSType) 1477 return LHSType; 1478 1479 // At this point, we have two different arithmetic types. 1480 1481 // Diagnose attempts to convert between __float128 and long double where 1482 // such conversions currently can't be handled. 1483 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1484 return QualType(); 1485 1486 // Handle complex types first (C99 6.3.1.8p1). 1487 if (LHSType->isComplexType() || RHSType->isComplexType()) 1488 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1489 ACK == ACK_CompAssign); 1490 1491 // Now handle "real" floating types (i.e. float, double, long double). 1492 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1493 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1494 ACK == ACK_CompAssign); 1495 1496 // Handle GCC complex int extension. 1497 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1498 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1499 ACK == ACK_CompAssign); 1500 1501 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1502 return handleFixedPointConversion(*this, LHSType, RHSType); 1503 1504 // Finally, we have two differing integer types. 1505 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1506 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1507 } 1508 1509 //===----------------------------------------------------------------------===// 1510 // Semantic Analysis for various Expression Types 1511 //===----------------------------------------------------------------------===// 1512 1513 1514 ExprResult 1515 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1516 SourceLocation DefaultLoc, 1517 SourceLocation RParenLoc, 1518 Expr *ControllingExpr, 1519 ArrayRef<ParsedType> ArgTypes, 1520 ArrayRef<Expr *> ArgExprs) { 1521 unsigned NumAssocs = ArgTypes.size(); 1522 assert(NumAssocs == ArgExprs.size()); 1523 1524 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1525 for (unsigned i = 0; i < NumAssocs; ++i) { 1526 if (ArgTypes[i]) 1527 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1528 else 1529 Types[i] = nullptr; 1530 } 1531 1532 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1533 ControllingExpr, 1534 llvm::makeArrayRef(Types, NumAssocs), 1535 ArgExprs); 1536 delete [] Types; 1537 return ER; 1538 } 1539 1540 ExprResult 1541 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1542 SourceLocation DefaultLoc, 1543 SourceLocation RParenLoc, 1544 Expr *ControllingExpr, 1545 ArrayRef<TypeSourceInfo *> Types, 1546 ArrayRef<Expr *> Exprs) { 1547 unsigned NumAssocs = Types.size(); 1548 assert(NumAssocs == Exprs.size()); 1549 1550 // Decay and strip qualifiers for the controlling expression type, and handle 1551 // placeholder type replacement. See committee discussion from WG14 DR423. 1552 { 1553 EnterExpressionEvaluationContext Unevaluated( 1554 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1555 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1556 if (R.isInvalid()) 1557 return ExprError(); 1558 ControllingExpr = R.get(); 1559 } 1560 1561 // The controlling expression is an unevaluated operand, so side effects are 1562 // likely unintended. 1563 if (!inTemplateInstantiation() && 1564 ControllingExpr->HasSideEffects(Context, false)) 1565 Diag(ControllingExpr->getExprLoc(), 1566 diag::warn_side_effects_unevaluated_context); 1567 1568 bool TypeErrorFound = false, 1569 IsResultDependent = ControllingExpr->isTypeDependent(), 1570 ContainsUnexpandedParameterPack 1571 = ControllingExpr->containsUnexpandedParameterPack(); 1572 1573 for (unsigned i = 0; i < NumAssocs; ++i) { 1574 if (Exprs[i]->containsUnexpandedParameterPack()) 1575 ContainsUnexpandedParameterPack = true; 1576 1577 if (Types[i]) { 1578 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1579 ContainsUnexpandedParameterPack = true; 1580 1581 if (Types[i]->getType()->isDependentType()) { 1582 IsResultDependent = true; 1583 } else { 1584 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1585 // complete object type other than a variably modified type." 1586 unsigned D = 0; 1587 if (Types[i]->getType()->isIncompleteType()) 1588 D = diag::err_assoc_type_incomplete; 1589 else if (!Types[i]->getType()->isObjectType()) 1590 D = diag::err_assoc_type_nonobject; 1591 else if (Types[i]->getType()->isVariablyModifiedType()) 1592 D = diag::err_assoc_type_variably_modified; 1593 1594 if (D != 0) { 1595 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1596 << Types[i]->getTypeLoc().getSourceRange() 1597 << Types[i]->getType(); 1598 TypeErrorFound = true; 1599 } 1600 1601 // C11 6.5.1.1p2 "No two generic associations in the same generic 1602 // selection shall specify compatible types." 1603 for (unsigned j = i+1; j < NumAssocs; ++j) 1604 if (Types[j] && !Types[j]->getType()->isDependentType() && 1605 Context.typesAreCompatible(Types[i]->getType(), 1606 Types[j]->getType())) { 1607 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1608 diag::err_assoc_compatible_types) 1609 << Types[j]->getTypeLoc().getSourceRange() 1610 << Types[j]->getType() 1611 << Types[i]->getType(); 1612 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1613 diag::note_compat_assoc) 1614 << Types[i]->getTypeLoc().getSourceRange() 1615 << Types[i]->getType(); 1616 TypeErrorFound = true; 1617 } 1618 } 1619 } 1620 } 1621 if (TypeErrorFound) 1622 return ExprError(); 1623 1624 // If we determined that the generic selection is result-dependent, don't 1625 // try to compute the result expression. 1626 if (IsResultDependent) 1627 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1628 Exprs, DefaultLoc, RParenLoc, 1629 ContainsUnexpandedParameterPack); 1630 1631 SmallVector<unsigned, 1> CompatIndices; 1632 unsigned DefaultIndex = -1U; 1633 for (unsigned i = 0; i < NumAssocs; ++i) { 1634 if (!Types[i]) 1635 DefaultIndex = i; 1636 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1637 Types[i]->getType())) 1638 CompatIndices.push_back(i); 1639 } 1640 1641 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1642 // type compatible with at most one of the types named in its generic 1643 // association list." 1644 if (CompatIndices.size() > 1) { 1645 // We strip parens here because the controlling expression is typically 1646 // parenthesized in macro definitions. 1647 ControllingExpr = ControllingExpr->IgnoreParens(); 1648 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1649 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1650 << (unsigned)CompatIndices.size(); 1651 for (unsigned I : CompatIndices) { 1652 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1653 diag::note_compat_assoc) 1654 << Types[I]->getTypeLoc().getSourceRange() 1655 << Types[I]->getType(); 1656 } 1657 return ExprError(); 1658 } 1659 1660 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1661 // its controlling expression shall have type compatible with exactly one of 1662 // the types named in its generic association list." 1663 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1664 // We strip parens here because the controlling expression is typically 1665 // parenthesized in macro definitions. 1666 ControllingExpr = ControllingExpr->IgnoreParens(); 1667 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1668 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1669 return ExprError(); 1670 } 1671 1672 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1673 // type name that is compatible with the type of the controlling expression, 1674 // then the result expression of the generic selection is the expression 1675 // in that generic association. Otherwise, the result expression of the 1676 // generic selection is the expression in the default generic association." 1677 unsigned ResultIndex = 1678 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1679 1680 return GenericSelectionExpr::Create( 1681 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1682 ContainsUnexpandedParameterPack, ResultIndex); 1683 } 1684 1685 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1686 /// location of the token and the offset of the ud-suffix within it. 1687 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1688 unsigned Offset) { 1689 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1690 S.getLangOpts()); 1691 } 1692 1693 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1694 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1695 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1696 IdentifierInfo *UDSuffix, 1697 SourceLocation UDSuffixLoc, 1698 ArrayRef<Expr*> Args, 1699 SourceLocation LitEndLoc) { 1700 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1701 1702 QualType ArgTy[2]; 1703 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1704 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1705 if (ArgTy[ArgIdx]->isArrayType()) 1706 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1707 } 1708 1709 DeclarationName OpName = 1710 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1711 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1712 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1713 1714 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1715 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1716 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1717 /*AllowStringTemplate*/ false, 1718 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1719 return ExprError(); 1720 1721 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1722 } 1723 1724 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1725 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1726 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1727 /// multiple tokens. However, the common case is that StringToks points to one 1728 /// string. 1729 /// 1730 ExprResult 1731 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1732 assert(!StringToks.empty() && "Must have at least one string!"); 1733 1734 StringLiteralParser Literal(StringToks, PP); 1735 if (Literal.hadError) 1736 return ExprError(); 1737 1738 SmallVector<SourceLocation, 4> StringTokLocs; 1739 for (const Token &Tok : StringToks) 1740 StringTokLocs.push_back(Tok.getLocation()); 1741 1742 QualType CharTy = Context.CharTy; 1743 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1744 if (Literal.isWide()) { 1745 CharTy = Context.getWideCharType(); 1746 Kind = StringLiteral::Wide; 1747 } else if (Literal.isUTF8()) { 1748 if (getLangOpts().Char8) 1749 CharTy = Context.Char8Ty; 1750 Kind = StringLiteral::UTF8; 1751 } else if (Literal.isUTF16()) { 1752 CharTy = Context.Char16Ty; 1753 Kind = StringLiteral::UTF16; 1754 } else if (Literal.isUTF32()) { 1755 CharTy = Context.Char32Ty; 1756 Kind = StringLiteral::UTF32; 1757 } else if (Literal.isPascal()) { 1758 CharTy = Context.UnsignedCharTy; 1759 } 1760 1761 // Warn on initializing an array of char from a u8 string literal; this 1762 // becomes ill-formed in C++2a. 1763 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1764 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1765 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1766 1767 // Create removals for all 'u8' prefixes in the string literal(s). This 1768 // ensures C++2a compatibility (but may change the program behavior when 1769 // built by non-Clang compilers for which the execution character set is 1770 // not always UTF-8). 1771 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1772 SourceLocation RemovalDiagLoc; 1773 for (const Token &Tok : StringToks) { 1774 if (Tok.getKind() == tok::utf8_string_literal) { 1775 if (RemovalDiagLoc.isInvalid()) 1776 RemovalDiagLoc = Tok.getLocation(); 1777 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1778 Tok.getLocation(), 1779 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1780 getSourceManager(), getLangOpts()))); 1781 } 1782 } 1783 Diag(RemovalDiagLoc, RemovalDiag); 1784 } 1785 1786 QualType StrTy = 1787 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1788 1789 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1790 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1791 Kind, Literal.Pascal, StrTy, 1792 &StringTokLocs[0], 1793 StringTokLocs.size()); 1794 if (Literal.getUDSuffix().empty()) 1795 return Lit; 1796 1797 // We're building a user-defined literal. 1798 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1799 SourceLocation UDSuffixLoc = 1800 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1801 Literal.getUDSuffixOffset()); 1802 1803 // Make sure we're allowed user-defined literals here. 1804 if (!UDLScope) 1805 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1806 1807 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1808 // operator "" X (str, len) 1809 QualType SizeType = Context.getSizeType(); 1810 1811 DeclarationName OpName = 1812 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1813 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1814 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1815 1816 QualType ArgTy[] = { 1817 Context.getArrayDecayedType(StrTy), SizeType 1818 }; 1819 1820 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1821 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1822 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1823 /*AllowStringTemplate*/ true, 1824 /*DiagnoseMissing*/ true)) { 1825 1826 case LOLR_Cooked: { 1827 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1828 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1829 StringTokLocs[0]); 1830 Expr *Args[] = { Lit, LenArg }; 1831 1832 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1833 } 1834 1835 case LOLR_StringTemplate: { 1836 TemplateArgumentListInfo ExplicitArgs; 1837 1838 unsigned CharBits = Context.getIntWidth(CharTy); 1839 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1840 llvm::APSInt Value(CharBits, CharIsUnsigned); 1841 1842 TemplateArgument TypeArg(CharTy); 1843 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1844 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1845 1846 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1847 Value = Lit->getCodeUnit(I); 1848 TemplateArgument Arg(Context, Value, CharTy); 1849 TemplateArgumentLocInfo ArgInfo; 1850 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1851 } 1852 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1853 &ExplicitArgs); 1854 } 1855 case LOLR_Raw: 1856 case LOLR_Template: 1857 case LOLR_ErrorNoDiagnostic: 1858 llvm_unreachable("unexpected literal operator lookup result"); 1859 case LOLR_Error: 1860 return ExprError(); 1861 } 1862 llvm_unreachable("unexpected literal operator lookup result"); 1863 } 1864 1865 DeclRefExpr * 1866 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1867 SourceLocation Loc, 1868 const CXXScopeSpec *SS) { 1869 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1870 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1871 } 1872 1873 DeclRefExpr * 1874 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1875 const DeclarationNameInfo &NameInfo, 1876 const CXXScopeSpec *SS, NamedDecl *FoundD, 1877 SourceLocation TemplateKWLoc, 1878 const TemplateArgumentListInfo *TemplateArgs) { 1879 NestedNameSpecifierLoc NNS = 1880 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1881 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1882 TemplateArgs); 1883 } 1884 1885 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1886 // A declaration named in an unevaluated operand never constitutes an odr-use. 1887 if (isUnevaluatedContext()) 1888 return NOUR_Unevaluated; 1889 1890 // C++2a [basic.def.odr]p4: 1891 // A variable x whose name appears as a potentially-evaluated expression e 1892 // is odr-used by e unless [...] x is a reference that is usable in 1893 // constant expressions. 1894 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1895 if (VD->getType()->isReferenceType() && 1896 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1897 VD->isUsableInConstantExpressions(Context)) 1898 return NOUR_Constant; 1899 } 1900 1901 // All remaining non-variable cases constitute an odr-use. For variables, we 1902 // need to wait and see how the expression is used. 1903 return NOUR_None; 1904 } 1905 1906 /// BuildDeclRefExpr - Build an expression that references a 1907 /// declaration that does not require a closure capture. 1908 DeclRefExpr * 1909 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1910 const DeclarationNameInfo &NameInfo, 1911 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1912 SourceLocation TemplateKWLoc, 1913 const TemplateArgumentListInfo *TemplateArgs) { 1914 bool RefersToCapturedVariable = 1915 isa<VarDecl>(D) && 1916 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1917 1918 DeclRefExpr *E = DeclRefExpr::Create( 1919 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1920 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1921 MarkDeclRefReferenced(E); 1922 1923 // C++ [except.spec]p17: 1924 // An exception-specification is considered to be needed when: 1925 // - in an expression, the function is the unique lookup result or 1926 // the selected member of a set of overloaded functions. 1927 // 1928 // We delay doing this until after we've built the function reference and 1929 // marked it as used so that: 1930 // a) if the function is defaulted, we get errors from defining it before / 1931 // instead of errors from computing its exception specification, and 1932 // b) if the function is a defaulted comparison, we can use the body we 1933 // build when defining it as input to the exception specification 1934 // computation rather than computing a new body. 1935 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1936 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1937 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1938 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1939 } 1940 } 1941 1942 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1943 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1944 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1945 getCurFunction()->recordUseOfWeak(E); 1946 1947 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1948 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1949 FD = IFD->getAnonField(); 1950 if (FD) { 1951 UnusedPrivateFields.remove(FD); 1952 // Just in case we're building an illegal pointer-to-member. 1953 if (FD->isBitField()) 1954 E->setObjectKind(OK_BitField); 1955 } 1956 1957 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1958 // designates a bit-field. 1959 if (auto *BD = dyn_cast<BindingDecl>(D)) 1960 if (auto *BE = BD->getBinding()) 1961 E->setObjectKind(BE->getObjectKind()); 1962 1963 return E; 1964 } 1965 1966 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1967 /// possibly a list of template arguments. 1968 /// 1969 /// If this produces template arguments, it is permitted to call 1970 /// DecomposeTemplateName. 1971 /// 1972 /// This actually loses a lot of source location information for 1973 /// non-standard name kinds; we should consider preserving that in 1974 /// some way. 1975 void 1976 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1977 TemplateArgumentListInfo &Buffer, 1978 DeclarationNameInfo &NameInfo, 1979 const TemplateArgumentListInfo *&TemplateArgs) { 1980 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1981 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1982 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1983 1984 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1985 Id.TemplateId->NumArgs); 1986 translateTemplateArguments(TemplateArgsPtr, Buffer); 1987 1988 TemplateName TName = Id.TemplateId->Template.get(); 1989 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1990 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1991 TemplateArgs = &Buffer; 1992 } else { 1993 NameInfo = GetNameFromUnqualifiedId(Id); 1994 TemplateArgs = nullptr; 1995 } 1996 } 1997 1998 static void emitEmptyLookupTypoDiagnostic( 1999 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2000 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2001 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2002 DeclContext *Ctx = 2003 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2004 if (!TC) { 2005 // Emit a special diagnostic for failed member lookups. 2006 // FIXME: computing the declaration context might fail here (?) 2007 if (Ctx) 2008 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2009 << SS.getRange(); 2010 else 2011 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2012 return; 2013 } 2014 2015 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2016 bool DroppedSpecifier = 2017 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2018 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2019 ? diag::note_implicit_param_decl 2020 : diag::note_previous_decl; 2021 if (!Ctx) 2022 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2023 SemaRef.PDiag(NoteID)); 2024 else 2025 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2026 << Typo << Ctx << DroppedSpecifier 2027 << SS.getRange(), 2028 SemaRef.PDiag(NoteID)); 2029 } 2030 2031 /// Diagnose an empty lookup. 2032 /// 2033 /// \return false if new lookup candidates were found 2034 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2035 CorrectionCandidateCallback &CCC, 2036 TemplateArgumentListInfo *ExplicitTemplateArgs, 2037 ArrayRef<Expr *> Args, TypoExpr **Out) { 2038 DeclarationName Name = R.getLookupName(); 2039 2040 unsigned diagnostic = diag::err_undeclared_var_use; 2041 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2042 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2043 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2044 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2045 diagnostic = diag::err_undeclared_use; 2046 diagnostic_suggest = diag::err_undeclared_use_suggest; 2047 } 2048 2049 // If the original lookup was an unqualified lookup, fake an 2050 // unqualified lookup. This is useful when (for example) the 2051 // original lookup would not have found something because it was a 2052 // dependent name. 2053 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2054 while (DC) { 2055 if (isa<CXXRecordDecl>(DC)) { 2056 LookupQualifiedName(R, DC); 2057 2058 if (!R.empty()) { 2059 // Don't give errors about ambiguities in this lookup. 2060 R.suppressDiagnostics(); 2061 2062 // During a default argument instantiation the CurContext points 2063 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2064 // function parameter list, hence add an explicit check. 2065 bool isDefaultArgument = 2066 !CodeSynthesisContexts.empty() && 2067 CodeSynthesisContexts.back().Kind == 2068 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2069 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2070 bool isInstance = CurMethod && 2071 CurMethod->isInstance() && 2072 DC == CurMethod->getParent() && !isDefaultArgument; 2073 2074 // Give a code modification hint to insert 'this->'. 2075 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2076 // Actually quite difficult! 2077 if (getLangOpts().MSVCCompat) 2078 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2079 if (isInstance) { 2080 Diag(R.getNameLoc(), diagnostic) << Name 2081 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2082 CheckCXXThisCapture(R.getNameLoc()); 2083 } else { 2084 Diag(R.getNameLoc(), diagnostic) << Name; 2085 } 2086 2087 // Do we really want to note all of these? 2088 for (NamedDecl *D : R) 2089 Diag(D->getLocation(), diag::note_dependent_var_use); 2090 2091 // Return true if we are inside a default argument instantiation 2092 // and the found name refers to an instance member function, otherwise 2093 // the function calling DiagnoseEmptyLookup will try to create an 2094 // implicit member call and this is wrong for default argument. 2095 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2096 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2097 return true; 2098 } 2099 2100 // Tell the callee to try to recover. 2101 return false; 2102 } 2103 2104 R.clear(); 2105 } 2106 2107 DC = DC->getLookupParent(); 2108 } 2109 2110 // We didn't find anything, so try to correct for a typo. 2111 TypoCorrection Corrected; 2112 if (S && Out) { 2113 SourceLocation TypoLoc = R.getNameLoc(); 2114 assert(!ExplicitTemplateArgs && 2115 "Diagnosing an empty lookup with explicit template args!"); 2116 *Out = CorrectTypoDelayed( 2117 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2118 [=](const TypoCorrection &TC) { 2119 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2120 diagnostic, diagnostic_suggest); 2121 }, 2122 nullptr, CTK_ErrorRecovery); 2123 if (*Out) 2124 return true; 2125 } else if (S && 2126 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2127 S, &SS, CCC, CTK_ErrorRecovery))) { 2128 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2129 bool DroppedSpecifier = 2130 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2131 R.setLookupName(Corrected.getCorrection()); 2132 2133 bool AcceptableWithRecovery = false; 2134 bool AcceptableWithoutRecovery = false; 2135 NamedDecl *ND = Corrected.getFoundDecl(); 2136 if (ND) { 2137 if (Corrected.isOverloaded()) { 2138 OverloadCandidateSet OCS(R.getNameLoc(), 2139 OverloadCandidateSet::CSK_Normal); 2140 OverloadCandidateSet::iterator Best; 2141 for (NamedDecl *CD : Corrected) { 2142 if (FunctionTemplateDecl *FTD = 2143 dyn_cast<FunctionTemplateDecl>(CD)) 2144 AddTemplateOverloadCandidate( 2145 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2146 Args, OCS); 2147 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2148 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2149 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2150 Args, OCS); 2151 } 2152 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2153 case OR_Success: 2154 ND = Best->FoundDecl; 2155 Corrected.setCorrectionDecl(ND); 2156 break; 2157 default: 2158 // FIXME: Arbitrarily pick the first declaration for the note. 2159 Corrected.setCorrectionDecl(ND); 2160 break; 2161 } 2162 } 2163 R.addDecl(ND); 2164 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2165 CXXRecordDecl *Record = nullptr; 2166 if (Corrected.getCorrectionSpecifier()) { 2167 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2168 Record = Ty->getAsCXXRecordDecl(); 2169 } 2170 if (!Record) 2171 Record = cast<CXXRecordDecl>( 2172 ND->getDeclContext()->getRedeclContext()); 2173 R.setNamingClass(Record); 2174 } 2175 2176 auto *UnderlyingND = ND->getUnderlyingDecl(); 2177 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2178 isa<FunctionTemplateDecl>(UnderlyingND); 2179 // FIXME: If we ended up with a typo for a type name or 2180 // Objective-C class name, we're in trouble because the parser 2181 // is in the wrong place to recover. Suggest the typo 2182 // correction, but don't make it a fix-it since we're not going 2183 // to recover well anyway. 2184 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2185 getAsTypeTemplateDecl(UnderlyingND) || 2186 isa<ObjCInterfaceDecl>(UnderlyingND); 2187 } else { 2188 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2189 // because we aren't able to recover. 2190 AcceptableWithoutRecovery = true; 2191 } 2192 2193 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2194 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2195 ? diag::note_implicit_param_decl 2196 : diag::note_previous_decl; 2197 if (SS.isEmpty()) 2198 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2199 PDiag(NoteID), AcceptableWithRecovery); 2200 else 2201 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2202 << Name << computeDeclContext(SS, false) 2203 << DroppedSpecifier << SS.getRange(), 2204 PDiag(NoteID), AcceptableWithRecovery); 2205 2206 // Tell the callee whether to try to recover. 2207 return !AcceptableWithRecovery; 2208 } 2209 } 2210 R.clear(); 2211 2212 // Emit a special diagnostic for failed member lookups. 2213 // FIXME: computing the declaration context might fail here (?) 2214 if (!SS.isEmpty()) { 2215 Diag(R.getNameLoc(), diag::err_no_member) 2216 << Name << computeDeclContext(SS, false) 2217 << SS.getRange(); 2218 return true; 2219 } 2220 2221 // Give up, we can't recover. 2222 Diag(R.getNameLoc(), diagnostic) << Name; 2223 return true; 2224 } 2225 2226 /// In Microsoft mode, if we are inside a template class whose parent class has 2227 /// dependent base classes, and we can't resolve an unqualified identifier, then 2228 /// assume the identifier is a member of a dependent base class. We can only 2229 /// recover successfully in static methods, instance methods, and other contexts 2230 /// where 'this' is available. This doesn't precisely match MSVC's 2231 /// instantiation model, but it's close enough. 2232 static Expr * 2233 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2234 DeclarationNameInfo &NameInfo, 2235 SourceLocation TemplateKWLoc, 2236 const TemplateArgumentListInfo *TemplateArgs) { 2237 // Only try to recover from lookup into dependent bases in static methods or 2238 // contexts where 'this' is available. 2239 QualType ThisType = S.getCurrentThisType(); 2240 const CXXRecordDecl *RD = nullptr; 2241 if (!ThisType.isNull()) 2242 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2243 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2244 RD = MD->getParent(); 2245 if (!RD || !RD->hasAnyDependentBases()) 2246 return nullptr; 2247 2248 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2249 // is available, suggest inserting 'this->' as a fixit. 2250 SourceLocation Loc = NameInfo.getLoc(); 2251 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2252 DB << NameInfo.getName() << RD; 2253 2254 if (!ThisType.isNull()) { 2255 DB << FixItHint::CreateInsertion(Loc, "this->"); 2256 return CXXDependentScopeMemberExpr::Create( 2257 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2258 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2259 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2260 } 2261 2262 // Synthesize a fake NNS that points to the derived class. This will 2263 // perform name lookup during template instantiation. 2264 CXXScopeSpec SS; 2265 auto *NNS = 2266 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2267 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2268 return DependentScopeDeclRefExpr::Create( 2269 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2270 TemplateArgs); 2271 } 2272 2273 ExprResult 2274 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2275 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2276 bool HasTrailingLParen, bool IsAddressOfOperand, 2277 CorrectionCandidateCallback *CCC, 2278 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2279 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2280 "cannot be direct & operand and have a trailing lparen"); 2281 if (SS.isInvalid()) 2282 return ExprError(); 2283 2284 TemplateArgumentListInfo TemplateArgsBuffer; 2285 2286 // Decompose the UnqualifiedId into the following data. 2287 DeclarationNameInfo NameInfo; 2288 const TemplateArgumentListInfo *TemplateArgs; 2289 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2290 2291 DeclarationName Name = NameInfo.getName(); 2292 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2293 SourceLocation NameLoc = NameInfo.getLoc(); 2294 2295 if (II && II->isEditorPlaceholder()) { 2296 // FIXME: When typed placeholders are supported we can create a typed 2297 // placeholder expression node. 2298 return ExprError(); 2299 } 2300 2301 // C++ [temp.dep.expr]p3: 2302 // An id-expression is type-dependent if it contains: 2303 // -- an identifier that was declared with a dependent type, 2304 // (note: handled after lookup) 2305 // -- a template-id that is dependent, 2306 // (note: handled in BuildTemplateIdExpr) 2307 // -- a conversion-function-id that specifies a dependent type, 2308 // -- a nested-name-specifier that contains a class-name that 2309 // names a dependent type. 2310 // Determine whether this is a member of an unknown specialization; 2311 // we need to handle these differently. 2312 bool DependentID = false; 2313 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2314 Name.getCXXNameType()->isDependentType()) { 2315 DependentID = true; 2316 } else if (SS.isSet()) { 2317 if (DeclContext *DC = computeDeclContext(SS, false)) { 2318 if (RequireCompleteDeclContext(SS, DC)) 2319 return ExprError(); 2320 } else { 2321 DependentID = true; 2322 } 2323 } 2324 2325 if (DependentID) 2326 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2327 IsAddressOfOperand, TemplateArgs); 2328 2329 // Perform the required lookup. 2330 LookupResult R(*this, NameInfo, 2331 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2332 ? LookupObjCImplicitSelfParam 2333 : LookupOrdinaryName); 2334 if (TemplateKWLoc.isValid() || TemplateArgs) { 2335 // Lookup the template name again to correctly establish the context in 2336 // which it was found. This is really unfortunate as we already did the 2337 // lookup to determine that it was a template name in the first place. If 2338 // this becomes a performance hit, we can work harder to preserve those 2339 // results until we get here but it's likely not worth it. 2340 bool MemberOfUnknownSpecialization; 2341 AssumedTemplateKind AssumedTemplate; 2342 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2343 MemberOfUnknownSpecialization, TemplateKWLoc, 2344 &AssumedTemplate)) 2345 return ExprError(); 2346 2347 if (MemberOfUnknownSpecialization || 2348 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2349 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2350 IsAddressOfOperand, TemplateArgs); 2351 } else { 2352 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2353 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2354 2355 // If the result might be in a dependent base class, this is a dependent 2356 // id-expression. 2357 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2358 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2359 IsAddressOfOperand, TemplateArgs); 2360 2361 // If this reference is in an Objective-C method, then we need to do 2362 // some special Objective-C lookup, too. 2363 if (IvarLookupFollowUp) { 2364 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2365 if (E.isInvalid()) 2366 return ExprError(); 2367 2368 if (Expr *Ex = E.getAs<Expr>()) 2369 return Ex; 2370 } 2371 } 2372 2373 if (R.isAmbiguous()) 2374 return ExprError(); 2375 2376 // This could be an implicitly declared function reference (legal in C90, 2377 // extension in C99, forbidden in C++). 2378 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2379 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2380 if (D) R.addDecl(D); 2381 } 2382 2383 // Determine whether this name might be a candidate for 2384 // argument-dependent lookup. 2385 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2386 2387 if (R.empty() && !ADL) { 2388 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2389 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2390 TemplateKWLoc, TemplateArgs)) 2391 return E; 2392 } 2393 2394 // Don't diagnose an empty lookup for inline assembly. 2395 if (IsInlineAsmIdentifier) 2396 return ExprError(); 2397 2398 // If this name wasn't predeclared and if this is not a function 2399 // call, diagnose the problem. 2400 TypoExpr *TE = nullptr; 2401 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2402 : nullptr); 2403 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2404 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2405 "Typo correction callback misconfigured"); 2406 if (CCC) { 2407 // Make sure the callback knows what the typo being diagnosed is. 2408 CCC->setTypoName(II); 2409 if (SS.isValid()) 2410 CCC->setTypoNNS(SS.getScopeRep()); 2411 } 2412 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2413 // a template name, but we happen to have always already looked up the name 2414 // before we get here if it must be a template name. 2415 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2416 None, &TE)) { 2417 if (TE && KeywordReplacement) { 2418 auto &State = getTypoExprState(TE); 2419 auto BestTC = State.Consumer->getNextCorrection(); 2420 if (BestTC.isKeyword()) { 2421 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2422 if (State.DiagHandler) 2423 State.DiagHandler(BestTC); 2424 KeywordReplacement->startToken(); 2425 KeywordReplacement->setKind(II->getTokenID()); 2426 KeywordReplacement->setIdentifierInfo(II); 2427 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2428 // Clean up the state associated with the TypoExpr, since it has 2429 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2430 clearDelayedTypo(TE); 2431 // Signal that a correction to a keyword was performed by returning a 2432 // valid-but-null ExprResult. 2433 return (Expr*)nullptr; 2434 } 2435 State.Consumer->resetCorrectionStream(); 2436 } 2437 return TE ? TE : ExprError(); 2438 } 2439 2440 assert(!R.empty() && 2441 "DiagnoseEmptyLookup returned false but added no results"); 2442 2443 // If we found an Objective-C instance variable, let 2444 // LookupInObjCMethod build the appropriate expression to 2445 // reference the ivar. 2446 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2447 R.clear(); 2448 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2449 // In a hopelessly buggy code, Objective-C instance variable 2450 // lookup fails and no expression will be built to reference it. 2451 if (!E.isInvalid() && !E.get()) 2452 return ExprError(); 2453 return E; 2454 } 2455 } 2456 2457 // This is guaranteed from this point on. 2458 assert(!R.empty() || ADL); 2459 2460 // Check whether this might be a C++ implicit instance member access. 2461 // C++ [class.mfct.non-static]p3: 2462 // When an id-expression that is not part of a class member access 2463 // syntax and not used to form a pointer to member is used in the 2464 // body of a non-static member function of class X, if name lookup 2465 // resolves the name in the id-expression to a non-static non-type 2466 // member of some class C, the id-expression is transformed into a 2467 // class member access expression using (*this) as the 2468 // postfix-expression to the left of the . operator. 2469 // 2470 // But we don't actually need to do this for '&' operands if R 2471 // resolved to a function or overloaded function set, because the 2472 // expression is ill-formed if it actually works out to be a 2473 // non-static member function: 2474 // 2475 // C++ [expr.ref]p4: 2476 // Otherwise, if E1.E2 refers to a non-static member function. . . 2477 // [t]he expression can be used only as the left-hand operand of a 2478 // member function call. 2479 // 2480 // There are other safeguards against such uses, but it's important 2481 // to get this right here so that we don't end up making a 2482 // spuriously dependent expression if we're inside a dependent 2483 // instance method. 2484 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2485 bool MightBeImplicitMember; 2486 if (!IsAddressOfOperand) 2487 MightBeImplicitMember = true; 2488 else if (!SS.isEmpty()) 2489 MightBeImplicitMember = false; 2490 else if (R.isOverloadedResult()) 2491 MightBeImplicitMember = false; 2492 else if (R.isUnresolvableResult()) 2493 MightBeImplicitMember = true; 2494 else 2495 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2496 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2497 isa<MSPropertyDecl>(R.getFoundDecl()); 2498 2499 if (MightBeImplicitMember) 2500 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2501 R, TemplateArgs, S); 2502 } 2503 2504 if (TemplateArgs || TemplateKWLoc.isValid()) { 2505 2506 // In C++1y, if this is a variable template id, then check it 2507 // in BuildTemplateIdExpr(). 2508 // The single lookup result must be a variable template declaration. 2509 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2510 Id.TemplateId->Kind == TNK_Var_template) { 2511 assert(R.getAsSingle<VarTemplateDecl>() && 2512 "There should only be one declaration found."); 2513 } 2514 2515 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2516 } 2517 2518 return BuildDeclarationNameExpr(SS, R, ADL); 2519 } 2520 2521 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2522 /// declaration name, generally during template instantiation. 2523 /// There's a large number of things which don't need to be done along 2524 /// this path. 2525 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2526 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2527 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2528 DeclContext *DC = computeDeclContext(SS, false); 2529 if (!DC) 2530 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2531 NameInfo, /*TemplateArgs=*/nullptr); 2532 2533 if (RequireCompleteDeclContext(SS, DC)) 2534 return ExprError(); 2535 2536 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2537 LookupQualifiedName(R, DC); 2538 2539 if (R.isAmbiguous()) 2540 return ExprError(); 2541 2542 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2543 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2544 NameInfo, /*TemplateArgs=*/nullptr); 2545 2546 if (R.empty()) { 2547 Diag(NameInfo.getLoc(), diag::err_no_member) 2548 << NameInfo.getName() << DC << SS.getRange(); 2549 return ExprError(); 2550 } 2551 2552 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2553 // Diagnose a missing typename if this resolved unambiguously to a type in 2554 // a dependent context. If we can recover with a type, downgrade this to 2555 // a warning in Microsoft compatibility mode. 2556 unsigned DiagID = diag::err_typename_missing; 2557 if (RecoveryTSI && getLangOpts().MSVCCompat) 2558 DiagID = diag::ext_typename_missing; 2559 SourceLocation Loc = SS.getBeginLoc(); 2560 auto D = Diag(Loc, DiagID); 2561 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2562 << SourceRange(Loc, NameInfo.getEndLoc()); 2563 2564 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2565 // context. 2566 if (!RecoveryTSI) 2567 return ExprError(); 2568 2569 // Only issue the fixit if we're prepared to recover. 2570 D << FixItHint::CreateInsertion(Loc, "typename "); 2571 2572 // Recover by pretending this was an elaborated type. 2573 QualType Ty = Context.getTypeDeclType(TD); 2574 TypeLocBuilder TLB; 2575 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2576 2577 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2578 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2579 QTL.setElaboratedKeywordLoc(SourceLocation()); 2580 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2581 2582 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2583 2584 return ExprEmpty(); 2585 } 2586 2587 // Defend against this resolving to an implicit member access. We usually 2588 // won't get here if this might be a legitimate a class member (we end up in 2589 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2590 // a pointer-to-member or in an unevaluated context in C++11. 2591 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2592 return BuildPossibleImplicitMemberExpr(SS, 2593 /*TemplateKWLoc=*/SourceLocation(), 2594 R, /*TemplateArgs=*/nullptr, S); 2595 2596 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2597 } 2598 2599 /// The parser has read a name in, and Sema has detected that we're currently 2600 /// inside an ObjC method. Perform some additional checks and determine if we 2601 /// should form a reference to an ivar. 2602 /// 2603 /// Ideally, most of this would be done by lookup, but there's 2604 /// actually quite a lot of extra work involved. 2605 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2606 IdentifierInfo *II) { 2607 SourceLocation Loc = Lookup.getNameLoc(); 2608 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2609 2610 // Check for error condition which is already reported. 2611 if (!CurMethod) 2612 return DeclResult(true); 2613 2614 // There are two cases to handle here. 1) scoped lookup could have failed, 2615 // in which case we should look for an ivar. 2) scoped lookup could have 2616 // found a decl, but that decl is outside the current instance method (i.e. 2617 // a global variable). In these two cases, we do a lookup for an ivar with 2618 // this name, if the lookup sucedes, we replace it our current decl. 2619 2620 // If we're in a class method, we don't normally want to look for 2621 // ivars. But if we don't find anything else, and there's an 2622 // ivar, that's an error. 2623 bool IsClassMethod = CurMethod->isClassMethod(); 2624 2625 bool LookForIvars; 2626 if (Lookup.empty()) 2627 LookForIvars = true; 2628 else if (IsClassMethod) 2629 LookForIvars = false; 2630 else 2631 LookForIvars = (Lookup.isSingleResult() && 2632 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2633 ObjCInterfaceDecl *IFace = nullptr; 2634 if (LookForIvars) { 2635 IFace = CurMethod->getClassInterface(); 2636 ObjCInterfaceDecl *ClassDeclared; 2637 ObjCIvarDecl *IV = nullptr; 2638 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2639 // Diagnose using an ivar in a class method. 2640 if (IsClassMethod) { 2641 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2642 return DeclResult(true); 2643 } 2644 2645 // Diagnose the use of an ivar outside of the declaring class. 2646 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2647 !declaresSameEntity(ClassDeclared, IFace) && 2648 !getLangOpts().DebuggerSupport) 2649 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2650 2651 // Success. 2652 return IV; 2653 } 2654 } else if (CurMethod->isInstanceMethod()) { 2655 // We should warn if a local variable hides an ivar. 2656 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2657 ObjCInterfaceDecl *ClassDeclared; 2658 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2659 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2660 declaresSameEntity(IFace, ClassDeclared)) 2661 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2662 } 2663 } 2664 } else if (Lookup.isSingleResult() && 2665 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2666 // If accessing a stand-alone ivar in a class method, this is an error. 2667 if (const ObjCIvarDecl *IV = 2668 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2669 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2670 return DeclResult(true); 2671 } 2672 } 2673 2674 // Didn't encounter an error, didn't find an ivar. 2675 return DeclResult(false); 2676 } 2677 2678 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2679 ObjCIvarDecl *IV) { 2680 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2681 assert(CurMethod && CurMethod->isInstanceMethod() && 2682 "should not reference ivar from this context"); 2683 2684 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2685 assert(IFace && "should not reference ivar from this context"); 2686 2687 // If we're referencing an invalid decl, just return this as a silent 2688 // error node. The error diagnostic was already emitted on the decl. 2689 if (IV->isInvalidDecl()) 2690 return ExprError(); 2691 2692 // Check if referencing a field with __attribute__((deprecated)). 2693 if (DiagnoseUseOfDecl(IV, Loc)) 2694 return ExprError(); 2695 2696 // FIXME: This should use a new expr for a direct reference, don't 2697 // turn this into Self->ivar, just return a BareIVarExpr or something. 2698 IdentifierInfo &II = Context.Idents.get("self"); 2699 UnqualifiedId SelfName; 2700 SelfName.setIdentifier(&II, SourceLocation()); 2701 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2702 CXXScopeSpec SelfScopeSpec; 2703 SourceLocation TemplateKWLoc; 2704 ExprResult SelfExpr = 2705 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2706 /*HasTrailingLParen=*/false, 2707 /*IsAddressOfOperand=*/false); 2708 if (SelfExpr.isInvalid()) 2709 return ExprError(); 2710 2711 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2712 if (SelfExpr.isInvalid()) 2713 return ExprError(); 2714 2715 MarkAnyDeclReferenced(Loc, IV, true); 2716 2717 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2718 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2719 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2720 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2721 2722 ObjCIvarRefExpr *Result = new (Context) 2723 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2724 IV->getLocation(), SelfExpr.get(), true, true); 2725 2726 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2727 if (!isUnevaluatedContext() && 2728 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2729 getCurFunction()->recordUseOfWeak(Result); 2730 } 2731 if (getLangOpts().ObjCAutoRefCount) 2732 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2733 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2734 2735 return Result; 2736 } 2737 2738 /// The parser has read a name in, and Sema has detected that we're currently 2739 /// inside an ObjC method. Perform some additional checks and determine if we 2740 /// should form a reference to an ivar. If so, build an expression referencing 2741 /// that ivar. 2742 ExprResult 2743 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2744 IdentifierInfo *II, bool AllowBuiltinCreation) { 2745 // FIXME: Integrate this lookup step into LookupParsedName. 2746 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2747 if (Ivar.isInvalid()) 2748 return ExprError(); 2749 if (Ivar.isUsable()) 2750 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2751 cast<ObjCIvarDecl>(Ivar.get())); 2752 2753 if (Lookup.empty() && II && AllowBuiltinCreation) 2754 LookupBuiltin(Lookup); 2755 2756 // Sentinel value saying that we didn't do anything special. 2757 return ExprResult(false); 2758 } 2759 2760 /// Cast a base object to a member's actual type. 2761 /// 2762 /// Logically this happens in three phases: 2763 /// 2764 /// * First we cast from the base type to the naming class. 2765 /// The naming class is the class into which we were looking 2766 /// when we found the member; it's the qualifier type if a 2767 /// qualifier was provided, and otherwise it's the base type. 2768 /// 2769 /// * Next we cast from the naming class to the declaring class. 2770 /// If the member we found was brought into a class's scope by 2771 /// a using declaration, this is that class; otherwise it's 2772 /// the class declaring the member. 2773 /// 2774 /// * Finally we cast from the declaring class to the "true" 2775 /// declaring class of the member. This conversion does not 2776 /// obey access control. 2777 ExprResult 2778 Sema::PerformObjectMemberConversion(Expr *From, 2779 NestedNameSpecifier *Qualifier, 2780 NamedDecl *FoundDecl, 2781 NamedDecl *Member) { 2782 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2783 if (!RD) 2784 return From; 2785 2786 QualType DestRecordType; 2787 QualType DestType; 2788 QualType FromRecordType; 2789 QualType FromType = From->getType(); 2790 bool PointerConversions = false; 2791 if (isa<FieldDecl>(Member)) { 2792 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2793 auto FromPtrType = FromType->getAs<PointerType>(); 2794 DestRecordType = Context.getAddrSpaceQualType( 2795 DestRecordType, FromPtrType 2796 ? FromType->getPointeeType().getAddressSpace() 2797 : FromType.getAddressSpace()); 2798 2799 if (FromPtrType) { 2800 DestType = Context.getPointerType(DestRecordType); 2801 FromRecordType = FromPtrType->getPointeeType(); 2802 PointerConversions = true; 2803 } else { 2804 DestType = DestRecordType; 2805 FromRecordType = FromType; 2806 } 2807 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2808 if (Method->isStatic()) 2809 return From; 2810 2811 DestType = Method->getThisType(); 2812 DestRecordType = DestType->getPointeeType(); 2813 2814 if (FromType->getAs<PointerType>()) { 2815 FromRecordType = FromType->getPointeeType(); 2816 PointerConversions = true; 2817 } else { 2818 FromRecordType = FromType; 2819 DestType = DestRecordType; 2820 } 2821 2822 LangAS FromAS = FromRecordType.getAddressSpace(); 2823 LangAS DestAS = DestRecordType.getAddressSpace(); 2824 if (FromAS != DestAS) { 2825 QualType FromRecordTypeWithoutAS = 2826 Context.removeAddrSpaceQualType(FromRecordType); 2827 QualType FromTypeWithDestAS = 2828 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2829 if (PointerConversions) 2830 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2831 From = ImpCastExprToType(From, FromTypeWithDestAS, 2832 CK_AddressSpaceConversion, From->getValueKind()) 2833 .get(); 2834 } 2835 } else { 2836 // No conversion necessary. 2837 return From; 2838 } 2839 2840 if (DestType->isDependentType() || FromType->isDependentType()) 2841 return From; 2842 2843 // If the unqualified types are the same, no conversion is necessary. 2844 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2845 return From; 2846 2847 SourceRange FromRange = From->getSourceRange(); 2848 SourceLocation FromLoc = FromRange.getBegin(); 2849 2850 ExprValueKind VK = From->getValueKind(); 2851 2852 // C++ [class.member.lookup]p8: 2853 // [...] Ambiguities can often be resolved by qualifying a name with its 2854 // class name. 2855 // 2856 // If the member was a qualified name and the qualified referred to a 2857 // specific base subobject type, we'll cast to that intermediate type 2858 // first and then to the object in which the member is declared. That allows 2859 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2860 // 2861 // class Base { public: int x; }; 2862 // class Derived1 : public Base { }; 2863 // class Derived2 : public Base { }; 2864 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2865 // 2866 // void VeryDerived::f() { 2867 // x = 17; // error: ambiguous base subobjects 2868 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2869 // } 2870 if (Qualifier && Qualifier->getAsType()) { 2871 QualType QType = QualType(Qualifier->getAsType(), 0); 2872 assert(QType->isRecordType() && "lookup done with non-record type"); 2873 2874 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2875 2876 // In C++98, the qualifier type doesn't actually have to be a base 2877 // type of the object type, in which case we just ignore it. 2878 // Otherwise build the appropriate casts. 2879 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2880 CXXCastPath BasePath; 2881 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2882 FromLoc, FromRange, &BasePath)) 2883 return ExprError(); 2884 2885 if (PointerConversions) 2886 QType = Context.getPointerType(QType); 2887 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2888 VK, &BasePath).get(); 2889 2890 FromType = QType; 2891 FromRecordType = QRecordType; 2892 2893 // If the qualifier type was the same as the destination type, 2894 // we're done. 2895 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2896 return From; 2897 } 2898 } 2899 2900 bool IgnoreAccess = false; 2901 2902 // If we actually found the member through a using declaration, cast 2903 // down to the using declaration's type. 2904 // 2905 // Pointer equality is fine here because only one declaration of a 2906 // class ever has member declarations. 2907 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2908 assert(isa<UsingShadowDecl>(FoundDecl)); 2909 QualType URecordType = Context.getTypeDeclType( 2910 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2911 2912 // We only need to do this if the naming-class to declaring-class 2913 // conversion is non-trivial. 2914 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2915 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2916 CXXCastPath BasePath; 2917 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2918 FromLoc, FromRange, &BasePath)) 2919 return ExprError(); 2920 2921 QualType UType = URecordType; 2922 if (PointerConversions) 2923 UType = Context.getPointerType(UType); 2924 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2925 VK, &BasePath).get(); 2926 FromType = UType; 2927 FromRecordType = URecordType; 2928 } 2929 2930 // We don't do access control for the conversion from the 2931 // declaring class to the true declaring class. 2932 IgnoreAccess = true; 2933 } 2934 2935 CXXCastPath BasePath; 2936 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2937 FromLoc, FromRange, &BasePath, 2938 IgnoreAccess)) 2939 return ExprError(); 2940 2941 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2942 VK, &BasePath); 2943 } 2944 2945 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2946 const LookupResult &R, 2947 bool HasTrailingLParen) { 2948 // Only when used directly as the postfix-expression of a call. 2949 if (!HasTrailingLParen) 2950 return false; 2951 2952 // Never if a scope specifier was provided. 2953 if (SS.isSet()) 2954 return false; 2955 2956 // Only in C++ or ObjC++. 2957 if (!getLangOpts().CPlusPlus) 2958 return false; 2959 2960 // Turn off ADL when we find certain kinds of declarations during 2961 // normal lookup: 2962 for (NamedDecl *D : R) { 2963 // C++0x [basic.lookup.argdep]p3: 2964 // -- a declaration of a class member 2965 // Since using decls preserve this property, we check this on the 2966 // original decl. 2967 if (D->isCXXClassMember()) 2968 return false; 2969 2970 // C++0x [basic.lookup.argdep]p3: 2971 // -- a block-scope function declaration that is not a 2972 // using-declaration 2973 // NOTE: we also trigger this for function templates (in fact, we 2974 // don't check the decl type at all, since all other decl types 2975 // turn off ADL anyway). 2976 if (isa<UsingShadowDecl>(D)) 2977 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2978 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2979 return false; 2980 2981 // C++0x [basic.lookup.argdep]p3: 2982 // -- a declaration that is neither a function or a function 2983 // template 2984 // And also for builtin functions. 2985 if (isa<FunctionDecl>(D)) { 2986 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2987 2988 // But also builtin functions. 2989 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2990 return false; 2991 } else if (!isa<FunctionTemplateDecl>(D)) 2992 return false; 2993 } 2994 2995 return true; 2996 } 2997 2998 2999 /// Diagnoses obvious problems with the use of the given declaration 3000 /// as an expression. This is only actually called for lookups that 3001 /// were not overloaded, and it doesn't promise that the declaration 3002 /// will in fact be used. 3003 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3004 if (D->isInvalidDecl()) 3005 return true; 3006 3007 if (isa<TypedefNameDecl>(D)) { 3008 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3009 return true; 3010 } 3011 3012 if (isa<ObjCInterfaceDecl>(D)) { 3013 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3014 return true; 3015 } 3016 3017 if (isa<NamespaceDecl>(D)) { 3018 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3019 return true; 3020 } 3021 3022 return false; 3023 } 3024 3025 // Certain multiversion types should be treated as overloaded even when there is 3026 // only one result. 3027 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3028 assert(R.isSingleResult() && "Expected only a single result"); 3029 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3030 return FD && 3031 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3032 } 3033 3034 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3035 LookupResult &R, bool NeedsADL, 3036 bool AcceptInvalidDecl) { 3037 // If this is a single, fully-resolved result and we don't need ADL, 3038 // just build an ordinary singleton decl ref. 3039 if (!NeedsADL && R.isSingleResult() && 3040 !R.getAsSingle<FunctionTemplateDecl>() && 3041 !ShouldLookupResultBeMultiVersionOverload(R)) 3042 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3043 R.getRepresentativeDecl(), nullptr, 3044 AcceptInvalidDecl); 3045 3046 // We only need to check the declaration if there's exactly one 3047 // result, because in the overloaded case the results can only be 3048 // functions and function templates. 3049 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3050 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3051 return ExprError(); 3052 3053 // Otherwise, just build an unresolved lookup expression. Suppress 3054 // any lookup-related diagnostics; we'll hash these out later, when 3055 // we've picked a target. 3056 R.suppressDiagnostics(); 3057 3058 UnresolvedLookupExpr *ULE 3059 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3060 SS.getWithLocInContext(Context), 3061 R.getLookupNameInfo(), 3062 NeedsADL, R.isOverloadedResult(), 3063 R.begin(), R.end()); 3064 3065 return ULE; 3066 } 3067 3068 static void 3069 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3070 ValueDecl *var, DeclContext *DC); 3071 3072 /// Complete semantic analysis for a reference to the given declaration. 3073 ExprResult Sema::BuildDeclarationNameExpr( 3074 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3075 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3076 bool AcceptInvalidDecl) { 3077 assert(D && "Cannot refer to a NULL declaration"); 3078 assert(!isa<FunctionTemplateDecl>(D) && 3079 "Cannot refer unambiguously to a function template"); 3080 3081 SourceLocation Loc = NameInfo.getLoc(); 3082 if (CheckDeclInExpr(*this, Loc, D)) 3083 return ExprError(); 3084 3085 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3086 // Specifically diagnose references to class templates that are missing 3087 // a template argument list. 3088 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3089 return ExprError(); 3090 } 3091 3092 // Make sure that we're referring to a value. 3093 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3094 if (!VD) { 3095 Diag(Loc, diag::err_ref_non_value) 3096 << D << SS.getRange(); 3097 Diag(D->getLocation(), diag::note_declared_at); 3098 return ExprError(); 3099 } 3100 3101 // Check whether this declaration can be used. Note that we suppress 3102 // this check when we're going to perform argument-dependent lookup 3103 // on this function name, because this might not be the function 3104 // that overload resolution actually selects. 3105 if (DiagnoseUseOfDecl(VD, Loc)) 3106 return ExprError(); 3107 3108 // Only create DeclRefExpr's for valid Decl's. 3109 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3110 return ExprError(); 3111 3112 // Handle members of anonymous structs and unions. If we got here, 3113 // and the reference is to a class member indirect field, then this 3114 // must be the subject of a pointer-to-member expression. 3115 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3116 if (!indirectField->isCXXClassMember()) 3117 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3118 indirectField); 3119 3120 { 3121 QualType type = VD->getType(); 3122 if (type.isNull()) 3123 return ExprError(); 3124 ExprValueKind valueKind = VK_RValue; 3125 3126 switch (D->getKind()) { 3127 // Ignore all the non-ValueDecl kinds. 3128 #define ABSTRACT_DECL(kind) 3129 #define VALUE(type, base) 3130 #define DECL(type, base) \ 3131 case Decl::type: 3132 #include "clang/AST/DeclNodes.inc" 3133 llvm_unreachable("invalid value decl kind"); 3134 3135 // These shouldn't make it here. 3136 case Decl::ObjCAtDefsField: 3137 llvm_unreachable("forming non-member reference to ivar?"); 3138 3139 // Enum constants are always r-values and never references. 3140 // Unresolved using declarations are dependent. 3141 case Decl::EnumConstant: 3142 case Decl::UnresolvedUsingValue: 3143 case Decl::OMPDeclareReduction: 3144 case Decl::OMPDeclareMapper: 3145 valueKind = VK_RValue; 3146 break; 3147 3148 // Fields and indirect fields that got here must be for 3149 // pointer-to-member expressions; we just call them l-values for 3150 // internal consistency, because this subexpression doesn't really 3151 // exist in the high-level semantics. 3152 case Decl::Field: 3153 case Decl::IndirectField: 3154 case Decl::ObjCIvar: 3155 assert(getLangOpts().CPlusPlus && 3156 "building reference to field in C?"); 3157 3158 // These can't have reference type in well-formed programs, but 3159 // for internal consistency we do this anyway. 3160 type = type.getNonReferenceType(); 3161 valueKind = VK_LValue; 3162 break; 3163 3164 // Non-type template parameters are either l-values or r-values 3165 // depending on the type. 3166 case Decl::NonTypeTemplateParm: { 3167 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3168 type = reftype->getPointeeType(); 3169 valueKind = VK_LValue; // even if the parameter is an r-value reference 3170 break; 3171 } 3172 3173 // For non-references, we need to strip qualifiers just in case 3174 // the template parameter was declared as 'const int' or whatever. 3175 valueKind = VK_RValue; 3176 type = type.getUnqualifiedType(); 3177 break; 3178 } 3179 3180 case Decl::Var: 3181 case Decl::VarTemplateSpecialization: 3182 case Decl::VarTemplatePartialSpecialization: 3183 case Decl::Decomposition: 3184 case Decl::OMPCapturedExpr: 3185 // In C, "extern void blah;" is valid and is an r-value. 3186 if (!getLangOpts().CPlusPlus && 3187 !type.hasQualifiers() && 3188 type->isVoidType()) { 3189 valueKind = VK_RValue; 3190 break; 3191 } 3192 LLVM_FALLTHROUGH; 3193 3194 case Decl::ImplicitParam: 3195 case Decl::ParmVar: { 3196 // These are always l-values. 3197 valueKind = VK_LValue; 3198 type = type.getNonReferenceType(); 3199 3200 // FIXME: Does the addition of const really only apply in 3201 // potentially-evaluated contexts? Since the variable isn't actually 3202 // captured in an unevaluated context, it seems that the answer is no. 3203 if (!isUnevaluatedContext()) { 3204 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3205 if (!CapturedType.isNull()) 3206 type = CapturedType; 3207 } 3208 3209 break; 3210 } 3211 3212 case Decl::Binding: { 3213 // These are always lvalues. 3214 valueKind = VK_LValue; 3215 type = type.getNonReferenceType(); 3216 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3217 // decides how that's supposed to work. 3218 auto *BD = cast<BindingDecl>(VD); 3219 if (BD->getDeclContext() != CurContext) { 3220 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3221 if (DD && DD->hasLocalStorage()) 3222 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3223 } 3224 break; 3225 } 3226 3227 case Decl::Function: { 3228 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3229 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3230 type = Context.BuiltinFnTy; 3231 valueKind = VK_RValue; 3232 break; 3233 } 3234 } 3235 3236 const FunctionType *fty = type->castAs<FunctionType>(); 3237 3238 // If we're referring to a function with an __unknown_anytype 3239 // result type, make the entire expression __unknown_anytype. 3240 if (fty->getReturnType() == Context.UnknownAnyTy) { 3241 type = Context.UnknownAnyTy; 3242 valueKind = VK_RValue; 3243 break; 3244 } 3245 3246 // Functions are l-values in C++. 3247 if (getLangOpts().CPlusPlus) { 3248 valueKind = VK_LValue; 3249 break; 3250 } 3251 3252 // C99 DR 316 says that, if a function type comes from a 3253 // function definition (without a prototype), that type is only 3254 // used for checking compatibility. Therefore, when referencing 3255 // the function, we pretend that we don't have the full function 3256 // type. 3257 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3258 isa<FunctionProtoType>(fty)) 3259 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3260 fty->getExtInfo()); 3261 3262 // Functions are r-values in C. 3263 valueKind = VK_RValue; 3264 break; 3265 } 3266 3267 case Decl::CXXDeductionGuide: 3268 llvm_unreachable("building reference to deduction guide"); 3269 3270 case Decl::MSProperty: 3271 valueKind = VK_LValue; 3272 break; 3273 3274 case Decl::CXXMethod: 3275 // If we're referring to a method with an __unknown_anytype 3276 // result type, make the entire expression __unknown_anytype. 3277 // This should only be possible with a type written directly. 3278 if (const FunctionProtoType *proto 3279 = dyn_cast<FunctionProtoType>(VD->getType())) 3280 if (proto->getReturnType() == Context.UnknownAnyTy) { 3281 type = Context.UnknownAnyTy; 3282 valueKind = VK_RValue; 3283 break; 3284 } 3285 3286 // C++ methods are l-values if static, r-values if non-static. 3287 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3288 valueKind = VK_LValue; 3289 break; 3290 } 3291 LLVM_FALLTHROUGH; 3292 3293 case Decl::CXXConversion: 3294 case Decl::CXXDestructor: 3295 case Decl::CXXConstructor: 3296 valueKind = VK_RValue; 3297 break; 3298 } 3299 3300 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3301 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3302 TemplateArgs); 3303 } 3304 } 3305 3306 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3307 SmallString<32> &Target) { 3308 Target.resize(CharByteWidth * (Source.size() + 1)); 3309 char *ResultPtr = &Target[0]; 3310 const llvm::UTF8 *ErrorPtr; 3311 bool success = 3312 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3313 (void)success; 3314 assert(success); 3315 Target.resize(ResultPtr - &Target[0]); 3316 } 3317 3318 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3319 PredefinedExpr::IdentKind IK) { 3320 // Pick the current block, lambda, captured statement or function. 3321 Decl *currentDecl = nullptr; 3322 if (const BlockScopeInfo *BSI = getCurBlock()) 3323 currentDecl = BSI->TheDecl; 3324 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3325 currentDecl = LSI->CallOperator; 3326 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3327 currentDecl = CSI->TheCapturedDecl; 3328 else 3329 currentDecl = getCurFunctionOrMethodDecl(); 3330 3331 if (!currentDecl) { 3332 Diag(Loc, diag::ext_predef_outside_function); 3333 currentDecl = Context.getTranslationUnitDecl(); 3334 } 3335 3336 QualType ResTy; 3337 StringLiteral *SL = nullptr; 3338 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3339 ResTy = Context.DependentTy; 3340 else { 3341 // Pre-defined identifiers are of type char[x], where x is the length of 3342 // the string. 3343 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3344 unsigned Length = Str.length(); 3345 3346 llvm::APInt LengthI(32, Length + 1); 3347 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3348 ResTy = 3349 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3350 SmallString<32> RawChars; 3351 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3352 Str, RawChars); 3353 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3354 ArrayType::Normal, 3355 /*IndexTypeQuals*/ 0); 3356 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3357 /*Pascal*/ false, ResTy, Loc); 3358 } else { 3359 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3360 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3361 ArrayType::Normal, 3362 /*IndexTypeQuals*/ 0); 3363 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3364 /*Pascal*/ false, ResTy, Loc); 3365 } 3366 } 3367 3368 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3369 } 3370 3371 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3372 PredefinedExpr::IdentKind IK; 3373 3374 switch (Kind) { 3375 default: llvm_unreachable("Unknown simple primary expr!"); 3376 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3377 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3378 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3379 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3380 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3381 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3382 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3383 } 3384 3385 return BuildPredefinedExpr(Loc, IK); 3386 } 3387 3388 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3389 SmallString<16> CharBuffer; 3390 bool Invalid = false; 3391 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3392 if (Invalid) 3393 return ExprError(); 3394 3395 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3396 PP, Tok.getKind()); 3397 if (Literal.hadError()) 3398 return ExprError(); 3399 3400 QualType Ty; 3401 if (Literal.isWide()) 3402 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3403 else if (Literal.isUTF8() && getLangOpts().Char8) 3404 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3405 else if (Literal.isUTF16()) 3406 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3407 else if (Literal.isUTF32()) 3408 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3409 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3410 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3411 else 3412 Ty = Context.CharTy; // 'x' -> char in C++ 3413 3414 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3415 if (Literal.isWide()) 3416 Kind = CharacterLiteral::Wide; 3417 else if (Literal.isUTF16()) 3418 Kind = CharacterLiteral::UTF16; 3419 else if (Literal.isUTF32()) 3420 Kind = CharacterLiteral::UTF32; 3421 else if (Literal.isUTF8()) 3422 Kind = CharacterLiteral::UTF8; 3423 3424 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3425 Tok.getLocation()); 3426 3427 if (Literal.getUDSuffix().empty()) 3428 return Lit; 3429 3430 // We're building a user-defined literal. 3431 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3432 SourceLocation UDSuffixLoc = 3433 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3434 3435 // Make sure we're allowed user-defined literals here. 3436 if (!UDLScope) 3437 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3438 3439 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3440 // operator "" X (ch) 3441 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3442 Lit, Tok.getLocation()); 3443 } 3444 3445 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3446 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3447 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3448 Context.IntTy, Loc); 3449 } 3450 3451 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3452 QualType Ty, SourceLocation Loc) { 3453 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3454 3455 using llvm::APFloat; 3456 APFloat Val(Format); 3457 3458 APFloat::opStatus result = Literal.GetFloatValue(Val); 3459 3460 // Overflow is always an error, but underflow is only an error if 3461 // we underflowed to zero (APFloat reports denormals as underflow). 3462 if ((result & APFloat::opOverflow) || 3463 ((result & APFloat::opUnderflow) && Val.isZero())) { 3464 unsigned diagnostic; 3465 SmallString<20> buffer; 3466 if (result & APFloat::opOverflow) { 3467 diagnostic = diag::warn_float_overflow; 3468 APFloat::getLargest(Format).toString(buffer); 3469 } else { 3470 diagnostic = diag::warn_float_underflow; 3471 APFloat::getSmallest(Format).toString(buffer); 3472 } 3473 3474 S.Diag(Loc, diagnostic) 3475 << Ty 3476 << StringRef(buffer.data(), buffer.size()); 3477 } 3478 3479 bool isExact = (result == APFloat::opOK); 3480 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3481 } 3482 3483 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3484 assert(E && "Invalid expression"); 3485 3486 if (E->isValueDependent()) 3487 return false; 3488 3489 QualType QT = E->getType(); 3490 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3491 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3492 return true; 3493 } 3494 3495 llvm::APSInt ValueAPS; 3496 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3497 3498 if (R.isInvalid()) 3499 return true; 3500 3501 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3502 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3503 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3504 << ValueAPS.toString(10) << ValueIsPositive; 3505 return true; 3506 } 3507 3508 return false; 3509 } 3510 3511 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3512 // Fast path for a single digit (which is quite common). A single digit 3513 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3514 if (Tok.getLength() == 1) { 3515 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3516 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3517 } 3518 3519 SmallString<128> SpellingBuffer; 3520 // NumericLiteralParser wants to overread by one character. Add padding to 3521 // the buffer in case the token is copied to the buffer. If getSpelling() 3522 // returns a StringRef to the memory buffer, it should have a null char at 3523 // the EOF, so it is also safe. 3524 SpellingBuffer.resize(Tok.getLength() + 1); 3525 3526 // Get the spelling of the token, which eliminates trigraphs, etc. 3527 bool Invalid = false; 3528 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3529 if (Invalid) 3530 return ExprError(); 3531 3532 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3533 if (Literal.hadError) 3534 return ExprError(); 3535 3536 if (Literal.hasUDSuffix()) { 3537 // We're building a user-defined literal. 3538 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3539 SourceLocation UDSuffixLoc = 3540 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3541 3542 // Make sure we're allowed user-defined literals here. 3543 if (!UDLScope) 3544 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3545 3546 QualType CookedTy; 3547 if (Literal.isFloatingLiteral()) { 3548 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3549 // long double, the literal is treated as a call of the form 3550 // operator "" X (f L) 3551 CookedTy = Context.LongDoubleTy; 3552 } else { 3553 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3554 // unsigned long long, the literal is treated as a call of the form 3555 // operator "" X (n ULL) 3556 CookedTy = Context.UnsignedLongLongTy; 3557 } 3558 3559 DeclarationName OpName = 3560 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3561 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3562 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3563 3564 SourceLocation TokLoc = Tok.getLocation(); 3565 3566 // Perform literal operator lookup to determine if we're building a raw 3567 // literal or a cooked one. 3568 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3569 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3570 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3571 /*AllowStringTemplate*/ false, 3572 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3573 case LOLR_ErrorNoDiagnostic: 3574 // Lookup failure for imaginary constants isn't fatal, there's still the 3575 // GNU extension producing _Complex types. 3576 break; 3577 case LOLR_Error: 3578 return ExprError(); 3579 case LOLR_Cooked: { 3580 Expr *Lit; 3581 if (Literal.isFloatingLiteral()) { 3582 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3583 } else { 3584 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3585 if (Literal.GetIntegerValue(ResultVal)) 3586 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3587 << /* Unsigned */ 1; 3588 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3589 Tok.getLocation()); 3590 } 3591 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3592 } 3593 3594 case LOLR_Raw: { 3595 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3596 // literal is treated as a call of the form 3597 // operator "" X ("n") 3598 unsigned Length = Literal.getUDSuffixOffset(); 3599 QualType StrTy = Context.getConstantArrayType( 3600 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3601 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3602 Expr *Lit = StringLiteral::Create( 3603 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3604 /*Pascal*/false, StrTy, &TokLoc, 1); 3605 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3606 } 3607 3608 case LOLR_Template: { 3609 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3610 // template), L is treated as a call fo the form 3611 // operator "" X <'c1', 'c2', ... 'ck'>() 3612 // where n is the source character sequence c1 c2 ... ck. 3613 TemplateArgumentListInfo ExplicitArgs; 3614 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3615 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3616 llvm::APSInt Value(CharBits, CharIsUnsigned); 3617 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3618 Value = TokSpelling[I]; 3619 TemplateArgument Arg(Context, Value, Context.CharTy); 3620 TemplateArgumentLocInfo ArgInfo; 3621 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3622 } 3623 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3624 &ExplicitArgs); 3625 } 3626 case LOLR_StringTemplate: 3627 llvm_unreachable("unexpected literal operator lookup result"); 3628 } 3629 } 3630 3631 Expr *Res; 3632 3633 if (Literal.isFixedPointLiteral()) { 3634 QualType Ty; 3635 3636 if (Literal.isAccum) { 3637 if (Literal.isHalf) { 3638 Ty = Context.ShortAccumTy; 3639 } else if (Literal.isLong) { 3640 Ty = Context.LongAccumTy; 3641 } else { 3642 Ty = Context.AccumTy; 3643 } 3644 } else if (Literal.isFract) { 3645 if (Literal.isHalf) { 3646 Ty = Context.ShortFractTy; 3647 } else if (Literal.isLong) { 3648 Ty = Context.LongFractTy; 3649 } else { 3650 Ty = Context.FractTy; 3651 } 3652 } 3653 3654 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3655 3656 bool isSigned = !Literal.isUnsigned; 3657 unsigned scale = Context.getFixedPointScale(Ty); 3658 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3659 3660 llvm::APInt Val(bit_width, 0, isSigned); 3661 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3662 bool ValIsZero = Val.isNullValue() && !Overflowed; 3663 3664 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3665 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3666 // Clause 6.4.4 - The value of a constant shall be in the range of 3667 // representable values for its type, with exception for constants of a 3668 // fract type with a value of exactly 1; such a constant shall denote 3669 // the maximal value for the type. 3670 --Val; 3671 else if (Val.ugt(MaxVal) || Overflowed) 3672 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3673 3674 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3675 Tok.getLocation(), scale); 3676 } else if (Literal.isFloatingLiteral()) { 3677 QualType Ty; 3678 if (Literal.isHalf){ 3679 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3680 Ty = Context.HalfTy; 3681 else { 3682 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3683 return ExprError(); 3684 } 3685 } else if (Literal.isFloat) 3686 Ty = Context.FloatTy; 3687 else if (Literal.isLong) 3688 Ty = Context.LongDoubleTy; 3689 else if (Literal.isFloat16) 3690 Ty = Context.Float16Ty; 3691 else if (Literal.isFloat128) 3692 Ty = Context.Float128Ty; 3693 else 3694 Ty = Context.DoubleTy; 3695 3696 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3697 3698 if (Ty == Context.DoubleTy) { 3699 if (getLangOpts().SinglePrecisionConstants) { 3700 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3701 if (BTy->getKind() != BuiltinType::Float) { 3702 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3703 } 3704 } else if (getLangOpts().OpenCL && 3705 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3706 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3707 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3708 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3709 } 3710 } 3711 } else if (!Literal.isIntegerLiteral()) { 3712 return ExprError(); 3713 } else { 3714 QualType Ty; 3715 3716 // 'long long' is a C99 or C++11 feature. 3717 if (!getLangOpts().C99 && Literal.isLongLong) { 3718 if (getLangOpts().CPlusPlus) 3719 Diag(Tok.getLocation(), 3720 getLangOpts().CPlusPlus11 ? 3721 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3722 else 3723 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3724 } 3725 3726 // Get the value in the widest-possible width. 3727 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3728 llvm::APInt ResultVal(MaxWidth, 0); 3729 3730 if (Literal.GetIntegerValue(ResultVal)) { 3731 // If this value didn't fit into uintmax_t, error and force to ull. 3732 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3733 << /* Unsigned */ 1; 3734 Ty = Context.UnsignedLongLongTy; 3735 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3736 "long long is not intmax_t?"); 3737 } else { 3738 // If this value fits into a ULL, try to figure out what else it fits into 3739 // according to the rules of C99 6.4.4.1p5. 3740 3741 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3742 // be an unsigned int. 3743 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3744 3745 // Check from smallest to largest, picking the smallest type we can. 3746 unsigned Width = 0; 3747 3748 // Microsoft specific integer suffixes are explicitly sized. 3749 if (Literal.MicrosoftInteger) { 3750 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3751 Width = 8; 3752 Ty = Context.CharTy; 3753 } else { 3754 Width = Literal.MicrosoftInteger; 3755 Ty = Context.getIntTypeForBitwidth(Width, 3756 /*Signed=*/!Literal.isUnsigned); 3757 } 3758 } 3759 3760 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3761 // Are int/unsigned possibilities? 3762 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3763 3764 // Does it fit in a unsigned int? 3765 if (ResultVal.isIntN(IntSize)) { 3766 // Does it fit in a signed int? 3767 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3768 Ty = Context.IntTy; 3769 else if (AllowUnsigned) 3770 Ty = Context.UnsignedIntTy; 3771 Width = IntSize; 3772 } 3773 } 3774 3775 // Are long/unsigned long possibilities? 3776 if (Ty.isNull() && !Literal.isLongLong) { 3777 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3778 3779 // Does it fit in a unsigned long? 3780 if (ResultVal.isIntN(LongSize)) { 3781 // Does it fit in a signed long? 3782 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3783 Ty = Context.LongTy; 3784 else if (AllowUnsigned) 3785 Ty = Context.UnsignedLongTy; 3786 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3787 // is compatible. 3788 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3789 const unsigned LongLongSize = 3790 Context.getTargetInfo().getLongLongWidth(); 3791 Diag(Tok.getLocation(), 3792 getLangOpts().CPlusPlus 3793 ? Literal.isLong 3794 ? diag::warn_old_implicitly_unsigned_long_cxx 3795 : /*C++98 UB*/ diag:: 3796 ext_old_implicitly_unsigned_long_cxx 3797 : diag::warn_old_implicitly_unsigned_long) 3798 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3799 : /*will be ill-formed*/ 1); 3800 Ty = Context.UnsignedLongTy; 3801 } 3802 Width = LongSize; 3803 } 3804 } 3805 3806 // Check long long if needed. 3807 if (Ty.isNull()) { 3808 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3809 3810 // Does it fit in a unsigned long long? 3811 if (ResultVal.isIntN(LongLongSize)) { 3812 // Does it fit in a signed long long? 3813 // To be compatible with MSVC, hex integer literals ending with the 3814 // LL or i64 suffix are always signed in Microsoft mode. 3815 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3816 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3817 Ty = Context.LongLongTy; 3818 else if (AllowUnsigned) 3819 Ty = Context.UnsignedLongLongTy; 3820 Width = LongLongSize; 3821 } 3822 } 3823 3824 // If we still couldn't decide a type, we probably have something that 3825 // does not fit in a signed long long, but has no U suffix. 3826 if (Ty.isNull()) { 3827 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3828 Ty = Context.UnsignedLongLongTy; 3829 Width = Context.getTargetInfo().getLongLongWidth(); 3830 } 3831 3832 if (ResultVal.getBitWidth() != Width) 3833 ResultVal = ResultVal.trunc(Width); 3834 } 3835 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3836 } 3837 3838 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3839 if (Literal.isImaginary) { 3840 Res = new (Context) ImaginaryLiteral(Res, 3841 Context.getComplexType(Res->getType())); 3842 3843 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3844 } 3845 return Res; 3846 } 3847 3848 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3849 assert(E && "ActOnParenExpr() missing expr"); 3850 return new (Context) ParenExpr(L, R, E); 3851 } 3852 3853 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3854 SourceLocation Loc, 3855 SourceRange ArgRange) { 3856 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3857 // scalar or vector data type argument..." 3858 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3859 // type (C99 6.2.5p18) or void. 3860 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3861 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3862 << T << ArgRange; 3863 return true; 3864 } 3865 3866 assert((T->isVoidType() || !T->isIncompleteType()) && 3867 "Scalar types should always be complete"); 3868 return false; 3869 } 3870 3871 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3872 SourceLocation Loc, 3873 SourceRange ArgRange, 3874 UnaryExprOrTypeTrait TraitKind) { 3875 // Invalid types must be hard errors for SFINAE in C++. 3876 if (S.LangOpts.CPlusPlus) 3877 return true; 3878 3879 // C99 6.5.3.4p1: 3880 if (T->isFunctionType() && 3881 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3882 TraitKind == UETT_PreferredAlignOf)) { 3883 // sizeof(function)/alignof(function) is allowed as an extension. 3884 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3885 << TraitKind << ArgRange; 3886 return false; 3887 } 3888 3889 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3890 // this is an error (OpenCL v1.1 s6.3.k) 3891 if (T->isVoidType()) { 3892 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3893 : diag::ext_sizeof_alignof_void_type; 3894 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3895 return false; 3896 } 3897 3898 return true; 3899 } 3900 3901 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3902 SourceLocation Loc, 3903 SourceRange ArgRange, 3904 UnaryExprOrTypeTrait TraitKind) { 3905 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3906 // runtime doesn't allow it. 3907 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3908 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3909 << T << (TraitKind == UETT_SizeOf) 3910 << ArgRange; 3911 return true; 3912 } 3913 3914 return false; 3915 } 3916 3917 /// Check whether E is a pointer from a decayed array type (the decayed 3918 /// pointer type is equal to T) and emit a warning if it is. 3919 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3920 Expr *E) { 3921 // Don't warn if the operation changed the type. 3922 if (T != E->getType()) 3923 return; 3924 3925 // Now look for array decays. 3926 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3927 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3928 return; 3929 3930 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3931 << ICE->getType() 3932 << ICE->getSubExpr()->getType(); 3933 } 3934 3935 /// Check the constraints on expression operands to unary type expression 3936 /// and type traits. 3937 /// 3938 /// Completes any types necessary and validates the constraints on the operand 3939 /// expression. The logic mostly mirrors the type-based overload, but may modify 3940 /// the expression as it completes the type for that expression through template 3941 /// instantiation, etc. 3942 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3943 UnaryExprOrTypeTrait ExprKind) { 3944 QualType ExprTy = E->getType(); 3945 assert(!ExprTy->isReferenceType()); 3946 3947 bool IsUnevaluatedOperand = 3948 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3949 ExprKind == UETT_PreferredAlignOf); 3950 if (IsUnevaluatedOperand) { 3951 ExprResult Result = CheckUnevaluatedOperand(E); 3952 if (Result.isInvalid()) 3953 return true; 3954 E = Result.get(); 3955 } 3956 3957 if (ExprKind == UETT_VecStep) 3958 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3959 E->getSourceRange()); 3960 3961 // Whitelist some types as extensions 3962 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3963 E->getSourceRange(), ExprKind)) 3964 return false; 3965 3966 // 'alignof' applied to an expression only requires the base element type of 3967 // the expression to be complete. 'sizeof' requires the expression's type to 3968 // be complete (and will attempt to complete it if it's an array of unknown 3969 // bound). 3970 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3971 if (RequireCompleteType(E->getExprLoc(), 3972 Context.getBaseElementType(E->getType()), 3973 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3974 E->getSourceRange())) 3975 return true; 3976 } else { 3977 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3978 ExprKind, E->getSourceRange())) 3979 return true; 3980 } 3981 3982 // Completing the expression's type may have changed it. 3983 ExprTy = E->getType(); 3984 assert(!ExprTy->isReferenceType()); 3985 3986 if (ExprTy->isFunctionType()) { 3987 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3988 << ExprKind << E->getSourceRange(); 3989 return true; 3990 } 3991 3992 // The operand for sizeof and alignof is in an unevaluated expression context, 3993 // so side effects could result in unintended consequences. 3994 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3995 E->HasSideEffects(Context, false)) 3996 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3997 3998 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3999 E->getSourceRange(), ExprKind)) 4000 return true; 4001 4002 if (ExprKind == UETT_SizeOf) { 4003 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4004 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4005 QualType OType = PVD->getOriginalType(); 4006 QualType Type = PVD->getType(); 4007 if (Type->isPointerType() && OType->isArrayType()) { 4008 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4009 << Type << OType; 4010 Diag(PVD->getLocation(), diag::note_declared_at); 4011 } 4012 } 4013 } 4014 4015 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4016 // decays into a pointer and returns an unintended result. This is most 4017 // likely a typo for "sizeof(array) op x". 4018 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4019 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4020 BO->getLHS()); 4021 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4022 BO->getRHS()); 4023 } 4024 } 4025 4026 return false; 4027 } 4028 4029 /// Check the constraints on operands to unary expression and type 4030 /// traits. 4031 /// 4032 /// This will complete any types necessary, and validate the various constraints 4033 /// on those operands. 4034 /// 4035 /// The UsualUnaryConversions() function is *not* called by this routine. 4036 /// C99 6.3.2.1p[2-4] all state: 4037 /// Except when it is the operand of the sizeof operator ... 4038 /// 4039 /// C++ [expr.sizeof]p4 4040 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4041 /// standard conversions are not applied to the operand of sizeof. 4042 /// 4043 /// This policy is followed for all of the unary trait expressions. 4044 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4045 SourceLocation OpLoc, 4046 SourceRange ExprRange, 4047 UnaryExprOrTypeTrait ExprKind) { 4048 if (ExprType->isDependentType()) 4049 return false; 4050 4051 // C++ [expr.sizeof]p2: 4052 // When applied to a reference or a reference type, the result 4053 // is the size of the referenced type. 4054 // C++11 [expr.alignof]p3: 4055 // When alignof is applied to a reference type, the result 4056 // shall be the alignment of the referenced type. 4057 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4058 ExprType = Ref->getPointeeType(); 4059 4060 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4061 // When alignof or _Alignof is applied to an array type, the result 4062 // is the alignment of the element type. 4063 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4064 ExprKind == UETT_OpenMPRequiredSimdAlign) 4065 ExprType = Context.getBaseElementType(ExprType); 4066 4067 if (ExprKind == UETT_VecStep) 4068 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4069 4070 // Whitelist some types as extensions 4071 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4072 ExprKind)) 4073 return false; 4074 4075 if (RequireCompleteType(OpLoc, ExprType, 4076 diag::err_sizeof_alignof_incomplete_type, 4077 ExprKind, ExprRange)) 4078 return true; 4079 4080 if (ExprType->isFunctionType()) { 4081 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4082 << ExprKind << ExprRange; 4083 return true; 4084 } 4085 4086 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4087 ExprKind)) 4088 return true; 4089 4090 return false; 4091 } 4092 4093 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4094 // Cannot know anything else if the expression is dependent. 4095 if (E->isTypeDependent()) 4096 return false; 4097 4098 if (E->getObjectKind() == OK_BitField) { 4099 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4100 << 1 << E->getSourceRange(); 4101 return true; 4102 } 4103 4104 ValueDecl *D = nullptr; 4105 Expr *Inner = E->IgnoreParens(); 4106 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4107 D = DRE->getDecl(); 4108 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4109 D = ME->getMemberDecl(); 4110 } 4111 4112 // If it's a field, require the containing struct to have a 4113 // complete definition so that we can compute the layout. 4114 // 4115 // This can happen in C++11 onwards, either by naming the member 4116 // in a way that is not transformed into a member access expression 4117 // (in an unevaluated operand, for instance), or by naming the member 4118 // in a trailing-return-type. 4119 // 4120 // For the record, since __alignof__ on expressions is a GCC 4121 // extension, GCC seems to permit this but always gives the 4122 // nonsensical answer 0. 4123 // 4124 // We don't really need the layout here --- we could instead just 4125 // directly check for all the appropriate alignment-lowing 4126 // attributes --- but that would require duplicating a lot of 4127 // logic that just isn't worth duplicating for such a marginal 4128 // use-case. 4129 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4130 // Fast path this check, since we at least know the record has a 4131 // definition if we can find a member of it. 4132 if (!FD->getParent()->isCompleteDefinition()) { 4133 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4134 << E->getSourceRange(); 4135 return true; 4136 } 4137 4138 // Otherwise, if it's a field, and the field doesn't have 4139 // reference type, then it must have a complete type (or be a 4140 // flexible array member, which we explicitly want to 4141 // white-list anyway), which makes the following checks trivial. 4142 if (!FD->getType()->isReferenceType()) 4143 return false; 4144 } 4145 4146 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4147 } 4148 4149 bool Sema::CheckVecStepExpr(Expr *E) { 4150 E = E->IgnoreParens(); 4151 4152 // Cannot know anything else if the expression is dependent. 4153 if (E->isTypeDependent()) 4154 return false; 4155 4156 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4157 } 4158 4159 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4160 CapturingScopeInfo *CSI) { 4161 assert(T->isVariablyModifiedType()); 4162 assert(CSI != nullptr); 4163 4164 // We're going to walk down into the type and look for VLA expressions. 4165 do { 4166 const Type *Ty = T.getTypePtr(); 4167 switch (Ty->getTypeClass()) { 4168 #define TYPE(Class, Base) 4169 #define ABSTRACT_TYPE(Class, Base) 4170 #define NON_CANONICAL_TYPE(Class, Base) 4171 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4172 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4173 #include "clang/AST/TypeNodes.inc" 4174 T = QualType(); 4175 break; 4176 // These types are never variably-modified. 4177 case Type::Builtin: 4178 case Type::Complex: 4179 case Type::Vector: 4180 case Type::ExtVector: 4181 case Type::Record: 4182 case Type::Enum: 4183 case Type::Elaborated: 4184 case Type::TemplateSpecialization: 4185 case Type::ObjCObject: 4186 case Type::ObjCInterface: 4187 case Type::ObjCObjectPointer: 4188 case Type::ObjCTypeParam: 4189 case Type::Pipe: 4190 llvm_unreachable("type class is never variably-modified!"); 4191 case Type::Adjusted: 4192 T = cast<AdjustedType>(Ty)->getOriginalType(); 4193 break; 4194 case Type::Decayed: 4195 T = cast<DecayedType>(Ty)->getPointeeType(); 4196 break; 4197 case Type::Pointer: 4198 T = cast<PointerType>(Ty)->getPointeeType(); 4199 break; 4200 case Type::BlockPointer: 4201 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4202 break; 4203 case Type::LValueReference: 4204 case Type::RValueReference: 4205 T = cast<ReferenceType>(Ty)->getPointeeType(); 4206 break; 4207 case Type::MemberPointer: 4208 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4209 break; 4210 case Type::ConstantArray: 4211 case Type::IncompleteArray: 4212 // Losing element qualification here is fine. 4213 T = cast<ArrayType>(Ty)->getElementType(); 4214 break; 4215 case Type::VariableArray: { 4216 // Losing element qualification here is fine. 4217 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4218 4219 // Unknown size indication requires no size computation. 4220 // Otherwise, evaluate and record it. 4221 auto Size = VAT->getSizeExpr(); 4222 if (Size && !CSI->isVLATypeCaptured(VAT) && 4223 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4224 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4225 4226 T = VAT->getElementType(); 4227 break; 4228 } 4229 case Type::FunctionProto: 4230 case Type::FunctionNoProto: 4231 T = cast<FunctionType>(Ty)->getReturnType(); 4232 break; 4233 case Type::Paren: 4234 case Type::TypeOf: 4235 case Type::UnaryTransform: 4236 case Type::Attributed: 4237 case Type::SubstTemplateTypeParm: 4238 case Type::PackExpansion: 4239 case Type::MacroQualified: 4240 // Keep walking after single level desugaring. 4241 T = T.getSingleStepDesugaredType(Context); 4242 break; 4243 case Type::Typedef: 4244 T = cast<TypedefType>(Ty)->desugar(); 4245 break; 4246 case Type::Decltype: 4247 T = cast<DecltypeType>(Ty)->desugar(); 4248 break; 4249 case Type::Auto: 4250 case Type::DeducedTemplateSpecialization: 4251 T = cast<DeducedType>(Ty)->getDeducedType(); 4252 break; 4253 case Type::TypeOfExpr: 4254 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4255 break; 4256 case Type::Atomic: 4257 T = cast<AtomicType>(Ty)->getValueType(); 4258 break; 4259 } 4260 } while (!T.isNull() && T->isVariablyModifiedType()); 4261 } 4262 4263 /// Build a sizeof or alignof expression given a type operand. 4264 ExprResult 4265 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4266 SourceLocation OpLoc, 4267 UnaryExprOrTypeTrait ExprKind, 4268 SourceRange R) { 4269 if (!TInfo) 4270 return ExprError(); 4271 4272 QualType T = TInfo->getType(); 4273 4274 if (!T->isDependentType() && 4275 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4276 return ExprError(); 4277 4278 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4279 if (auto *TT = T->getAs<TypedefType>()) { 4280 for (auto I = FunctionScopes.rbegin(), 4281 E = std::prev(FunctionScopes.rend()); 4282 I != E; ++I) { 4283 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4284 if (CSI == nullptr) 4285 break; 4286 DeclContext *DC = nullptr; 4287 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4288 DC = LSI->CallOperator; 4289 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4290 DC = CRSI->TheCapturedDecl; 4291 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4292 DC = BSI->TheDecl; 4293 if (DC) { 4294 if (DC->containsDecl(TT->getDecl())) 4295 break; 4296 captureVariablyModifiedType(Context, T, CSI); 4297 } 4298 } 4299 } 4300 } 4301 4302 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4303 return new (Context) UnaryExprOrTypeTraitExpr( 4304 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4305 } 4306 4307 /// Build a sizeof or alignof expression given an expression 4308 /// operand. 4309 ExprResult 4310 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4311 UnaryExprOrTypeTrait ExprKind) { 4312 ExprResult PE = CheckPlaceholderExpr(E); 4313 if (PE.isInvalid()) 4314 return ExprError(); 4315 4316 E = PE.get(); 4317 4318 // Verify that the operand is valid. 4319 bool isInvalid = false; 4320 if (E->isTypeDependent()) { 4321 // Delay type-checking for type-dependent expressions. 4322 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4323 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4324 } else if (ExprKind == UETT_VecStep) { 4325 isInvalid = CheckVecStepExpr(E); 4326 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4327 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4328 isInvalid = true; 4329 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4330 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4331 isInvalid = true; 4332 } else { 4333 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4334 } 4335 4336 if (isInvalid) 4337 return ExprError(); 4338 4339 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4340 PE = TransformToPotentiallyEvaluated(E); 4341 if (PE.isInvalid()) return ExprError(); 4342 E = PE.get(); 4343 } 4344 4345 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4346 return new (Context) UnaryExprOrTypeTraitExpr( 4347 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4348 } 4349 4350 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4351 /// expr and the same for @c alignof and @c __alignof 4352 /// Note that the ArgRange is invalid if isType is false. 4353 ExprResult 4354 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4355 UnaryExprOrTypeTrait ExprKind, bool IsType, 4356 void *TyOrEx, SourceRange ArgRange) { 4357 // If error parsing type, ignore. 4358 if (!TyOrEx) return ExprError(); 4359 4360 if (IsType) { 4361 TypeSourceInfo *TInfo; 4362 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4363 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4364 } 4365 4366 Expr *ArgEx = (Expr *)TyOrEx; 4367 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4368 return Result; 4369 } 4370 4371 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4372 bool IsReal) { 4373 if (V.get()->isTypeDependent()) 4374 return S.Context.DependentTy; 4375 4376 // _Real and _Imag are only l-values for normal l-values. 4377 if (V.get()->getObjectKind() != OK_Ordinary) { 4378 V = S.DefaultLvalueConversion(V.get()); 4379 if (V.isInvalid()) 4380 return QualType(); 4381 } 4382 4383 // These operators return the element type of a complex type. 4384 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4385 return CT->getElementType(); 4386 4387 // Otherwise they pass through real integer and floating point types here. 4388 if (V.get()->getType()->isArithmeticType()) 4389 return V.get()->getType(); 4390 4391 // Test for placeholders. 4392 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4393 if (PR.isInvalid()) return QualType(); 4394 if (PR.get() != V.get()) { 4395 V = PR; 4396 return CheckRealImagOperand(S, V, Loc, IsReal); 4397 } 4398 4399 // Reject anything else. 4400 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4401 << (IsReal ? "__real" : "__imag"); 4402 return QualType(); 4403 } 4404 4405 4406 4407 ExprResult 4408 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4409 tok::TokenKind Kind, Expr *Input) { 4410 UnaryOperatorKind Opc; 4411 switch (Kind) { 4412 default: llvm_unreachable("Unknown unary op!"); 4413 case tok::plusplus: Opc = UO_PostInc; break; 4414 case tok::minusminus: Opc = UO_PostDec; break; 4415 } 4416 4417 // Since this might is a postfix expression, get rid of ParenListExprs. 4418 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4419 if (Result.isInvalid()) return ExprError(); 4420 Input = Result.get(); 4421 4422 return BuildUnaryOp(S, OpLoc, Opc, Input); 4423 } 4424 4425 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4426 /// 4427 /// \return true on error 4428 static bool checkArithmeticOnObjCPointer(Sema &S, 4429 SourceLocation opLoc, 4430 Expr *op) { 4431 assert(op->getType()->isObjCObjectPointerType()); 4432 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4433 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4434 return false; 4435 4436 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4437 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4438 << op->getSourceRange(); 4439 return true; 4440 } 4441 4442 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4443 auto *BaseNoParens = Base->IgnoreParens(); 4444 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4445 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4446 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4447 } 4448 4449 ExprResult 4450 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4451 Expr *idx, SourceLocation rbLoc) { 4452 if (base && !base->getType().isNull() && 4453 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4454 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4455 /*Length=*/nullptr, rbLoc); 4456 4457 // Since this might be a postfix expression, get rid of ParenListExprs. 4458 if (isa<ParenListExpr>(base)) { 4459 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4460 if (result.isInvalid()) return ExprError(); 4461 base = result.get(); 4462 } 4463 4464 // A comma-expression as the index is deprecated in C++2a onwards. 4465 if (getLangOpts().CPlusPlus2a && 4466 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4467 (isa<CXXOperatorCallExpr>(idx) && 4468 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4469 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4470 << SourceRange(base->getBeginLoc(), rbLoc); 4471 } 4472 4473 // Handle any non-overload placeholder types in the base and index 4474 // expressions. We can't handle overloads here because the other 4475 // operand might be an overloadable type, in which case the overload 4476 // resolution for the operator overload should get the first crack 4477 // at the overload. 4478 bool IsMSPropertySubscript = false; 4479 if (base->getType()->isNonOverloadPlaceholderType()) { 4480 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4481 if (!IsMSPropertySubscript) { 4482 ExprResult result = CheckPlaceholderExpr(base); 4483 if (result.isInvalid()) 4484 return ExprError(); 4485 base = result.get(); 4486 } 4487 } 4488 if (idx->getType()->isNonOverloadPlaceholderType()) { 4489 ExprResult result = CheckPlaceholderExpr(idx); 4490 if (result.isInvalid()) return ExprError(); 4491 idx = result.get(); 4492 } 4493 4494 // Build an unanalyzed expression if either operand is type-dependent. 4495 if (getLangOpts().CPlusPlus && 4496 (base->isTypeDependent() || idx->isTypeDependent())) { 4497 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4498 VK_LValue, OK_Ordinary, rbLoc); 4499 } 4500 4501 // MSDN, property (C++) 4502 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4503 // This attribute can also be used in the declaration of an empty array in a 4504 // class or structure definition. For example: 4505 // __declspec(property(get=GetX, put=PutX)) int x[]; 4506 // The above statement indicates that x[] can be used with one or more array 4507 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4508 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4509 if (IsMSPropertySubscript) { 4510 // Build MS property subscript expression if base is MS property reference 4511 // or MS property subscript. 4512 return new (Context) MSPropertySubscriptExpr( 4513 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4514 } 4515 4516 // Use C++ overloaded-operator rules if either operand has record 4517 // type. The spec says to do this if either type is *overloadable*, 4518 // but enum types can't declare subscript operators or conversion 4519 // operators, so there's nothing interesting for overload resolution 4520 // to do if there aren't any record types involved. 4521 // 4522 // ObjC pointers have their own subscripting logic that is not tied 4523 // to overload resolution and so should not take this path. 4524 if (getLangOpts().CPlusPlus && 4525 (base->getType()->isRecordType() || 4526 (!base->getType()->isObjCObjectPointerType() && 4527 idx->getType()->isRecordType()))) { 4528 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4529 } 4530 4531 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4532 4533 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4534 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4535 4536 return Res; 4537 } 4538 4539 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4540 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4541 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4542 4543 // For expressions like `&(*s).b`, the base is recorded and what should be 4544 // checked. 4545 const MemberExpr *Member = nullptr; 4546 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4547 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4548 4549 LastRecord.PossibleDerefs.erase(StrippedExpr); 4550 } 4551 4552 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4553 QualType ResultTy = E->getType(); 4554 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4555 4556 // Bail if the element is an array since it is not memory access. 4557 if (isa<ArrayType>(ResultTy)) 4558 return; 4559 4560 if (ResultTy->hasAttr(attr::NoDeref)) { 4561 LastRecord.PossibleDerefs.insert(E); 4562 return; 4563 } 4564 4565 // Check if the base type is a pointer to a member access of a struct 4566 // marked with noderef. 4567 const Expr *Base = E->getBase(); 4568 QualType BaseTy = Base->getType(); 4569 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4570 // Not a pointer access 4571 return; 4572 4573 const MemberExpr *Member = nullptr; 4574 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4575 Member->isArrow()) 4576 Base = Member->getBase(); 4577 4578 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4579 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4580 LastRecord.PossibleDerefs.insert(E); 4581 } 4582 } 4583 4584 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4585 Expr *LowerBound, 4586 SourceLocation ColonLoc, Expr *Length, 4587 SourceLocation RBLoc) { 4588 if (Base->getType()->isPlaceholderType() && 4589 !Base->getType()->isSpecificPlaceholderType( 4590 BuiltinType::OMPArraySection)) { 4591 ExprResult Result = CheckPlaceholderExpr(Base); 4592 if (Result.isInvalid()) 4593 return ExprError(); 4594 Base = Result.get(); 4595 } 4596 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4597 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4598 if (Result.isInvalid()) 4599 return ExprError(); 4600 Result = DefaultLvalueConversion(Result.get()); 4601 if (Result.isInvalid()) 4602 return ExprError(); 4603 LowerBound = Result.get(); 4604 } 4605 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4606 ExprResult Result = CheckPlaceholderExpr(Length); 4607 if (Result.isInvalid()) 4608 return ExprError(); 4609 Result = DefaultLvalueConversion(Result.get()); 4610 if (Result.isInvalid()) 4611 return ExprError(); 4612 Length = Result.get(); 4613 } 4614 4615 // Build an unanalyzed expression if either operand is type-dependent. 4616 if (Base->isTypeDependent() || 4617 (LowerBound && 4618 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4619 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4620 return new (Context) 4621 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4622 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4623 } 4624 4625 // Perform default conversions. 4626 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4627 QualType ResultTy; 4628 if (OriginalTy->isAnyPointerType()) { 4629 ResultTy = OriginalTy->getPointeeType(); 4630 } else if (OriginalTy->isArrayType()) { 4631 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4632 } else { 4633 return ExprError( 4634 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4635 << Base->getSourceRange()); 4636 } 4637 // C99 6.5.2.1p1 4638 if (LowerBound) { 4639 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4640 LowerBound); 4641 if (Res.isInvalid()) 4642 return ExprError(Diag(LowerBound->getExprLoc(), 4643 diag::err_omp_typecheck_section_not_integer) 4644 << 0 << LowerBound->getSourceRange()); 4645 LowerBound = Res.get(); 4646 4647 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4648 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4649 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4650 << 0 << LowerBound->getSourceRange(); 4651 } 4652 if (Length) { 4653 auto Res = 4654 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4655 if (Res.isInvalid()) 4656 return ExprError(Diag(Length->getExprLoc(), 4657 diag::err_omp_typecheck_section_not_integer) 4658 << 1 << Length->getSourceRange()); 4659 Length = Res.get(); 4660 4661 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4662 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4663 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4664 << 1 << Length->getSourceRange(); 4665 } 4666 4667 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4668 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4669 // type. Note that functions are not objects, and that (in C99 parlance) 4670 // incomplete types are not object types. 4671 if (ResultTy->isFunctionType()) { 4672 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4673 << ResultTy << Base->getSourceRange(); 4674 return ExprError(); 4675 } 4676 4677 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4678 diag::err_omp_section_incomplete_type, Base)) 4679 return ExprError(); 4680 4681 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4682 Expr::EvalResult Result; 4683 if (LowerBound->EvaluateAsInt(Result, Context)) { 4684 // OpenMP 4.5, [2.4 Array Sections] 4685 // The array section must be a subset of the original array. 4686 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4687 if (LowerBoundValue.isNegative()) { 4688 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4689 << LowerBound->getSourceRange(); 4690 return ExprError(); 4691 } 4692 } 4693 } 4694 4695 if (Length) { 4696 Expr::EvalResult Result; 4697 if (Length->EvaluateAsInt(Result, Context)) { 4698 // OpenMP 4.5, [2.4 Array Sections] 4699 // The length must evaluate to non-negative integers. 4700 llvm::APSInt LengthValue = Result.Val.getInt(); 4701 if (LengthValue.isNegative()) { 4702 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4703 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4704 << Length->getSourceRange(); 4705 return ExprError(); 4706 } 4707 } 4708 } else if (ColonLoc.isValid() && 4709 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4710 !OriginalTy->isVariableArrayType()))) { 4711 // OpenMP 4.5, [2.4 Array Sections] 4712 // When the size of the array dimension is not known, the length must be 4713 // specified explicitly. 4714 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4715 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4716 return ExprError(); 4717 } 4718 4719 if (!Base->getType()->isSpecificPlaceholderType( 4720 BuiltinType::OMPArraySection)) { 4721 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4722 if (Result.isInvalid()) 4723 return ExprError(); 4724 Base = Result.get(); 4725 } 4726 return new (Context) 4727 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4728 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4729 } 4730 4731 ExprResult 4732 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4733 Expr *Idx, SourceLocation RLoc) { 4734 Expr *LHSExp = Base; 4735 Expr *RHSExp = Idx; 4736 4737 ExprValueKind VK = VK_LValue; 4738 ExprObjectKind OK = OK_Ordinary; 4739 4740 // Per C++ core issue 1213, the result is an xvalue if either operand is 4741 // a non-lvalue array, and an lvalue otherwise. 4742 if (getLangOpts().CPlusPlus11) { 4743 for (auto *Op : {LHSExp, RHSExp}) { 4744 Op = Op->IgnoreImplicit(); 4745 if (Op->getType()->isArrayType() && !Op->isLValue()) 4746 VK = VK_XValue; 4747 } 4748 } 4749 4750 // Perform default conversions. 4751 if (!LHSExp->getType()->getAs<VectorType>()) { 4752 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4753 if (Result.isInvalid()) 4754 return ExprError(); 4755 LHSExp = Result.get(); 4756 } 4757 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4758 if (Result.isInvalid()) 4759 return ExprError(); 4760 RHSExp = Result.get(); 4761 4762 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4763 4764 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4765 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4766 // in the subscript position. As a result, we need to derive the array base 4767 // and index from the expression types. 4768 Expr *BaseExpr, *IndexExpr; 4769 QualType ResultType; 4770 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4771 BaseExpr = LHSExp; 4772 IndexExpr = RHSExp; 4773 ResultType = Context.DependentTy; 4774 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4775 BaseExpr = LHSExp; 4776 IndexExpr = RHSExp; 4777 ResultType = PTy->getPointeeType(); 4778 } else if (const ObjCObjectPointerType *PTy = 4779 LHSTy->getAs<ObjCObjectPointerType>()) { 4780 BaseExpr = LHSExp; 4781 IndexExpr = RHSExp; 4782 4783 // Use custom logic if this should be the pseudo-object subscript 4784 // expression. 4785 if (!LangOpts.isSubscriptPointerArithmetic()) 4786 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4787 nullptr); 4788 4789 ResultType = PTy->getPointeeType(); 4790 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4791 // Handle the uncommon case of "123[Ptr]". 4792 BaseExpr = RHSExp; 4793 IndexExpr = LHSExp; 4794 ResultType = PTy->getPointeeType(); 4795 } else if (const ObjCObjectPointerType *PTy = 4796 RHSTy->getAs<ObjCObjectPointerType>()) { 4797 // Handle the uncommon case of "123[Ptr]". 4798 BaseExpr = RHSExp; 4799 IndexExpr = LHSExp; 4800 ResultType = PTy->getPointeeType(); 4801 if (!LangOpts.isSubscriptPointerArithmetic()) { 4802 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4803 << ResultType << BaseExpr->getSourceRange(); 4804 return ExprError(); 4805 } 4806 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4807 BaseExpr = LHSExp; // vectors: V[123] 4808 IndexExpr = RHSExp; 4809 // We apply C++ DR1213 to vector subscripting too. 4810 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4811 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4812 if (Materialized.isInvalid()) 4813 return ExprError(); 4814 LHSExp = Materialized.get(); 4815 } 4816 VK = LHSExp->getValueKind(); 4817 if (VK != VK_RValue) 4818 OK = OK_VectorComponent; 4819 4820 ResultType = VTy->getElementType(); 4821 QualType BaseType = BaseExpr->getType(); 4822 Qualifiers BaseQuals = BaseType.getQualifiers(); 4823 Qualifiers MemberQuals = ResultType.getQualifiers(); 4824 Qualifiers Combined = BaseQuals + MemberQuals; 4825 if (Combined != MemberQuals) 4826 ResultType = Context.getQualifiedType(ResultType, Combined); 4827 } else if (LHSTy->isArrayType()) { 4828 // If we see an array that wasn't promoted by 4829 // DefaultFunctionArrayLvalueConversion, it must be an array that 4830 // wasn't promoted because of the C90 rule that doesn't 4831 // allow promoting non-lvalue arrays. Warn, then 4832 // force the promotion here. 4833 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4834 << LHSExp->getSourceRange(); 4835 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4836 CK_ArrayToPointerDecay).get(); 4837 LHSTy = LHSExp->getType(); 4838 4839 BaseExpr = LHSExp; 4840 IndexExpr = RHSExp; 4841 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4842 } else if (RHSTy->isArrayType()) { 4843 // Same as previous, except for 123[f().a] case 4844 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4845 << RHSExp->getSourceRange(); 4846 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4847 CK_ArrayToPointerDecay).get(); 4848 RHSTy = RHSExp->getType(); 4849 4850 BaseExpr = RHSExp; 4851 IndexExpr = LHSExp; 4852 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4853 } else { 4854 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4855 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4856 } 4857 // C99 6.5.2.1p1 4858 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4859 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4860 << IndexExpr->getSourceRange()); 4861 4862 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4863 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4864 && !IndexExpr->isTypeDependent()) 4865 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4866 4867 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4868 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4869 // type. Note that Functions are not objects, and that (in C99 parlance) 4870 // incomplete types are not object types. 4871 if (ResultType->isFunctionType()) { 4872 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4873 << ResultType << BaseExpr->getSourceRange(); 4874 return ExprError(); 4875 } 4876 4877 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4878 // GNU extension: subscripting on pointer to void 4879 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4880 << BaseExpr->getSourceRange(); 4881 4882 // C forbids expressions of unqualified void type from being l-values. 4883 // See IsCForbiddenLValueType. 4884 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4885 } else if (!ResultType->isDependentType() && 4886 RequireCompleteType(LLoc, ResultType, 4887 diag::err_subscript_incomplete_type, BaseExpr)) 4888 return ExprError(); 4889 4890 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4891 !ResultType.isCForbiddenLValueType()); 4892 4893 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4894 FunctionScopes.size() > 1) { 4895 if (auto *TT = 4896 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4897 for (auto I = FunctionScopes.rbegin(), 4898 E = std::prev(FunctionScopes.rend()); 4899 I != E; ++I) { 4900 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4901 if (CSI == nullptr) 4902 break; 4903 DeclContext *DC = nullptr; 4904 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4905 DC = LSI->CallOperator; 4906 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4907 DC = CRSI->TheCapturedDecl; 4908 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4909 DC = BSI->TheDecl; 4910 if (DC) { 4911 if (DC->containsDecl(TT->getDecl())) 4912 break; 4913 captureVariablyModifiedType( 4914 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4915 } 4916 } 4917 } 4918 } 4919 4920 return new (Context) 4921 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4922 } 4923 4924 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4925 ParmVarDecl *Param) { 4926 if (Param->hasUnparsedDefaultArg()) { 4927 Diag(CallLoc, 4928 diag::err_use_of_default_argument_to_function_declared_later) << 4929 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4930 Diag(UnparsedDefaultArgLocs[Param], 4931 diag::note_default_argument_declared_here); 4932 return true; 4933 } 4934 4935 if (Param->hasUninstantiatedDefaultArg()) { 4936 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4937 4938 EnterExpressionEvaluationContext EvalContext( 4939 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4940 4941 // Instantiate the expression. 4942 // 4943 // FIXME: Pass in a correct Pattern argument, otherwise 4944 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4945 // 4946 // template<typename T> 4947 // struct A { 4948 // static int FooImpl(); 4949 // 4950 // template<typename Tp> 4951 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4952 // // template argument list [[T], [Tp]], should be [[Tp]]. 4953 // friend A<Tp> Foo(int a); 4954 // }; 4955 // 4956 // template<typename T> 4957 // A<T> Foo(int a = A<T>::FooImpl()); 4958 MultiLevelTemplateArgumentList MutiLevelArgList 4959 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4960 4961 InstantiatingTemplate Inst(*this, CallLoc, Param, 4962 MutiLevelArgList.getInnermost()); 4963 if (Inst.isInvalid()) 4964 return true; 4965 if (Inst.isAlreadyInstantiating()) { 4966 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4967 Param->setInvalidDecl(); 4968 return true; 4969 } 4970 4971 ExprResult Result; 4972 { 4973 // C++ [dcl.fct.default]p5: 4974 // The names in the [default argument] expression are bound, and 4975 // the semantic constraints are checked, at the point where the 4976 // default argument expression appears. 4977 ContextRAII SavedContext(*this, FD); 4978 LocalInstantiationScope Local(*this); 4979 runWithSufficientStackSpace(CallLoc, [&] { 4980 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4981 /*DirectInit*/false); 4982 }); 4983 } 4984 if (Result.isInvalid()) 4985 return true; 4986 4987 // Check the expression as an initializer for the parameter. 4988 InitializedEntity Entity 4989 = InitializedEntity::InitializeParameter(Context, Param); 4990 InitializationKind Kind = InitializationKind::CreateCopy( 4991 Param->getLocation(), 4992 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4993 Expr *ResultE = Result.getAs<Expr>(); 4994 4995 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4996 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4997 if (Result.isInvalid()) 4998 return true; 4999 5000 Result = 5001 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5002 /*DiscardedValue*/ false); 5003 if (Result.isInvalid()) 5004 return true; 5005 5006 // Remember the instantiated default argument. 5007 Param->setDefaultArg(Result.getAs<Expr>()); 5008 if (ASTMutationListener *L = getASTMutationListener()) { 5009 L->DefaultArgumentInstantiated(Param); 5010 } 5011 } 5012 5013 // If the default argument expression is not set yet, we are building it now. 5014 if (!Param->hasInit()) { 5015 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5016 Param->setInvalidDecl(); 5017 return true; 5018 } 5019 5020 // If the default expression creates temporaries, we need to 5021 // push them to the current stack of expression temporaries so they'll 5022 // be properly destroyed. 5023 // FIXME: We should really be rebuilding the default argument with new 5024 // bound temporaries; see the comment in PR5810. 5025 // We don't need to do that with block decls, though, because 5026 // blocks in default argument expression can never capture anything. 5027 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5028 // Set the "needs cleanups" bit regardless of whether there are 5029 // any explicit objects. 5030 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5031 5032 // Append all the objects to the cleanup list. Right now, this 5033 // should always be a no-op, because blocks in default argument 5034 // expressions should never be able to capture anything. 5035 assert(!Init->getNumObjects() && 5036 "default argument expression has capturing blocks?"); 5037 } 5038 5039 // We already type-checked the argument, so we know it works. 5040 // Just mark all of the declarations in this potentially-evaluated expression 5041 // as being "referenced". 5042 EnterExpressionEvaluationContext EvalContext( 5043 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5044 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5045 /*SkipLocalVariables=*/true); 5046 return false; 5047 } 5048 5049 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5050 FunctionDecl *FD, ParmVarDecl *Param) { 5051 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5052 return ExprError(); 5053 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5054 } 5055 5056 Sema::VariadicCallType 5057 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5058 Expr *Fn) { 5059 if (Proto && Proto->isVariadic()) { 5060 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5061 return VariadicConstructor; 5062 else if (Fn && Fn->getType()->isBlockPointerType()) 5063 return VariadicBlock; 5064 else if (FDecl) { 5065 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5066 if (Method->isInstance()) 5067 return VariadicMethod; 5068 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5069 return VariadicMethod; 5070 return VariadicFunction; 5071 } 5072 return VariadicDoesNotApply; 5073 } 5074 5075 namespace { 5076 class FunctionCallCCC final : public FunctionCallFilterCCC { 5077 public: 5078 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5079 unsigned NumArgs, MemberExpr *ME) 5080 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5081 FunctionName(FuncName) {} 5082 5083 bool ValidateCandidate(const TypoCorrection &candidate) override { 5084 if (!candidate.getCorrectionSpecifier() || 5085 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5086 return false; 5087 } 5088 5089 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5090 } 5091 5092 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5093 return std::make_unique<FunctionCallCCC>(*this); 5094 } 5095 5096 private: 5097 const IdentifierInfo *const FunctionName; 5098 }; 5099 } 5100 5101 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5102 FunctionDecl *FDecl, 5103 ArrayRef<Expr *> Args) { 5104 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5105 DeclarationName FuncName = FDecl->getDeclName(); 5106 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5107 5108 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5109 if (TypoCorrection Corrected = S.CorrectTypo( 5110 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5111 S.getScopeForContext(S.CurContext), nullptr, CCC, 5112 Sema::CTK_ErrorRecovery)) { 5113 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5114 if (Corrected.isOverloaded()) { 5115 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5116 OverloadCandidateSet::iterator Best; 5117 for (NamedDecl *CD : Corrected) { 5118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5119 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5120 OCS); 5121 } 5122 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5123 case OR_Success: 5124 ND = Best->FoundDecl; 5125 Corrected.setCorrectionDecl(ND); 5126 break; 5127 default: 5128 break; 5129 } 5130 } 5131 ND = ND->getUnderlyingDecl(); 5132 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5133 return Corrected; 5134 } 5135 } 5136 return TypoCorrection(); 5137 } 5138 5139 /// ConvertArgumentsForCall - Converts the arguments specified in 5140 /// Args/NumArgs to the parameter types of the function FDecl with 5141 /// function prototype Proto. Call is the call expression itself, and 5142 /// Fn is the function expression. For a C++ member function, this 5143 /// routine does not attempt to convert the object argument. Returns 5144 /// true if the call is ill-formed. 5145 bool 5146 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5147 FunctionDecl *FDecl, 5148 const FunctionProtoType *Proto, 5149 ArrayRef<Expr *> Args, 5150 SourceLocation RParenLoc, 5151 bool IsExecConfig) { 5152 // Bail out early if calling a builtin with custom typechecking. 5153 if (FDecl) 5154 if (unsigned ID = FDecl->getBuiltinID()) 5155 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5156 return false; 5157 5158 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5159 // assignment, to the types of the corresponding parameter, ... 5160 unsigned NumParams = Proto->getNumParams(); 5161 bool Invalid = false; 5162 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5163 unsigned FnKind = Fn->getType()->isBlockPointerType() 5164 ? 1 /* block */ 5165 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5166 : 0 /* function */); 5167 5168 // If too few arguments are available (and we don't have default 5169 // arguments for the remaining parameters), don't make the call. 5170 if (Args.size() < NumParams) { 5171 if (Args.size() < MinArgs) { 5172 TypoCorrection TC; 5173 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5174 unsigned diag_id = 5175 MinArgs == NumParams && !Proto->isVariadic() 5176 ? diag::err_typecheck_call_too_few_args_suggest 5177 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5178 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5179 << static_cast<unsigned>(Args.size()) 5180 << TC.getCorrectionRange()); 5181 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5182 Diag(RParenLoc, 5183 MinArgs == NumParams && !Proto->isVariadic() 5184 ? diag::err_typecheck_call_too_few_args_one 5185 : diag::err_typecheck_call_too_few_args_at_least_one) 5186 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5187 else 5188 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5189 ? diag::err_typecheck_call_too_few_args 5190 : diag::err_typecheck_call_too_few_args_at_least) 5191 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5192 << Fn->getSourceRange(); 5193 5194 // Emit the location of the prototype. 5195 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5196 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5197 5198 return true; 5199 } 5200 // We reserve space for the default arguments when we create 5201 // the call expression, before calling ConvertArgumentsForCall. 5202 assert((Call->getNumArgs() == NumParams) && 5203 "We should have reserved space for the default arguments before!"); 5204 } 5205 5206 // If too many are passed and not variadic, error on the extras and drop 5207 // them. 5208 if (Args.size() > NumParams) { 5209 if (!Proto->isVariadic()) { 5210 TypoCorrection TC; 5211 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5212 unsigned diag_id = 5213 MinArgs == NumParams && !Proto->isVariadic() 5214 ? diag::err_typecheck_call_too_many_args_suggest 5215 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5216 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5217 << static_cast<unsigned>(Args.size()) 5218 << TC.getCorrectionRange()); 5219 } else if (NumParams == 1 && FDecl && 5220 FDecl->getParamDecl(0)->getDeclName()) 5221 Diag(Args[NumParams]->getBeginLoc(), 5222 MinArgs == NumParams 5223 ? diag::err_typecheck_call_too_many_args_one 5224 : diag::err_typecheck_call_too_many_args_at_most_one) 5225 << FnKind << FDecl->getParamDecl(0) 5226 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5227 << SourceRange(Args[NumParams]->getBeginLoc(), 5228 Args.back()->getEndLoc()); 5229 else 5230 Diag(Args[NumParams]->getBeginLoc(), 5231 MinArgs == NumParams 5232 ? diag::err_typecheck_call_too_many_args 5233 : diag::err_typecheck_call_too_many_args_at_most) 5234 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5235 << Fn->getSourceRange() 5236 << SourceRange(Args[NumParams]->getBeginLoc(), 5237 Args.back()->getEndLoc()); 5238 5239 // Emit the location of the prototype. 5240 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5241 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5242 5243 // This deletes the extra arguments. 5244 Call->shrinkNumArgs(NumParams); 5245 return true; 5246 } 5247 } 5248 SmallVector<Expr *, 8> AllArgs; 5249 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5250 5251 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5252 AllArgs, CallType); 5253 if (Invalid) 5254 return true; 5255 unsigned TotalNumArgs = AllArgs.size(); 5256 for (unsigned i = 0; i < TotalNumArgs; ++i) 5257 Call->setArg(i, AllArgs[i]); 5258 5259 return false; 5260 } 5261 5262 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5263 const FunctionProtoType *Proto, 5264 unsigned FirstParam, ArrayRef<Expr *> Args, 5265 SmallVectorImpl<Expr *> &AllArgs, 5266 VariadicCallType CallType, bool AllowExplicit, 5267 bool IsListInitialization) { 5268 unsigned NumParams = Proto->getNumParams(); 5269 bool Invalid = false; 5270 size_t ArgIx = 0; 5271 // Continue to check argument types (even if we have too few/many args). 5272 for (unsigned i = FirstParam; i < NumParams; i++) { 5273 QualType ProtoArgType = Proto->getParamType(i); 5274 5275 Expr *Arg; 5276 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5277 if (ArgIx < Args.size()) { 5278 Arg = Args[ArgIx++]; 5279 5280 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5281 diag::err_call_incomplete_argument, Arg)) 5282 return true; 5283 5284 // Strip the unbridged-cast placeholder expression off, if applicable. 5285 bool CFAudited = false; 5286 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5287 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5288 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5289 Arg = stripARCUnbridgedCast(Arg); 5290 else if (getLangOpts().ObjCAutoRefCount && 5291 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5292 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5293 CFAudited = true; 5294 5295 if (Proto->getExtParameterInfo(i).isNoEscape()) 5296 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5297 BE->getBlockDecl()->setDoesNotEscape(); 5298 5299 InitializedEntity Entity = 5300 Param ? InitializedEntity::InitializeParameter(Context, Param, 5301 ProtoArgType) 5302 : InitializedEntity::InitializeParameter( 5303 Context, ProtoArgType, Proto->isParamConsumed(i)); 5304 5305 // Remember that parameter belongs to a CF audited API. 5306 if (CFAudited) 5307 Entity.setParameterCFAudited(); 5308 5309 ExprResult ArgE = PerformCopyInitialization( 5310 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5311 if (ArgE.isInvalid()) 5312 return true; 5313 5314 Arg = ArgE.getAs<Expr>(); 5315 } else { 5316 assert(Param && "can't use default arguments without a known callee"); 5317 5318 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5319 if (ArgExpr.isInvalid()) 5320 return true; 5321 5322 Arg = ArgExpr.getAs<Expr>(); 5323 } 5324 5325 // Check for array bounds violations for each argument to the call. This 5326 // check only triggers warnings when the argument isn't a more complex Expr 5327 // with its own checking, such as a BinaryOperator. 5328 CheckArrayAccess(Arg); 5329 5330 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5331 CheckStaticArrayArgument(CallLoc, Param, Arg); 5332 5333 AllArgs.push_back(Arg); 5334 } 5335 5336 // If this is a variadic call, handle args passed through "...". 5337 if (CallType != VariadicDoesNotApply) { 5338 // Assume that extern "C" functions with variadic arguments that 5339 // return __unknown_anytype aren't *really* variadic. 5340 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5341 FDecl->isExternC()) { 5342 for (Expr *A : Args.slice(ArgIx)) { 5343 QualType paramType; // ignored 5344 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5345 Invalid |= arg.isInvalid(); 5346 AllArgs.push_back(arg.get()); 5347 } 5348 5349 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5350 } else { 5351 for (Expr *A : Args.slice(ArgIx)) { 5352 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5353 Invalid |= Arg.isInvalid(); 5354 // Copy blocks to the heap. 5355 if (A->getType()->isBlockPointerType()) 5356 maybeExtendBlockObject(Arg); 5357 AllArgs.push_back(Arg.get()); 5358 } 5359 } 5360 5361 // Check for array bounds violations. 5362 for (Expr *A : Args.slice(ArgIx)) 5363 CheckArrayAccess(A); 5364 } 5365 return Invalid; 5366 } 5367 5368 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5369 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5370 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5371 TL = DTL.getOriginalLoc(); 5372 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5373 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5374 << ATL.getLocalSourceRange(); 5375 } 5376 5377 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5378 /// array parameter, check that it is non-null, and that if it is formed by 5379 /// array-to-pointer decay, the underlying array is sufficiently large. 5380 /// 5381 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5382 /// array type derivation, then for each call to the function, the value of the 5383 /// corresponding actual argument shall provide access to the first element of 5384 /// an array with at least as many elements as specified by the size expression. 5385 void 5386 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5387 ParmVarDecl *Param, 5388 const Expr *ArgExpr) { 5389 // Static array parameters are not supported in C++. 5390 if (!Param || getLangOpts().CPlusPlus) 5391 return; 5392 5393 QualType OrigTy = Param->getOriginalType(); 5394 5395 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5396 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5397 return; 5398 5399 if (ArgExpr->isNullPointerConstant(Context, 5400 Expr::NPC_NeverValueDependent)) { 5401 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5402 DiagnoseCalleeStaticArrayParam(*this, Param); 5403 return; 5404 } 5405 5406 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5407 if (!CAT) 5408 return; 5409 5410 const ConstantArrayType *ArgCAT = 5411 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5412 if (!ArgCAT) 5413 return; 5414 5415 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5416 ArgCAT->getElementType())) { 5417 if (ArgCAT->getSize().ult(CAT->getSize())) { 5418 Diag(CallLoc, diag::warn_static_array_too_small) 5419 << ArgExpr->getSourceRange() 5420 << (unsigned)ArgCAT->getSize().getZExtValue() 5421 << (unsigned)CAT->getSize().getZExtValue() << 0; 5422 DiagnoseCalleeStaticArrayParam(*this, Param); 5423 } 5424 return; 5425 } 5426 5427 Optional<CharUnits> ArgSize = 5428 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5429 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5430 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5431 Diag(CallLoc, diag::warn_static_array_too_small) 5432 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5433 << (unsigned)ParmSize->getQuantity() << 1; 5434 DiagnoseCalleeStaticArrayParam(*this, Param); 5435 } 5436 } 5437 5438 /// Given a function expression of unknown-any type, try to rebuild it 5439 /// to have a function type. 5440 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5441 5442 /// Is the given type a placeholder that we need to lower out 5443 /// immediately during argument processing? 5444 static bool isPlaceholderToRemoveAsArg(QualType type) { 5445 // Placeholders are never sugared. 5446 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5447 if (!placeholder) return false; 5448 5449 switch (placeholder->getKind()) { 5450 // Ignore all the non-placeholder types. 5451 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5452 case BuiltinType::Id: 5453 #include "clang/Basic/OpenCLImageTypes.def" 5454 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5455 case BuiltinType::Id: 5456 #include "clang/Basic/OpenCLExtensionTypes.def" 5457 // In practice we'll never use this, since all SVE types are sugared 5458 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5459 #define SVE_TYPE(Name, Id, SingletonId) \ 5460 case BuiltinType::Id: 5461 #include "clang/Basic/AArch64SVEACLETypes.def" 5462 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5463 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5464 #include "clang/AST/BuiltinTypes.def" 5465 return false; 5466 5467 // We cannot lower out overload sets; they might validly be resolved 5468 // by the call machinery. 5469 case BuiltinType::Overload: 5470 return false; 5471 5472 // Unbridged casts in ARC can be handled in some call positions and 5473 // should be left in place. 5474 case BuiltinType::ARCUnbridgedCast: 5475 return false; 5476 5477 // Pseudo-objects should be converted as soon as possible. 5478 case BuiltinType::PseudoObject: 5479 return true; 5480 5481 // The debugger mode could theoretically but currently does not try 5482 // to resolve unknown-typed arguments based on known parameter types. 5483 case BuiltinType::UnknownAny: 5484 return true; 5485 5486 // These are always invalid as call arguments and should be reported. 5487 case BuiltinType::BoundMember: 5488 case BuiltinType::BuiltinFn: 5489 case BuiltinType::OMPArraySection: 5490 return true; 5491 5492 } 5493 llvm_unreachable("bad builtin type kind"); 5494 } 5495 5496 /// Check an argument list for placeholders that we won't try to 5497 /// handle later. 5498 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5499 // Apply this processing to all the arguments at once instead of 5500 // dying at the first failure. 5501 bool hasInvalid = false; 5502 for (size_t i = 0, e = args.size(); i != e; i++) { 5503 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5504 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5505 if (result.isInvalid()) hasInvalid = true; 5506 else args[i] = result.get(); 5507 } else if (hasInvalid) { 5508 (void)S.CorrectDelayedTyposInExpr(args[i]); 5509 } 5510 } 5511 return hasInvalid; 5512 } 5513 5514 /// If a builtin function has a pointer argument with no explicit address 5515 /// space, then it should be able to accept a pointer to any address 5516 /// space as input. In order to do this, we need to replace the 5517 /// standard builtin declaration with one that uses the same address space 5518 /// as the call. 5519 /// 5520 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5521 /// it does not contain any pointer arguments without 5522 /// an address space qualifer. Otherwise the rewritten 5523 /// FunctionDecl is returned. 5524 /// TODO: Handle pointer return types. 5525 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5526 FunctionDecl *FDecl, 5527 MultiExprArg ArgExprs) { 5528 5529 QualType DeclType = FDecl->getType(); 5530 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5531 5532 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5533 ArgExprs.size() < FT->getNumParams()) 5534 return nullptr; 5535 5536 bool NeedsNewDecl = false; 5537 unsigned i = 0; 5538 SmallVector<QualType, 8> OverloadParams; 5539 5540 for (QualType ParamType : FT->param_types()) { 5541 5542 // Convert array arguments to pointer to simplify type lookup. 5543 ExprResult ArgRes = 5544 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5545 if (ArgRes.isInvalid()) 5546 return nullptr; 5547 Expr *Arg = ArgRes.get(); 5548 QualType ArgType = Arg->getType(); 5549 if (!ParamType->isPointerType() || 5550 ParamType.hasAddressSpace() || 5551 !ArgType->isPointerType() || 5552 !ArgType->getPointeeType().hasAddressSpace()) { 5553 OverloadParams.push_back(ParamType); 5554 continue; 5555 } 5556 5557 QualType PointeeType = ParamType->getPointeeType(); 5558 if (PointeeType.hasAddressSpace()) 5559 continue; 5560 5561 NeedsNewDecl = true; 5562 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5563 5564 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5565 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5566 } 5567 5568 if (!NeedsNewDecl) 5569 return nullptr; 5570 5571 FunctionProtoType::ExtProtoInfo EPI; 5572 EPI.Variadic = FT->isVariadic(); 5573 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5574 OverloadParams, EPI); 5575 DeclContext *Parent = FDecl->getParent(); 5576 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5577 FDecl->getLocation(), 5578 FDecl->getLocation(), 5579 FDecl->getIdentifier(), 5580 OverloadTy, 5581 /*TInfo=*/nullptr, 5582 SC_Extern, false, 5583 /*hasPrototype=*/true); 5584 SmallVector<ParmVarDecl*, 16> Params; 5585 FT = cast<FunctionProtoType>(OverloadTy); 5586 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5587 QualType ParamType = FT->getParamType(i); 5588 ParmVarDecl *Parm = 5589 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5590 SourceLocation(), nullptr, ParamType, 5591 /*TInfo=*/nullptr, SC_None, nullptr); 5592 Parm->setScopeInfo(0, i); 5593 Params.push_back(Parm); 5594 } 5595 OverloadDecl->setParams(Params); 5596 return OverloadDecl; 5597 } 5598 5599 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5600 FunctionDecl *Callee, 5601 MultiExprArg ArgExprs) { 5602 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5603 // similar attributes) really don't like it when functions are called with an 5604 // invalid number of args. 5605 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5606 /*PartialOverloading=*/false) && 5607 !Callee->isVariadic()) 5608 return; 5609 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5610 return; 5611 5612 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5613 S.Diag(Fn->getBeginLoc(), 5614 isa<CXXMethodDecl>(Callee) 5615 ? diag::err_ovl_no_viable_member_function_in_call 5616 : diag::err_ovl_no_viable_function_in_call) 5617 << Callee << Callee->getSourceRange(); 5618 S.Diag(Callee->getLocation(), 5619 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5620 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5621 return; 5622 } 5623 } 5624 5625 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5626 const UnresolvedMemberExpr *const UME, Sema &S) { 5627 5628 const auto GetFunctionLevelDCIfCXXClass = 5629 [](Sema &S) -> const CXXRecordDecl * { 5630 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5631 if (!DC || !DC->getParent()) 5632 return nullptr; 5633 5634 // If the call to some member function was made from within a member 5635 // function body 'M' return return 'M's parent. 5636 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5637 return MD->getParent()->getCanonicalDecl(); 5638 // else the call was made from within a default member initializer of a 5639 // class, so return the class. 5640 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5641 return RD->getCanonicalDecl(); 5642 return nullptr; 5643 }; 5644 // If our DeclContext is neither a member function nor a class (in the 5645 // case of a lambda in a default member initializer), we can't have an 5646 // enclosing 'this'. 5647 5648 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5649 if (!CurParentClass) 5650 return false; 5651 5652 // The naming class for implicit member functions call is the class in which 5653 // name lookup starts. 5654 const CXXRecordDecl *const NamingClass = 5655 UME->getNamingClass()->getCanonicalDecl(); 5656 assert(NamingClass && "Must have naming class even for implicit access"); 5657 5658 // If the unresolved member functions were found in a 'naming class' that is 5659 // related (either the same or derived from) to the class that contains the 5660 // member function that itself contained the implicit member access. 5661 5662 return CurParentClass == NamingClass || 5663 CurParentClass->isDerivedFrom(NamingClass); 5664 } 5665 5666 static void 5667 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5668 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5669 5670 if (!UME) 5671 return; 5672 5673 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5674 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5675 // already been captured, or if this is an implicit member function call (if 5676 // it isn't, an attempt to capture 'this' should already have been made). 5677 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5678 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5679 return; 5680 5681 // Check if the naming class in which the unresolved members were found is 5682 // related (same as or is a base of) to the enclosing class. 5683 5684 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5685 return; 5686 5687 5688 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5689 // If the enclosing function is not dependent, then this lambda is 5690 // capture ready, so if we can capture this, do so. 5691 if (!EnclosingFunctionCtx->isDependentContext()) { 5692 // If the current lambda and all enclosing lambdas can capture 'this' - 5693 // then go ahead and capture 'this' (since our unresolved overload set 5694 // contains at least one non-static member function). 5695 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5696 S.CheckCXXThisCapture(CallLoc); 5697 } else if (S.CurContext->isDependentContext()) { 5698 // ... since this is an implicit member reference, that might potentially 5699 // involve a 'this' capture, mark 'this' for potential capture in 5700 // enclosing lambdas. 5701 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5702 CurLSI->addPotentialThisCapture(CallLoc); 5703 } 5704 } 5705 5706 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5707 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5708 Expr *ExecConfig) { 5709 ExprResult Call = 5710 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5711 if (Call.isInvalid()) 5712 return Call; 5713 5714 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5715 // language modes. 5716 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5717 if (ULE->hasExplicitTemplateArgs() && 5718 ULE->decls_begin() == ULE->decls_end()) { 5719 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5720 ? diag::warn_cxx17_compat_adl_only_template_id 5721 : diag::ext_adl_only_template_id) 5722 << ULE->getName(); 5723 } 5724 } 5725 5726 return Call; 5727 } 5728 5729 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5730 /// This provides the location of the left/right parens and a list of comma 5731 /// locations. 5732 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5733 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5734 Expr *ExecConfig, bool IsExecConfig) { 5735 // Since this might be a postfix expression, get rid of ParenListExprs. 5736 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5737 if (Result.isInvalid()) return ExprError(); 5738 Fn = Result.get(); 5739 5740 if (checkArgsForPlaceholders(*this, ArgExprs)) 5741 return ExprError(); 5742 5743 if (getLangOpts().CPlusPlus) { 5744 // If this is a pseudo-destructor expression, build the call immediately. 5745 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5746 if (!ArgExprs.empty()) { 5747 // Pseudo-destructor calls should not have any arguments. 5748 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5749 << FixItHint::CreateRemoval( 5750 SourceRange(ArgExprs.front()->getBeginLoc(), 5751 ArgExprs.back()->getEndLoc())); 5752 } 5753 5754 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5755 VK_RValue, RParenLoc); 5756 } 5757 if (Fn->getType() == Context.PseudoObjectTy) { 5758 ExprResult result = CheckPlaceholderExpr(Fn); 5759 if (result.isInvalid()) return ExprError(); 5760 Fn = result.get(); 5761 } 5762 5763 // Determine whether this is a dependent call inside a C++ template, 5764 // in which case we won't do any semantic analysis now. 5765 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5766 if (ExecConfig) { 5767 return CUDAKernelCallExpr::Create( 5768 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5769 Context.DependentTy, VK_RValue, RParenLoc); 5770 } else { 5771 5772 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5773 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5774 Fn->getBeginLoc()); 5775 5776 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5777 VK_RValue, RParenLoc); 5778 } 5779 } 5780 5781 // Determine whether this is a call to an object (C++ [over.call.object]). 5782 if (Fn->getType()->isRecordType()) 5783 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5784 RParenLoc); 5785 5786 if (Fn->getType() == Context.UnknownAnyTy) { 5787 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5788 if (result.isInvalid()) return ExprError(); 5789 Fn = result.get(); 5790 } 5791 5792 if (Fn->getType() == Context.BoundMemberTy) { 5793 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5794 RParenLoc); 5795 } 5796 } 5797 5798 // Check for overloaded calls. This can happen even in C due to extensions. 5799 if (Fn->getType() == Context.OverloadTy) { 5800 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5801 5802 // We aren't supposed to apply this logic if there's an '&' involved. 5803 if (!find.HasFormOfMemberPointer) { 5804 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5805 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5806 VK_RValue, RParenLoc); 5807 OverloadExpr *ovl = find.Expression; 5808 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5809 return BuildOverloadedCallExpr( 5810 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5811 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5812 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5813 RParenLoc); 5814 } 5815 } 5816 5817 // If we're directly calling a function, get the appropriate declaration. 5818 if (Fn->getType() == Context.UnknownAnyTy) { 5819 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5820 if (result.isInvalid()) return ExprError(); 5821 Fn = result.get(); 5822 } 5823 5824 Expr *NakedFn = Fn->IgnoreParens(); 5825 5826 bool CallingNDeclIndirectly = false; 5827 NamedDecl *NDecl = nullptr; 5828 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5829 if (UnOp->getOpcode() == UO_AddrOf) { 5830 CallingNDeclIndirectly = true; 5831 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5832 } 5833 } 5834 5835 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5836 NDecl = DRE->getDecl(); 5837 5838 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5839 if (FDecl && FDecl->getBuiltinID()) { 5840 // Rewrite the function decl for this builtin by replacing parameters 5841 // with no explicit address space with the address space of the arguments 5842 // in ArgExprs. 5843 if ((FDecl = 5844 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5845 NDecl = FDecl; 5846 Fn = DeclRefExpr::Create( 5847 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5848 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5849 nullptr, DRE->isNonOdrUse()); 5850 } 5851 } 5852 } else if (isa<MemberExpr>(NakedFn)) 5853 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5854 5855 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5856 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5857 FD, /*Complain=*/true, Fn->getBeginLoc())) 5858 return ExprError(); 5859 5860 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5861 return ExprError(); 5862 5863 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5864 } 5865 5866 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5867 ExecConfig, IsExecConfig); 5868 } 5869 5870 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5871 /// 5872 /// __builtin_astype( value, dst type ) 5873 /// 5874 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5875 SourceLocation BuiltinLoc, 5876 SourceLocation RParenLoc) { 5877 ExprValueKind VK = VK_RValue; 5878 ExprObjectKind OK = OK_Ordinary; 5879 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5880 QualType SrcTy = E->getType(); 5881 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5882 return ExprError(Diag(BuiltinLoc, 5883 diag::err_invalid_astype_of_different_size) 5884 << DstTy 5885 << SrcTy 5886 << E->getSourceRange()); 5887 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5888 } 5889 5890 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5891 /// provided arguments. 5892 /// 5893 /// __builtin_convertvector( value, dst type ) 5894 /// 5895 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5896 SourceLocation BuiltinLoc, 5897 SourceLocation RParenLoc) { 5898 TypeSourceInfo *TInfo; 5899 GetTypeFromParser(ParsedDestTy, &TInfo); 5900 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5901 } 5902 5903 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5904 /// i.e. an expression not of \p OverloadTy. The expression should 5905 /// unary-convert to an expression of function-pointer or 5906 /// block-pointer type. 5907 /// 5908 /// \param NDecl the declaration being called, if available 5909 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5910 SourceLocation LParenLoc, 5911 ArrayRef<Expr *> Args, 5912 SourceLocation RParenLoc, Expr *Config, 5913 bool IsExecConfig, ADLCallKind UsesADL) { 5914 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5915 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5916 5917 // Functions with 'interrupt' attribute cannot be called directly. 5918 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5919 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5920 return ExprError(); 5921 } 5922 5923 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5924 // so there's some risk when calling out to non-interrupt handler functions 5925 // that the callee might not preserve them. This is easy to diagnose here, 5926 // but can be very challenging to debug. 5927 if (auto *Caller = getCurFunctionDecl()) 5928 if (Caller->hasAttr<ARMInterruptAttr>()) { 5929 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5930 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5931 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5932 } 5933 5934 // Promote the function operand. 5935 // We special-case function promotion here because we only allow promoting 5936 // builtin functions to function pointers in the callee of a call. 5937 ExprResult Result; 5938 QualType ResultTy; 5939 if (BuiltinID && 5940 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5941 // Extract the return type from the (builtin) function pointer type. 5942 // FIXME Several builtins still have setType in 5943 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5944 // Builtins.def to ensure they are correct before removing setType calls. 5945 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5946 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5947 ResultTy = FDecl->getCallResultType(); 5948 } else { 5949 Result = CallExprUnaryConversions(Fn); 5950 ResultTy = Context.BoolTy; 5951 } 5952 if (Result.isInvalid()) 5953 return ExprError(); 5954 Fn = Result.get(); 5955 5956 // Check for a valid function type, but only if it is not a builtin which 5957 // requires custom type checking. These will be handled by 5958 // CheckBuiltinFunctionCall below just after creation of the call expression. 5959 const FunctionType *FuncT = nullptr; 5960 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5961 retry: 5962 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5963 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5964 // have type pointer to function". 5965 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5966 if (!FuncT) 5967 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5968 << Fn->getType() << Fn->getSourceRange()); 5969 } else if (const BlockPointerType *BPT = 5970 Fn->getType()->getAs<BlockPointerType>()) { 5971 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5972 } else { 5973 // Handle calls to expressions of unknown-any type. 5974 if (Fn->getType() == Context.UnknownAnyTy) { 5975 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5976 if (rewrite.isInvalid()) 5977 return ExprError(); 5978 Fn = rewrite.get(); 5979 goto retry; 5980 } 5981 5982 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5983 << Fn->getType() << Fn->getSourceRange()); 5984 } 5985 } 5986 5987 // Get the number of parameters in the function prototype, if any. 5988 // We will allocate space for max(Args.size(), NumParams) arguments 5989 // in the call expression. 5990 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5991 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5992 5993 CallExpr *TheCall; 5994 if (Config) { 5995 assert(UsesADL == ADLCallKind::NotADL && 5996 "CUDAKernelCallExpr should not use ADL"); 5997 TheCall = 5998 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5999 ResultTy, VK_RValue, RParenLoc, NumParams); 6000 } else { 6001 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6002 RParenLoc, NumParams, UsesADL); 6003 } 6004 6005 if (!getLangOpts().CPlusPlus) { 6006 // Forget about the nulled arguments since typo correction 6007 // do not handle them well. 6008 TheCall->shrinkNumArgs(Args.size()); 6009 // C cannot always handle TypoExpr nodes in builtin calls and direct 6010 // function calls as their argument checking don't necessarily handle 6011 // dependent types properly, so make sure any TypoExprs have been 6012 // dealt with. 6013 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6014 if (!Result.isUsable()) return ExprError(); 6015 CallExpr *TheOldCall = TheCall; 6016 TheCall = dyn_cast<CallExpr>(Result.get()); 6017 bool CorrectedTypos = TheCall != TheOldCall; 6018 if (!TheCall) return Result; 6019 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6020 6021 // A new call expression node was created if some typos were corrected. 6022 // However it may not have been constructed with enough storage. In this 6023 // case, rebuild the node with enough storage. The waste of space is 6024 // immaterial since this only happens when some typos were corrected. 6025 if (CorrectedTypos && Args.size() < NumParams) { 6026 if (Config) 6027 TheCall = CUDAKernelCallExpr::Create( 6028 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6029 RParenLoc, NumParams); 6030 else 6031 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6032 RParenLoc, NumParams, UsesADL); 6033 } 6034 // We can now handle the nulled arguments for the default arguments. 6035 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6036 } 6037 6038 // Bail out early if calling a builtin with custom type checking. 6039 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6040 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6041 6042 if (getLangOpts().CUDA) { 6043 if (Config) { 6044 // CUDA: Kernel calls must be to global functions 6045 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6046 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6047 << FDecl << Fn->getSourceRange()); 6048 6049 // CUDA: Kernel function must have 'void' return type 6050 if (!FuncT->getReturnType()->isVoidType() && 6051 !FuncT->getReturnType()->getAs<AutoType>() && 6052 !FuncT->getReturnType()->isInstantiationDependentType()) 6053 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6054 << Fn->getType() << Fn->getSourceRange()); 6055 } else { 6056 // CUDA: Calls to global functions must be configured 6057 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6058 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6059 << FDecl << Fn->getSourceRange()); 6060 } 6061 } 6062 6063 // Check for a valid return type 6064 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6065 FDecl)) 6066 return ExprError(); 6067 6068 // We know the result type of the call, set it. 6069 TheCall->setType(FuncT->getCallResultType(Context)); 6070 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6071 6072 if (Proto) { 6073 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6074 IsExecConfig)) 6075 return ExprError(); 6076 } else { 6077 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6078 6079 if (FDecl) { 6080 // Check if we have too few/too many template arguments, based 6081 // on our knowledge of the function definition. 6082 const FunctionDecl *Def = nullptr; 6083 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6084 Proto = Def->getType()->getAs<FunctionProtoType>(); 6085 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6086 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6087 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6088 } 6089 6090 // If the function we're calling isn't a function prototype, but we have 6091 // a function prototype from a prior declaratiom, use that prototype. 6092 if (!FDecl->hasPrototype()) 6093 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6094 } 6095 6096 // Promote the arguments (C99 6.5.2.2p6). 6097 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6098 Expr *Arg = Args[i]; 6099 6100 if (Proto && i < Proto->getNumParams()) { 6101 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6102 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6103 ExprResult ArgE = 6104 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6105 if (ArgE.isInvalid()) 6106 return true; 6107 6108 Arg = ArgE.getAs<Expr>(); 6109 6110 } else { 6111 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6112 6113 if (ArgE.isInvalid()) 6114 return true; 6115 6116 Arg = ArgE.getAs<Expr>(); 6117 } 6118 6119 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6120 diag::err_call_incomplete_argument, Arg)) 6121 return ExprError(); 6122 6123 TheCall->setArg(i, Arg); 6124 } 6125 } 6126 6127 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6128 if (!Method->isStatic()) 6129 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6130 << Fn->getSourceRange()); 6131 6132 // Check for sentinels 6133 if (NDecl) 6134 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6135 6136 // Do special checking on direct calls to functions. 6137 if (FDecl) { 6138 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6139 return ExprError(); 6140 6141 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6142 6143 if (BuiltinID) 6144 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6145 } else if (NDecl) { 6146 if (CheckPointerCall(NDecl, TheCall, Proto)) 6147 return ExprError(); 6148 } else { 6149 if (CheckOtherCall(TheCall, Proto)) 6150 return ExprError(); 6151 } 6152 6153 return MaybeBindToTemporary(TheCall); 6154 } 6155 6156 ExprResult 6157 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6158 SourceLocation RParenLoc, Expr *InitExpr) { 6159 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6160 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6161 6162 TypeSourceInfo *TInfo; 6163 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6164 if (!TInfo) 6165 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6166 6167 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6168 } 6169 6170 ExprResult 6171 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6172 SourceLocation RParenLoc, Expr *LiteralExpr) { 6173 QualType literalType = TInfo->getType(); 6174 6175 if (literalType->isArrayType()) { 6176 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6177 diag::err_illegal_decl_array_incomplete_type, 6178 SourceRange(LParenLoc, 6179 LiteralExpr->getSourceRange().getEnd()))) 6180 return ExprError(); 6181 if (literalType->isVariableArrayType()) 6182 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6183 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6184 } else if (!literalType->isDependentType() && 6185 RequireCompleteType(LParenLoc, literalType, 6186 diag::err_typecheck_decl_incomplete_type, 6187 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6188 return ExprError(); 6189 6190 InitializedEntity Entity 6191 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6192 InitializationKind Kind 6193 = InitializationKind::CreateCStyleCast(LParenLoc, 6194 SourceRange(LParenLoc, RParenLoc), 6195 /*InitList=*/true); 6196 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6197 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6198 &literalType); 6199 if (Result.isInvalid()) 6200 return ExprError(); 6201 LiteralExpr = Result.get(); 6202 6203 bool isFileScope = !CurContext->isFunctionOrMethod(); 6204 6205 // In C, compound literals are l-values for some reason. 6206 // For GCC compatibility, in C++, file-scope array compound literals with 6207 // constant initializers are also l-values, and compound literals are 6208 // otherwise prvalues. 6209 // 6210 // (GCC also treats C++ list-initialized file-scope array prvalues with 6211 // constant initializers as l-values, but that's non-conforming, so we don't 6212 // follow it there.) 6213 // 6214 // FIXME: It would be better to handle the lvalue cases as materializing and 6215 // lifetime-extending a temporary object, but our materialized temporaries 6216 // representation only supports lifetime extension from a variable, not "out 6217 // of thin air". 6218 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6219 // is bound to the result of applying array-to-pointer decay to the compound 6220 // literal. 6221 // FIXME: GCC supports compound literals of reference type, which should 6222 // obviously have a value kind derived from the kind of reference involved. 6223 ExprValueKind VK = 6224 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6225 ? VK_RValue 6226 : VK_LValue; 6227 6228 if (isFileScope) 6229 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6230 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6231 Expr *Init = ILE->getInit(i); 6232 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6233 } 6234 6235 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6236 VK, LiteralExpr, isFileScope); 6237 if (isFileScope) { 6238 if (!LiteralExpr->isTypeDependent() && 6239 !LiteralExpr->isValueDependent() && 6240 !literalType->isDependentType()) // C99 6.5.2.5p3 6241 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6242 return ExprError(); 6243 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6244 literalType.getAddressSpace() != LangAS::Default) { 6245 // Embedded-C extensions to C99 6.5.2.5: 6246 // "If the compound literal occurs inside the body of a function, the 6247 // type name shall not be qualified by an address-space qualifier." 6248 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6249 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6250 return ExprError(); 6251 } 6252 6253 // Compound literals that have automatic storage duration are destroyed at 6254 // the end of the scope. Emit diagnostics if it is or contains a C union type 6255 // that is non-trivial to destruct. 6256 if (!isFileScope) 6257 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6258 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6259 NTCUC_CompoundLiteral, NTCUK_Destruct); 6260 6261 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6262 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6263 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6264 E->getInitializer()->getExprLoc()); 6265 6266 return MaybeBindToTemporary(E); 6267 } 6268 6269 ExprResult 6270 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6271 SourceLocation RBraceLoc) { 6272 // Only produce each kind of designated initialization diagnostic once. 6273 SourceLocation FirstDesignator; 6274 bool DiagnosedArrayDesignator = false; 6275 bool DiagnosedNestedDesignator = false; 6276 bool DiagnosedMixedDesignator = false; 6277 6278 // Check that any designated initializers are syntactically valid in the 6279 // current language mode. 6280 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6281 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6282 if (FirstDesignator.isInvalid()) 6283 FirstDesignator = DIE->getBeginLoc(); 6284 6285 if (!getLangOpts().CPlusPlus) 6286 break; 6287 6288 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6289 DiagnosedNestedDesignator = true; 6290 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6291 << DIE->getDesignatorsSourceRange(); 6292 } 6293 6294 for (auto &Desig : DIE->designators()) { 6295 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6296 DiagnosedArrayDesignator = true; 6297 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6298 << Desig.getSourceRange(); 6299 } 6300 } 6301 6302 if (!DiagnosedMixedDesignator && 6303 !isa<DesignatedInitExpr>(InitArgList[0])) { 6304 DiagnosedMixedDesignator = true; 6305 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6306 << DIE->getSourceRange(); 6307 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6308 << InitArgList[0]->getSourceRange(); 6309 } 6310 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6311 isa<DesignatedInitExpr>(InitArgList[0])) { 6312 DiagnosedMixedDesignator = true; 6313 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6314 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6315 << DIE->getSourceRange(); 6316 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6317 << InitArgList[I]->getSourceRange(); 6318 } 6319 } 6320 6321 if (FirstDesignator.isValid()) { 6322 // Only diagnose designated initiaization as a C++20 extension if we didn't 6323 // already diagnose use of (non-C++20) C99 designator syntax. 6324 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6325 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6326 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6327 ? diag::warn_cxx17_compat_designated_init 6328 : diag::ext_cxx_designated_init); 6329 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6330 Diag(FirstDesignator, diag::ext_designated_init); 6331 } 6332 } 6333 6334 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6335 } 6336 6337 ExprResult 6338 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6339 SourceLocation RBraceLoc) { 6340 // Semantic analysis for initializers is done by ActOnDeclarator() and 6341 // CheckInitializer() - it requires knowledge of the object being initialized. 6342 6343 // Immediately handle non-overload placeholders. Overloads can be 6344 // resolved contextually, but everything else here can't. 6345 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6346 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6347 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6348 6349 // Ignore failures; dropping the entire initializer list because 6350 // of one failure would be terrible for indexing/etc. 6351 if (result.isInvalid()) continue; 6352 6353 InitArgList[I] = result.get(); 6354 } 6355 } 6356 6357 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6358 RBraceLoc); 6359 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6360 return E; 6361 } 6362 6363 /// Do an explicit extend of the given block pointer if we're in ARC. 6364 void Sema::maybeExtendBlockObject(ExprResult &E) { 6365 assert(E.get()->getType()->isBlockPointerType()); 6366 assert(E.get()->isRValue()); 6367 6368 // Only do this in an r-value context. 6369 if (!getLangOpts().ObjCAutoRefCount) return; 6370 6371 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6372 CK_ARCExtendBlockObject, E.get(), 6373 /*base path*/ nullptr, VK_RValue); 6374 Cleanup.setExprNeedsCleanups(true); 6375 } 6376 6377 /// Prepare a conversion of the given expression to an ObjC object 6378 /// pointer type. 6379 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6380 QualType type = E.get()->getType(); 6381 if (type->isObjCObjectPointerType()) { 6382 return CK_BitCast; 6383 } else if (type->isBlockPointerType()) { 6384 maybeExtendBlockObject(E); 6385 return CK_BlockPointerToObjCPointerCast; 6386 } else { 6387 assert(type->isPointerType()); 6388 return CK_CPointerToObjCPointerCast; 6389 } 6390 } 6391 6392 /// Prepares for a scalar cast, performing all the necessary stages 6393 /// except the final cast and returning the kind required. 6394 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6395 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6396 // Also, callers should have filtered out the invalid cases with 6397 // pointers. Everything else should be possible. 6398 6399 QualType SrcTy = Src.get()->getType(); 6400 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6401 return CK_NoOp; 6402 6403 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6404 case Type::STK_MemberPointer: 6405 llvm_unreachable("member pointer type in C"); 6406 6407 case Type::STK_CPointer: 6408 case Type::STK_BlockPointer: 6409 case Type::STK_ObjCObjectPointer: 6410 switch (DestTy->getScalarTypeKind()) { 6411 case Type::STK_CPointer: { 6412 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6413 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6414 if (SrcAS != DestAS) 6415 return CK_AddressSpaceConversion; 6416 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6417 return CK_NoOp; 6418 return CK_BitCast; 6419 } 6420 case Type::STK_BlockPointer: 6421 return (SrcKind == Type::STK_BlockPointer 6422 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6423 case Type::STK_ObjCObjectPointer: 6424 if (SrcKind == Type::STK_ObjCObjectPointer) 6425 return CK_BitCast; 6426 if (SrcKind == Type::STK_CPointer) 6427 return CK_CPointerToObjCPointerCast; 6428 maybeExtendBlockObject(Src); 6429 return CK_BlockPointerToObjCPointerCast; 6430 case Type::STK_Bool: 6431 return CK_PointerToBoolean; 6432 case Type::STK_Integral: 6433 return CK_PointerToIntegral; 6434 case Type::STK_Floating: 6435 case Type::STK_FloatingComplex: 6436 case Type::STK_IntegralComplex: 6437 case Type::STK_MemberPointer: 6438 case Type::STK_FixedPoint: 6439 llvm_unreachable("illegal cast from pointer"); 6440 } 6441 llvm_unreachable("Should have returned before this"); 6442 6443 case Type::STK_FixedPoint: 6444 switch (DestTy->getScalarTypeKind()) { 6445 case Type::STK_FixedPoint: 6446 return CK_FixedPointCast; 6447 case Type::STK_Bool: 6448 return CK_FixedPointToBoolean; 6449 case Type::STK_Integral: 6450 return CK_FixedPointToIntegral; 6451 case Type::STK_Floating: 6452 case Type::STK_IntegralComplex: 6453 case Type::STK_FloatingComplex: 6454 Diag(Src.get()->getExprLoc(), 6455 diag::err_unimplemented_conversion_with_fixed_point_type) 6456 << DestTy; 6457 return CK_IntegralCast; 6458 case Type::STK_CPointer: 6459 case Type::STK_ObjCObjectPointer: 6460 case Type::STK_BlockPointer: 6461 case Type::STK_MemberPointer: 6462 llvm_unreachable("illegal cast to pointer type"); 6463 } 6464 llvm_unreachable("Should have returned before this"); 6465 6466 case Type::STK_Bool: // casting from bool is like casting from an integer 6467 case Type::STK_Integral: 6468 switch (DestTy->getScalarTypeKind()) { 6469 case Type::STK_CPointer: 6470 case Type::STK_ObjCObjectPointer: 6471 case Type::STK_BlockPointer: 6472 if (Src.get()->isNullPointerConstant(Context, 6473 Expr::NPC_ValueDependentIsNull)) 6474 return CK_NullToPointer; 6475 return CK_IntegralToPointer; 6476 case Type::STK_Bool: 6477 return CK_IntegralToBoolean; 6478 case Type::STK_Integral: 6479 return CK_IntegralCast; 6480 case Type::STK_Floating: 6481 return CK_IntegralToFloating; 6482 case Type::STK_IntegralComplex: 6483 Src = ImpCastExprToType(Src.get(), 6484 DestTy->castAs<ComplexType>()->getElementType(), 6485 CK_IntegralCast); 6486 return CK_IntegralRealToComplex; 6487 case Type::STK_FloatingComplex: 6488 Src = ImpCastExprToType(Src.get(), 6489 DestTy->castAs<ComplexType>()->getElementType(), 6490 CK_IntegralToFloating); 6491 return CK_FloatingRealToComplex; 6492 case Type::STK_MemberPointer: 6493 llvm_unreachable("member pointer type in C"); 6494 case Type::STK_FixedPoint: 6495 return CK_IntegralToFixedPoint; 6496 } 6497 llvm_unreachable("Should have returned before this"); 6498 6499 case Type::STK_Floating: 6500 switch (DestTy->getScalarTypeKind()) { 6501 case Type::STK_Floating: 6502 return CK_FloatingCast; 6503 case Type::STK_Bool: 6504 return CK_FloatingToBoolean; 6505 case Type::STK_Integral: 6506 return CK_FloatingToIntegral; 6507 case Type::STK_FloatingComplex: 6508 Src = ImpCastExprToType(Src.get(), 6509 DestTy->castAs<ComplexType>()->getElementType(), 6510 CK_FloatingCast); 6511 return CK_FloatingRealToComplex; 6512 case Type::STK_IntegralComplex: 6513 Src = ImpCastExprToType(Src.get(), 6514 DestTy->castAs<ComplexType>()->getElementType(), 6515 CK_FloatingToIntegral); 6516 return CK_IntegralRealToComplex; 6517 case Type::STK_CPointer: 6518 case Type::STK_ObjCObjectPointer: 6519 case Type::STK_BlockPointer: 6520 llvm_unreachable("valid float->pointer cast?"); 6521 case Type::STK_MemberPointer: 6522 llvm_unreachable("member pointer type in C"); 6523 case Type::STK_FixedPoint: 6524 Diag(Src.get()->getExprLoc(), 6525 diag::err_unimplemented_conversion_with_fixed_point_type) 6526 << SrcTy; 6527 return CK_IntegralCast; 6528 } 6529 llvm_unreachable("Should have returned before this"); 6530 6531 case Type::STK_FloatingComplex: 6532 switch (DestTy->getScalarTypeKind()) { 6533 case Type::STK_FloatingComplex: 6534 return CK_FloatingComplexCast; 6535 case Type::STK_IntegralComplex: 6536 return CK_FloatingComplexToIntegralComplex; 6537 case Type::STK_Floating: { 6538 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6539 if (Context.hasSameType(ET, DestTy)) 6540 return CK_FloatingComplexToReal; 6541 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6542 return CK_FloatingCast; 6543 } 6544 case Type::STK_Bool: 6545 return CK_FloatingComplexToBoolean; 6546 case Type::STK_Integral: 6547 Src = ImpCastExprToType(Src.get(), 6548 SrcTy->castAs<ComplexType>()->getElementType(), 6549 CK_FloatingComplexToReal); 6550 return CK_FloatingToIntegral; 6551 case Type::STK_CPointer: 6552 case Type::STK_ObjCObjectPointer: 6553 case Type::STK_BlockPointer: 6554 llvm_unreachable("valid complex float->pointer cast?"); 6555 case Type::STK_MemberPointer: 6556 llvm_unreachable("member pointer type in C"); 6557 case Type::STK_FixedPoint: 6558 Diag(Src.get()->getExprLoc(), 6559 diag::err_unimplemented_conversion_with_fixed_point_type) 6560 << SrcTy; 6561 return CK_IntegralCast; 6562 } 6563 llvm_unreachable("Should have returned before this"); 6564 6565 case Type::STK_IntegralComplex: 6566 switch (DestTy->getScalarTypeKind()) { 6567 case Type::STK_FloatingComplex: 6568 return CK_IntegralComplexToFloatingComplex; 6569 case Type::STK_IntegralComplex: 6570 return CK_IntegralComplexCast; 6571 case Type::STK_Integral: { 6572 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6573 if (Context.hasSameType(ET, DestTy)) 6574 return CK_IntegralComplexToReal; 6575 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6576 return CK_IntegralCast; 6577 } 6578 case Type::STK_Bool: 6579 return CK_IntegralComplexToBoolean; 6580 case Type::STK_Floating: 6581 Src = ImpCastExprToType(Src.get(), 6582 SrcTy->castAs<ComplexType>()->getElementType(), 6583 CK_IntegralComplexToReal); 6584 return CK_IntegralToFloating; 6585 case Type::STK_CPointer: 6586 case Type::STK_ObjCObjectPointer: 6587 case Type::STK_BlockPointer: 6588 llvm_unreachable("valid complex int->pointer cast?"); 6589 case Type::STK_MemberPointer: 6590 llvm_unreachable("member pointer type in C"); 6591 case Type::STK_FixedPoint: 6592 Diag(Src.get()->getExprLoc(), 6593 diag::err_unimplemented_conversion_with_fixed_point_type) 6594 << SrcTy; 6595 return CK_IntegralCast; 6596 } 6597 llvm_unreachable("Should have returned before this"); 6598 } 6599 6600 llvm_unreachable("Unhandled scalar cast"); 6601 } 6602 6603 static bool breakDownVectorType(QualType type, uint64_t &len, 6604 QualType &eltType) { 6605 // Vectors are simple. 6606 if (const VectorType *vecType = type->getAs<VectorType>()) { 6607 len = vecType->getNumElements(); 6608 eltType = vecType->getElementType(); 6609 assert(eltType->isScalarType()); 6610 return true; 6611 } 6612 6613 // We allow lax conversion to and from non-vector types, but only if 6614 // they're real types (i.e. non-complex, non-pointer scalar types). 6615 if (!type->isRealType()) return false; 6616 6617 len = 1; 6618 eltType = type; 6619 return true; 6620 } 6621 6622 /// Are the two types lax-compatible vector types? That is, given 6623 /// that one of them is a vector, do they have equal storage sizes, 6624 /// where the storage size is the number of elements times the element 6625 /// size? 6626 /// 6627 /// This will also return false if either of the types is neither a 6628 /// vector nor a real type. 6629 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6630 assert(destTy->isVectorType() || srcTy->isVectorType()); 6631 6632 // Disallow lax conversions between scalars and ExtVectors (these 6633 // conversions are allowed for other vector types because common headers 6634 // depend on them). Most scalar OP ExtVector cases are handled by the 6635 // splat path anyway, which does what we want (convert, not bitcast). 6636 // What this rules out for ExtVectors is crazy things like char4*float. 6637 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6638 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6639 6640 uint64_t srcLen, destLen; 6641 QualType srcEltTy, destEltTy; 6642 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6643 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6644 6645 // ASTContext::getTypeSize will return the size rounded up to a 6646 // power of 2, so instead of using that, we need to use the raw 6647 // element size multiplied by the element count. 6648 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6649 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6650 6651 return (srcLen * srcEltSize == destLen * destEltSize); 6652 } 6653 6654 /// Is this a legal conversion between two types, one of which is 6655 /// known to be a vector type? 6656 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6657 assert(destTy->isVectorType() || srcTy->isVectorType()); 6658 6659 switch (Context.getLangOpts().getLaxVectorConversions()) { 6660 case LangOptions::LaxVectorConversionKind::None: 6661 return false; 6662 6663 case LangOptions::LaxVectorConversionKind::Integer: 6664 if (!srcTy->isIntegralOrEnumerationType()) { 6665 auto *Vec = srcTy->getAs<VectorType>(); 6666 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6667 return false; 6668 } 6669 if (!destTy->isIntegralOrEnumerationType()) { 6670 auto *Vec = destTy->getAs<VectorType>(); 6671 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6672 return false; 6673 } 6674 // OK, integer (vector) -> integer (vector) bitcast. 6675 break; 6676 6677 case LangOptions::LaxVectorConversionKind::All: 6678 break; 6679 } 6680 6681 return areLaxCompatibleVectorTypes(srcTy, destTy); 6682 } 6683 6684 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6685 CastKind &Kind) { 6686 assert(VectorTy->isVectorType() && "Not a vector type!"); 6687 6688 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6689 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6690 return Diag(R.getBegin(), 6691 Ty->isVectorType() ? 6692 diag::err_invalid_conversion_between_vectors : 6693 diag::err_invalid_conversion_between_vector_and_integer) 6694 << VectorTy << Ty << R; 6695 } else 6696 return Diag(R.getBegin(), 6697 diag::err_invalid_conversion_between_vector_and_scalar) 6698 << VectorTy << Ty << R; 6699 6700 Kind = CK_BitCast; 6701 return false; 6702 } 6703 6704 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6705 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6706 6707 if (DestElemTy == SplattedExpr->getType()) 6708 return SplattedExpr; 6709 6710 assert(DestElemTy->isFloatingType() || 6711 DestElemTy->isIntegralOrEnumerationType()); 6712 6713 CastKind CK; 6714 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6715 // OpenCL requires that we convert `true` boolean expressions to -1, but 6716 // only when splatting vectors. 6717 if (DestElemTy->isFloatingType()) { 6718 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6719 // in two steps: boolean to signed integral, then to floating. 6720 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6721 CK_BooleanToSignedIntegral); 6722 SplattedExpr = CastExprRes.get(); 6723 CK = CK_IntegralToFloating; 6724 } else { 6725 CK = CK_BooleanToSignedIntegral; 6726 } 6727 } else { 6728 ExprResult CastExprRes = SplattedExpr; 6729 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6730 if (CastExprRes.isInvalid()) 6731 return ExprError(); 6732 SplattedExpr = CastExprRes.get(); 6733 } 6734 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6735 } 6736 6737 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6738 Expr *CastExpr, CastKind &Kind) { 6739 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6740 6741 QualType SrcTy = CastExpr->getType(); 6742 6743 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6744 // an ExtVectorType. 6745 // In OpenCL, casts between vectors of different types are not allowed. 6746 // (See OpenCL 6.2). 6747 if (SrcTy->isVectorType()) { 6748 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6749 (getLangOpts().OpenCL && 6750 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6751 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6752 << DestTy << SrcTy << R; 6753 return ExprError(); 6754 } 6755 Kind = CK_BitCast; 6756 return CastExpr; 6757 } 6758 6759 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6760 // conversion will take place first from scalar to elt type, and then 6761 // splat from elt type to vector. 6762 if (SrcTy->isPointerType()) 6763 return Diag(R.getBegin(), 6764 diag::err_invalid_conversion_between_vector_and_scalar) 6765 << DestTy << SrcTy << R; 6766 6767 Kind = CK_VectorSplat; 6768 return prepareVectorSplat(DestTy, CastExpr); 6769 } 6770 6771 ExprResult 6772 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6773 Declarator &D, ParsedType &Ty, 6774 SourceLocation RParenLoc, Expr *CastExpr) { 6775 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6776 "ActOnCastExpr(): missing type or expr"); 6777 6778 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6779 if (D.isInvalidType()) 6780 return ExprError(); 6781 6782 if (getLangOpts().CPlusPlus) { 6783 // Check that there are no default arguments (C++ only). 6784 CheckExtraCXXDefaultArguments(D); 6785 } else { 6786 // Make sure any TypoExprs have been dealt with. 6787 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6788 if (!Res.isUsable()) 6789 return ExprError(); 6790 CastExpr = Res.get(); 6791 } 6792 6793 checkUnusedDeclAttributes(D); 6794 6795 QualType castType = castTInfo->getType(); 6796 Ty = CreateParsedType(castType, castTInfo); 6797 6798 bool isVectorLiteral = false; 6799 6800 // Check for an altivec or OpenCL literal, 6801 // i.e. all the elements are integer constants. 6802 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6803 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6804 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6805 && castType->isVectorType() && (PE || PLE)) { 6806 if (PLE && PLE->getNumExprs() == 0) { 6807 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6808 return ExprError(); 6809 } 6810 if (PE || PLE->getNumExprs() == 1) { 6811 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6812 if (!E->getType()->isVectorType()) 6813 isVectorLiteral = true; 6814 } 6815 else 6816 isVectorLiteral = true; 6817 } 6818 6819 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6820 // then handle it as such. 6821 if (isVectorLiteral) 6822 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6823 6824 // If the Expr being casted is a ParenListExpr, handle it specially. 6825 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6826 // sequence of BinOp comma operators. 6827 if (isa<ParenListExpr>(CastExpr)) { 6828 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6829 if (Result.isInvalid()) return ExprError(); 6830 CastExpr = Result.get(); 6831 } 6832 6833 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6834 !getSourceManager().isInSystemMacro(LParenLoc)) 6835 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6836 6837 CheckTollFreeBridgeCast(castType, CastExpr); 6838 6839 CheckObjCBridgeRelatedCast(castType, CastExpr); 6840 6841 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6842 6843 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6844 } 6845 6846 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6847 SourceLocation RParenLoc, Expr *E, 6848 TypeSourceInfo *TInfo) { 6849 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6850 "Expected paren or paren list expression"); 6851 6852 Expr **exprs; 6853 unsigned numExprs; 6854 Expr *subExpr; 6855 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6856 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6857 LiteralLParenLoc = PE->getLParenLoc(); 6858 LiteralRParenLoc = PE->getRParenLoc(); 6859 exprs = PE->getExprs(); 6860 numExprs = PE->getNumExprs(); 6861 } else { // isa<ParenExpr> by assertion at function entrance 6862 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6863 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6864 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6865 exprs = &subExpr; 6866 numExprs = 1; 6867 } 6868 6869 QualType Ty = TInfo->getType(); 6870 assert(Ty->isVectorType() && "Expected vector type"); 6871 6872 SmallVector<Expr *, 8> initExprs; 6873 const VectorType *VTy = Ty->castAs<VectorType>(); 6874 unsigned numElems = VTy->getNumElements(); 6875 6876 // '(...)' form of vector initialization in AltiVec: the number of 6877 // initializers must be one or must match the size of the vector. 6878 // If a single value is specified in the initializer then it will be 6879 // replicated to all the components of the vector 6880 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6881 // The number of initializers must be one or must match the size of the 6882 // vector. If a single value is specified in the initializer then it will 6883 // be replicated to all the components of the vector 6884 if (numExprs == 1) { 6885 QualType ElemTy = VTy->getElementType(); 6886 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6887 if (Literal.isInvalid()) 6888 return ExprError(); 6889 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6890 PrepareScalarCast(Literal, ElemTy)); 6891 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6892 } 6893 else if (numExprs < numElems) { 6894 Diag(E->getExprLoc(), 6895 diag::err_incorrect_number_of_vector_initializers); 6896 return ExprError(); 6897 } 6898 else 6899 initExprs.append(exprs, exprs + numExprs); 6900 } 6901 else { 6902 // For OpenCL, when the number of initializers is a single value, 6903 // it will be replicated to all components of the vector. 6904 if (getLangOpts().OpenCL && 6905 VTy->getVectorKind() == VectorType::GenericVector && 6906 numExprs == 1) { 6907 QualType ElemTy = VTy->getElementType(); 6908 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6909 if (Literal.isInvalid()) 6910 return ExprError(); 6911 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6912 PrepareScalarCast(Literal, ElemTy)); 6913 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6914 } 6915 6916 initExprs.append(exprs, exprs + numExprs); 6917 } 6918 // FIXME: This means that pretty-printing the final AST will produce curly 6919 // braces instead of the original commas. 6920 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6921 initExprs, LiteralRParenLoc); 6922 initE->setType(Ty); 6923 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6924 } 6925 6926 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6927 /// the ParenListExpr into a sequence of comma binary operators. 6928 ExprResult 6929 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6930 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6931 if (!E) 6932 return OrigExpr; 6933 6934 ExprResult Result(E->getExpr(0)); 6935 6936 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6937 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6938 E->getExpr(i)); 6939 6940 if (Result.isInvalid()) return ExprError(); 6941 6942 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6943 } 6944 6945 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6946 SourceLocation R, 6947 MultiExprArg Val) { 6948 return ParenListExpr::Create(Context, L, Val, R); 6949 } 6950 6951 /// Emit a specialized diagnostic when one expression is a null pointer 6952 /// constant and the other is not a pointer. Returns true if a diagnostic is 6953 /// emitted. 6954 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6955 SourceLocation QuestionLoc) { 6956 Expr *NullExpr = LHSExpr; 6957 Expr *NonPointerExpr = RHSExpr; 6958 Expr::NullPointerConstantKind NullKind = 6959 NullExpr->isNullPointerConstant(Context, 6960 Expr::NPC_ValueDependentIsNotNull); 6961 6962 if (NullKind == Expr::NPCK_NotNull) { 6963 NullExpr = RHSExpr; 6964 NonPointerExpr = LHSExpr; 6965 NullKind = 6966 NullExpr->isNullPointerConstant(Context, 6967 Expr::NPC_ValueDependentIsNotNull); 6968 } 6969 6970 if (NullKind == Expr::NPCK_NotNull) 6971 return false; 6972 6973 if (NullKind == Expr::NPCK_ZeroExpression) 6974 return false; 6975 6976 if (NullKind == Expr::NPCK_ZeroLiteral) { 6977 // In this case, check to make sure that we got here from a "NULL" 6978 // string in the source code. 6979 NullExpr = NullExpr->IgnoreParenImpCasts(); 6980 SourceLocation loc = NullExpr->getExprLoc(); 6981 if (!findMacroSpelling(loc, "NULL")) 6982 return false; 6983 } 6984 6985 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6986 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6987 << NonPointerExpr->getType() << DiagType 6988 << NonPointerExpr->getSourceRange(); 6989 return true; 6990 } 6991 6992 /// Return false if the condition expression is valid, true otherwise. 6993 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6994 QualType CondTy = Cond->getType(); 6995 6996 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6997 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6998 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6999 << CondTy << Cond->getSourceRange(); 7000 return true; 7001 } 7002 7003 // C99 6.5.15p2 7004 if (CondTy->isScalarType()) return false; 7005 7006 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7007 << CondTy << Cond->getSourceRange(); 7008 return true; 7009 } 7010 7011 /// Handle when one or both operands are void type. 7012 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7013 ExprResult &RHS) { 7014 Expr *LHSExpr = LHS.get(); 7015 Expr *RHSExpr = RHS.get(); 7016 7017 if (!LHSExpr->getType()->isVoidType()) 7018 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7019 << RHSExpr->getSourceRange(); 7020 if (!RHSExpr->getType()->isVoidType()) 7021 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7022 << LHSExpr->getSourceRange(); 7023 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7024 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7025 return S.Context.VoidTy; 7026 } 7027 7028 /// Return false if the NullExpr can be promoted to PointerTy, 7029 /// true otherwise. 7030 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7031 QualType PointerTy) { 7032 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7033 !NullExpr.get()->isNullPointerConstant(S.Context, 7034 Expr::NPC_ValueDependentIsNull)) 7035 return true; 7036 7037 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7038 return false; 7039 } 7040 7041 /// Checks compatibility between two pointers and return the resulting 7042 /// type. 7043 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7044 ExprResult &RHS, 7045 SourceLocation Loc) { 7046 QualType LHSTy = LHS.get()->getType(); 7047 QualType RHSTy = RHS.get()->getType(); 7048 7049 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7050 // Two identical pointers types are always compatible. 7051 return LHSTy; 7052 } 7053 7054 QualType lhptee, rhptee; 7055 7056 // Get the pointee types. 7057 bool IsBlockPointer = false; 7058 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7059 lhptee = LHSBTy->getPointeeType(); 7060 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7061 IsBlockPointer = true; 7062 } else { 7063 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7064 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7065 } 7066 7067 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7068 // differently qualified versions of compatible types, the result type is 7069 // a pointer to an appropriately qualified version of the composite 7070 // type. 7071 7072 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7073 // clause doesn't make sense for our extensions. E.g. address space 2 should 7074 // be incompatible with address space 3: they may live on different devices or 7075 // anything. 7076 Qualifiers lhQual = lhptee.getQualifiers(); 7077 Qualifiers rhQual = rhptee.getQualifiers(); 7078 7079 LangAS ResultAddrSpace = LangAS::Default; 7080 LangAS LAddrSpace = lhQual.getAddressSpace(); 7081 LangAS RAddrSpace = rhQual.getAddressSpace(); 7082 7083 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7084 // spaces is disallowed. 7085 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7086 ResultAddrSpace = LAddrSpace; 7087 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7088 ResultAddrSpace = RAddrSpace; 7089 else { 7090 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7091 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7092 << RHS.get()->getSourceRange(); 7093 return QualType(); 7094 } 7095 7096 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7097 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7098 lhQual.removeCVRQualifiers(); 7099 rhQual.removeCVRQualifiers(); 7100 7101 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7102 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7103 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7104 // qual types are compatible iff 7105 // * corresponded types are compatible 7106 // * CVR qualifiers are equal 7107 // * address spaces are equal 7108 // Thus for conditional operator we merge CVR and address space unqualified 7109 // pointees and if there is a composite type we return a pointer to it with 7110 // merged qualifiers. 7111 LHSCastKind = 7112 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7113 RHSCastKind = 7114 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7115 lhQual.removeAddressSpace(); 7116 rhQual.removeAddressSpace(); 7117 7118 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7119 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7120 7121 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7122 7123 if (CompositeTy.isNull()) { 7124 // In this situation, we assume void* type. No especially good 7125 // reason, but this is what gcc does, and we do have to pick 7126 // to get a consistent AST. 7127 QualType incompatTy; 7128 incompatTy = S.Context.getPointerType( 7129 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7130 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7131 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7132 7133 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7134 // for casts between types with incompatible address space qualifiers. 7135 // For the following code the compiler produces casts between global and 7136 // local address spaces of the corresponded innermost pointees: 7137 // local int *global *a; 7138 // global int *global *b; 7139 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7140 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7141 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7142 << RHS.get()->getSourceRange(); 7143 7144 return incompatTy; 7145 } 7146 7147 // The pointer types are compatible. 7148 // In case of OpenCL ResultTy should have the address space qualifier 7149 // which is a superset of address spaces of both the 2nd and the 3rd 7150 // operands of the conditional operator. 7151 QualType ResultTy = [&, ResultAddrSpace]() { 7152 if (S.getLangOpts().OpenCL) { 7153 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7154 CompositeQuals.setAddressSpace(ResultAddrSpace); 7155 return S.Context 7156 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7157 .withCVRQualifiers(MergedCVRQual); 7158 } 7159 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7160 }(); 7161 if (IsBlockPointer) 7162 ResultTy = S.Context.getBlockPointerType(ResultTy); 7163 else 7164 ResultTy = S.Context.getPointerType(ResultTy); 7165 7166 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7167 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7168 return ResultTy; 7169 } 7170 7171 /// Return the resulting type when the operands are both block pointers. 7172 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7173 ExprResult &LHS, 7174 ExprResult &RHS, 7175 SourceLocation Loc) { 7176 QualType LHSTy = LHS.get()->getType(); 7177 QualType RHSTy = RHS.get()->getType(); 7178 7179 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7180 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7181 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7182 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7183 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7184 return destType; 7185 } 7186 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7187 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7188 << RHS.get()->getSourceRange(); 7189 return QualType(); 7190 } 7191 7192 // We have 2 block pointer types. 7193 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7194 } 7195 7196 /// Return the resulting type when the operands are both pointers. 7197 static QualType 7198 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7199 ExprResult &RHS, 7200 SourceLocation Loc) { 7201 // get the pointer types 7202 QualType LHSTy = LHS.get()->getType(); 7203 QualType RHSTy = RHS.get()->getType(); 7204 7205 // get the "pointed to" types 7206 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7207 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7208 7209 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7210 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7211 // Figure out necessary qualifiers (C99 6.5.15p6) 7212 QualType destPointee 7213 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7214 QualType destType = S.Context.getPointerType(destPointee); 7215 // Add qualifiers if necessary. 7216 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7217 // Promote to void*. 7218 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7219 return destType; 7220 } 7221 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7222 QualType destPointee 7223 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7224 QualType destType = S.Context.getPointerType(destPointee); 7225 // Add qualifiers if necessary. 7226 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7227 // Promote to void*. 7228 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7229 return destType; 7230 } 7231 7232 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7233 } 7234 7235 /// Return false if the first expression is not an integer and the second 7236 /// expression is not a pointer, true otherwise. 7237 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7238 Expr* PointerExpr, SourceLocation Loc, 7239 bool IsIntFirstExpr) { 7240 if (!PointerExpr->getType()->isPointerType() || 7241 !Int.get()->getType()->isIntegerType()) 7242 return false; 7243 7244 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7245 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7246 7247 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7248 << Expr1->getType() << Expr2->getType() 7249 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7250 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7251 CK_IntegralToPointer); 7252 return true; 7253 } 7254 7255 /// Simple conversion between integer and floating point types. 7256 /// 7257 /// Used when handling the OpenCL conditional operator where the 7258 /// condition is a vector while the other operands are scalar. 7259 /// 7260 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7261 /// types are either integer or floating type. Between the two 7262 /// operands, the type with the higher rank is defined as the "result 7263 /// type". The other operand needs to be promoted to the same type. No 7264 /// other type promotion is allowed. We cannot use 7265 /// UsualArithmeticConversions() for this purpose, since it always 7266 /// promotes promotable types. 7267 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7268 ExprResult &RHS, 7269 SourceLocation QuestionLoc) { 7270 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7271 if (LHS.isInvalid()) 7272 return QualType(); 7273 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7274 if (RHS.isInvalid()) 7275 return QualType(); 7276 7277 // For conversion purposes, we ignore any qualifiers. 7278 // For example, "const float" and "float" are equivalent. 7279 QualType LHSType = 7280 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7281 QualType RHSType = 7282 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7283 7284 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7285 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7286 << LHSType << LHS.get()->getSourceRange(); 7287 return QualType(); 7288 } 7289 7290 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7291 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7292 << RHSType << RHS.get()->getSourceRange(); 7293 return QualType(); 7294 } 7295 7296 // If both types are identical, no conversion is needed. 7297 if (LHSType == RHSType) 7298 return LHSType; 7299 7300 // Now handle "real" floating types (i.e. float, double, long double). 7301 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7302 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7303 /*IsCompAssign = */ false); 7304 7305 // Finally, we have two differing integer types. 7306 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7307 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7308 } 7309 7310 /// Convert scalar operands to a vector that matches the 7311 /// condition in length. 7312 /// 7313 /// Used when handling the OpenCL conditional operator where the 7314 /// condition is a vector while the other operands are scalar. 7315 /// 7316 /// We first compute the "result type" for the scalar operands 7317 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7318 /// into a vector of that type where the length matches the condition 7319 /// vector type. s6.11.6 requires that the element types of the result 7320 /// and the condition must have the same number of bits. 7321 static QualType 7322 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7323 QualType CondTy, SourceLocation QuestionLoc) { 7324 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7325 if (ResTy.isNull()) return QualType(); 7326 7327 const VectorType *CV = CondTy->getAs<VectorType>(); 7328 assert(CV); 7329 7330 // Determine the vector result type 7331 unsigned NumElements = CV->getNumElements(); 7332 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7333 7334 // Ensure that all types have the same number of bits 7335 if (S.Context.getTypeSize(CV->getElementType()) 7336 != S.Context.getTypeSize(ResTy)) { 7337 // Since VectorTy is created internally, it does not pretty print 7338 // with an OpenCL name. Instead, we just print a description. 7339 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7340 SmallString<64> Str; 7341 llvm::raw_svector_ostream OS(Str); 7342 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7343 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7344 << CondTy << OS.str(); 7345 return QualType(); 7346 } 7347 7348 // Convert operands to the vector result type 7349 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7350 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7351 7352 return VectorTy; 7353 } 7354 7355 /// Return false if this is a valid OpenCL condition vector 7356 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7357 SourceLocation QuestionLoc) { 7358 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7359 // integral type. 7360 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7361 assert(CondTy); 7362 QualType EleTy = CondTy->getElementType(); 7363 if (EleTy->isIntegerType()) return false; 7364 7365 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7366 << Cond->getType() << Cond->getSourceRange(); 7367 return true; 7368 } 7369 7370 /// Return false if the vector condition type and the vector 7371 /// result type are compatible. 7372 /// 7373 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7374 /// number of elements, and their element types have the same number 7375 /// of bits. 7376 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7377 SourceLocation QuestionLoc) { 7378 const VectorType *CV = CondTy->getAs<VectorType>(); 7379 const VectorType *RV = VecResTy->getAs<VectorType>(); 7380 assert(CV && RV); 7381 7382 if (CV->getNumElements() != RV->getNumElements()) { 7383 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7384 << CondTy << VecResTy; 7385 return true; 7386 } 7387 7388 QualType CVE = CV->getElementType(); 7389 QualType RVE = RV->getElementType(); 7390 7391 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7392 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7393 << CondTy << VecResTy; 7394 return true; 7395 } 7396 7397 return false; 7398 } 7399 7400 /// Return the resulting type for the conditional operator in 7401 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7402 /// s6.3.i) when the condition is a vector type. 7403 static QualType 7404 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7405 ExprResult &LHS, ExprResult &RHS, 7406 SourceLocation QuestionLoc) { 7407 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7408 if (Cond.isInvalid()) 7409 return QualType(); 7410 QualType CondTy = Cond.get()->getType(); 7411 7412 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7413 return QualType(); 7414 7415 // If either operand is a vector then find the vector type of the 7416 // result as specified in OpenCL v1.1 s6.3.i. 7417 if (LHS.get()->getType()->isVectorType() || 7418 RHS.get()->getType()->isVectorType()) { 7419 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7420 /*isCompAssign*/false, 7421 /*AllowBothBool*/true, 7422 /*AllowBoolConversions*/false); 7423 if (VecResTy.isNull()) return QualType(); 7424 // The result type must match the condition type as specified in 7425 // OpenCL v1.1 s6.11.6. 7426 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7427 return QualType(); 7428 return VecResTy; 7429 } 7430 7431 // Both operands are scalar. 7432 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7433 } 7434 7435 /// Return true if the Expr is block type 7436 static bool checkBlockType(Sema &S, const Expr *E) { 7437 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7438 QualType Ty = CE->getCallee()->getType(); 7439 if (Ty->isBlockPointerType()) { 7440 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7441 return true; 7442 } 7443 } 7444 return false; 7445 } 7446 7447 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7448 /// In that case, LHS = cond. 7449 /// C99 6.5.15 7450 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7451 ExprResult &RHS, ExprValueKind &VK, 7452 ExprObjectKind &OK, 7453 SourceLocation QuestionLoc) { 7454 7455 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7456 if (!LHSResult.isUsable()) return QualType(); 7457 LHS = LHSResult; 7458 7459 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7460 if (!RHSResult.isUsable()) return QualType(); 7461 RHS = RHSResult; 7462 7463 // C++ is sufficiently different to merit its own checker. 7464 if (getLangOpts().CPlusPlus) 7465 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7466 7467 VK = VK_RValue; 7468 OK = OK_Ordinary; 7469 7470 // The OpenCL operator with a vector condition is sufficiently 7471 // different to merit its own checker. 7472 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7473 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7474 7475 // First, check the condition. 7476 Cond = UsualUnaryConversions(Cond.get()); 7477 if (Cond.isInvalid()) 7478 return QualType(); 7479 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7480 return QualType(); 7481 7482 // Now check the two expressions. 7483 if (LHS.get()->getType()->isVectorType() || 7484 RHS.get()->getType()->isVectorType()) 7485 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7486 /*AllowBothBool*/true, 7487 /*AllowBoolConversions*/false); 7488 7489 QualType ResTy = 7490 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7491 if (LHS.isInvalid() || RHS.isInvalid()) 7492 return QualType(); 7493 7494 QualType LHSTy = LHS.get()->getType(); 7495 QualType RHSTy = RHS.get()->getType(); 7496 7497 // Diagnose attempts to convert between __float128 and long double where 7498 // such conversions currently can't be handled. 7499 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7500 Diag(QuestionLoc, 7501 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7502 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7503 return QualType(); 7504 } 7505 7506 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7507 // selection operator (?:). 7508 if (getLangOpts().OpenCL && 7509 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7510 return QualType(); 7511 } 7512 7513 // If both operands have arithmetic type, do the usual arithmetic conversions 7514 // to find a common type: C99 6.5.15p3,5. 7515 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7516 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7517 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7518 7519 return ResTy; 7520 } 7521 7522 // If both operands are the same structure or union type, the result is that 7523 // type. 7524 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7525 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7526 if (LHSRT->getDecl() == RHSRT->getDecl()) 7527 // "If both the operands have structure or union type, the result has 7528 // that type." This implies that CV qualifiers are dropped. 7529 return LHSTy.getUnqualifiedType(); 7530 // FIXME: Type of conditional expression must be complete in C mode. 7531 } 7532 7533 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7534 // The following || allows only one side to be void (a GCC-ism). 7535 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7536 return checkConditionalVoidType(*this, LHS, RHS); 7537 } 7538 7539 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7540 // the type of the other operand." 7541 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7542 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7543 7544 // All objective-c pointer type analysis is done here. 7545 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7546 QuestionLoc); 7547 if (LHS.isInvalid() || RHS.isInvalid()) 7548 return QualType(); 7549 if (!compositeType.isNull()) 7550 return compositeType; 7551 7552 7553 // Handle block pointer types. 7554 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7555 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7556 QuestionLoc); 7557 7558 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7559 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7560 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7561 QuestionLoc); 7562 7563 // GCC compatibility: soften pointer/integer mismatch. Note that 7564 // null pointers have been filtered out by this point. 7565 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7566 /*IsIntFirstExpr=*/true)) 7567 return RHSTy; 7568 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7569 /*IsIntFirstExpr=*/false)) 7570 return LHSTy; 7571 7572 // Emit a better diagnostic if one of the expressions is a null pointer 7573 // constant and the other is not a pointer type. In this case, the user most 7574 // likely forgot to take the address of the other expression. 7575 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7576 return QualType(); 7577 7578 // Otherwise, the operands are not compatible. 7579 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7580 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7581 << RHS.get()->getSourceRange(); 7582 return QualType(); 7583 } 7584 7585 /// FindCompositeObjCPointerType - Helper method to find composite type of 7586 /// two objective-c pointer types of the two input expressions. 7587 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7588 SourceLocation QuestionLoc) { 7589 QualType LHSTy = LHS.get()->getType(); 7590 QualType RHSTy = RHS.get()->getType(); 7591 7592 // Handle things like Class and struct objc_class*. Here we case the result 7593 // to the pseudo-builtin, because that will be implicitly cast back to the 7594 // redefinition type if an attempt is made to access its fields. 7595 if (LHSTy->isObjCClassType() && 7596 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7597 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7598 return LHSTy; 7599 } 7600 if (RHSTy->isObjCClassType() && 7601 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7602 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7603 return RHSTy; 7604 } 7605 // And the same for struct objc_object* / id 7606 if (LHSTy->isObjCIdType() && 7607 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7608 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7609 return LHSTy; 7610 } 7611 if (RHSTy->isObjCIdType() && 7612 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7613 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7614 return RHSTy; 7615 } 7616 // And the same for struct objc_selector* / SEL 7617 if (Context.isObjCSelType(LHSTy) && 7618 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7619 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7620 return LHSTy; 7621 } 7622 if (Context.isObjCSelType(RHSTy) && 7623 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7624 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7625 return RHSTy; 7626 } 7627 // Check constraints for Objective-C object pointers types. 7628 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7629 7630 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7631 // Two identical object pointer types are always compatible. 7632 return LHSTy; 7633 } 7634 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7635 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7636 QualType compositeType = LHSTy; 7637 7638 // If both operands are interfaces and either operand can be 7639 // assigned to the other, use that type as the composite 7640 // type. This allows 7641 // xxx ? (A*) a : (B*) b 7642 // where B is a subclass of A. 7643 // 7644 // Additionally, as for assignment, if either type is 'id' 7645 // allow silent coercion. Finally, if the types are 7646 // incompatible then make sure to use 'id' as the composite 7647 // type so the result is acceptable for sending messages to. 7648 7649 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7650 // It could return the composite type. 7651 if (!(compositeType = 7652 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7653 // Nothing more to do. 7654 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7655 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7656 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7657 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7658 } else if ((LHSOPT->isObjCQualifiedIdType() || 7659 RHSOPT->isObjCQualifiedIdType()) && 7660 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7661 true)) { 7662 // Need to handle "id<xx>" explicitly. 7663 // GCC allows qualified id and any Objective-C type to devolve to 7664 // id. Currently localizing to here until clear this should be 7665 // part of ObjCQualifiedIdTypesAreCompatible. 7666 compositeType = Context.getObjCIdType(); 7667 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7668 compositeType = Context.getObjCIdType(); 7669 } else { 7670 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7671 << LHSTy << RHSTy 7672 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7673 QualType incompatTy = Context.getObjCIdType(); 7674 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7675 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7676 return incompatTy; 7677 } 7678 // The object pointer types are compatible. 7679 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7680 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7681 return compositeType; 7682 } 7683 // Check Objective-C object pointer types and 'void *' 7684 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7685 if (getLangOpts().ObjCAutoRefCount) { 7686 // ARC forbids the implicit conversion of object pointers to 'void *', 7687 // so these types are not compatible. 7688 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7689 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7690 LHS = RHS = true; 7691 return QualType(); 7692 } 7693 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7694 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7695 QualType destPointee 7696 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7697 QualType destType = Context.getPointerType(destPointee); 7698 // Add qualifiers if necessary. 7699 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7700 // Promote to void*. 7701 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7702 return destType; 7703 } 7704 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7705 if (getLangOpts().ObjCAutoRefCount) { 7706 // ARC forbids the implicit conversion of object pointers to 'void *', 7707 // so these types are not compatible. 7708 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7709 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7710 LHS = RHS = true; 7711 return QualType(); 7712 } 7713 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7714 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7715 QualType destPointee 7716 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7717 QualType destType = Context.getPointerType(destPointee); 7718 // Add qualifiers if necessary. 7719 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7720 // Promote to void*. 7721 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7722 return destType; 7723 } 7724 return QualType(); 7725 } 7726 7727 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7728 /// ParenRange in parentheses. 7729 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7730 const PartialDiagnostic &Note, 7731 SourceRange ParenRange) { 7732 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7733 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7734 EndLoc.isValid()) { 7735 Self.Diag(Loc, Note) 7736 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7737 << FixItHint::CreateInsertion(EndLoc, ")"); 7738 } else { 7739 // We can't display the parentheses, so just show the bare note. 7740 Self.Diag(Loc, Note) << ParenRange; 7741 } 7742 } 7743 7744 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7745 return BinaryOperator::isAdditiveOp(Opc) || 7746 BinaryOperator::isMultiplicativeOp(Opc) || 7747 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7748 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7749 // not any of the logical operators. Bitwise-xor is commonly used as a 7750 // logical-xor because there is no logical-xor operator. The logical 7751 // operators, including uses of xor, have a high false positive rate for 7752 // precedence warnings. 7753 } 7754 7755 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7756 /// expression, either using a built-in or overloaded operator, 7757 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7758 /// expression. 7759 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7760 Expr **RHSExprs) { 7761 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7762 E = E->IgnoreImpCasts(); 7763 E = E->IgnoreConversionOperator(); 7764 E = E->IgnoreImpCasts(); 7765 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7766 E = MTE->getSubExpr(); 7767 E = E->IgnoreImpCasts(); 7768 } 7769 7770 // Built-in binary operator. 7771 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7772 if (IsArithmeticOp(OP->getOpcode())) { 7773 *Opcode = OP->getOpcode(); 7774 *RHSExprs = OP->getRHS(); 7775 return true; 7776 } 7777 } 7778 7779 // Overloaded operator. 7780 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7781 if (Call->getNumArgs() != 2) 7782 return false; 7783 7784 // Make sure this is really a binary operator that is safe to pass into 7785 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7786 OverloadedOperatorKind OO = Call->getOperator(); 7787 if (OO < OO_Plus || OO > OO_Arrow || 7788 OO == OO_PlusPlus || OO == OO_MinusMinus) 7789 return false; 7790 7791 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7792 if (IsArithmeticOp(OpKind)) { 7793 *Opcode = OpKind; 7794 *RHSExprs = Call->getArg(1); 7795 return true; 7796 } 7797 } 7798 7799 return false; 7800 } 7801 7802 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7803 /// or is a logical expression such as (x==y) which has int type, but is 7804 /// commonly interpreted as boolean. 7805 static bool ExprLooksBoolean(Expr *E) { 7806 E = E->IgnoreParenImpCasts(); 7807 7808 if (E->getType()->isBooleanType()) 7809 return true; 7810 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7811 return OP->isComparisonOp() || OP->isLogicalOp(); 7812 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7813 return OP->getOpcode() == UO_LNot; 7814 if (E->getType()->isPointerType()) 7815 return true; 7816 // FIXME: What about overloaded operator calls returning "unspecified boolean 7817 // type"s (commonly pointer-to-members)? 7818 7819 return false; 7820 } 7821 7822 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7823 /// and binary operator are mixed in a way that suggests the programmer assumed 7824 /// the conditional operator has higher precedence, for example: 7825 /// "int x = a + someBinaryCondition ? 1 : 2". 7826 static void DiagnoseConditionalPrecedence(Sema &Self, 7827 SourceLocation OpLoc, 7828 Expr *Condition, 7829 Expr *LHSExpr, 7830 Expr *RHSExpr) { 7831 BinaryOperatorKind CondOpcode; 7832 Expr *CondRHS; 7833 7834 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7835 return; 7836 if (!ExprLooksBoolean(CondRHS)) 7837 return; 7838 7839 // The condition is an arithmetic binary expression, with a right- 7840 // hand side that looks boolean, so warn. 7841 7842 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7843 ? diag::warn_precedence_bitwise_conditional 7844 : diag::warn_precedence_conditional; 7845 7846 Self.Diag(OpLoc, DiagID) 7847 << Condition->getSourceRange() 7848 << BinaryOperator::getOpcodeStr(CondOpcode); 7849 7850 SuggestParentheses( 7851 Self, OpLoc, 7852 Self.PDiag(diag::note_precedence_silence) 7853 << BinaryOperator::getOpcodeStr(CondOpcode), 7854 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7855 7856 SuggestParentheses(Self, OpLoc, 7857 Self.PDiag(diag::note_precedence_conditional_first), 7858 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7859 } 7860 7861 /// Compute the nullability of a conditional expression. 7862 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7863 QualType LHSTy, QualType RHSTy, 7864 ASTContext &Ctx) { 7865 if (!ResTy->isAnyPointerType()) 7866 return ResTy; 7867 7868 auto GetNullability = [&Ctx](QualType Ty) { 7869 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7870 if (Kind) 7871 return *Kind; 7872 return NullabilityKind::Unspecified; 7873 }; 7874 7875 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7876 NullabilityKind MergedKind; 7877 7878 // Compute nullability of a binary conditional expression. 7879 if (IsBin) { 7880 if (LHSKind == NullabilityKind::NonNull) 7881 MergedKind = NullabilityKind::NonNull; 7882 else 7883 MergedKind = RHSKind; 7884 // Compute nullability of a normal conditional expression. 7885 } else { 7886 if (LHSKind == NullabilityKind::Nullable || 7887 RHSKind == NullabilityKind::Nullable) 7888 MergedKind = NullabilityKind::Nullable; 7889 else if (LHSKind == NullabilityKind::NonNull) 7890 MergedKind = RHSKind; 7891 else if (RHSKind == NullabilityKind::NonNull) 7892 MergedKind = LHSKind; 7893 else 7894 MergedKind = NullabilityKind::Unspecified; 7895 } 7896 7897 // Return if ResTy already has the correct nullability. 7898 if (GetNullability(ResTy) == MergedKind) 7899 return ResTy; 7900 7901 // Strip all nullability from ResTy. 7902 while (ResTy->getNullability(Ctx)) 7903 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7904 7905 // Create a new AttributedType with the new nullability kind. 7906 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7907 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7908 } 7909 7910 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7911 /// in the case of a the GNU conditional expr extension. 7912 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7913 SourceLocation ColonLoc, 7914 Expr *CondExpr, Expr *LHSExpr, 7915 Expr *RHSExpr) { 7916 if (!getLangOpts().CPlusPlus) { 7917 // C cannot handle TypoExpr nodes in the condition because it 7918 // doesn't handle dependent types properly, so make sure any TypoExprs have 7919 // been dealt with before checking the operands. 7920 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7921 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7922 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7923 7924 if (!CondResult.isUsable()) 7925 return ExprError(); 7926 7927 if (LHSExpr) { 7928 if (!LHSResult.isUsable()) 7929 return ExprError(); 7930 } 7931 7932 if (!RHSResult.isUsable()) 7933 return ExprError(); 7934 7935 CondExpr = CondResult.get(); 7936 LHSExpr = LHSResult.get(); 7937 RHSExpr = RHSResult.get(); 7938 } 7939 7940 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7941 // was the condition. 7942 OpaqueValueExpr *opaqueValue = nullptr; 7943 Expr *commonExpr = nullptr; 7944 if (!LHSExpr) { 7945 commonExpr = CondExpr; 7946 // Lower out placeholder types first. This is important so that we don't 7947 // try to capture a placeholder. This happens in few cases in C++; such 7948 // as Objective-C++'s dictionary subscripting syntax. 7949 if (commonExpr->hasPlaceholderType()) { 7950 ExprResult result = CheckPlaceholderExpr(commonExpr); 7951 if (!result.isUsable()) return ExprError(); 7952 commonExpr = result.get(); 7953 } 7954 // We usually want to apply unary conversions *before* saving, except 7955 // in the special case of a C++ l-value conditional. 7956 if (!(getLangOpts().CPlusPlus 7957 && !commonExpr->isTypeDependent() 7958 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7959 && commonExpr->isGLValue() 7960 && commonExpr->isOrdinaryOrBitFieldObject() 7961 && RHSExpr->isOrdinaryOrBitFieldObject() 7962 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7963 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7964 if (commonRes.isInvalid()) 7965 return ExprError(); 7966 commonExpr = commonRes.get(); 7967 } 7968 7969 // If the common expression is a class or array prvalue, materialize it 7970 // so that we can safely refer to it multiple times. 7971 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7972 commonExpr->getType()->isArrayType())) { 7973 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7974 if (MatExpr.isInvalid()) 7975 return ExprError(); 7976 commonExpr = MatExpr.get(); 7977 } 7978 7979 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7980 commonExpr->getType(), 7981 commonExpr->getValueKind(), 7982 commonExpr->getObjectKind(), 7983 commonExpr); 7984 LHSExpr = CondExpr = opaqueValue; 7985 } 7986 7987 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7988 ExprValueKind VK = VK_RValue; 7989 ExprObjectKind OK = OK_Ordinary; 7990 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7991 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7992 VK, OK, QuestionLoc); 7993 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7994 RHS.isInvalid()) 7995 return ExprError(); 7996 7997 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7998 RHS.get()); 7999 8000 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8001 8002 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8003 Context); 8004 8005 if (!commonExpr) 8006 return new (Context) 8007 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8008 RHS.get(), result, VK, OK); 8009 8010 return new (Context) BinaryConditionalOperator( 8011 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8012 ColonLoc, result, VK, OK); 8013 } 8014 8015 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8016 // being closely modeled after the C99 spec:-). The odd characteristic of this 8017 // routine is it effectively iqnores the qualifiers on the top level pointee. 8018 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8019 // FIXME: add a couple examples in this comment. 8020 static Sema::AssignConvertType 8021 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8022 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8023 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8024 8025 // get the "pointed to" type (ignoring qualifiers at the top level) 8026 const Type *lhptee, *rhptee; 8027 Qualifiers lhq, rhq; 8028 std::tie(lhptee, lhq) = 8029 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8030 std::tie(rhptee, rhq) = 8031 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8032 8033 Sema::AssignConvertType ConvTy = Sema::Compatible; 8034 8035 // C99 6.5.16.1p1: This following citation is common to constraints 8036 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8037 // qualifiers of the type *pointed to* by the right; 8038 8039 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8040 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8041 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8042 // Ignore lifetime for further calculation. 8043 lhq.removeObjCLifetime(); 8044 rhq.removeObjCLifetime(); 8045 } 8046 8047 if (!lhq.compatiblyIncludes(rhq)) { 8048 // Treat address-space mismatches as fatal. 8049 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8050 return Sema::IncompatiblePointerDiscardsQualifiers; 8051 8052 // It's okay to add or remove GC or lifetime qualifiers when converting to 8053 // and from void*. 8054 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8055 .compatiblyIncludes( 8056 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8057 && (lhptee->isVoidType() || rhptee->isVoidType())) 8058 ; // keep old 8059 8060 // Treat lifetime mismatches as fatal. 8061 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8062 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8063 8064 // For GCC/MS compatibility, other qualifier mismatches are treated 8065 // as still compatible in C. 8066 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8067 } 8068 8069 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8070 // incomplete type and the other is a pointer to a qualified or unqualified 8071 // version of void... 8072 if (lhptee->isVoidType()) { 8073 if (rhptee->isIncompleteOrObjectType()) 8074 return ConvTy; 8075 8076 // As an extension, we allow cast to/from void* to function pointer. 8077 assert(rhptee->isFunctionType()); 8078 return Sema::FunctionVoidPointer; 8079 } 8080 8081 if (rhptee->isVoidType()) { 8082 if (lhptee->isIncompleteOrObjectType()) 8083 return ConvTy; 8084 8085 // As an extension, we allow cast to/from void* to function pointer. 8086 assert(lhptee->isFunctionType()); 8087 return Sema::FunctionVoidPointer; 8088 } 8089 8090 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8091 // unqualified versions of compatible types, ... 8092 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8093 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8094 // Check if the pointee types are compatible ignoring the sign. 8095 // We explicitly check for char so that we catch "char" vs 8096 // "unsigned char" on systems where "char" is unsigned. 8097 if (lhptee->isCharType()) 8098 ltrans = S.Context.UnsignedCharTy; 8099 else if (lhptee->hasSignedIntegerRepresentation()) 8100 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8101 8102 if (rhptee->isCharType()) 8103 rtrans = S.Context.UnsignedCharTy; 8104 else if (rhptee->hasSignedIntegerRepresentation()) 8105 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8106 8107 if (ltrans == rtrans) { 8108 // Types are compatible ignoring the sign. Qualifier incompatibility 8109 // takes priority over sign incompatibility because the sign 8110 // warning can be disabled. 8111 if (ConvTy != Sema::Compatible) 8112 return ConvTy; 8113 8114 return Sema::IncompatiblePointerSign; 8115 } 8116 8117 // If we are a multi-level pointer, it's possible that our issue is simply 8118 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8119 // the eventual target type is the same and the pointers have the same 8120 // level of indirection, this must be the issue. 8121 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8122 do { 8123 std::tie(lhptee, lhq) = 8124 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8125 std::tie(rhptee, rhq) = 8126 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8127 8128 // Inconsistent address spaces at this point is invalid, even if the 8129 // address spaces would be compatible. 8130 // FIXME: This doesn't catch address space mismatches for pointers of 8131 // different nesting levels, like: 8132 // __local int *** a; 8133 // int ** b = a; 8134 // It's not clear how to actually determine when such pointers are 8135 // invalidly incompatible. 8136 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8137 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8138 8139 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8140 8141 if (lhptee == rhptee) 8142 return Sema::IncompatibleNestedPointerQualifiers; 8143 } 8144 8145 // General pointer incompatibility takes priority over qualifiers. 8146 return Sema::IncompatiblePointer; 8147 } 8148 if (!S.getLangOpts().CPlusPlus && 8149 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8150 return Sema::IncompatiblePointer; 8151 return ConvTy; 8152 } 8153 8154 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8155 /// block pointer types are compatible or whether a block and normal pointer 8156 /// are compatible. It is more restrict than comparing two function pointer 8157 // types. 8158 static Sema::AssignConvertType 8159 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8160 QualType RHSType) { 8161 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8162 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8163 8164 QualType lhptee, rhptee; 8165 8166 // get the "pointed to" type (ignoring qualifiers at the top level) 8167 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8168 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8169 8170 // In C++, the types have to match exactly. 8171 if (S.getLangOpts().CPlusPlus) 8172 return Sema::IncompatibleBlockPointer; 8173 8174 Sema::AssignConvertType ConvTy = Sema::Compatible; 8175 8176 // For blocks we enforce that qualifiers are identical. 8177 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8178 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8179 if (S.getLangOpts().OpenCL) { 8180 LQuals.removeAddressSpace(); 8181 RQuals.removeAddressSpace(); 8182 } 8183 if (LQuals != RQuals) 8184 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8185 8186 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8187 // assignment. 8188 // The current behavior is similar to C++ lambdas. A block might be 8189 // assigned to a variable iff its return type and parameters are compatible 8190 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8191 // an assignment. Presumably it should behave in way that a function pointer 8192 // assignment does in C, so for each parameter and return type: 8193 // * CVR and address space of LHS should be a superset of CVR and address 8194 // space of RHS. 8195 // * unqualified types should be compatible. 8196 if (S.getLangOpts().OpenCL) { 8197 if (!S.Context.typesAreBlockPointerCompatible( 8198 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8199 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8200 return Sema::IncompatibleBlockPointer; 8201 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8202 return Sema::IncompatibleBlockPointer; 8203 8204 return ConvTy; 8205 } 8206 8207 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8208 /// for assignment compatibility. 8209 static Sema::AssignConvertType 8210 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8211 QualType RHSType) { 8212 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8213 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8214 8215 if (LHSType->isObjCBuiltinType()) { 8216 // Class is not compatible with ObjC object pointers. 8217 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8218 !RHSType->isObjCQualifiedClassType()) 8219 return Sema::IncompatiblePointer; 8220 return Sema::Compatible; 8221 } 8222 if (RHSType->isObjCBuiltinType()) { 8223 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8224 !LHSType->isObjCQualifiedClassType()) 8225 return Sema::IncompatiblePointer; 8226 return Sema::Compatible; 8227 } 8228 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8229 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8230 8231 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8232 // make an exception for id<P> 8233 !LHSType->isObjCQualifiedIdType()) 8234 return Sema::CompatiblePointerDiscardsQualifiers; 8235 8236 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8237 return Sema::Compatible; 8238 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8239 return Sema::IncompatibleObjCQualifiedId; 8240 return Sema::IncompatiblePointer; 8241 } 8242 8243 Sema::AssignConvertType 8244 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8245 QualType LHSType, QualType RHSType) { 8246 // Fake up an opaque expression. We don't actually care about what 8247 // cast operations are required, so if CheckAssignmentConstraints 8248 // adds casts to this they'll be wasted, but fortunately that doesn't 8249 // usually happen on valid code. 8250 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8251 ExprResult RHSPtr = &RHSExpr; 8252 CastKind K; 8253 8254 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8255 } 8256 8257 /// This helper function returns true if QT is a vector type that has element 8258 /// type ElementType. 8259 static bool isVector(QualType QT, QualType ElementType) { 8260 if (const VectorType *VT = QT->getAs<VectorType>()) 8261 return VT->getElementType() == ElementType; 8262 return false; 8263 } 8264 8265 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8266 /// has code to accommodate several GCC extensions when type checking 8267 /// pointers. Here are some objectionable examples that GCC considers warnings: 8268 /// 8269 /// int a, *pint; 8270 /// short *pshort; 8271 /// struct foo *pfoo; 8272 /// 8273 /// pint = pshort; // warning: assignment from incompatible pointer type 8274 /// a = pint; // warning: assignment makes integer from pointer without a cast 8275 /// pint = a; // warning: assignment makes pointer from integer without a cast 8276 /// pint = pfoo; // warning: assignment from incompatible pointer type 8277 /// 8278 /// As a result, the code for dealing with pointers is more complex than the 8279 /// C99 spec dictates. 8280 /// 8281 /// Sets 'Kind' for any result kind except Incompatible. 8282 Sema::AssignConvertType 8283 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8284 CastKind &Kind, bool ConvertRHS) { 8285 QualType RHSType = RHS.get()->getType(); 8286 QualType OrigLHSType = LHSType; 8287 8288 // Get canonical types. We're not formatting these types, just comparing 8289 // them. 8290 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8291 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8292 8293 // Common case: no conversion required. 8294 if (LHSType == RHSType) { 8295 Kind = CK_NoOp; 8296 return Compatible; 8297 } 8298 8299 // If we have an atomic type, try a non-atomic assignment, then just add an 8300 // atomic qualification step. 8301 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8302 Sema::AssignConvertType result = 8303 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8304 if (result != Compatible) 8305 return result; 8306 if (Kind != CK_NoOp && ConvertRHS) 8307 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8308 Kind = CK_NonAtomicToAtomic; 8309 return Compatible; 8310 } 8311 8312 // If the left-hand side is a reference type, then we are in a 8313 // (rare!) case where we've allowed the use of references in C, 8314 // e.g., as a parameter type in a built-in function. In this case, 8315 // just make sure that the type referenced is compatible with the 8316 // right-hand side type. The caller is responsible for adjusting 8317 // LHSType so that the resulting expression does not have reference 8318 // type. 8319 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8320 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8321 Kind = CK_LValueBitCast; 8322 return Compatible; 8323 } 8324 return Incompatible; 8325 } 8326 8327 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8328 // to the same ExtVector type. 8329 if (LHSType->isExtVectorType()) { 8330 if (RHSType->isExtVectorType()) 8331 return Incompatible; 8332 if (RHSType->isArithmeticType()) { 8333 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8334 if (ConvertRHS) 8335 RHS = prepareVectorSplat(LHSType, RHS.get()); 8336 Kind = CK_VectorSplat; 8337 return Compatible; 8338 } 8339 } 8340 8341 // Conversions to or from vector type. 8342 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8343 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8344 // Allow assignments of an AltiVec vector type to an equivalent GCC 8345 // vector type and vice versa 8346 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8347 Kind = CK_BitCast; 8348 return Compatible; 8349 } 8350 8351 // If we are allowing lax vector conversions, and LHS and RHS are both 8352 // vectors, the total size only needs to be the same. This is a bitcast; 8353 // no bits are changed but the result type is different. 8354 if (isLaxVectorConversion(RHSType, LHSType)) { 8355 Kind = CK_BitCast; 8356 return IncompatibleVectors; 8357 } 8358 } 8359 8360 // When the RHS comes from another lax conversion (e.g. binops between 8361 // scalars and vectors) the result is canonicalized as a vector. When the 8362 // LHS is also a vector, the lax is allowed by the condition above. Handle 8363 // the case where LHS is a scalar. 8364 if (LHSType->isScalarType()) { 8365 const VectorType *VecType = RHSType->getAs<VectorType>(); 8366 if (VecType && VecType->getNumElements() == 1 && 8367 isLaxVectorConversion(RHSType, LHSType)) { 8368 ExprResult *VecExpr = &RHS; 8369 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8370 Kind = CK_BitCast; 8371 return Compatible; 8372 } 8373 } 8374 8375 return Incompatible; 8376 } 8377 8378 // Diagnose attempts to convert between __float128 and long double where 8379 // such conversions currently can't be handled. 8380 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8381 return Incompatible; 8382 8383 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8384 // discards the imaginary part. 8385 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8386 !LHSType->getAs<ComplexType>()) 8387 return Incompatible; 8388 8389 // Arithmetic conversions. 8390 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8391 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8392 if (ConvertRHS) 8393 Kind = PrepareScalarCast(RHS, LHSType); 8394 return Compatible; 8395 } 8396 8397 // Conversions to normal pointers. 8398 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8399 // U* -> T* 8400 if (isa<PointerType>(RHSType)) { 8401 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8402 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8403 if (AddrSpaceL != AddrSpaceR) 8404 Kind = CK_AddressSpaceConversion; 8405 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8406 Kind = CK_NoOp; 8407 else 8408 Kind = CK_BitCast; 8409 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8410 } 8411 8412 // int -> T* 8413 if (RHSType->isIntegerType()) { 8414 Kind = CK_IntegralToPointer; // FIXME: null? 8415 return IntToPointer; 8416 } 8417 8418 // C pointers are not compatible with ObjC object pointers, 8419 // with two exceptions: 8420 if (isa<ObjCObjectPointerType>(RHSType)) { 8421 // - conversions to void* 8422 if (LHSPointer->getPointeeType()->isVoidType()) { 8423 Kind = CK_BitCast; 8424 return Compatible; 8425 } 8426 8427 // - conversions from 'Class' to the redefinition type 8428 if (RHSType->isObjCClassType() && 8429 Context.hasSameType(LHSType, 8430 Context.getObjCClassRedefinitionType())) { 8431 Kind = CK_BitCast; 8432 return Compatible; 8433 } 8434 8435 Kind = CK_BitCast; 8436 return IncompatiblePointer; 8437 } 8438 8439 // U^ -> void* 8440 if (RHSType->getAs<BlockPointerType>()) { 8441 if (LHSPointer->getPointeeType()->isVoidType()) { 8442 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8443 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8444 ->getPointeeType() 8445 .getAddressSpace(); 8446 Kind = 8447 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8448 return Compatible; 8449 } 8450 } 8451 8452 return Incompatible; 8453 } 8454 8455 // Conversions to block pointers. 8456 if (isa<BlockPointerType>(LHSType)) { 8457 // U^ -> T^ 8458 if (RHSType->isBlockPointerType()) { 8459 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8460 ->getPointeeType() 8461 .getAddressSpace(); 8462 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8463 ->getPointeeType() 8464 .getAddressSpace(); 8465 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8466 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8467 } 8468 8469 // int or null -> T^ 8470 if (RHSType->isIntegerType()) { 8471 Kind = CK_IntegralToPointer; // FIXME: null 8472 return IntToBlockPointer; 8473 } 8474 8475 // id -> T^ 8476 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8477 Kind = CK_AnyPointerToBlockPointerCast; 8478 return Compatible; 8479 } 8480 8481 // void* -> T^ 8482 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8483 if (RHSPT->getPointeeType()->isVoidType()) { 8484 Kind = CK_AnyPointerToBlockPointerCast; 8485 return Compatible; 8486 } 8487 8488 return Incompatible; 8489 } 8490 8491 // Conversions to Objective-C pointers. 8492 if (isa<ObjCObjectPointerType>(LHSType)) { 8493 // A* -> B* 8494 if (RHSType->isObjCObjectPointerType()) { 8495 Kind = CK_BitCast; 8496 Sema::AssignConvertType result = 8497 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8498 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8499 result == Compatible && 8500 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8501 result = IncompatibleObjCWeakRef; 8502 return result; 8503 } 8504 8505 // int or null -> A* 8506 if (RHSType->isIntegerType()) { 8507 Kind = CK_IntegralToPointer; // FIXME: null 8508 return IntToPointer; 8509 } 8510 8511 // In general, C pointers are not compatible with ObjC object pointers, 8512 // with two exceptions: 8513 if (isa<PointerType>(RHSType)) { 8514 Kind = CK_CPointerToObjCPointerCast; 8515 8516 // - conversions from 'void*' 8517 if (RHSType->isVoidPointerType()) { 8518 return Compatible; 8519 } 8520 8521 // - conversions to 'Class' from its redefinition type 8522 if (LHSType->isObjCClassType() && 8523 Context.hasSameType(RHSType, 8524 Context.getObjCClassRedefinitionType())) { 8525 return Compatible; 8526 } 8527 8528 return IncompatiblePointer; 8529 } 8530 8531 // Only under strict condition T^ is compatible with an Objective-C pointer. 8532 if (RHSType->isBlockPointerType() && 8533 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8534 if (ConvertRHS) 8535 maybeExtendBlockObject(RHS); 8536 Kind = CK_BlockPointerToObjCPointerCast; 8537 return Compatible; 8538 } 8539 8540 return Incompatible; 8541 } 8542 8543 // Conversions from pointers that are not covered by the above. 8544 if (isa<PointerType>(RHSType)) { 8545 // T* -> _Bool 8546 if (LHSType == Context.BoolTy) { 8547 Kind = CK_PointerToBoolean; 8548 return Compatible; 8549 } 8550 8551 // T* -> int 8552 if (LHSType->isIntegerType()) { 8553 Kind = CK_PointerToIntegral; 8554 return PointerToInt; 8555 } 8556 8557 return Incompatible; 8558 } 8559 8560 // Conversions from Objective-C pointers that are not covered by the above. 8561 if (isa<ObjCObjectPointerType>(RHSType)) { 8562 // T* -> _Bool 8563 if (LHSType == Context.BoolTy) { 8564 Kind = CK_PointerToBoolean; 8565 return Compatible; 8566 } 8567 8568 // T* -> int 8569 if (LHSType->isIntegerType()) { 8570 Kind = CK_PointerToIntegral; 8571 return PointerToInt; 8572 } 8573 8574 return Incompatible; 8575 } 8576 8577 // struct A -> struct B 8578 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8579 if (Context.typesAreCompatible(LHSType, RHSType)) { 8580 Kind = CK_NoOp; 8581 return Compatible; 8582 } 8583 } 8584 8585 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8586 Kind = CK_IntToOCLSampler; 8587 return Compatible; 8588 } 8589 8590 return Incompatible; 8591 } 8592 8593 /// Constructs a transparent union from an expression that is 8594 /// used to initialize the transparent union. 8595 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8596 ExprResult &EResult, QualType UnionType, 8597 FieldDecl *Field) { 8598 // Build an initializer list that designates the appropriate member 8599 // of the transparent union. 8600 Expr *E = EResult.get(); 8601 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8602 E, SourceLocation()); 8603 Initializer->setType(UnionType); 8604 Initializer->setInitializedFieldInUnion(Field); 8605 8606 // Build a compound literal constructing a value of the transparent 8607 // union type from this initializer list. 8608 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8609 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8610 VK_RValue, Initializer, false); 8611 } 8612 8613 Sema::AssignConvertType 8614 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8615 ExprResult &RHS) { 8616 QualType RHSType = RHS.get()->getType(); 8617 8618 // If the ArgType is a Union type, we want to handle a potential 8619 // transparent_union GCC extension. 8620 const RecordType *UT = ArgType->getAsUnionType(); 8621 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8622 return Incompatible; 8623 8624 // The field to initialize within the transparent union. 8625 RecordDecl *UD = UT->getDecl(); 8626 FieldDecl *InitField = nullptr; 8627 // It's compatible if the expression matches any of the fields. 8628 for (auto *it : UD->fields()) { 8629 if (it->getType()->isPointerType()) { 8630 // If the transparent union contains a pointer type, we allow: 8631 // 1) void pointer 8632 // 2) null pointer constant 8633 if (RHSType->isPointerType()) 8634 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8635 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8636 InitField = it; 8637 break; 8638 } 8639 8640 if (RHS.get()->isNullPointerConstant(Context, 8641 Expr::NPC_ValueDependentIsNull)) { 8642 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8643 CK_NullToPointer); 8644 InitField = it; 8645 break; 8646 } 8647 } 8648 8649 CastKind Kind; 8650 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8651 == Compatible) { 8652 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8653 InitField = it; 8654 break; 8655 } 8656 } 8657 8658 if (!InitField) 8659 return Incompatible; 8660 8661 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8662 return Compatible; 8663 } 8664 8665 Sema::AssignConvertType 8666 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8667 bool Diagnose, 8668 bool DiagnoseCFAudited, 8669 bool ConvertRHS) { 8670 // We need to be able to tell the caller whether we diagnosed a problem, if 8671 // they ask us to issue diagnostics. 8672 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8673 8674 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8675 // we can't avoid *all* modifications at the moment, so we need some somewhere 8676 // to put the updated value. 8677 ExprResult LocalRHS = CallerRHS; 8678 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8679 8680 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8681 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8682 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8683 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8684 Diag(RHS.get()->getExprLoc(), 8685 diag::warn_noderef_to_dereferenceable_pointer) 8686 << RHS.get()->getSourceRange(); 8687 } 8688 } 8689 } 8690 8691 if (getLangOpts().CPlusPlus) { 8692 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8693 // C++ 5.17p3: If the left operand is not of class type, the 8694 // expression is implicitly converted (C++ 4) to the 8695 // cv-unqualified type of the left operand. 8696 QualType RHSType = RHS.get()->getType(); 8697 if (Diagnose) { 8698 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8699 AA_Assigning); 8700 } else { 8701 ImplicitConversionSequence ICS = 8702 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8703 /*SuppressUserConversions=*/false, 8704 /*AllowExplicit=*/false, 8705 /*InOverloadResolution=*/false, 8706 /*CStyle=*/false, 8707 /*AllowObjCWritebackConversion=*/false); 8708 if (ICS.isFailure()) 8709 return Incompatible; 8710 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8711 ICS, AA_Assigning); 8712 } 8713 if (RHS.isInvalid()) 8714 return Incompatible; 8715 Sema::AssignConvertType result = Compatible; 8716 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8717 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8718 result = IncompatibleObjCWeakRef; 8719 return result; 8720 } 8721 8722 // FIXME: Currently, we fall through and treat C++ classes like C 8723 // structures. 8724 // FIXME: We also fall through for atomics; not sure what should 8725 // happen there, though. 8726 } else if (RHS.get()->getType() == Context.OverloadTy) { 8727 // As a set of extensions to C, we support overloading on functions. These 8728 // functions need to be resolved here. 8729 DeclAccessPair DAP; 8730 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8731 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8732 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8733 else 8734 return Incompatible; 8735 } 8736 8737 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8738 // a null pointer constant. 8739 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8740 LHSType->isBlockPointerType()) && 8741 RHS.get()->isNullPointerConstant(Context, 8742 Expr::NPC_ValueDependentIsNull)) { 8743 if (Diagnose || ConvertRHS) { 8744 CastKind Kind; 8745 CXXCastPath Path; 8746 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8747 /*IgnoreBaseAccess=*/false, Diagnose); 8748 if (ConvertRHS) 8749 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8750 } 8751 return Compatible; 8752 } 8753 8754 // OpenCL queue_t type assignment. 8755 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8756 Context, Expr::NPC_ValueDependentIsNull)) { 8757 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8758 return Compatible; 8759 } 8760 8761 // This check seems unnatural, however it is necessary to ensure the proper 8762 // conversion of functions/arrays. If the conversion were done for all 8763 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8764 // expressions that suppress this implicit conversion (&, sizeof). 8765 // 8766 // Suppress this for references: C++ 8.5.3p5. 8767 if (!LHSType->isReferenceType()) { 8768 // FIXME: We potentially allocate here even if ConvertRHS is false. 8769 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8770 if (RHS.isInvalid()) 8771 return Incompatible; 8772 } 8773 CastKind Kind; 8774 Sema::AssignConvertType result = 8775 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8776 8777 // C99 6.5.16.1p2: The value of the right operand is converted to the 8778 // type of the assignment expression. 8779 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8780 // so that we can use references in built-in functions even in C. 8781 // The getNonReferenceType() call makes sure that the resulting expression 8782 // does not have reference type. 8783 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8784 QualType Ty = LHSType.getNonLValueExprType(Context); 8785 Expr *E = RHS.get(); 8786 8787 // Check for various Objective-C errors. If we are not reporting 8788 // diagnostics and just checking for errors, e.g., during overload 8789 // resolution, return Incompatible to indicate the failure. 8790 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8791 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8792 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8793 if (!Diagnose) 8794 return Incompatible; 8795 } 8796 if (getLangOpts().ObjC && 8797 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8798 E->getType(), E, Diagnose) || 8799 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8800 if (!Diagnose) 8801 return Incompatible; 8802 // Replace the expression with a corrected version and continue so we 8803 // can find further errors. 8804 RHS = E; 8805 return Compatible; 8806 } 8807 8808 if (ConvertRHS) 8809 RHS = ImpCastExprToType(E, Ty, Kind); 8810 } 8811 8812 return result; 8813 } 8814 8815 namespace { 8816 /// The original operand to an operator, prior to the application of the usual 8817 /// arithmetic conversions and converting the arguments of a builtin operator 8818 /// candidate. 8819 struct OriginalOperand { 8820 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8821 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8822 Op = MTE->getSubExpr(); 8823 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8824 Op = BTE->getSubExpr(); 8825 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8826 Orig = ICE->getSubExprAsWritten(); 8827 Conversion = ICE->getConversionFunction(); 8828 } 8829 } 8830 8831 QualType getType() const { return Orig->getType(); } 8832 8833 Expr *Orig; 8834 NamedDecl *Conversion; 8835 }; 8836 } 8837 8838 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8839 ExprResult &RHS) { 8840 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8841 8842 Diag(Loc, diag::err_typecheck_invalid_operands) 8843 << OrigLHS.getType() << OrigRHS.getType() 8844 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8845 8846 // If a user-defined conversion was applied to either of the operands prior 8847 // to applying the built-in operator rules, tell the user about it. 8848 if (OrigLHS.Conversion) { 8849 Diag(OrigLHS.Conversion->getLocation(), 8850 diag::note_typecheck_invalid_operands_converted) 8851 << 0 << LHS.get()->getType(); 8852 } 8853 if (OrigRHS.Conversion) { 8854 Diag(OrigRHS.Conversion->getLocation(), 8855 diag::note_typecheck_invalid_operands_converted) 8856 << 1 << RHS.get()->getType(); 8857 } 8858 8859 return QualType(); 8860 } 8861 8862 // Diagnose cases where a scalar was implicitly converted to a vector and 8863 // diagnose the underlying types. Otherwise, diagnose the error 8864 // as invalid vector logical operands for non-C++ cases. 8865 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8866 ExprResult &RHS) { 8867 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8868 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8869 8870 bool LHSNatVec = LHSType->isVectorType(); 8871 bool RHSNatVec = RHSType->isVectorType(); 8872 8873 if (!(LHSNatVec && RHSNatVec)) { 8874 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8875 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8876 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8877 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8878 << Vector->getSourceRange(); 8879 return QualType(); 8880 } 8881 8882 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8883 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8884 << RHS.get()->getSourceRange(); 8885 8886 return QualType(); 8887 } 8888 8889 /// Try to convert a value of non-vector type to a vector type by converting 8890 /// the type to the element type of the vector and then performing a splat. 8891 /// If the language is OpenCL, we only use conversions that promote scalar 8892 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8893 /// for float->int. 8894 /// 8895 /// OpenCL V2.0 6.2.6.p2: 8896 /// An error shall occur if any scalar operand type has greater rank 8897 /// than the type of the vector element. 8898 /// 8899 /// \param scalar - if non-null, actually perform the conversions 8900 /// \return true if the operation fails (but without diagnosing the failure) 8901 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8902 QualType scalarTy, 8903 QualType vectorEltTy, 8904 QualType vectorTy, 8905 unsigned &DiagID) { 8906 // The conversion to apply to the scalar before splatting it, 8907 // if necessary. 8908 CastKind scalarCast = CK_NoOp; 8909 8910 if (vectorEltTy->isIntegralType(S.Context)) { 8911 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8912 (scalarTy->isIntegerType() && 8913 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8914 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8915 return true; 8916 } 8917 if (!scalarTy->isIntegralType(S.Context)) 8918 return true; 8919 scalarCast = CK_IntegralCast; 8920 } else if (vectorEltTy->isRealFloatingType()) { 8921 if (scalarTy->isRealFloatingType()) { 8922 if (S.getLangOpts().OpenCL && 8923 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8924 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8925 return true; 8926 } 8927 scalarCast = CK_FloatingCast; 8928 } 8929 else if (scalarTy->isIntegralType(S.Context)) 8930 scalarCast = CK_IntegralToFloating; 8931 else 8932 return true; 8933 } else { 8934 return true; 8935 } 8936 8937 // Adjust scalar if desired. 8938 if (scalar) { 8939 if (scalarCast != CK_NoOp) 8940 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8941 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8942 } 8943 return false; 8944 } 8945 8946 /// Convert vector E to a vector with the same number of elements but different 8947 /// element type. 8948 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8949 const auto *VecTy = E->getType()->getAs<VectorType>(); 8950 assert(VecTy && "Expression E must be a vector"); 8951 QualType NewVecTy = S.Context.getVectorType(ElementType, 8952 VecTy->getNumElements(), 8953 VecTy->getVectorKind()); 8954 8955 // Look through the implicit cast. Return the subexpression if its type is 8956 // NewVecTy. 8957 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8958 if (ICE->getSubExpr()->getType() == NewVecTy) 8959 return ICE->getSubExpr(); 8960 8961 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8962 return S.ImpCastExprToType(E, NewVecTy, Cast); 8963 } 8964 8965 /// Test if a (constant) integer Int can be casted to another integer type 8966 /// IntTy without losing precision. 8967 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8968 QualType OtherIntTy) { 8969 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8970 8971 // Reject cases where the value of the Int is unknown as that would 8972 // possibly cause truncation, but accept cases where the scalar can be 8973 // demoted without loss of precision. 8974 Expr::EvalResult EVResult; 8975 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8976 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8977 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8978 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8979 8980 if (CstInt) { 8981 // If the scalar is constant and is of a higher order and has more active 8982 // bits that the vector element type, reject it. 8983 llvm::APSInt Result = EVResult.Val.getInt(); 8984 unsigned NumBits = IntSigned 8985 ? (Result.isNegative() ? Result.getMinSignedBits() 8986 : Result.getActiveBits()) 8987 : Result.getActiveBits(); 8988 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8989 return true; 8990 8991 // If the signedness of the scalar type and the vector element type 8992 // differs and the number of bits is greater than that of the vector 8993 // element reject it. 8994 return (IntSigned != OtherIntSigned && 8995 NumBits > S.Context.getIntWidth(OtherIntTy)); 8996 } 8997 8998 // Reject cases where the value of the scalar is not constant and it's 8999 // order is greater than that of the vector element type. 9000 return (Order < 0); 9001 } 9002 9003 /// Test if a (constant) integer Int can be casted to floating point type 9004 /// FloatTy without losing precision. 9005 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9006 QualType FloatTy) { 9007 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9008 9009 // Determine if the integer constant can be expressed as a floating point 9010 // number of the appropriate type. 9011 Expr::EvalResult EVResult; 9012 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9013 9014 uint64_t Bits = 0; 9015 if (CstInt) { 9016 // Reject constants that would be truncated if they were converted to 9017 // the floating point type. Test by simple to/from conversion. 9018 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9019 // could be avoided if there was a convertFromAPInt method 9020 // which could signal back if implicit truncation occurred. 9021 llvm::APSInt Result = EVResult.Val.getInt(); 9022 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9023 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9024 llvm::APFloat::rmTowardZero); 9025 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9026 !IntTy->hasSignedIntegerRepresentation()); 9027 bool Ignored = false; 9028 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9029 &Ignored); 9030 if (Result != ConvertBack) 9031 return true; 9032 } else { 9033 // Reject types that cannot be fully encoded into the mantissa of 9034 // the float. 9035 Bits = S.Context.getTypeSize(IntTy); 9036 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9037 S.Context.getFloatTypeSemantics(FloatTy)); 9038 if (Bits > FloatPrec) 9039 return true; 9040 } 9041 9042 return false; 9043 } 9044 9045 /// Attempt to convert and splat Scalar into a vector whose types matches 9046 /// Vector following GCC conversion rules. The rule is that implicit 9047 /// conversion can occur when Scalar can be casted to match Vector's element 9048 /// type without causing truncation of Scalar. 9049 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9050 ExprResult *Vector) { 9051 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9052 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9053 const VectorType *VT = VectorTy->getAs<VectorType>(); 9054 9055 assert(!isa<ExtVectorType>(VT) && 9056 "ExtVectorTypes should not be handled here!"); 9057 9058 QualType VectorEltTy = VT->getElementType(); 9059 9060 // Reject cases where the vector element type or the scalar element type are 9061 // not integral or floating point types. 9062 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9063 return true; 9064 9065 // The conversion to apply to the scalar before splatting it, 9066 // if necessary. 9067 CastKind ScalarCast = CK_NoOp; 9068 9069 // Accept cases where the vector elements are integers and the scalar is 9070 // an integer. 9071 // FIXME: Notionally if the scalar was a floating point value with a precise 9072 // integral representation, we could cast it to an appropriate integer 9073 // type and then perform the rest of the checks here. GCC will perform 9074 // this conversion in some cases as determined by the input language. 9075 // We should accept it on a language independent basis. 9076 if (VectorEltTy->isIntegralType(S.Context) && 9077 ScalarTy->isIntegralType(S.Context) && 9078 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9079 9080 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9081 return true; 9082 9083 ScalarCast = CK_IntegralCast; 9084 } else if (VectorEltTy->isIntegralType(S.Context) && 9085 ScalarTy->isRealFloatingType()) { 9086 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9087 ScalarCast = CK_FloatingToIntegral; 9088 else 9089 return true; 9090 } else if (VectorEltTy->isRealFloatingType()) { 9091 if (ScalarTy->isRealFloatingType()) { 9092 9093 // Reject cases where the scalar type is not a constant and has a higher 9094 // Order than the vector element type. 9095 llvm::APFloat Result(0.0); 9096 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 9097 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9098 if (!CstScalar && Order < 0) 9099 return true; 9100 9101 // If the scalar cannot be safely casted to the vector element type, 9102 // reject it. 9103 if (CstScalar) { 9104 bool Truncated = false; 9105 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9106 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9107 if (Truncated) 9108 return true; 9109 } 9110 9111 ScalarCast = CK_FloatingCast; 9112 } else if (ScalarTy->isIntegralType(S.Context)) { 9113 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9114 return true; 9115 9116 ScalarCast = CK_IntegralToFloating; 9117 } else 9118 return true; 9119 } 9120 9121 // Adjust scalar if desired. 9122 if (Scalar) { 9123 if (ScalarCast != CK_NoOp) 9124 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9125 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9126 } 9127 return false; 9128 } 9129 9130 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9131 SourceLocation Loc, bool IsCompAssign, 9132 bool AllowBothBool, 9133 bool AllowBoolConversions) { 9134 if (!IsCompAssign) { 9135 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9136 if (LHS.isInvalid()) 9137 return QualType(); 9138 } 9139 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9140 if (RHS.isInvalid()) 9141 return QualType(); 9142 9143 // For conversion purposes, we ignore any qualifiers. 9144 // For example, "const float" and "float" are equivalent. 9145 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9146 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9147 9148 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9149 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9150 assert(LHSVecType || RHSVecType); 9151 9152 // AltiVec-style "vector bool op vector bool" combinations are allowed 9153 // for some operators but not others. 9154 if (!AllowBothBool && 9155 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9156 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9157 return InvalidOperands(Loc, LHS, RHS); 9158 9159 // If the vector types are identical, return. 9160 if (Context.hasSameType(LHSType, RHSType)) 9161 return LHSType; 9162 9163 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9164 if (LHSVecType && RHSVecType && 9165 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9166 if (isa<ExtVectorType>(LHSVecType)) { 9167 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9168 return LHSType; 9169 } 9170 9171 if (!IsCompAssign) 9172 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9173 return RHSType; 9174 } 9175 9176 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9177 // can be mixed, with the result being the non-bool type. The non-bool 9178 // operand must have integer element type. 9179 if (AllowBoolConversions && LHSVecType && RHSVecType && 9180 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9181 (Context.getTypeSize(LHSVecType->getElementType()) == 9182 Context.getTypeSize(RHSVecType->getElementType()))) { 9183 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9184 LHSVecType->getElementType()->isIntegerType() && 9185 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9186 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9187 return LHSType; 9188 } 9189 if (!IsCompAssign && 9190 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9191 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9192 RHSVecType->getElementType()->isIntegerType()) { 9193 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9194 return RHSType; 9195 } 9196 } 9197 9198 // If there's a vector type and a scalar, try to convert the scalar to 9199 // the vector element type and splat. 9200 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9201 if (!RHSVecType) { 9202 if (isa<ExtVectorType>(LHSVecType)) { 9203 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9204 LHSVecType->getElementType(), LHSType, 9205 DiagID)) 9206 return LHSType; 9207 } else { 9208 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9209 return LHSType; 9210 } 9211 } 9212 if (!LHSVecType) { 9213 if (isa<ExtVectorType>(RHSVecType)) { 9214 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9215 LHSType, RHSVecType->getElementType(), 9216 RHSType, DiagID)) 9217 return RHSType; 9218 } else { 9219 if (LHS.get()->getValueKind() == VK_LValue || 9220 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9221 return RHSType; 9222 } 9223 } 9224 9225 // FIXME: The code below also handles conversion between vectors and 9226 // non-scalars, we should break this down into fine grained specific checks 9227 // and emit proper diagnostics. 9228 QualType VecType = LHSVecType ? LHSType : RHSType; 9229 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9230 QualType OtherType = LHSVecType ? RHSType : LHSType; 9231 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9232 if (isLaxVectorConversion(OtherType, VecType)) { 9233 // If we're allowing lax vector conversions, only the total (data) size 9234 // needs to be the same. For non compound assignment, if one of the types is 9235 // scalar, the result is always the vector type. 9236 if (!IsCompAssign) { 9237 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9238 return VecType; 9239 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9240 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9241 // type. Note that this is already done by non-compound assignments in 9242 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9243 // <1 x T> -> T. The result is also a vector type. 9244 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9245 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9246 ExprResult *RHSExpr = &RHS; 9247 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9248 return VecType; 9249 } 9250 } 9251 9252 // Okay, the expression is invalid. 9253 9254 // If there's a non-vector, non-real operand, diagnose that. 9255 if ((!RHSVecType && !RHSType->isRealType()) || 9256 (!LHSVecType && !LHSType->isRealType())) { 9257 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9258 << LHSType << RHSType 9259 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9260 return QualType(); 9261 } 9262 9263 // OpenCL V1.1 6.2.6.p1: 9264 // If the operands are of more than one vector type, then an error shall 9265 // occur. Implicit conversions between vector types are not permitted, per 9266 // section 6.2.1. 9267 if (getLangOpts().OpenCL && 9268 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9269 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9270 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9271 << RHSType; 9272 return QualType(); 9273 } 9274 9275 9276 // If there is a vector type that is not a ExtVector and a scalar, we reach 9277 // this point if scalar could not be converted to the vector's element type 9278 // without truncation. 9279 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9280 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9281 QualType Scalar = LHSVecType ? RHSType : LHSType; 9282 QualType Vector = LHSVecType ? LHSType : RHSType; 9283 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9284 Diag(Loc, 9285 diag::err_typecheck_vector_not_convertable_implict_truncation) 9286 << ScalarOrVector << Scalar << Vector; 9287 9288 return QualType(); 9289 } 9290 9291 // Otherwise, use the generic diagnostic. 9292 Diag(Loc, DiagID) 9293 << LHSType << RHSType 9294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9295 return QualType(); 9296 } 9297 9298 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9299 // expression. These are mainly cases where the null pointer is used as an 9300 // integer instead of a pointer. 9301 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9302 SourceLocation Loc, bool IsCompare) { 9303 // The canonical way to check for a GNU null is with isNullPointerConstant, 9304 // but we use a bit of a hack here for speed; this is a relatively 9305 // hot path, and isNullPointerConstant is slow. 9306 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9307 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9308 9309 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9310 9311 // Avoid analyzing cases where the result will either be invalid (and 9312 // diagnosed as such) or entirely valid and not something to warn about. 9313 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9314 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9315 return; 9316 9317 // Comparison operations would not make sense with a null pointer no matter 9318 // what the other expression is. 9319 if (!IsCompare) { 9320 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9321 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9322 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9323 return; 9324 } 9325 9326 // The rest of the operations only make sense with a null pointer 9327 // if the other expression is a pointer. 9328 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9329 NonNullType->canDecayToPointerType()) 9330 return; 9331 9332 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9333 << LHSNull /* LHS is NULL */ << NonNullType 9334 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9335 } 9336 9337 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9338 SourceLocation Loc) { 9339 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9340 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9341 if (!LUE || !RUE) 9342 return; 9343 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9344 RUE->getKind() != UETT_SizeOf) 9345 return; 9346 9347 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9348 QualType LHSTy = LHSArg->getType(); 9349 QualType RHSTy; 9350 9351 if (RUE->isArgumentType()) 9352 RHSTy = RUE->getArgumentType(); 9353 else 9354 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9355 9356 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9357 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9358 return; 9359 9360 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9361 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9362 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9363 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9364 << LHSArgDecl; 9365 } 9366 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9367 QualType ArrayElemTy = ArrayTy->getElementType(); 9368 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9369 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9370 ArrayElemTy->isCharType() || 9371 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9372 return; 9373 S.Diag(Loc, diag::warn_division_sizeof_array) 9374 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9375 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9376 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9377 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9378 << LHSArgDecl; 9379 } 9380 9381 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9382 } 9383 } 9384 9385 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9386 ExprResult &RHS, 9387 SourceLocation Loc, bool IsDiv) { 9388 // Check for division/remainder by zero. 9389 Expr::EvalResult RHSValue; 9390 if (!RHS.get()->isValueDependent() && 9391 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9392 RHSValue.Val.getInt() == 0) 9393 S.DiagRuntimeBehavior(Loc, RHS.get(), 9394 S.PDiag(diag::warn_remainder_division_by_zero) 9395 << IsDiv << RHS.get()->getSourceRange()); 9396 } 9397 9398 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9399 SourceLocation Loc, 9400 bool IsCompAssign, bool IsDiv) { 9401 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9402 9403 if (LHS.get()->getType()->isVectorType() || 9404 RHS.get()->getType()->isVectorType()) 9405 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9406 /*AllowBothBool*/getLangOpts().AltiVec, 9407 /*AllowBoolConversions*/false); 9408 9409 QualType compType = UsualArithmeticConversions( 9410 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9411 if (LHS.isInvalid() || RHS.isInvalid()) 9412 return QualType(); 9413 9414 9415 if (compType.isNull() || !compType->isArithmeticType()) 9416 return InvalidOperands(Loc, LHS, RHS); 9417 if (IsDiv) { 9418 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9419 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9420 } 9421 return compType; 9422 } 9423 9424 QualType Sema::CheckRemainderOperands( 9425 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9426 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9427 9428 if (LHS.get()->getType()->isVectorType() || 9429 RHS.get()->getType()->isVectorType()) { 9430 if (LHS.get()->getType()->hasIntegerRepresentation() && 9431 RHS.get()->getType()->hasIntegerRepresentation()) 9432 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9433 /*AllowBothBool*/getLangOpts().AltiVec, 9434 /*AllowBoolConversions*/false); 9435 return InvalidOperands(Loc, LHS, RHS); 9436 } 9437 9438 QualType compType = UsualArithmeticConversions( 9439 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9440 if (LHS.isInvalid() || RHS.isInvalid()) 9441 return QualType(); 9442 9443 if (compType.isNull() || !compType->isIntegerType()) 9444 return InvalidOperands(Loc, LHS, RHS); 9445 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9446 return compType; 9447 } 9448 9449 /// Diagnose invalid arithmetic on two void pointers. 9450 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9451 Expr *LHSExpr, Expr *RHSExpr) { 9452 S.Diag(Loc, S.getLangOpts().CPlusPlus 9453 ? diag::err_typecheck_pointer_arith_void_type 9454 : diag::ext_gnu_void_ptr) 9455 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9456 << RHSExpr->getSourceRange(); 9457 } 9458 9459 /// Diagnose invalid arithmetic on a void pointer. 9460 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9461 Expr *Pointer) { 9462 S.Diag(Loc, S.getLangOpts().CPlusPlus 9463 ? diag::err_typecheck_pointer_arith_void_type 9464 : diag::ext_gnu_void_ptr) 9465 << 0 /* one pointer */ << Pointer->getSourceRange(); 9466 } 9467 9468 /// Diagnose invalid arithmetic on a null pointer. 9469 /// 9470 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9471 /// idiom, which we recognize as a GNU extension. 9472 /// 9473 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9474 Expr *Pointer, bool IsGNUIdiom) { 9475 if (IsGNUIdiom) 9476 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9477 << Pointer->getSourceRange(); 9478 else 9479 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9480 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9481 } 9482 9483 /// Diagnose invalid arithmetic on two function pointers. 9484 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9485 Expr *LHS, Expr *RHS) { 9486 assert(LHS->getType()->isAnyPointerType()); 9487 assert(RHS->getType()->isAnyPointerType()); 9488 S.Diag(Loc, S.getLangOpts().CPlusPlus 9489 ? diag::err_typecheck_pointer_arith_function_type 9490 : diag::ext_gnu_ptr_func_arith) 9491 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9492 // We only show the second type if it differs from the first. 9493 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9494 RHS->getType()) 9495 << RHS->getType()->getPointeeType() 9496 << LHS->getSourceRange() << RHS->getSourceRange(); 9497 } 9498 9499 /// Diagnose invalid arithmetic on a function pointer. 9500 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9501 Expr *Pointer) { 9502 assert(Pointer->getType()->isAnyPointerType()); 9503 S.Diag(Loc, S.getLangOpts().CPlusPlus 9504 ? diag::err_typecheck_pointer_arith_function_type 9505 : diag::ext_gnu_ptr_func_arith) 9506 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9507 << 0 /* one pointer, so only one type */ 9508 << Pointer->getSourceRange(); 9509 } 9510 9511 /// Emit error if Operand is incomplete pointer type 9512 /// 9513 /// \returns True if pointer has incomplete type 9514 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9515 Expr *Operand) { 9516 QualType ResType = Operand->getType(); 9517 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9518 ResType = ResAtomicType->getValueType(); 9519 9520 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9521 QualType PointeeTy = ResType->getPointeeType(); 9522 return S.RequireCompleteType(Loc, PointeeTy, 9523 diag::err_typecheck_arithmetic_incomplete_type, 9524 PointeeTy, Operand->getSourceRange()); 9525 } 9526 9527 /// Check the validity of an arithmetic pointer operand. 9528 /// 9529 /// If the operand has pointer type, this code will check for pointer types 9530 /// which are invalid in arithmetic operations. These will be diagnosed 9531 /// appropriately, including whether or not the use is supported as an 9532 /// extension. 9533 /// 9534 /// \returns True when the operand is valid to use (even if as an extension). 9535 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9536 Expr *Operand) { 9537 QualType ResType = Operand->getType(); 9538 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9539 ResType = ResAtomicType->getValueType(); 9540 9541 if (!ResType->isAnyPointerType()) return true; 9542 9543 QualType PointeeTy = ResType->getPointeeType(); 9544 if (PointeeTy->isVoidType()) { 9545 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9546 return !S.getLangOpts().CPlusPlus; 9547 } 9548 if (PointeeTy->isFunctionType()) { 9549 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9550 return !S.getLangOpts().CPlusPlus; 9551 } 9552 9553 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9554 9555 return true; 9556 } 9557 9558 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9559 /// operands. 9560 /// 9561 /// This routine will diagnose any invalid arithmetic on pointer operands much 9562 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9563 /// for emitting a single diagnostic even for operations where both LHS and RHS 9564 /// are (potentially problematic) pointers. 9565 /// 9566 /// \returns True when the operand is valid to use (even if as an extension). 9567 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9568 Expr *LHSExpr, Expr *RHSExpr) { 9569 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9570 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9571 if (!isLHSPointer && !isRHSPointer) return true; 9572 9573 QualType LHSPointeeTy, RHSPointeeTy; 9574 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9575 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9576 9577 // if both are pointers check if operation is valid wrt address spaces 9578 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9579 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9580 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9581 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9582 S.Diag(Loc, 9583 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9584 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9585 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9586 return false; 9587 } 9588 } 9589 9590 // Check for arithmetic on pointers to incomplete types. 9591 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9592 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9593 if (isLHSVoidPtr || isRHSVoidPtr) { 9594 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9595 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9596 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9597 9598 return !S.getLangOpts().CPlusPlus; 9599 } 9600 9601 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9602 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9603 if (isLHSFuncPtr || isRHSFuncPtr) { 9604 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9605 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9606 RHSExpr); 9607 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9608 9609 return !S.getLangOpts().CPlusPlus; 9610 } 9611 9612 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9613 return false; 9614 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9615 return false; 9616 9617 return true; 9618 } 9619 9620 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9621 /// literal. 9622 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9623 Expr *LHSExpr, Expr *RHSExpr) { 9624 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9625 Expr* IndexExpr = RHSExpr; 9626 if (!StrExpr) { 9627 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9628 IndexExpr = LHSExpr; 9629 } 9630 9631 bool IsStringPlusInt = StrExpr && 9632 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9633 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9634 return; 9635 9636 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9637 Self.Diag(OpLoc, diag::warn_string_plus_int) 9638 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9639 9640 // Only print a fixit for "str" + int, not for int + "str". 9641 if (IndexExpr == RHSExpr) { 9642 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9643 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9644 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9645 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9646 << FixItHint::CreateInsertion(EndLoc, "]"); 9647 } else 9648 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9649 } 9650 9651 /// Emit a warning when adding a char literal to a string. 9652 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9653 Expr *LHSExpr, Expr *RHSExpr) { 9654 const Expr *StringRefExpr = LHSExpr; 9655 const CharacterLiteral *CharExpr = 9656 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9657 9658 if (!CharExpr) { 9659 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9660 StringRefExpr = RHSExpr; 9661 } 9662 9663 if (!CharExpr || !StringRefExpr) 9664 return; 9665 9666 const QualType StringType = StringRefExpr->getType(); 9667 9668 // Return if not a PointerType. 9669 if (!StringType->isAnyPointerType()) 9670 return; 9671 9672 // Return if not a CharacterType. 9673 if (!StringType->getPointeeType()->isAnyCharacterType()) 9674 return; 9675 9676 ASTContext &Ctx = Self.getASTContext(); 9677 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9678 9679 const QualType CharType = CharExpr->getType(); 9680 if (!CharType->isAnyCharacterType() && 9681 CharType->isIntegerType() && 9682 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9683 Self.Diag(OpLoc, diag::warn_string_plus_char) 9684 << DiagRange << Ctx.CharTy; 9685 } else { 9686 Self.Diag(OpLoc, diag::warn_string_plus_char) 9687 << DiagRange << CharExpr->getType(); 9688 } 9689 9690 // Only print a fixit for str + char, not for char + str. 9691 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9692 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9693 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9694 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9695 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9696 << FixItHint::CreateInsertion(EndLoc, "]"); 9697 } else { 9698 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9699 } 9700 } 9701 9702 /// Emit error when two pointers are incompatible. 9703 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9704 Expr *LHSExpr, Expr *RHSExpr) { 9705 assert(LHSExpr->getType()->isAnyPointerType()); 9706 assert(RHSExpr->getType()->isAnyPointerType()); 9707 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9708 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9709 << RHSExpr->getSourceRange(); 9710 } 9711 9712 // C99 6.5.6 9713 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9714 SourceLocation Loc, BinaryOperatorKind Opc, 9715 QualType* CompLHSTy) { 9716 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9717 9718 if (LHS.get()->getType()->isVectorType() || 9719 RHS.get()->getType()->isVectorType()) { 9720 QualType compType = CheckVectorOperands( 9721 LHS, RHS, Loc, CompLHSTy, 9722 /*AllowBothBool*/getLangOpts().AltiVec, 9723 /*AllowBoolConversions*/getLangOpts().ZVector); 9724 if (CompLHSTy) *CompLHSTy = compType; 9725 return compType; 9726 } 9727 9728 QualType compType = UsualArithmeticConversions( 9729 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9730 if (LHS.isInvalid() || RHS.isInvalid()) 9731 return QualType(); 9732 9733 // Diagnose "string literal" '+' int and string '+' "char literal". 9734 if (Opc == BO_Add) { 9735 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9736 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9737 } 9738 9739 // handle the common case first (both operands are arithmetic). 9740 if (!compType.isNull() && compType->isArithmeticType()) { 9741 if (CompLHSTy) *CompLHSTy = compType; 9742 return compType; 9743 } 9744 9745 // Type-checking. Ultimately the pointer's going to be in PExp; 9746 // note that we bias towards the LHS being the pointer. 9747 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9748 9749 bool isObjCPointer; 9750 if (PExp->getType()->isPointerType()) { 9751 isObjCPointer = false; 9752 } else if (PExp->getType()->isObjCObjectPointerType()) { 9753 isObjCPointer = true; 9754 } else { 9755 std::swap(PExp, IExp); 9756 if (PExp->getType()->isPointerType()) { 9757 isObjCPointer = false; 9758 } else if (PExp->getType()->isObjCObjectPointerType()) { 9759 isObjCPointer = true; 9760 } else { 9761 return InvalidOperands(Loc, LHS, RHS); 9762 } 9763 } 9764 assert(PExp->getType()->isAnyPointerType()); 9765 9766 if (!IExp->getType()->isIntegerType()) 9767 return InvalidOperands(Loc, LHS, RHS); 9768 9769 // Adding to a null pointer results in undefined behavior. 9770 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9771 Context, Expr::NPC_ValueDependentIsNotNull)) { 9772 // In C++ adding zero to a null pointer is defined. 9773 Expr::EvalResult KnownVal; 9774 if (!getLangOpts().CPlusPlus || 9775 (!IExp->isValueDependent() && 9776 (!IExp->EvaluateAsInt(KnownVal, Context) || 9777 KnownVal.Val.getInt() != 0))) { 9778 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9779 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9780 Context, BO_Add, PExp, IExp); 9781 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9782 } 9783 } 9784 9785 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9786 return QualType(); 9787 9788 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9789 return QualType(); 9790 9791 // Check array bounds for pointer arithemtic 9792 CheckArrayAccess(PExp, IExp); 9793 9794 if (CompLHSTy) { 9795 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9796 if (LHSTy.isNull()) { 9797 LHSTy = LHS.get()->getType(); 9798 if (LHSTy->isPromotableIntegerType()) 9799 LHSTy = Context.getPromotedIntegerType(LHSTy); 9800 } 9801 *CompLHSTy = LHSTy; 9802 } 9803 9804 return PExp->getType(); 9805 } 9806 9807 // C99 6.5.6 9808 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9809 SourceLocation Loc, 9810 QualType* CompLHSTy) { 9811 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9812 9813 if (LHS.get()->getType()->isVectorType() || 9814 RHS.get()->getType()->isVectorType()) { 9815 QualType compType = CheckVectorOperands( 9816 LHS, RHS, Loc, CompLHSTy, 9817 /*AllowBothBool*/getLangOpts().AltiVec, 9818 /*AllowBoolConversions*/getLangOpts().ZVector); 9819 if (CompLHSTy) *CompLHSTy = compType; 9820 return compType; 9821 } 9822 9823 QualType compType = UsualArithmeticConversions( 9824 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9825 if (LHS.isInvalid() || RHS.isInvalid()) 9826 return QualType(); 9827 9828 // Enforce type constraints: C99 6.5.6p3. 9829 9830 // Handle the common case first (both operands are arithmetic). 9831 if (!compType.isNull() && compType->isArithmeticType()) { 9832 if (CompLHSTy) *CompLHSTy = compType; 9833 return compType; 9834 } 9835 9836 // Either ptr - int or ptr - ptr. 9837 if (LHS.get()->getType()->isAnyPointerType()) { 9838 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9839 9840 // Diagnose bad cases where we step over interface counts. 9841 if (LHS.get()->getType()->isObjCObjectPointerType() && 9842 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9843 return QualType(); 9844 9845 // The result type of a pointer-int computation is the pointer type. 9846 if (RHS.get()->getType()->isIntegerType()) { 9847 // Subtracting from a null pointer should produce a warning. 9848 // The last argument to the diagnose call says this doesn't match the 9849 // GNU int-to-pointer idiom. 9850 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9851 Expr::NPC_ValueDependentIsNotNull)) { 9852 // In C++ adding zero to a null pointer is defined. 9853 Expr::EvalResult KnownVal; 9854 if (!getLangOpts().CPlusPlus || 9855 (!RHS.get()->isValueDependent() && 9856 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9857 KnownVal.Val.getInt() != 0))) { 9858 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9859 } 9860 } 9861 9862 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9863 return QualType(); 9864 9865 // Check array bounds for pointer arithemtic 9866 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9867 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9868 9869 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9870 return LHS.get()->getType(); 9871 } 9872 9873 // Handle pointer-pointer subtractions. 9874 if (const PointerType *RHSPTy 9875 = RHS.get()->getType()->getAs<PointerType>()) { 9876 QualType rpointee = RHSPTy->getPointeeType(); 9877 9878 if (getLangOpts().CPlusPlus) { 9879 // Pointee types must be the same: C++ [expr.add] 9880 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9881 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9882 } 9883 } else { 9884 // Pointee types must be compatible C99 6.5.6p3 9885 if (!Context.typesAreCompatible( 9886 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9887 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9888 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9889 return QualType(); 9890 } 9891 } 9892 9893 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9894 LHS.get(), RHS.get())) 9895 return QualType(); 9896 9897 // FIXME: Add warnings for nullptr - ptr. 9898 9899 // The pointee type may have zero size. As an extension, a structure or 9900 // union may have zero size or an array may have zero length. In this 9901 // case subtraction does not make sense. 9902 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9903 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9904 if (ElementSize.isZero()) { 9905 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9906 << rpointee.getUnqualifiedType() 9907 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9908 } 9909 } 9910 9911 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9912 return Context.getPointerDiffType(); 9913 } 9914 } 9915 9916 return InvalidOperands(Loc, LHS, RHS); 9917 } 9918 9919 static bool isScopedEnumerationType(QualType T) { 9920 if (const EnumType *ET = T->getAs<EnumType>()) 9921 return ET->getDecl()->isScoped(); 9922 return false; 9923 } 9924 9925 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9926 SourceLocation Loc, BinaryOperatorKind Opc, 9927 QualType LHSType) { 9928 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9929 // so skip remaining warnings as we don't want to modify values within Sema. 9930 if (S.getLangOpts().OpenCL) 9931 return; 9932 9933 // Check right/shifter operand 9934 Expr::EvalResult RHSResult; 9935 if (RHS.get()->isValueDependent() || 9936 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9937 return; 9938 llvm::APSInt Right = RHSResult.Val.getInt(); 9939 9940 if (Right.isNegative()) { 9941 S.DiagRuntimeBehavior(Loc, RHS.get(), 9942 S.PDiag(diag::warn_shift_negative) 9943 << RHS.get()->getSourceRange()); 9944 return; 9945 } 9946 llvm::APInt LeftBits(Right.getBitWidth(), 9947 S.Context.getTypeSize(LHS.get()->getType())); 9948 if (Right.uge(LeftBits)) { 9949 S.DiagRuntimeBehavior(Loc, RHS.get(), 9950 S.PDiag(diag::warn_shift_gt_typewidth) 9951 << RHS.get()->getSourceRange()); 9952 return; 9953 } 9954 if (Opc != BO_Shl) 9955 return; 9956 9957 // When left shifting an ICE which is signed, we can check for overflow which 9958 // according to C++ standards prior to C++2a has undefined behavior 9959 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9960 // more than the maximum value representable in the result type, so never 9961 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9962 // expression is still probably a bug.) 9963 Expr::EvalResult LHSResult; 9964 if (LHS.get()->isValueDependent() || 9965 LHSType->hasUnsignedIntegerRepresentation() || 9966 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9967 return; 9968 llvm::APSInt Left = LHSResult.Val.getInt(); 9969 9970 // If LHS does not have a signed type and non-negative value 9971 // then, the behavior is undefined before C++2a. Warn about it. 9972 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9973 !S.getLangOpts().CPlusPlus2a) { 9974 S.DiagRuntimeBehavior(Loc, LHS.get(), 9975 S.PDiag(diag::warn_shift_lhs_negative) 9976 << LHS.get()->getSourceRange()); 9977 return; 9978 } 9979 9980 llvm::APInt ResultBits = 9981 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9982 if (LeftBits.uge(ResultBits)) 9983 return; 9984 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9985 Result = Result.shl(Right); 9986 9987 // Print the bit representation of the signed integer as an unsigned 9988 // hexadecimal number. 9989 SmallString<40> HexResult; 9990 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9991 9992 // If we are only missing a sign bit, this is less likely to result in actual 9993 // bugs -- if the result is cast back to an unsigned type, it will have the 9994 // expected value. Thus we place this behind a different warning that can be 9995 // turned off separately if needed. 9996 if (LeftBits == ResultBits - 1) { 9997 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9998 << HexResult << LHSType 9999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10000 return; 10001 } 10002 10003 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10004 << HexResult.str() << Result.getMinSignedBits() << LHSType 10005 << Left.getBitWidth() << LHS.get()->getSourceRange() 10006 << RHS.get()->getSourceRange(); 10007 } 10008 10009 /// Return the resulting type when a vector is shifted 10010 /// by a scalar or vector shift amount. 10011 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10012 SourceLocation Loc, bool IsCompAssign) { 10013 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10014 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10015 !LHS.get()->getType()->isVectorType()) { 10016 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10017 << RHS.get()->getType() << LHS.get()->getType() 10018 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10019 return QualType(); 10020 } 10021 10022 if (!IsCompAssign) { 10023 LHS = S.UsualUnaryConversions(LHS.get()); 10024 if (LHS.isInvalid()) return QualType(); 10025 } 10026 10027 RHS = S.UsualUnaryConversions(RHS.get()); 10028 if (RHS.isInvalid()) return QualType(); 10029 10030 QualType LHSType = LHS.get()->getType(); 10031 // Note that LHS might be a scalar because the routine calls not only in 10032 // OpenCL case. 10033 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10034 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10035 10036 // Note that RHS might not be a vector. 10037 QualType RHSType = RHS.get()->getType(); 10038 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10039 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10040 10041 // The operands need to be integers. 10042 if (!LHSEleType->isIntegerType()) { 10043 S.Diag(Loc, diag::err_typecheck_expect_int) 10044 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10045 return QualType(); 10046 } 10047 10048 if (!RHSEleType->isIntegerType()) { 10049 S.Diag(Loc, diag::err_typecheck_expect_int) 10050 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10051 return QualType(); 10052 } 10053 10054 if (!LHSVecTy) { 10055 assert(RHSVecTy); 10056 if (IsCompAssign) 10057 return RHSType; 10058 if (LHSEleType != RHSEleType) { 10059 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10060 LHSEleType = RHSEleType; 10061 } 10062 QualType VecTy = 10063 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10064 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10065 LHSType = VecTy; 10066 } else if (RHSVecTy) { 10067 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10068 // are applied component-wise. So if RHS is a vector, then ensure 10069 // that the number of elements is the same as LHS... 10070 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10071 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10072 << LHS.get()->getType() << RHS.get()->getType() 10073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10074 return QualType(); 10075 } 10076 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10077 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10078 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10079 if (LHSBT != RHSBT && 10080 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10081 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10082 << LHS.get()->getType() << RHS.get()->getType() 10083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10084 } 10085 } 10086 } else { 10087 // ...else expand RHS to match the number of elements in LHS. 10088 QualType VecTy = 10089 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10090 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10091 } 10092 10093 return LHSType; 10094 } 10095 10096 // C99 6.5.7 10097 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10098 SourceLocation Loc, BinaryOperatorKind Opc, 10099 bool IsCompAssign) { 10100 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10101 10102 // Vector shifts promote their scalar inputs to vector type. 10103 if (LHS.get()->getType()->isVectorType() || 10104 RHS.get()->getType()->isVectorType()) { 10105 if (LangOpts.ZVector) { 10106 // The shift operators for the z vector extensions work basically 10107 // like general shifts, except that neither the LHS nor the RHS is 10108 // allowed to be a "vector bool". 10109 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10110 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10111 return InvalidOperands(Loc, LHS, RHS); 10112 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10113 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10114 return InvalidOperands(Loc, LHS, RHS); 10115 } 10116 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10117 } 10118 10119 // Shifts don't perform usual arithmetic conversions, they just do integer 10120 // promotions on each operand. C99 6.5.7p3 10121 10122 // For the LHS, do usual unary conversions, but then reset them away 10123 // if this is a compound assignment. 10124 ExprResult OldLHS = LHS; 10125 LHS = UsualUnaryConversions(LHS.get()); 10126 if (LHS.isInvalid()) 10127 return QualType(); 10128 QualType LHSType = LHS.get()->getType(); 10129 if (IsCompAssign) LHS = OldLHS; 10130 10131 // The RHS is simpler. 10132 RHS = UsualUnaryConversions(RHS.get()); 10133 if (RHS.isInvalid()) 10134 return QualType(); 10135 QualType RHSType = RHS.get()->getType(); 10136 10137 // C99 6.5.7p2: Each of the operands shall have integer type. 10138 if (!LHSType->hasIntegerRepresentation() || 10139 !RHSType->hasIntegerRepresentation()) 10140 return InvalidOperands(Loc, LHS, RHS); 10141 10142 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10143 // hasIntegerRepresentation() above instead of this. 10144 if (isScopedEnumerationType(LHSType) || 10145 isScopedEnumerationType(RHSType)) { 10146 return InvalidOperands(Loc, LHS, RHS); 10147 } 10148 // Sanity-check shift operands 10149 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10150 10151 // "The type of the result is that of the promoted left operand." 10152 return LHSType; 10153 } 10154 10155 /// Diagnose bad pointer comparisons. 10156 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10157 ExprResult &LHS, ExprResult &RHS, 10158 bool IsError) { 10159 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10160 : diag::ext_typecheck_comparison_of_distinct_pointers) 10161 << LHS.get()->getType() << RHS.get()->getType() 10162 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10163 } 10164 10165 /// Returns false if the pointers are converted to a composite type, 10166 /// true otherwise. 10167 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10168 ExprResult &LHS, ExprResult &RHS) { 10169 // C++ [expr.rel]p2: 10170 // [...] Pointer conversions (4.10) and qualification 10171 // conversions (4.4) are performed on pointer operands (or on 10172 // a pointer operand and a null pointer constant) to bring 10173 // them to their composite pointer type. [...] 10174 // 10175 // C++ [expr.eq]p1 uses the same notion for (in)equality 10176 // comparisons of pointers. 10177 10178 QualType LHSType = LHS.get()->getType(); 10179 QualType RHSType = RHS.get()->getType(); 10180 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10181 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10182 10183 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10184 if (T.isNull()) { 10185 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10186 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10187 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10188 else 10189 S.InvalidOperands(Loc, LHS, RHS); 10190 return true; 10191 } 10192 10193 return false; 10194 } 10195 10196 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10197 ExprResult &LHS, 10198 ExprResult &RHS, 10199 bool IsError) { 10200 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10201 : diag::ext_typecheck_comparison_of_fptr_to_void) 10202 << LHS.get()->getType() << RHS.get()->getType() 10203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10204 } 10205 10206 static bool isObjCObjectLiteral(ExprResult &E) { 10207 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10208 case Stmt::ObjCArrayLiteralClass: 10209 case Stmt::ObjCDictionaryLiteralClass: 10210 case Stmt::ObjCStringLiteralClass: 10211 case Stmt::ObjCBoxedExprClass: 10212 return true; 10213 default: 10214 // Note that ObjCBoolLiteral is NOT an object literal! 10215 return false; 10216 } 10217 } 10218 10219 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10220 const ObjCObjectPointerType *Type = 10221 LHS->getType()->getAs<ObjCObjectPointerType>(); 10222 10223 // If this is not actually an Objective-C object, bail out. 10224 if (!Type) 10225 return false; 10226 10227 // Get the LHS object's interface type. 10228 QualType InterfaceType = Type->getPointeeType(); 10229 10230 // If the RHS isn't an Objective-C object, bail out. 10231 if (!RHS->getType()->isObjCObjectPointerType()) 10232 return false; 10233 10234 // Try to find the -isEqual: method. 10235 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10236 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10237 InterfaceType, 10238 /*IsInstance=*/true); 10239 if (!Method) { 10240 if (Type->isObjCIdType()) { 10241 // For 'id', just check the global pool. 10242 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10243 /*receiverId=*/true); 10244 } else { 10245 // Check protocols. 10246 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10247 /*IsInstance=*/true); 10248 } 10249 } 10250 10251 if (!Method) 10252 return false; 10253 10254 QualType T = Method->parameters()[0]->getType(); 10255 if (!T->isObjCObjectPointerType()) 10256 return false; 10257 10258 QualType R = Method->getReturnType(); 10259 if (!R->isScalarType()) 10260 return false; 10261 10262 return true; 10263 } 10264 10265 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10266 FromE = FromE->IgnoreParenImpCasts(); 10267 switch (FromE->getStmtClass()) { 10268 default: 10269 break; 10270 case Stmt::ObjCStringLiteralClass: 10271 // "string literal" 10272 return LK_String; 10273 case Stmt::ObjCArrayLiteralClass: 10274 // "array literal" 10275 return LK_Array; 10276 case Stmt::ObjCDictionaryLiteralClass: 10277 // "dictionary literal" 10278 return LK_Dictionary; 10279 case Stmt::BlockExprClass: 10280 return LK_Block; 10281 case Stmt::ObjCBoxedExprClass: { 10282 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10283 switch (Inner->getStmtClass()) { 10284 case Stmt::IntegerLiteralClass: 10285 case Stmt::FloatingLiteralClass: 10286 case Stmt::CharacterLiteralClass: 10287 case Stmt::ObjCBoolLiteralExprClass: 10288 case Stmt::CXXBoolLiteralExprClass: 10289 // "numeric literal" 10290 return LK_Numeric; 10291 case Stmt::ImplicitCastExprClass: { 10292 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10293 // Boolean literals can be represented by implicit casts. 10294 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10295 return LK_Numeric; 10296 break; 10297 } 10298 default: 10299 break; 10300 } 10301 return LK_Boxed; 10302 } 10303 } 10304 return LK_None; 10305 } 10306 10307 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10308 ExprResult &LHS, ExprResult &RHS, 10309 BinaryOperator::Opcode Opc){ 10310 Expr *Literal; 10311 Expr *Other; 10312 if (isObjCObjectLiteral(LHS)) { 10313 Literal = LHS.get(); 10314 Other = RHS.get(); 10315 } else { 10316 Literal = RHS.get(); 10317 Other = LHS.get(); 10318 } 10319 10320 // Don't warn on comparisons against nil. 10321 Other = Other->IgnoreParenCasts(); 10322 if (Other->isNullPointerConstant(S.getASTContext(), 10323 Expr::NPC_ValueDependentIsNotNull)) 10324 return; 10325 10326 // This should be kept in sync with warn_objc_literal_comparison. 10327 // LK_String should always be after the other literals, since it has its own 10328 // warning flag. 10329 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10330 assert(LiteralKind != Sema::LK_Block); 10331 if (LiteralKind == Sema::LK_None) { 10332 llvm_unreachable("Unknown Objective-C object literal kind"); 10333 } 10334 10335 if (LiteralKind == Sema::LK_String) 10336 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10337 << Literal->getSourceRange(); 10338 else 10339 S.Diag(Loc, diag::warn_objc_literal_comparison) 10340 << LiteralKind << Literal->getSourceRange(); 10341 10342 if (BinaryOperator::isEqualityOp(Opc) && 10343 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10344 SourceLocation Start = LHS.get()->getBeginLoc(); 10345 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10346 CharSourceRange OpRange = 10347 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10348 10349 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10350 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10351 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10352 << FixItHint::CreateInsertion(End, "]"); 10353 } 10354 } 10355 10356 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10357 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10358 ExprResult &RHS, SourceLocation Loc, 10359 BinaryOperatorKind Opc) { 10360 // Check that left hand side is !something. 10361 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10362 if (!UO || UO->getOpcode() != UO_LNot) return; 10363 10364 // Only check if the right hand side is non-bool arithmetic type. 10365 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10366 10367 // Make sure that the something in !something is not bool. 10368 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10369 if (SubExpr->isKnownToHaveBooleanValue()) return; 10370 10371 // Emit warning. 10372 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10373 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10374 << Loc << IsBitwiseOp; 10375 10376 // First note suggest !(x < y) 10377 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10378 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10379 FirstClose = S.getLocForEndOfToken(FirstClose); 10380 if (FirstClose.isInvalid()) 10381 FirstOpen = SourceLocation(); 10382 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10383 << IsBitwiseOp 10384 << FixItHint::CreateInsertion(FirstOpen, "(") 10385 << FixItHint::CreateInsertion(FirstClose, ")"); 10386 10387 // Second note suggests (!x) < y 10388 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10389 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10390 SecondClose = S.getLocForEndOfToken(SecondClose); 10391 if (SecondClose.isInvalid()) 10392 SecondOpen = SourceLocation(); 10393 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10394 << FixItHint::CreateInsertion(SecondOpen, "(") 10395 << FixItHint::CreateInsertion(SecondClose, ")"); 10396 } 10397 10398 // Returns true if E refers to a non-weak array. 10399 static bool checkForArray(const Expr *E) { 10400 const ValueDecl *D = nullptr; 10401 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10402 D = DR->getDecl(); 10403 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10404 if (Mem->isImplicitAccess()) 10405 D = Mem->getMemberDecl(); 10406 } 10407 if (!D) 10408 return false; 10409 return D->getType()->isArrayType() && !D->isWeak(); 10410 } 10411 10412 /// Diagnose some forms of syntactically-obvious tautological comparison. 10413 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10414 Expr *LHS, Expr *RHS, 10415 BinaryOperatorKind Opc) { 10416 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10417 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10418 10419 QualType LHSType = LHS->getType(); 10420 QualType RHSType = RHS->getType(); 10421 if (LHSType->hasFloatingRepresentation() || 10422 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10423 S.inTemplateInstantiation()) 10424 return; 10425 10426 // Comparisons between two array types are ill-formed for operator<=>, so 10427 // we shouldn't emit any additional warnings about it. 10428 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10429 return; 10430 10431 // For non-floating point types, check for self-comparisons of the form 10432 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10433 // often indicate logic errors in the program. 10434 // 10435 // NOTE: Don't warn about comparison expressions resulting from macro 10436 // expansion. Also don't warn about comparisons which are only self 10437 // comparisons within a template instantiation. The warnings should catch 10438 // obvious cases in the definition of the template anyways. The idea is to 10439 // warn when the typed comparison operator will always evaluate to the same 10440 // result. 10441 10442 // Used for indexing into %select in warn_comparison_always 10443 enum { 10444 AlwaysConstant, 10445 AlwaysTrue, 10446 AlwaysFalse, 10447 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10448 }; 10449 10450 // C++2a [depr.array.comp]: 10451 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10452 // operands of array type are deprecated. 10453 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10454 RHSStripped->getType()->isArrayType()) { 10455 S.Diag(Loc, diag::warn_depr_array_comparison) 10456 << LHS->getSourceRange() << RHS->getSourceRange() 10457 << LHSStripped->getType() << RHSStripped->getType(); 10458 // Carry on to produce the tautological comparison warning, if this 10459 // expression is potentially-evaluated, we can resolve the array to a 10460 // non-weak declaration, and so on. 10461 } 10462 10463 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10464 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10465 unsigned Result; 10466 switch (Opc) { 10467 case BO_EQ: 10468 case BO_LE: 10469 case BO_GE: 10470 Result = AlwaysTrue; 10471 break; 10472 case BO_NE: 10473 case BO_LT: 10474 case BO_GT: 10475 Result = AlwaysFalse; 10476 break; 10477 case BO_Cmp: 10478 Result = AlwaysEqual; 10479 break; 10480 default: 10481 Result = AlwaysConstant; 10482 break; 10483 } 10484 S.DiagRuntimeBehavior(Loc, nullptr, 10485 S.PDiag(diag::warn_comparison_always) 10486 << 0 /*self-comparison*/ 10487 << Result); 10488 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10489 // What is it always going to evaluate to? 10490 unsigned Result; 10491 switch (Opc) { 10492 case BO_EQ: // e.g. array1 == array2 10493 Result = AlwaysFalse; 10494 break; 10495 case BO_NE: // e.g. array1 != array2 10496 Result = AlwaysTrue; 10497 break; 10498 default: // e.g. array1 <= array2 10499 // The best we can say is 'a constant' 10500 Result = AlwaysConstant; 10501 break; 10502 } 10503 S.DiagRuntimeBehavior(Loc, nullptr, 10504 S.PDiag(diag::warn_comparison_always) 10505 << 1 /*array comparison*/ 10506 << Result); 10507 } 10508 } 10509 10510 if (isa<CastExpr>(LHSStripped)) 10511 LHSStripped = LHSStripped->IgnoreParenCasts(); 10512 if (isa<CastExpr>(RHSStripped)) 10513 RHSStripped = RHSStripped->IgnoreParenCasts(); 10514 10515 // Warn about comparisons against a string constant (unless the other 10516 // operand is null); the user probably wants string comparison function. 10517 Expr *LiteralString = nullptr; 10518 Expr *LiteralStringStripped = nullptr; 10519 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10520 !RHSStripped->isNullPointerConstant(S.Context, 10521 Expr::NPC_ValueDependentIsNull)) { 10522 LiteralString = LHS; 10523 LiteralStringStripped = LHSStripped; 10524 } else if ((isa<StringLiteral>(RHSStripped) || 10525 isa<ObjCEncodeExpr>(RHSStripped)) && 10526 !LHSStripped->isNullPointerConstant(S.Context, 10527 Expr::NPC_ValueDependentIsNull)) { 10528 LiteralString = RHS; 10529 LiteralStringStripped = RHSStripped; 10530 } 10531 10532 if (LiteralString) { 10533 S.DiagRuntimeBehavior(Loc, nullptr, 10534 S.PDiag(diag::warn_stringcompare) 10535 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10536 << LiteralString->getSourceRange()); 10537 } 10538 } 10539 10540 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10541 switch (CK) { 10542 default: { 10543 #ifndef NDEBUG 10544 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10545 << "\n"; 10546 #endif 10547 llvm_unreachable("unhandled cast kind"); 10548 } 10549 case CK_UserDefinedConversion: 10550 return ICK_Identity; 10551 case CK_LValueToRValue: 10552 return ICK_Lvalue_To_Rvalue; 10553 case CK_ArrayToPointerDecay: 10554 return ICK_Array_To_Pointer; 10555 case CK_FunctionToPointerDecay: 10556 return ICK_Function_To_Pointer; 10557 case CK_IntegralCast: 10558 return ICK_Integral_Conversion; 10559 case CK_FloatingCast: 10560 return ICK_Floating_Conversion; 10561 case CK_IntegralToFloating: 10562 case CK_FloatingToIntegral: 10563 return ICK_Floating_Integral; 10564 case CK_IntegralComplexCast: 10565 case CK_FloatingComplexCast: 10566 case CK_FloatingComplexToIntegralComplex: 10567 case CK_IntegralComplexToFloatingComplex: 10568 return ICK_Complex_Conversion; 10569 case CK_FloatingComplexToReal: 10570 case CK_FloatingRealToComplex: 10571 case CK_IntegralComplexToReal: 10572 case CK_IntegralRealToComplex: 10573 return ICK_Complex_Real; 10574 } 10575 } 10576 10577 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10578 QualType FromType, 10579 SourceLocation Loc) { 10580 // Check for a narrowing implicit conversion. 10581 StandardConversionSequence SCS; 10582 SCS.setAsIdentityConversion(); 10583 SCS.setToType(0, FromType); 10584 SCS.setToType(1, ToType); 10585 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10586 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10587 10588 APValue PreNarrowingValue; 10589 QualType PreNarrowingType; 10590 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10591 PreNarrowingType, 10592 /*IgnoreFloatToIntegralConversion*/ true)) { 10593 case NK_Dependent_Narrowing: 10594 // Implicit conversion to a narrower type, but the expression is 10595 // value-dependent so we can't tell whether it's actually narrowing. 10596 case NK_Not_Narrowing: 10597 return false; 10598 10599 case NK_Constant_Narrowing: 10600 // Implicit conversion to a narrower type, and the value is not a constant 10601 // expression. 10602 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10603 << /*Constant*/ 1 10604 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10605 return true; 10606 10607 case NK_Variable_Narrowing: 10608 // Implicit conversion to a narrower type, and the value is not a constant 10609 // expression. 10610 case NK_Type_Narrowing: 10611 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10612 << /*Constant*/ 0 << FromType << ToType; 10613 // TODO: It's not a constant expression, but what if the user intended it 10614 // to be? Can we produce notes to help them figure out why it isn't? 10615 return true; 10616 } 10617 llvm_unreachable("unhandled case in switch"); 10618 } 10619 10620 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10621 ExprResult &LHS, 10622 ExprResult &RHS, 10623 SourceLocation Loc) { 10624 QualType LHSType = LHS.get()->getType(); 10625 QualType RHSType = RHS.get()->getType(); 10626 // Dig out the original argument type and expression before implicit casts 10627 // were applied. These are the types/expressions we need to check the 10628 // [expr.spaceship] requirements against. 10629 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10630 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10631 QualType LHSStrippedType = LHSStripped.get()->getType(); 10632 QualType RHSStrippedType = RHSStripped.get()->getType(); 10633 10634 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10635 // other is not, the program is ill-formed. 10636 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10637 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10638 return QualType(); 10639 } 10640 10641 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10642 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10643 RHSStrippedType->isEnumeralType(); 10644 if (NumEnumArgs == 1) { 10645 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10646 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10647 if (OtherTy->hasFloatingRepresentation()) { 10648 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10649 return QualType(); 10650 } 10651 } 10652 if (NumEnumArgs == 2) { 10653 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10654 // type E, the operator yields the result of converting the operands 10655 // to the underlying type of E and applying <=> to the converted operands. 10656 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10657 S.InvalidOperands(Loc, LHS, RHS); 10658 return QualType(); 10659 } 10660 QualType IntType = 10661 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10662 assert(IntType->isArithmeticType()); 10663 10664 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10665 // promote the boolean type, and all other promotable integer types, to 10666 // avoid this. 10667 if (IntType->isPromotableIntegerType()) 10668 IntType = S.Context.getPromotedIntegerType(IntType); 10669 10670 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10671 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10672 LHSType = RHSType = IntType; 10673 } 10674 10675 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10676 // usual arithmetic conversions are applied to the operands. 10677 QualType Type = 10678 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10679 if (LHS.isInvalid() || RHS.isInvalid()) 10680 return QualType(); 10681 if (Type.isNull()) 10682 return S.InvalidOperands(Loc, LHS, RHS); 10683 10684 Optional<ComparisonCategoryType> CCT = 10685 getComparisonCategoryForBuiltinCmp(Type); 10686 if (!CCT) 10687 return S.InvalidOperands(Loc, LHS, RHS); 10688 10689 bool HasNarrowing = checkThreeWayNarrowingConversion( 10690 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10691 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10692 RHS.get()->getBeginLoc()); 10693 if (HasNarrowing) 10694 return QualType(); 10695 10696 assert(!Type.isNull() && "composite type for <=> has not been set"); 10697 10698 return S.CheckComparisonCategoryType( 10699 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 10700 } 10701 10702 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10703 ExprResult &RHS, 10704 SourceLocation Loc, 10705 BinaryOperatorKind Opc) { 10706 if (Opc == BO_Cmp) 10707 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10708 10709 // C99 6.5.8p3 / C99 6.5.9p4 10710 QualType Type = 10711 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10712 if (LHS.isInvalid() || RHS.isInvalid()) 10713 return QualType(); 10714 if (Type.isNull()) 10715 return S.InvalidOperands(Loc, LHS, RHS); 10716 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10717 10718 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10719 return S.InvalidOperands(Loc, LHS, RHS); 10720 10721 // Check for comparisons of floating point operands using != and ==. 10722 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10723 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10724 10725 // The result of comparisons is 'bool' in C++, 'int' in C. 10726 return S.Context.getLogicalOperationType(); 10727 } 10728 10729 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10730 if (!NullE.get()->getType()->isAnyPointerType()) 10731 return; 10732 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10733 if (!E.get()->getType()->isAnyPointerType() && 10734 E.get()->isNullPointerConstant(Context, 10735 Expr::NPC_ValueDependentIsNotNull) == 10736 Expr::NPCK_ZeroExpression) { 10737 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10738 if (CL->getValue() == 0) 10739 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10740 << NullValue 10741 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10742 NullValue ? "NULL" : "(void *)0"); 10743 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10744 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10745 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10746 if (T == Context.CharTy) 10747 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10748 << NullValue 10749 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10750 NullValue ? "NULL" : "(void *)0"); 10751 } 10752 } 10753 } 10754 10755 // C99 6.5.8, C++ [expr.rel] 10756 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10757 SourceLocation Loc, 10758 BinaryOperatorKind Opc) { 10759 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10760 bool IsThreeWay = Opc == BO_Cmp; 10761 bool IsOrdered = IsRelational || IsThreeWay; 10762 auto IsAnyPointerType = [](ExprResult E) { 10763 QualType Ty = E.get()->getType(); 10764 return Ty->isPointerType() || Ty->isMemberPointerType(); 10765 }; 10766 10767 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10768 // type, array-to-pointer, ..., conversions are performed on both operands to 10769 // bring them to their composite type. 10770 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10771 // any type-related checks. 10772 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10773 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10774 if (LHS.isInvalid()) 10775 return QualType(); 10776 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10777 if (RHS.isInvalid()) 10778 return QualType(); 10779 } else { 10780 LHS = DefaultLvalueConversion(LHS.get()); 10781 if (LHS.isInvalid()) 10782 return QualType(); 10783 RHS = DefaultLvalueConversion(RHS.get()); 10784 if (RHS.isInvalid()) 10785 return QualType(); 10786 } 10787 10788 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10789 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10790 CheckPtrComparisonWithNullChar(LHS, RHS); 10791 CheckPtrComparisonWithNullChar(RHS, LHS); 10792 } 10793 10794 // Handle vector comparisons separately. 10795 if (LHS.get()->getType()->isVectorType() || 10796 RHS.get()->getType()->isVectorType()) 10797 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10798 10799 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10800 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10801 10802 QualType LHSType = LHS.get()->getType(); 10803 QualType RHSType = RHS.get()->getType(); 10804 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10805 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10806 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10807 10808 const Expr::NullPointerConstantKind LHSNullKind = 10809 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10810 const Expr::NullPointerConstantKind RHSNullKind = 10811 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10812 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10813 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10814 10815 auto computeResultTy = [&]() { 10816 if (Opc != BO_Cmp) 10817 return Context.getLogicalOperationType(); 10818 assert(getLangOpts().CPlusPlus); 10819 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10820 10821 QualType CompositeTy = LHS.get()->getType(); 10822 assert(!CompositeTy->isReferenceType()); 10823 10824 Optional<ComparisonCategoryType> CCT = 10825 getComparisonCategoryForBuiltinCmp(CompositeTy); 10826 if (!CCT) 10827 return InvalidOperands(Loc, LHS, RHS); 10828 10829 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10830 // P0946R0: Comparisons between a null pointer constant and an object 10831 // pointer result in std::strong_equality, which is ill-formed under 10832 // P1959R0. 10833 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 10834 << (LHSIsNull ? LHS.get()->getSourceRange() 10835 : RHS.get()->getSourceRange()); 10836 return QualType(); 10837 } 10838 10839 return CheckComparisonCategoryType( 10840 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 10841 }; 10842 10843 if (!IsOrdered && LHSIsNull != RHSIsNull) { 10844 bool IsEquality = Opc == BO_EQ; 10845 if (RHSIsNull) 10846 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10847 RHS.get()->getSourceRange()); 10848 else 10849 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10850 LHS.get()->getSourceRange()); 10851 } 10852 10853 if ((LHSType->isIntegerType() && !LHSIsNull) || 10854 (RHSType->isIntegerType() && !RHSIsNull)) { 10855 // Skip normal pointer conversion checks in this case; we have better 10856 // diagnostics for this below. 10857 } else if (getLangOpts().CPlusPlus) { 10858 // Equality comparison of a function pointer to a void pointer is invalid, 10859 // but we allow it as an extension. 10860 // FIXME: If we really want to allow this, should it be part of composite 10861 // pointer type computation so it works in conditionals too? 10862 if (!IsOrdered && 10863 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10864 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10865 // This is a gcc extension compatibility comparison. 10866 // In a SFINAE context, we treat this as a hard error to maintain 10867 // conformance with the C++ standard. 10868 diagnoseFunctionPointerToVoidComparison( 10869 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10870 10871 if (isSFINAEContext()) 10872 return QualType(); 10873 10874 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10875 return computeResultTy(); 10876 } 10877 10878 // C++ [expr.eq]p2: 10879 // If at least one operand is a pointer [...] bring them to their 10880 // composite pointer type. 10881 // C++ [expr.spaceship]p6 10882 // If at least one of the operands is of pointer type, [...] bring them 10883 // to their composite pointer type. 10884 // C++ [expr.rel]p2: 10885 // If both operands are pointers, [...] bring them to their composite 10886 // pointer type. 10887 // For <=>, the only valid non-pointer types are arrays and functions, and 10888 // we already decayed those, so this is really the same as the relational 10889 // comparison rule. 10890 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10891 (IsOrdered ? 2 : 1) && 10892 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10893 RHSType->isObjCObjectPointerType()))) { 10894 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10895 return QualType(); 10896 return computeResultTy(); 10897 } 10898 } else if (LHSType->isPointerType() && 10899 RHSType->isPointerType()) { // C99 6.5.8p2 10900 // All of the following pointer-related warnings are GCC extensions, except 10901 // when handling null pointer constants. 10902 QualType LCanPointeeTy = 10903 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10904 QualType RCanPointeeTy = 10905 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10906 10907 // C99 6.5.9p2 and C99 6.5.8p2 10908 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10909 RCanPointeeTy.getUnqualifiedType())) { 10910 // Valid unless a relational comparison of function pointers 10911 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10912 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10913 << LHSType << RHSType << LHS.get()->getSourceRange() 10914 << RHS.get()->getSourceRange(); 10915 } 10916 } else if (!IsRelational && 10917 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10918 // Valid unless comparison between non-null pointer and function pointer 10919 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10920 && !LHSIsNull && !RHSIsNull) 10921 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10922 /*isError*/false); 10923 } else { 10924 // Invalid 10925 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10926 } 10927 if (LCanPointeeTy != RCanPointeeTy) { 10928 // Treat NULL constant as a special case in OpenCL. 10929 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10930 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10931 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10932 Diag(Loc, 10933 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10934 << LHSType << RHSType << 0 /* comparison */ 10935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10936 } 10937 } 10938 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10939 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10940 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10941 : CK_BitCast; 10942 if (LHSIsNull && !RHSIsNull) 10943 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10944 else 10945 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10946 } 10947 return computeResultTy(); 10948 } 10949 10950 if (getLangOpts().CPlusPlus) { 10951 // C++ [expr.eq]p4: 10952 // Two operands of type std::nullptr_t or one operand of type 10953 // std::nullptr_t and the other a null pointer constant compare equal. 10954 if (!IsOrdered && LHSIsNull && RHSIsNull) { 10955 if (LHSType->isNullPtrType()) { 10956 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10957 return computeResultTy(); 10958 } 10959 if (RHSType->isNullPtrType()) { 10960 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10961 return computeResultTy(); 10962 } 10963 } 10964 10965 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10966 // These aren't covered by the composite pointer type rules. 10967 if (!IsOrdered && RHSType->isNullPtrType() && 10968 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10969 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10970 return computeResultTy(); 10971 } 10972 if (!IsOrdered && LHSType->isNullPtrType() && 10973 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10974 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10975 return computeResultTy(); 10976 } 10977 10978 if (IsRelational && 10979 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10980 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10981 // HACK: Relational comparison of nullptr_t against a pointer type is 10982 // invalid per DR583, but we allow it within std::less<> and friends, 10983 // since otherwise common uses of it break. 10984 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10985 // friends to have std::nullptr_t overload candidates. 10986 DeclContext *DC = CurContext; 10987 if (isa<FunctionDecl>(DC)) 10988 DC = DC->getParent(); 10989 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10990 if (CTSD->isInStdNamespace() && 10991 llvm::StringSwitch<bool>(CTSD->getName()) 10992 .Cases("less", "less_equal", "greater", "greater_equal", true) 10993 .Default(false)) { 10994 if (RHSType->isNullPtrType()) 10995 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10996 else 10997 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10998 return computeResultTy(); 10999 } 11000 } 11001 } 11002 11003 // C++ [expr.eq]p2: 11004 // If at least one operand is a pointer to member, [...] bring them to 11005 // their composite pointer type. 11006 if (!IsOrdered && 11007 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11008 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11009 return QualType(); 11010 else 11011 return computeResultTy(); 11012 } 11013 } 11014 11015 // Handle block pointer types. 11016 if (!IsOrdered && LHSType->isBlockPointerType() && 11017 RHSType->isBlockPointerType()) { 11018 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11019 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11020 11021 if (!LHSIsNull && !RHSIsNull && 11022 !Context.typesAreCompatible(lpointee, rpointee)) { 11023 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11024 << LHSType << RHSType << LHS.get()->getSourceRange() 11025 << RHS.get()->getSourceRange(); 11026 } 11027 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11028 return computeResultTy(); 11029 } 11030 11031 // Allow block pointers to be compared with null pointer constants. 11032 if (!IsOrdered 11033 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11034 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11035 if (!LHSIsNull && !RHSIsNull) { 11036 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11037 ->getPointeeType()->isVoidType()) 11038 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11039 ->getPointeeType()->isVoidType()))) 11040 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11041 << LHSType << RHSType << LHS.get()->getSourceRange() 11042 << RHS.get()->getSourceRange(); 11043 } 11044 if (LHSIsNull && !RHSIsNull) 11045 LHS = ImpCastExprToType(LHS.get(), RHSType, 11046 RHSType->isPointerType() ? CK_BitCast 11047 : CK_AnyPointerToBlockPointerCast); 11048 else 11049 RHS = ImpCastExprToType(RHS.get(), LHSType, 11050 LHSType->isPointerType() ? CK_BitCast 11051 : CK_AnyPointerToBlockPointerCast); 11052 return computeResultTy(); 11053 } 11054 11055 if (LHSType->isObjCObjectPointerType() || 11056 RHSType->isObjCObjectPointerType()) { 11057 const PointerType *LPT = LHSType->getAs<PointerType>(); 11058 const PointerType *RPT = RHSType->getAs<PointerType>(); 11059 if (LPT || RPT) { 11060 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11061 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11062 11063 if (!LPtrToVoid && !RPtrToVoid && 11064 !Context.typesAreCompatible(LHSType, RHSType)) { 11065 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11066 /*isError*/false); 11067 } 11068 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11069 // the RHS, but we have test coverage for this behavior. 11070 // FIXME: Consider using convertPointersToCompositeType in C++. 11071 if (LHSIsNull && !RHSIsNull) { 11072 Expr *E = LHS.get(); 11073 if (getLangOpts().ObjCAutoRefCount) 11074 CheckObjCConversion(SourceRange(), RHSType, E, 11075 CCK_ImplicitConversion); 11076 LHS = ImpCastExprToType(E, RHSType, 11077 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11078 } 11079 else { 11080 Expr *E = RHS.get(); 11081 if (getLangOpts().ObjCAutoRefCount) 11082 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11083 /*Diagnose=*/true, 11084 /*DiagnoseCFAudited=*/false, Opc); 11085 RHS = ImpCastExprToType(E, LHSType, 11086 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11087 } 11088 return computeResultTy(); 11089 } 11090 if (LHSType->isObjCObjectPointerType() && 11091 RHSType->isObjCObjectPointerType()) { 11092 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11093 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11094 /*isError*/false); 11095 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11096 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11097 11098 if (LHSIsNull && !RHSIsNull) 11099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11100 else 11101 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11102 return computeResultTy(); 11103 } 11104 11105 if (!IsOrdered && LHSType->isBlockPointerType() && 11106 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11107 LHS = ImpCastExprToType(LHS.get(), RHSType, 11108 CK_BlockPointerToObjCPointerCast); 11109 return computeResultTy(); 11110 } else if (!IsOrdered && 11111 LHSType->isBlockCompatibleObjCPointerType(Context) && 11112 RHSType->isBlockPointerType()) { 11113 RHS = ImpCastExprToType(RHS.get(), LHSType, 11114 CK_BlockPointerToObjCPointerCast); 11115 return computeResultTy(); 11116 } 11117 } 11118 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11119 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11120 unsigned DiagID = 0; 11121 bool isError = false; 11122 if (LangOpts.DebuggerSupport) { 11123 // Under a debugger, allow the comparison of pointers to integers, 11124 // since users tend to want to compare addresses. 11125 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11126 (RHSIsNull && RHSType->isIntegerType())) { 11127 if (IsOrdered) { 11128 isError = getLangOpts().CPlusPlus; 11129 DiagID = 11130 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11131 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11132 } 11133 } else if (getLangOpts().CPlusPlus) { 11134 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11135 isError = true; 11136 } else if (IsOrdered) 11137 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11138 else 11139 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11140 11141 if (DiagID) { 11142 Diag(Loc, DiagID) 11143 << LHSType << RHSType << LHS.get()->getSourceRange() 11144 << RHS.get()->getSourceRange(); 11145 if (isError) 11146 return QualType(); 11147 } 11148 11149 if (LHSType->isIntegerType()) 11150 LHS = ImpCastExprToType(LHS.get(), RHSType, 11151 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11152 else 11153 RHS = ImpCastExprToType(RHS.get(), LHSType, 11154 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11155 return computeResultTy(); 11156 } 11157 11158 // Handle block pointers. 11159 if (!IsOrdered && RHSIsNull 11160 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11162 return computeResultTy(); 11163 } 11164 if (!IsOrdered && LHSIsNull 11165 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11166 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11167 return computeResultTy(); 11168 } 11169 11170 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11171 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11172 return computeResultTy(); 11173 } 11174 11175 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11176 return computeResultTy(); 11177 } 11178 11179 if (LHSIsNull && RHSType->isQueueT()) { 11180 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11181 return computeResultTy(); 11182 } 11183 11184 if (LHSType->isQueueT() && RHSIsNull) { 11185 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11186 return computeResultTy(); 11187 } 11188 } 11189 11190 return InvalidOperands(Loc, LHS, RHS); 11191 } 11192 11193 // Return a signed ext_vector_type that is of identical size and number of 11194 // elements. For floating point vectors, return an integer type of identical 11195 // size and number of elements. In the non ext_vector_type case, search from 11196 // the largest type to the smallest type to avoid cases where long long == long, 11197 // where long gets picked over long long. 11198 QualType Sema::GetSignedVectorType(QualType V) { 11199 const VectorType *VTy = V->castAs<VectorType>(); 11200 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11201 11202 if (isa<ExtVectorType>(VTy)) { 11203 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11204 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11205 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11206 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11207 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11208 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11209 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11210 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11211 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11212 "Unhandled vector element size in vector compare"); 11213 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11214 } 11215 11216 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11217 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11218 VectorType::GenericVector); 11219 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11220 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11221 VectorType::GenericVector); 11222 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11223 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11224 VectorType::GenericVector); 11225 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11226 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11227 VectorType::GenericVector); 11228 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11229 "Unhandled vector element size in vector compare"); 11230 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11231 VectorType::GenericVector); 11232 } 11233 11234 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11235 /// operates on extended vector types. Instead of producing an IntTy result, 11236 /// like a scalar comparison, a vector comparison produces a vector of integer 11237 /// types. 11238 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11239 SourceLocation Loc, 11240 BinaryOperatorKind Opc) { 11241 if (Opc == BO_Cmp) { 11242 Diag(Loc, diag::err_three_way_vector_comparison); 11243 return QualType(); 11244 } 11245 11246 // Check to make sure we're operating on vectors of the same type and width, 11247 // Allowing one side to be a scalar of element type. 11248 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11249 /*AllowBothBool*/true, 11250 /*AllowBoolConversions*/getLangOpts().ZVector); 11251 if (vType.isNull()) 11252 return vType; 11253 11254 QualType LHSType = LHS.get()->getType(); 11255 11256 // If AltiVec, the comparison results in a numeric type, i.e. 11257 // bool for C++, int for C 11258 if (getLangOpts().AltiVec && 11259 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11260 return Context.getLogicalOperationType(); 11261 11262 // For non-floating point types, check for self-comparisons of the form 11263 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11264 // often indicate logic errors in the program. 11265 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11266 11267 // Check for comparisons of floating point operands using != and ==. 11268 if (BinaryOperator::isEqualityOp(Opc) && 11269 LHSType->hasFloatingRepresentation()) { 11270 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11271 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11272 } 11273 11274 // Return a signed type for the vector. 11275 return GetSignedVectorType(vType); 11276 } 11277 11278 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11279 const ExprResult &XorRHS, 11280 const SourceLocation Loc) { 11281 // Do not diagnose macros. 11282 if (Loc.isMacroID()) 11283 return; 11284 11285 bool Negative = false; 11286 bool ExplicitPlus = false; 11287 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11288 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11289 11290 if (!LHSInt) 11291 return; 11292 if (!RHSInt) { 11293 // Check negative literals. 11294 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11295 UnaryOperatorKind Opc = UO->getOpcode(); 11296 if (Opc != UO_Minus && Opc != UO_Plus) 11297 return; 11298 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11299 if (!RHSInt) 11300 return; 11301 Negative = (Opc == UO_Minus); 11302 ExplicitPlus = !Negative; 11303 } else { 11304 return; 11305 } 11306 } 11307 11308 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11309 llvm::APInt RightSideValue = RHSInt->getValue(); 11310 if (LeftSideValue != 2 && LeftSideValue != 10) 11311 return; 11312 11313 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11314 return; 11315 11316 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11317 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11318 llvm::StringRef ExprStr = 11319 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11320 11321 CharSourceRange XorRange = 11322 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11323 llvm::StringRef XorStr = 11324 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11325 // Do not diagnose if xor keyword/macro is used. 11326 if (XorStr == "xor") 11327 return; 11328 11329 std::string LHSStr = Lexer::getSourceText( 11330 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11331 S.getSourceManager(), S.getLangOpts()); 11332 std::string RHSStr = Lexer::getSourceText( 11333 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11334 S.getSourceManager(), S.getLangOpts()); 11335 11336 if (Negative) { 11337 RightSideValue = -RightSideValue; 11338 RHSStr = "-" + RHSStr; 11339 } else if (ExplicitPlus) { 11340 RHSStr = "+" + RHSStr; 11341 } 11342 11343 StringRef LHSStrRef = LHSStr; 11344 StringRef RHSStrRef = RHSStr; 11345 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11346 // literals. 11347 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11348 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11349 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11350 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11351 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11352 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11353 LHSStrRef.find('\'') != StringRef::npos || 11354 RHSStrRef.find('\'') != StringRef::npos) 11355 return; 11356 11357 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11358 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11359 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11360 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11361 std::string SuggestedExpr = "1 << " + RHSStr; 11362 bool Overflow = false; 11363 llvm::APInt One = (LeftSideValue - 1); 11364 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11365 if (Overflow) { 11366 if (RightSideIntValue < 64) 11367 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11368 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11369 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11370 else if (RightSideIntValue == 64) 11371 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11372 else 11373 return; 11374 } else { 11375 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11376 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11377 << PowValue.toString(10, true) 11378 << FixItHint::CreateReplacement( 11379 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11380 } 11381 11382 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11383 } else if (LeftSideValue == 10) { 11384 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11385 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11386 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11387 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11388 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11389 } 11390 } 11391 11392 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11393 SourceLocation Loc) { 11394 // Ensure that either both operands are of the same vector type, or 11395 // one operand is of a vector type and the other is of its element type. 11396 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11397 /*AllowBothBool*/true, 11398 /*AllowBoolConversions*/false); 11399 if (vType.isNull()) 11400 return InvalidOperands(Loc, LHS, RHS); 11401 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11402 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11403 return InvalidOperands(Loc, LHS, RHS); 11404 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11405 // usage of the logical operators && and || with vectors in C. This 11406 // check could be notionally dropped. 11407 if (!getLangOpts().CPlusPlus && 11408 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11409 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11410 11411 return GetSignedVectorType(LHS.get()->getType()); 11412 } 11413 11414 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11415 SourceLocation Loc, 11416 BinaryOperatorKind Opc) { 11417 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11418 11419 bool IsCompAssign = 11420 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11421 11422 if (LHS.get()->getType()->isVectorType() || 11423 RHS.get()->getType()->isVectorType()) { 11424 if (LHS.get()->getType()->hasIntegerRepresentation() && 11425 RHS.get()->getType()->hasIntegerRepresentation()) 11426 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11427 /*AllowBothBool*/true, 11428 /*AllowBoolConversions*/getLangOpts().ZVector); 11429 return InvalidOperands(Loc, LHS, RHS); 11430 } 11431 11432 if (Opc == BO_And) 11433 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11434 11435 if (LHS.get()->getType()->hasFloatingRepresentation() || 11436 RHS.get()->getType()->hasFloatingRepresentation()) 11437 return InvalidOperands(Loc, LHS, RHS); 11438 11439 ExprResult LHSResult = LHS, RHSResult = RHS; 11440 QualType compType = UsualArithmeticConversions( 11441 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11442 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11443 return QualType(); 11444 LHS = LHSResult.get(); 11445 RHS = RHSResult.get(); 11446 11447 if (Opc == BO_Xor) 11448 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11449 11450 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11451 return compType; 11452 return InvalidOperands(Loc, LHS, RHS); 11453 } 11454 11455 // C99 6.5.[13,14] 11456 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11457 SourceLocation Loc, 11458 BinaryOperatorKind Opc) { 11459 // Check vector operands differently. 11460 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11461 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11462 11463 bool EnumConstantInBoolContext = false; 11464 for (const ExprResult &HS : {LHS, RHS}) { 11465 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11466 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11467 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11468 EnumConstantInBoolContext = true; 11469 } 11470 } 11471 11472 if (EnumConstantInBoolContext) 11473 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11474 11475 // Diagnose cases where the user write a logical and/or but probably meant a 11476 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11477 // is a constant. 11478 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11479 !LHS.get()->getType()->isBooleanType() && 11480 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11481 // Don't warn in macros or template instantiations. 11482 !Loc.isMacroID() && !inTemplateInstantiation()) { 11483 // If the RHS can be constant folded, and if it constant folds to something 11484 // that isn't 0 or 1 (which indicate a potential logical operation that 11485 // happened to fold to true/false) then warn. 11486 // Parens on the RHS are ignored. 11487 Expr::EvalResult EVResult; 11488 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11489 llvm::APSInt Result = EVResult.Val.getInt(); 11490 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11491 !RHS.get()->getExprLoc().isMacroID()) || 11492 (Result != 0 && Result != 1)) { 11493 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11494 << RHS.get()->getSourceRange() 11495 << (Opc == BO_LAnd ? "&&" : "||"); 11496 // Suggest replacing the logical operator with the bitwise version 11497 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11498 << (Opc == BO_LAnd ? "&" : "|") 11499 << FixItHint::CreateReplacement(SourceRange( 11500 Loc, getLocForEndOfToken(Loc)), 11501 Opc == BO_LAnd ? "&" : "|"); 11502 if (Opc == BO_LAnd) 11503 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11504 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11505 << FixItHint::CreateRemoval( 11506 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11507 RHS.get()->getEndLoc())); 11508 } 11509 } 11510 } 11511 11512 if (!Context.getLangOpts().CPlusPlus) { 11513 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11514 // not operate on the built-in scalar and vector float types. 11515 if (Context.getLangOpts().OpenCL && 11516 Context.getLangOpts().OpenCLVersion < 120) { 11517 if (LHS.get()->getType()->isFloatingType() || 11518 RHS.get()->getType()->isFloatingType()) 11519 return InvalidOperands(Loc, LHS, RHS); 11520 } 11521 11522 LHS = UsualUnaryConversions(LHS.get()); 11523 if (LHS.isInvalid()) 11524 return QualType(); 11525 11526 RHS = UsualUnaryConversions(RHS.get()); 11527 if (RHS.isInvalid()) 11528 return QualType(); 11529 11530 if (!LHS.get()->getType()->isScalarType() || 11531 !RHS.get()->getType()->isScalarType()) 11532 return InvalidOperands(Loc, LHS, RHS); 11533 11534 return Context.IntTy; 11535 } 11536 11537 // The following is safe because we only use this method for 11538 // non-overloadable operands. 11539 11540 // C++ [expr.log.and]p1 11541 // C++ [expr.log.or]p1 11542 // The operands are both contextually converted to type bool. 11543 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11544 if (LHSRes.isInvalid()) 11545 return InvalidOperands(Loc, LHS, RHS); 11546 LHS = LHSRes; 11547 11548 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11549 if (RHSRes.isInvalid()) 11550 return InvalidOperands(Loc, LHS, RHS); 11551 RHS = RHSRes; 11552 11553 // C++ [expr.log.and]p2 11554 // C++ [expr.log.or]p2 11555 // The result is a bool. 11556 return Context.BoolTy; 11557 } 11558 11559 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11560 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11561 if (!ME) return false; 11562 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11563 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11564 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11565 if (!Base) return false; 11566 return Base->getMethodDecl() != nullptr; 11567 } 11568 11569 /// Is the given expression (which must be 'const') a reference to a 11570 /// variable which was originally non-const, but which has become 11571 /// 'const' due to being captured within a block? 11572 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11573 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11574 assert(E->isLValue() && E->getType().isConstQualified()); 11575 E = E->IgnoreParens(); 11576 11577 // Must be a reference to a declaration from an enclosing scope. 11578 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11579 if (!DRE) return NCCK_None; 11580 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11581 11582 // The declaration must be a variable which is not declared 'const'. 11583 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11584 if (!var) return NCCK_None; 11585 if (var->getType().isConstQualified()) return NCCK_None; 11586 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11587 11588 // Decide whether the first capture was for a block or a lambda. 11589 DeclContext *DC = S.CurContext, *Prev = nullptr; 11590 // Decide whether the first capture was for a block or a lambda. 11591 while (DC) { 11592 // For init-capture, it is possible that the variable belongs to the 11593 // template pattern of the current context. 11594 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11595 if (var->isInitCapture() && 11596 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11597 break; 11598 if (DC == var->getDeclContext()) 11599 break; 11600 Prev = DC; 11601 DC = DC->getParent(); 11602 } 11603 // Unless we have an init-capture, we've gone one step too far. 11604 if (!var->isInitCapture()) 11605 DC = Prev; 11606 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11607 } 11608 11609 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11610 Ty = Ty.getNonReferenceType(); 11611 if (IsDereference && Ty->isPointerType()) 11612 Ty = Ty->getPointeeType(); 11613 return !Ty.isConstQualified(); 11614 } 11615 11616 // Update err_typecheck_assign_const and note_typecheck_assign_const 11617 // when this enum is changed. 11618 enum { 11619 ConstFunction, 11620 ConstVariable, 11621 ConstMember, 11622 ConstMethod, 11623 NestedConstMember, 11624 ConstUnknown, // Keep as last element 11625 }; 11626 11627 /// Emit the "read-only variable not assignable" error and print notes to give 11628 /// more information about why the variable is not assignable, such as pointing 11629 /// to the declaration of a const variable, showing that a method is const, or 11630 /// that the function is returning a const reference. 11631 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11632 SourceLocation Loc) { 11633 SourceRange ExprRange = E->getSourceRange(); 11634 11635 // Only emit one error on the first const found. All other consts will emit 11636 // a note to the error. 11637 bool DiagnosticEmitted = false; 11638 11639 // Track if the current expression is the result of a dereference, and if the 11640 // next checked expression is the result of a dereference. 11641 bool IsDereference = false; 11642 bool NextIsDereference = false; 11643 11644 // Loop to process MemberExpr chains. 11645 while (true) { 11646 IsDereference = NextIsDereference; 11647 11648 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11649 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11650 NextIsDereference = ME->isArrow(); 11651 const ValueDecl *VD = ME->getMemberDecl(); 11652 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11653 // Mutable fields can be modified even if the class is const. 11654 if (Field->isMutable()) { 11655 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11656 break; 11657 } 11658 11659 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11660 if (!DiagnosticEmitted) { 11661 S.Diag(Loc, diag::err_typecheck_assign_const) 11662 << ExprRange << ConstMember << false /*static*/ << Field 11663 << Field->getType(); 11664 DiagnosticEmitted = true; 11665 } 11666 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11667 << ConstMember << false /*static*/ << Field << Field->getType() 11668 << Field->getSourceRange(); 11669 } 11670 E = ME->getBase(); 11671 continue; 11672 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11673 if (VDecl->getType().isConstQualified()) { 11674 if (!DiagnosticEmitted) { 11675 S.Diag(Loc, diag::err_typecheck_assign_const) 11676 << ExprRange << ConstMember << true /*static*/ << VDecl 11677 << VDecl->getType(); 11678 DiagnosticEmitted = true; 11679 } 11680 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11681 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11682 << VDecl->getSourceRange(); 11683 } 11684 // Static fields do not inherit constness from parents. 11685 break; 11686 } 11687 break; // End MemberExpr 11688 } else if (const ArraySubscriptExpr *ASE = 11689 dyn_cast<ArraySubscriptExpr>(E)) { 11690 E = ASE->getBase()->IgnoreParenImpCasts(); 11691 continue; 11692 } else if (const ExtVectorElementExpr *EVE = 11693 dyn_cast<ExtVectorElementExpr>(E)) { 11694 E = EVE->getBase()->IgnoreParenImpCasts(); 11695 continue; 11696 } 11697 break; 11698 } 11699 11700 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11701 // Function calls 11702 const FunctionDecl *FD = CE->getDirectCallee(); 11703 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11704 if (!DiagnosticEmitted) { 11705 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11706 << ConstFunction << FD; 11707 DiagnosticEmitted = true; 11708 } 11709 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11710 diag::note_typecheck_assign_const) 11711 << ConstFunction << FD << FD->getReturnType() 11712 << FD->getReturnTypeSourceRange(); 11713 } 11714 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11715 // Point to variable declaration. 11716 if (const ValueDecl *VD = DRE->getDecl()) { 11717 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11718 if (!DiagnosticEmitted) { 11719 S.Diag(Loc, diag::err_typecheck_assign_const) 11720 << ExprRange << ConstVariable << VD << VD->getType(); 11721 DiagnosticEmitted = true; 11722 } 11723 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11724 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11725 } 11726 } 11727 } else if (isa<CXXThisExpr>(E)) { 11728 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11730 if (MD->isConst()) { 11731 if (!DiagnosticEmitted) { 11732 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11733 << ConstMethod << MD; 11734 DiagnosticEmitted = true; 11735 } 11736 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11737 << ConstMethod << MD << MD->getSourceRange(); 11738 } 11739 } 11740 } 11741 } 11742 11743 if (DiagnosticEmitted) 11744 return; 11745 11746 // Can't determine a more specific message, so display the generic error. 11747 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11748 } 11749 11750 enum OriginalExprKind { 11751 OEK_Variable, 11752 OEK_Member, 11753 OEK_LValue 11754 }; 11755 11756 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11757 const RecordType *Ty, 11758 SourceLocation Loc, SourceRange Range, 11759 OriginalExprKind OEK, 11760 bool &DiagnosticEmitted) { 11761 std::vector<const RecordType *> RecordTypeList; 11762 RecordTypeList.push_back(Ty); 11763 unsigned NextToCheckIndex = 0; 11764 // We walk the record hierarchy breadth-first to ensure that we print 11765 // diagnostics in field nesting order. 11766 while (RecordTypeList.size() > NextToCheckIndex) { 11767 bool IsNested = NextToCheckIndex > 0; 11768 for (const FieldDecl *Field : 11769 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11770 // First, check every field for constness. 11771 QualType FieldTy = Field->getType(); 11772 if (FieldTy.isConstQualified()) { 11773 if (!DiagnosticEmitted) { 11774 S.Diag(Loc, diag::err_typecheck_assign_const) 11775 << Range << NestedConstMember << OEK << VD 11776 << IsNested << Field; 11777 DiagnosticEmitted = true; 11778 } 11779 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11780 << NestedConstMember << IsNested << Field 11781 << FieldTy << Field->getSourceRange(); 11782 } 11783 11784 // Then we append it to the list to check next in order. 11785 FieldTy = FieldTy.getCanonicalType(); 11786 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11787 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11788 RecordTypeList.push_back(FieldRecTy); 11789 } 11790 } 11791 ++NextToCheckIndex; 11792 } 11793 } 11794 11795 /// Emit an error for the case where a record we are trying to assign to has a 11796 /// const-qualified field somewhere in its hierarchy. 11797 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11798 SourceLocation Loc) { 11799 QualType Ty = E->getType(); 11800 assert(Ty->isRecordType() && "lvalue was not record?"); 11801 SourceRange Range = E->getSourceRange(); 11802 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11803 bool DiagEmitted = false; 11804 11805 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11806 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11807 Range, OEK_Member, DiagEmitted); 11808 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11809 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11810 Range, OEK_Variable, DiagEmitted); 11811 else 11812 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11813 Range, OEK_LValue, DiagEmitted); 11814 if (!DiagEmitted) 11815 DiagnoseConstAssignment(S, E, Loc); 11816 } 11817 11818 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11819 /// emit an error and return true. If so, return false. 11820 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11821 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11822 11823 S.CheckShadowingDeclModification(E, Loc); 11824 11825 SourceLocation OrigLoc = Loc; 11826 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11827 &Loc); 11828 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11829 IsLV = Expr::MLV_InvalidMessageExpression; 11830 if (IsLV == Expr::MLV_Valid) 11831 return false; 11832 11833 unsigned DiagID = 0; 11834 bool NeedType = false; 11835 switch (IsLV) { // C99 6.5.16p2 11836 case Expr::MLV_ConstQualified: 11837 // Use a specialized diagnostic when we're assigning to an object 11838 // from an enclosing function or block. 11839 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11840 if (NCCK == NCCK_Block) 11841 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11842 else 11843 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11844 break; 11845 } 11846 11847 // In ARC, use some specialized diagnostics for occasions where we 11848 // infer 'const'. These are always pseudo-strong variables. 11849 if (S.getLangOpts().ObjCAutoRefCount) { 11850 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11851 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11852 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11853 11854 // Use the normal diagnostic if it's pseudo-__strong but the 11855 // user actually wrote 'const'. 11856 if (var->isARCPseudoStrong() && 11857 (!var->getTypeSourceInfo() || 11858 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11859 // There are three pseudo-strong cases: 11860 // - self 11861 ObjCMethodDecl *method = S.getCurMethodDecl(); 11862 if (method && var == method->getSelfDecl()) { 11863 DiagID = method->isClassMethod() 11864 ? diag::err_typecheck_arc_assign_self_class_method 11865 : diag::err_typecheck_arc_assign_self; 11866 11867 // - Objective-C externally_retained attribute. 11868 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11869 isa<ParmVarDecl>(var)) { 11870 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11871 11872 // - fast enumeration variables 11873 } else { 11874 DiagID = diag::err_typecheck_arr_assign_enumeration; 11875 } 11876 11877 SourceRange Assign; 11878 if (Loc != OrigLoc) 11879 Assign = SourceRange(OrigLoc, OrigLoc); 11880 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11881 // We need to preserve the AST regardless, so migration tool 11882 // can do its job. 11883 return false; 11884 } 11885 } 11886 } 11887 11888 // If none of the special cases above are triggered, then this is a 11889 // simple const assignment. 11890 if (DiagID == 0) { 11891 DiagnoseConstAssignment(S, E, Loc); 11892 return true; 11893 } 11894 11895 break; 11896 case Expr::MLV_ConstAddrSpace: 11897 DiagnoseConstAssignment(S, E, Loc); 11898 return true; 11899 case Expr::MLV_ConstQualifiedField: 11900 DiagnoseRecursiveConstFields(S, E, Loc); 11901 return true; 11902 case Expr::MLV_ArrayType: 11903 case Expr::MLV_ArrayTemporary: 11904 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11905 NeedType = true; 11906 break; 11907 case Expr::MLV_NotObjectType: 11908 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11909 NeedType = true; 11910 break; 11911 case Expr::MLV_LValueCast: 11912 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11913 break; 11914 case Expr::MLV_Valid: 11915 llvm_unreachable("did not take early return for MLV_Valid"); 11916 case Expr::MLV_InvalidExpression: 11917 case Expr::MLV_MemberFunction: 11918 case Expr::MLV_ClassTemporary: 11919 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11920 break; 11921 case Expr::MLV_IncompleteType: 11922 case Expr::MLV_IncompleteVoidType: 11923 return S.RequireCompleteType(Loc, E->getType(), 11924 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11925 case Expr::MLV_DuplicateVectorComponents: 11926 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11927 break; 11928 case Expr::MLV_NoSetterProperty: 11929 llvm_unreachable("readonly properties should be processed differently"); 11930 case Expr::MLV_InvalidMessageExpression: 11931 DiagID = diag::err_readonly_message_assignment; 11932 break; 11933 case Expr::MLV_SubObjCPropertySetting: 11934 DiagID = diag::err_no_subobject_property_setting; 11935 break; 11936 } 11937 11938 SourceRange Assign; 11939 if (Loc != OrigLoc) 11940 Assign = SourceRange(OrigLoc, OrigLoc); 11941 if (NeedType) 11942 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11943 else 11944 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11945 return true; 11946 } 11947 11948 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11949 SourceLocation Loc, 11950 Sema &Sema) { 11951 if (Sema.inTemplateInstantiation()) 11952 return; 11953 if (Sema.isUnevaluatedContext()) 11954 return; 11955 if (Loc.isInvalid() || Loc.isMacroID()) 11956 return; 11957 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11958 return; 11959 11960 // C / C++ fields 11961 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11962 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11963 if (ML && MR) { 11964 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11965 return; 11966 const ValueDecl *LHSDecl = 11967 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11968 const ValueDecl *RHSDecl = 11969 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11970 if (LHSDecl != RHSDecl) 11971 return; 11972 if (LHSDecl->getType().isVolatileQualified()) 11973 return; 11974 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11975 if (RefTy->getPointeeType().isVolatileQualified()) 11976 return; 11977 11978 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11979 } 11980 11981 // Objective-C instance variables 11982 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11983 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11984 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11985 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11986 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11987 if (RL && RR && RL->getDecl() == RR->getDecl()) 11988 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11989 } 11990 } 11991 11992 // C99 6.5.16.1 11993 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11994 SourceLocation Loc, 11995 QualType CompoundType) { 11996 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11997 11998 // Verify that LHS is a modifiable lvalue, and emit error if not. 11999 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12000 return QualType(); 12001 12002 QualType LHSType = LHSExpr->getType(); 12003 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12004 CompoundType; 12005 // OpenCL v1.2 s6.1.1.1 p2: 12006 // The half data type can only be used to declare a pointer to a buffer that 12007 // contains half values 12008 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12009 LHSType->isHalfType()) { 12010 Diag(Loc, diag::err_opencl_half_load_store) << 1 12011 << LHSType.getUnqualifiedType(); 12012 return QualType(); 12013 } 12014 12015 AssignConvertType ConvTy; 12016 if (CompoundType.isNull()) { 12017 Expr *RHSCheck = RHS.get(); 12018 12019 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12020 12021 QualType LHSTy(LHSType); 12022 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12023 if (RHS.isInvalid()) 12024 return QualType(); 12025 // Special case of NSObject attributes on c-style pointer types. 12026 if (ConvTy == IncompatiblePointer && 12027 ((Context.isObjCNSObjectType(LHSType) && 12028 RHSType->isObjCObjectPointerType()) || 12029 (Context.isObjCNSObjectType(RHSType) && 12030 LHSType->isObjCObjectPointerType()))) 12031 ConvTy = Compatible; 12032 12033 if (ConvTy == Compatible && 12034 LHSType->isObjCObjectType()) 12035 Diag(Loc, diag::err_objc_object_assignment) 12036 << LHSType; 12037 12038 // If the RHS is a unary plus or minus, check to see if they = and + are 12039 // right next to each other. If so, the user may have typo'd "x =+ 4" 12040 // instead of "x += 4". 12041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12042 RHSCheck = ICE->getSubExpr(); 12043 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12044 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12045 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12046 // Only if the two operators are exactly adjacent. 12047 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12048 // And there is a space or other character before the subexpr of the 12049 // unary +/-. We don't want to warn on "x=-1". 12050 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12051 UO->getSubExpr()->getBeginLoc().isFileID()) { 12052 Diag(Loc, diag::warn_not_compound_assign) 12053 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12054 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12055 } 12056 } 12057 12058 if (ConvTy == Compatible) { 12059 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12060 // Warn about retain cycles where a block captures the LHS, but 12061 // not if the LHS is a simple variable into which the block is 12062 // being stored...unless that variable can be captured by reference! 12063 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12064 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12065 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12066 checkRetainCycles(LHSExpr, RHS.get()); 12067 } 12068 12069 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12070 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12071 // It is safe to assign a weak reference into a strong variable. 12072 // Although this code can still have problems: 12073 // id x = self.weakProp; 12074 // id y = self.weakProp; 12075 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12076 // paths through the function. This should be revisited if 12077 // -Wrepeated-use-of-weak is made flow-sensitive. 12078 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12079 // variable, which will be valid for the current autorelease scope. 12080 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12081 RHS.get()->getBeginLoc())) 12082 getCurFunction()->markSafeWeakUse(RHS.get()); 12083 12084 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12085 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12086 } 12087 } 12088 } else { 12089 // Compound assignment "x += y" 12090 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12091 } 12092 12093 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12094 RHS.get(), AA_Assigning)) 12095 return QualType(); 12096 12097 CheckForNullPointerDereference(*this, LHSExpr); 12098 12099 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12100 if (CompoundType.isNull()) { 12101 // C++2a [expr.ass]p5: 12102 // A simple-assignment whose left operand is of a volatile-qualified 12103 // type is deprecated unless the assignment is either a discarded-value 12104 // expression or an unevaluated operand 12105 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12106 } else { 12107 // C++2a [expr.ass]p6: 12108 // [Compound-assignment] expressions are deprecated if E1 has 12109 // volatile-qualified type 12110 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12111 } 12112 } 12113 12114 // C99 6.5.16p3: The type of an assignment expression is the type of the 12115 // left operand unless the left operand has qualified type, in which case 12116 // it is the unqualified version of the type of the left operand. 12117 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12118 // is converted to the type of the assignment expression (above). 12119 // C++ 5.17p1: the type of the assignment expression is that of its left 12120 // operand. 12121 return (getLangOpts().CPlusPlus 12122 ? LHSType : LHSType.getUnqualifiedType()); 12123 } 12124 12125 // Only ignore explicit casts to void. 12126 static bool IgnoreCommaOperand(const Expr *E) { 12127 E = E->IgnoreParens(); 12128 12129 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12130 if (CE->getCastKind() == CK_ToVoid) { 12131 return true; 12132 } 12133 12134 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12135 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12136 CE->getSubExpr()->getType()->isDependentType()) { 12137 return true; 12138 } 12139 } 12140 12141 return false; 12142 } 12143 12144 // Look for instances where it is likely the comma operator is confused with 12145 // another operator. There is a whitelist of acceptable expressions for the 12146 // left hand side of the comma operator, otherwise emit a warning. 12147 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12148 // No warnings in macros 12149 if (Loc.isMacroID()) 12150 return; 12151 12152 // Don't warn in template instantiations. 12153 if (inTemplateInstantiation()) 12154 return; 12155 12156 // Scope isn't fine-grained enough to whitelist the specific cases, so 12157 // instead, skip more than needed, then call back into here with the 12158 // CommaVisitor in SemaStmt.cpp. 12159 // The whitelisted locations are the initialization and increment portions 12160 // of a for loop. The additional checks are on the condition of 12161 // if statements, do/while loops, and for loops. 12162 // Differences in scope flags for C89 mode requires the extra logic. 12163 const unsigned ForIncrementFlags = 12164 getLangOpts().C99 || getLangOpts().CPlusPlus 12165 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12166 : Scope::ContinueScope | Scope::BreakScope; 12167 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12168 const unsigned ScopeFlags = getCurScope()->getFlags(); 12169 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12170 (ScopeFlags & ForInitFlags) == ForInitFlags) 12171 return; 12172 12173 // If there are multiple comma operators used together, get the RHS of the 12174 // of the comma operator as the LHS. 12175 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12176 if (BO->getOpcode() != BO_Comma) 12177 break; 12178 LHS = BO->getRHS(); 12179 } 12180 12181 // Only allow some expressions on LHS to not warn. 12182 if (IgnoreCommaOperand(LHS)) 12183 return; 12184 12185 Diag(Loc, diag::warn_comma_operator); 12186 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12187 << LHS->getSourceRange() 12188 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12189 LangOpts.CPlusPlus ? "static_cast<void>(" 12190 : "(void)(") 12191 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12192 ")"); 12193 } 12194 12195 // C99 6.5.17 12196 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12197 SourceLocation Loc) { 12198 LHS = S.CheckPlaceholderExpr(LHS.get()); 12199 RHS = S.CheckPlaceholderExpr(RHS.get()); 12200 if (LHS.isInvalid() || RHS.isInvalid()) 12201 return QualType(); 12202 12203 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12204 // operands, but not unary promotions. 12205 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12206 12207 // So we treat the LHS as a ignored value, and in C++ we allow the 12208 // containing site to determine what should be done with the RHS. 12209 LHS = S.IgnoredValueConversions(LHS.get()); 12210 if (LHS.isInvalid()) 12211 return QualType(); 12212 12213 S.DiagnoseUnusedExprResult(LHS.get()); 12214 12215 if (!S.getLangOpts().CPlusPlus) { 12216 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12217 if (RHS.isInvalid()) 12218 return QualType(); 12219 if (!RHS.get()->getType()->isVoidType()) 12220 S.RequireCompleteType(Loc, RHS.get()->getType(), 12221 diag::err_incomplete_type); 12222 } 12223 12224 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12225 S.DiagnoseCommaOperator(LHS.get(), Loc); 12226 12227 return RHS.get()->getType(); 12228 } 12229 12230 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12231 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12232 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12233 ExprValueKind &VK, 12234 ExprObjectKind &OK, 12235 SourceLocation OpLoc, 12236 bool IsInc, bool IsPrefix) { 12237 if (Op->isTypeDependent()) 12238 return S.Context.DependentTy; 12239 12240 QualType ResType = Op->getType(); 12241 // Atomic types can be used for increment / decrement where the non-atomic 12242 // versions can, so ignore the _Atomic() specifier for the purpose of 12243 // checking. 12244 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12245 ResType = ResAtomicType->getValueType(); 12246 12247 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12248 12249 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12250 // Decrement of bool is not allowed. 12251 if (!IsInc) { 12252 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12253 return QualType(); 12254 } 12255 // Increment of bool sets it to true, but is deprecated. 12256 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12257 : diag::warn_increment_bool) 12258 << Op->getSourceRange(); 12259 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12260 // Error on enum increments and decrements in C++ mode 12261 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12262 return QualType(); 12263 } else if (ResType->isRealType()) { 12264 // OK! 12265 } else if (ResType->isPointerType()) { 12266 // C99 6.5.2.4p2, 6.5.6p2 12267 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12268 return QualType(); 12269 } else if (ResType->isObjCObjectPointerType()) { 12270 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12271 // Otherwise, we just need a complete type. 12272 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12273 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12274 return QualType(); 12275 } else if (ResType->isAnyComplexType()) { 12276 // C99 does not support ++/-- on complex types, we allow as an extension. 12277 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12278 << ResType << Op->getSourceRange(); 12279 } else if (ResType->isPlaceholderType()) { 12280 ExprResult PR = S.CheckPlaceholderExpr(Op); 12281 if (PR.isInvalid()) return QualType(); 12282 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12283 IsInc, IsPrefix); 12284 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12285 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12286 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12287 (ResType->castAs<VectorType>()->getVectorKind() != 12288 VectorType::AltiVecBool)) { 12289 // The z vector extensions allow ++ and -- for non-bool vectors. 12290 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12291 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12292 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12293 } else { 12294 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12295 << ResType << int(IsInc) << Op->getSourceRange(); 12296 return QualType(); 12297 } 12298 // At this point, we know we have a real, complex or pointer type. 12299 // Now make sure the operand is a modifiable lvalue. 12300 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12301 return QualType(); 12302 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12303 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12304 // An operand with volatile-qualified type is deprecated 12305 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12306 << IsInc << ResType; 12307 } 12308 // In C++, a prefix increment is the same type as the operand. Otherwise 12309 // (in C or with postfix), the increment is the unqualified type of the 12310 // operand. 12311 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12312 VK = VK_LValue; 12313 OK = Op->getObjectKind(); 12314 return ResType; 12315 } else { 12316 VK = VK_RValue; 12317 return ResType.getUnqualifiedType(); 12318 } 12319 } 12320 12321 12322 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12323 /// This routine allows us to typecheck complex/recursive expressions 12324 /// where the declaration is needed for type checking. We only need to 12325 /// handle cases when the expression references a function designator 12326 /// or is an lvalue. Here are some examples: 12327 /// - &(x) => x 12328 /// - &*****f => f for f a function designator. 12329 /// - &s.xx => s 12330 /// - &s.zz[1].yy -> s, if zz is an array 12331 /// - *(x + 1) -> x, if x is an array 12332 /// - &"123"[2] -> 0 12333 /// - & __real__ x -> x 12334 static ValueDecl *getPrimaryDecl(Expr *E) { 12335 switch (E->getStmtClass()) { 12336 case Stmt::DeclRefExprClass: 12337 return cast<DeclRefExpr>(E)->getDecl(); 12338 case Stmt::MemberExprClass: 12339 // If this is an arrow operator, the address is an offset from 12340 // the base's value, so the object the base refers to is 12341 // irrelevant. 12342 if (cast<MemberExpr>(E)->isArrow()) 12343 return nullptr; 12344 // Otherwise, the expression refers to a part of the base 12345 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12346 case Stmt::ArraySubscriptExprClass: { 12347 // FIXME: This code shouldn't be necessary! We should catch the implicit 12348 // promotion of register arrays earlier. 12349 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12350 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12351 if (ICE->getSubExpr()->getType()->isArrayType()) 12352 return getPrimaryDecl(ICE->getSubExpr()); 12353 } 12354 return nullptr; 12355 } 12356 case Stmt::UnaryOperatorClass: { 12357 UnaryOperator *UO = cast<UnaryOperator>(E); 12358 12359 switch(UO->getOpcode()) { 12360 case UO_Real: 12361 case UO_Imag: 12362 case UO_Extension: 12363 return getPrimaryDecl(UO->getSubExpr()); 12364 default: 12365 return nullptr; 12366 } 12367 } 12368 case Stmt::ParenExprClass: 12369 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12370 case Stmt::ImplicitCastExprClass: 12371 // If the result of an implicit cast is an l-value, we care about 12372 // the sub-expression; otherwise, the result here doesn't matter. 12373 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12374 default: 12375 return nullptr; 12376 } 12377 } 12378 12379 namespace { 12380 enum { 12381 AO_Bit_Field = 0, 12382 AO_Vector_Element = 1, 12383 AO_Property_Expansion = 2, 12384 AO_Register_Variable = 3, 12385 AO_No_Error = 4 12386 }; 12387 } 12388 /// Diagnose invalid operand for address of operations. 12389 /// 12390 /// \param Type The type of operand which cannot have its address taken. 12391 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12392 Expr *E, unsigned Type) { 12393 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12394 } 12395 12396 /// CheckAddressOfOperand - The operand of & must be either a function 12397 /// designator or an lvalue designating an object. If it is an lvalue, the 12398 /// object cannot be declared with storage class register or be a bit field. 12399 /// Note: The usual conversions are *not* applied to the operand of the & 12400 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12401 /// In C++, the operand might be an overloaded function name, in which case 12402 /// we allow the '&' but retain the overloaded-function type. 12403 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12404 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12405 if (PTy->getKind() == BuiltinType::Overload) { 12406 Expr *E = OrigOp.get()->IgnoreParens(); 12407 if (!isa<OverloadExpr>(E)) { 12408 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12409 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12410 << OrigOp.get()->getSourceRange(); 12411 return QualType(); 12412 } 12413 12414 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12415 if (isa<UnresolvedMemberExpr>(Ovl)) 12416 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12417 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12418 << OrigOp.get()->getSourceRange(); 12419 return QualType(); 12420 } 12421 12422 return Context.OverloadTy; 12423 } 12424 12425 if (PTy->getKind() == BuiltinType::UnknownAny) 12426 return Context.UnknownAnyTy; 12427 12428 if (PTy->getKind() == BuiltinType::BoundMember) { 12429 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12430 << OrigOp.get()->getSourceRange(); 12431 return QualType(); 12432 } 12433 12434 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12435 if (OrigOp.isInvalid()) return QualType(); 12436 } 12437 12438 if (OrigOp.get()->isTypeDependent()) 12439 return Context.DependentTy; 12440 12441 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12442 12443 // Make sure to ignore parentheses in subsequent checks 12444 Expr *op = OrigOp.get()->IgnoreParens(); 12445 12446 // In OpenCL captures for blocks called as lambda functions 12447 // are located in the private address space. Blocks used in 12448 // enqueue_kernel can be located in a different address space 12449 // depending on a vendor implementation. Thus preventing 12450 // taking an address of the capture to avoid invalid AS casts. 12451 if (LangOpts.OpenCL) { 12452 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12453 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12454 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12455 return QualType(); 12456 } 12457 } 12458 12459 if (getLangOpts().C99) { 12460 // Implement C99-only parts of addressof rules. 12461 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12462 if (uOp->getOpcode() == UO_Deref) 12463 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12464 // (assuming the deref expression is valid). 12465 return uOp->getSubExpr()->getType(); 12466 } 12467 // Technically, there should be a check for array subscript 12468 // expressions here, but the result of one is always an lvalue anyway. 12469 } 12470 ValueDecl *dcl = getPrimaryDecl(op); 12471 12472 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12473 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12474 op->getBeginLoc())) 12475 return QualType(); 12476 12477 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12478 unsigned AddressOfError = AO_No_Error; 12479 12480 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12481 bool sfinae = (bool)isSFINAEContext(); 12482 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12483 : diag::ext_typecheck_addrof_temporary) 12484 << op->getType() << op->getSourceRange(); 12485 if (sfinae) 12486 return QualType(); 12487 // Materialize the temporary as an lvalue so that we can take its address. 12488 OrigOp = op = 12489 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12490 } else if (isa<ObjCSelectorExpr>(op)) { 12491 return Context.getPointerType(op->getType()); 12492 } else if (lval == Expr::LV_MemberFunction) { 12493 // If it's an instance method, make a member pointer. 12494 // The expression must have exactly the form &A::foo. 12495 12496 // If the underlying expression isn't a decl ref, give up. 12497 if (!isa<DeclRefExpr>(op)) { 12498 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12499 << OrigOp.get()->getSourceRange(); 12500 return QualType(); 12501 } 12502 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12503 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12504 12505 // The id-expression was parenthesized. 12506 if (OrigOp.get() != DRE) { 12507 Diag(OpLoc, diag::err_parens_pointer_member_function) 12508 << OrigOp.get()->getSourceRange(); 12509 12510 // The method was named without a qualifier. 12511 } else if (!DRE->getQualifier()) { 12512 if (MD->getParent()->getName().empty()) 12513 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12514 << op->getSourceRange(); 12515 else { 12516 SmallString<32> Str; 12517 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12518 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12519 << op->getSourceRange() 12520 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12521 } 12522 } 12523 12524 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12525 if (isa<CXXDestructorDecl>(MD)) 12526 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12527 12528 QualType MPTy = Context.getMemberPointerType( 12529 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12530 // Under the MS ABI, lock down the inheritance model now. 12531 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12532 (void)isCompleteType(OpLoc, MPTy); 12533 return MPTy; 12534 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12535 // C99 6.5.3.2p1 12536 // The operand must be either an l-value or a function designator 12537 if (!op->getType()->isFunctionType()) { 12538 // Use a special diagnostic for loads from property references. 12539 if (isa<PseudoObjectExpr>(op)) { 12540 AddressOfError = AO_Property_Expansion; 12541 } else { 12542 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12543 << op->getType() << op->getSourceRange(); 12544 return QualType(); 12545 } 12546 } 12547 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12548 // The operand cannot be a bit-field 12549 AddressOfError = AO_Bit_Field; 12550 } else if (op->getObjectKind() == OK_VectorComponent) { 12551 // The operand cannot be an element of a vector 12552 AddressOfError = AO_Vector_Element; 12553 } else if (dcl) { // C99 6.5.3.2p1 12554 // We have an lvalue with a decl. Make sure the decl is not declared 12555 // with the register storage-class specifier. 12556 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12557 // in C++ it is not error to take address of a register 12558 // variable (c++03 7.1.1P3) 12559 if (vd->getStorageClass() == SC_Register && 12560 !getLangOpts().CPlusPlus) { 12561 AddressOfError = AO_Register_Variable; 12562 } 12563 } else if (isa<MSPropertyDecl>(dcl)) { 12564 AddressOfError = AO_Property_Expansion; 12565 } else if (isa<FunctionTemplateDecl>(dcl)) { 12566 return Context.OverloadTy; 12567 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12568 // Okay: we can take the address of a field. 12569 // Could be a pointer to member, though, if there is an explicit 12570 // scope qualifier for the class. 12571 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12572 DeclContext *Ctx = dcl->getDeclContext(); 12573 if (Ctx && Ctx->isRecord()) { 12574 if (dcl->getType()->isReferenceType()) { 12575 Diag(OpLoc, 12576 diag::err_cannot_form_pointer_to_member_of_reference_type) 12577 << dcl->getDeclName() << dcl->getType(); 12578 return QualType(); 12579 } 12580 12581 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12582 Ctx = Ctx->getParent(); 12583 12584 QualType MPTy = Context.getMemberPointerType( 12585 op->getType(), 12586 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12587 // Under the MS ABI, lock down the inheritance model now. 12588 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12589 (void)isCompleteType(OpLoc, MPTy); 12590 return MPTy; 12591 } 12592 } 12593 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12594 !isa<BindingDecl>(dcl)) 12595 llvm_unreachable("Unknown/unexpected decl type"); 12596 } 12597 12598 if (AddressOfError != AO_No_Error) { 12599 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12600 return QualType(); 12601 } 12602 12603 if (lval == Expr::LV_IncompleteVoidType) { 12604 // Taking the address of a void variable is technically illegal, but we 12605 // allow it in cases which are otherwise valid. 12606 // Example: "extern void x; void* y = &x;". 12607 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12608 } 12609 12610 // If the operand has type "type", the result has type "pointer to type". 12611 if (op->getType()->isObjCObjectType()) 12612 return Context.getObjCObjectPointerType(op->getType()); 12613 12614 CheckAddressOfPackedMember(op); 12615 12616 return Context.getPointerType(op->getType()); 12617 } 12618 12619 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12620 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12621 if (!DRE) 12622 return; 12623 const Decl *D = DRE->getDecl(); 12624 if (!D) 12625 return; 12626 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12627 if (!Param) 12628 return; 12629 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12630 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12631 return; 12632 if (FunctionScopeInfo *FD = S.getCurFunction()) 12633 if (!FD->ModifiedNonNullParams.count(Param)) 12634 FD->ModifiedNonNullParams.insert(Param); 12635 } 12636 12637 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12638 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12639 SourceLocation OpLoc) { 12640 if (Op->isTypeDependent()) 12641 return S.Context.DependentTy; 12642 12643 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12644 if (ConvResult.isInvalid()) 12645 return QualType(); 12646 Op = ConvResult.get(); 12647 QualType OpTy = Op->getType(); 12648 QualType Result; 12649 12650 if (isa<CXXReinterpretCastExpr>(Op)) { 12651 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12652 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12653 Op->getSourceRange()); 12654 } 12655 12656 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12657 { 12658 Result = PT->getPointeeType(); 12659 } 12660 else if (const ObjCObjectPointerType *OPT = 12661 OpTy->getAs<ObjCObjectPointerType>()) 12662 Result = OPT->getPointeeType(); 12663 else { 12664 ExprResult PR = S.CheckPlaceholderExpr(Op); 12665 if (PR.isInvalid()) return QualType(); 12666 if (PR.get() != Op) 12667 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12668 } 12669 12670 if (Result.isNull()) { 12671 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12672 << OpTy << Op->getSourceRange(); 12673 return QualType(); 12674 } 12675 12676 // Note that per both C89 and C99, indirection is always legal, even if Result 12677 // is an incomplete type or void. It would be possible to warn about 12678 // dereferencing a void pointer, but it's completely well-defined, and such a 12679 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12680 // for pointers to 'void' but is fine for any other pointer type: 12681 // 12682 // C++ [expr.unary.op]p1: 12683 // [...] the expression to which [the unary * operator] is applied shall 12684 // be a pointer to an object type, or a pointer to a function type 12685 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12686 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12687 << OpTy << Op->getSourceRange(); 12688 12689 // Dereferences are usually l-values... 12690 VK = VK_LValue; 12691 12692 // ...except that certain expressions are never l-values in C. 12693 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12694 VK = VK_RValue; 12695 12696 return Result; 12697 } 12698 12699 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12700 BinaryOperatorKind Opc; 12701 switch (Kind) { 12702 default: llvm_unreachable("Unknown binop!"); 12703 case tok::periodstar: Opc = BO_PtrMemD; break; 12704 case tok::arrowstar: Opc = BO_PtrMemI; break; 12705 case tok::star: Opc = BO_Mul; break; 12706 case tok::slash: Opc = BO_Div; break; 12707 case tok::percent: Opc = BO_Rem; break; 12708 case tok::plus: Opc = BO_Add; break; 12709 case tok::minus: Opc = BO_Sub; break; 12710 case tok::lessless: Opc = BO_Shl; break; 12711 case tok::greatergreater: Opc = BO_Shr; break; 12712 case tok::lessequal: Opc = BO_LE; break; 12713 case tok::less: Opc = BO_LT; break; 12714 case tok::greaterequal: Opc = BO_GE; break; 12715 case tok::greater: Opc = BO_GT; break; 12716 case tok::exclaimequal: Opc = BO_NE; break; 12717 case tok::equalequal: Opc = BO_EQ; break; 12718 case tok::spaceship: Opc = BO_Cmp; break; 12719 case tok::amp: Opc = BO_And; break; 12720 case tok::caret: Opc = BO_Xor; break; 12721 case tok::pipe: Opc = BO_Or; break; 12722 case tok::ampamp: Opc = BO_LAnd; break; 12723 case tok::pipepipe: Opc = BO_LOr; break; 12724 case tok::equal: Opc = BO_Assign; break; 12725 case tok::starequal: Opc = BO_MulAssign; break; 12726 case tok::slashequal: Opc = BO_DivAssign; break; 12727 case tok::percentequal: Opc = BO_RemAssign; break; 12728 case tok::plusequal: Opc = BO_AddAssign; break; 12729 case tok::minusequal: Opc = BO_SubAssign; break; 12730 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12731 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12732 case tok::ampequal: Opc = BO_AndAssign; break; 12733 case tok::caretequal: Opc = BO_XorAssign; break; 12734 case tok::pipeequal: Opc = BO_OrAssign; break; 12735 case tok::comma: Opc = BO_Comma; break; 12736 } 12737 return Opc; 12738 } 12739 12740 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12741 tok::TokenKind Kind) { 12742 UnaryOperatorKind Opc; 12743 switch (Kind) { 12744 default: llvm_unreachable("Unknown unary op!"); 12745 case tok::plusplus: Opc = UO_PreInc; break; 12746 case tok::minusminus: Opc = UO_PreDec; break; 12747 case tok::amp: Opc = UO_AddrOf; break; 12748 case tok::star: Opc = UO_Deref; break; 12749 case tok::plus: Opc = UO_Plus; break; 12750 case tok::minus: Opc = UO_Minus; break; 12751 case tok::tilde: Opc = UO_Not; break; 12752 case tok::exclaim: Opc = UO_LNot; break; 12753 case tok::kw___real: Opc = UO_Real; break; 12754 case tok::kw___imag: Opc = UO_Imag; break; 12755 case tok::kw___extension__: Opc = UO_Extension; break; 12756 } 12757 return Opc; 12758 } 12759 12760 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12761 /// This warning suppressed in the event of macro expansions. 12762 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12763 SourceLocation OpLoc, bool IsBuiltin) { 12764 if (S.inTemplateInstantiation()) 12765 return; 12766 if (S.isUnevaluatedContext()) 12767 return; 12768 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12769 return; 12770 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12771 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12772 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12773 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12774 if (!LHSDeclRef || !RHSDeclRef || 12775 LHSDeclRef->getLocation().isMacroID() || 12776 RHSDeclRef->getLocation().isMacroID()) 12777 return; 12778 const ValueDecl *LHSDecl = 12779 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12780 const ValueDecl *RHSDecl = 12781 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12782 if (LHSDecl != RHSDecl) 12783 return; 12784 if (LHSDecl->getType().isVolatileQualified()) 12785 return; 12786 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12787 if (RefTy->getPointeeType().isVolatileQualified()) 12788 return; 12789 12790 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12791 : diag::warn_self_assignment_overloaded) 12792 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12793 << RHSExpr->getSourceRange(); 12794 } 12795 12796 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12797 /// is usually indicative of introspection within the Objective-C pointer. 12798 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12799 SourceLocation OpLoc) { 12800 if (!S.getLangOpts().ObjC) 12801 return; 12802 12803 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12804 const Expr *LHS = L.get(); 12805 const Expr *RHS = R.get(); 12806 12807 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12808 ObjCPointerExpr = LHS; 12809 OtherExpr = RHS; 12810 } 12811 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12812 ObjCPointerExpr = RHS; 12813 OtherExpr = LHS; 12814 } 12815 12816 // This warning is deliberately made very specific to reduce false 12817 // positives with logic that uses '&' for hashing. This logic mainly 12818 // looks for code trying to introspect into tagged pointers, which 12819 // code should generally never do. 12820 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12821 unsigned Diag = diag::warn_objc_pointer_masking; 12822 // Determine if we are introspecting the result of performSelectorXXX. 12823 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12824 // Special case messages to -performSelector and friends, which 12825 // can return non-pointer values boxed in a pointer value. 12826 // Some clients may wish to silence warnings in this subcase. 12827 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12828 Selector S = ME->getSelector(); 12829 StringRef SelArg0 = S.getNameForSlot(0); 12830 if (SelArg0.startswith("performSelector")) 12831 Diag = diag::warn_objc_pointer_masking_performSelector; 12832 } 12833 12834 S.Diag(OpLoc, Diag) 12835 << ObjCPointerExpr->getSourceRange(); 12836 } 12837 } 12838 12839 static NamedDecl *getDeclFromExpr(Expr *E) { 12840 if (!E) 12841 return nullptr; 12842 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12843 return DRE->getDecl(); 12844 if (auto *ME = dyn_cast<MemberExpr>(E)) 12845 return ME->getMemberDecl(); 12846 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12847 return IRE->getDecl(); 12848 return nullptr; 12849 } 12850 12851 // This helper function promotes a binary operator's operands (which are of a 12852 // half vector type) to a vector of floats and then truncates the result to 12853 // a vector of either half or short. 12854 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12855 BinaryOperatorKind Opc, QualType ResultTy, 12856 ExprValueKind VK, ExprObjectKind OK, 12857 bool IsCompAssign, SourceLocation OpLoc, 12858 FPOptions FPFeatures) { 12859 auto &Context = S.getASTContext(); 12860 assert((isVector(ResultTy, Context.HalfTy) || 12861 isVector(ResultTy, Context.ShortTy)) && 12862 "Result must be a vector of half or short"); 12863 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12864 isVector(RHS.get()->getType(), Context.HalfTy) && 12865 "both operands expected to be a half vector"); 12866 12867 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12868 QualType BinOpResTy = RHS.get()->getType(); 12869 12870 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12871 // change BinOpResTy to a vector of ints. 12872 if (isVector(ResultTy, Context.ShortTy)) 12873 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12874 12875 if (IsCompAssign) 12876 return new (Context) CompoundAssignOperator( 12877 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12878 OpLoc, FPFeatures); 12879 12880 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12881 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12882 VK, OK, OpLoc, FPFeatures); 12883 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12884 } 12885 12886 static std::pair<ExprResult, ExprResult> 12887 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12888 Expr *RHSExpr) { 12889 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12890 if (!S.getLangOpts().CPlusPlus) { 12891 // C cannot handle TypoExpr nodes on either side of a binop because it 12892 // doesn't handle dependent types properly, so make sure any TypoExprs have 12893 // been dealt with before checking the operands. 12894 LHS = S.CorrectDelayedTyposInExpr(LHS); 12895 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12896 if (Opc != BO_Assign) 12897 return ExprResult(E); 12898 // Avoid correcting the RHS to the same Expr as the LHS. 12899 Decl *D = getDeclFromExpr(E); 12900 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12901 }); 12902 } 12903 return std::make_pair(LHS, RHS); 12904 } 12905 12906 /// Returns true if conversion between vectors of halfs and vectors of floats 12907 /// is needed. 12908 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12909 QualType SrcType) { 12910 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12911 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12912 isVector(SrcType, Ctx.HalfTy); 12913 } 12914 12915 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12916 /// operator @p Opc at location @c TokLoc. This routine only supports 12917 /// built-in operations; ActOnBinOp handles overloaded operators. 12918 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12919 BinaryOperatorKind Opc, 12920 Expr *LHSExpr, Expr *RHSExpr) { 12921 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12922 // The syntax only allows initializer lists on the RHS of assignment, 12923 // so we don't need to worry about accepting invalid code for 12924 // non-assignment operators. 12925 // C++11 5.17p9: 12926 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12927 // of x = {} is x = T(). 12928 InitializationKind Kind = InitializationKind::CreateDirectList( 12929 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12930 InitializedEntity Entity = 12931 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12932 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12933 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12934 if (Init.isInvalid()) 12935 return Init; 12936 RHSExpr = Init.get(); 12937 } 12938 12939 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12940 QualType ResultTy; // Result type of the binary operator. 12941 // The following two variables are used for compound assignment operators 12942 QualType CompLHSTy; // Type of LHS after promotions for computation 12943 QualType CompResultTy; // Type of computation result 12944 ExprValueKind VK = VK_RValue; 12945 ExprObjectKind OK = OK_Ordinary; 12946 bool ConvertHalfVec = false; 12947 12948 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12949 if (!LHS.isUsable() || !RHS.isUsable()) 12950 return ExprError(); 12951 12952 if (getLangOpts().OpenCL) { 12953 QualType LHSTy = LHSExpr->getType(); 12954 QualType RHSTy = RHSExpr->getType(); 12955 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12956 // the ATOMIC_VAR_INIT macro. 12957 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12958 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12959 if (BO_Assign == Opc) 12960 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12961 else 12962 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12963 return ExprError(); 12964 } 12965 12966 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12967 // only with a builtin functions and therefore should be disallowed here. 12968 if (LHSTy->isImageType() || RHSTy->isImageType() || 12969 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12970 LHSTy->isPipeType() || RHSTy->isPipeType() || 12971 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12972 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12973 return ExprError(); 12974 } 12975 } 12976 12977 // Diagnose operations on the unsupported types for OpenMP device compilation. 12978 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12979 if (Opc != BO_Assign && Opc != BO_Comma) { 12980 checkOpenMPDeviceExpr(LHSExpr); 12981 checkOpenMPDeviceExpr(RHSExpr); 12982 } 12983 } 12984 12985 switch (Opc) { 12986 case BO_Assign: 12987 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12988 if (getLangOpts().CPlusPlus && 12989 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12990 VK = LHS.get()->getValueKind(); 12991 OK = LHS.get()->getObjectKind(); 12992 } 12993 if (!ResultTy.isNull()) { 12994 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12995 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12996 12997 // Avoid copying a block to the heap if the block is assigned to a local 12998 // auto variable that is declared in the same scope as the block. This 12999 // optimization is unsafe if the local variable is declared in an outer 13000 // scope. For example: 13001 // 13002 // BlockTy b; 13003 // { 13004 // b = ^{...}; 13005 // } 13006 // // It is unsafe to invoke the block here if it wasn't copied to the 13007 // // heap. 13008 // b(); 13009 13010 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13011 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13012 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13013 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13014 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13015 13016 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13017 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13018 NTCUC_Assignment, NTCUK_Copy); 13019 } 13020 RecordModifiableNonNullParam(*this, LHS.get()); 13021 break; 13022 case BO_PtrMemD: 13023 case BO_PtrMemI: 13024 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13025 Opc == BO_PtrMemI); 13026 break; 13027 case BO_Mul: 13028 case BO_Div: 13029 ConvertHalfVec = true; 13030 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13031 Opc == BO_Div); 13032 break; 13033 case BO_Rem: 13034 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13035 break; 13036 case BO_Add: 13037 ConvertHalfVec = true; 13038 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13039 break; 13040 case BO_Sub: 13041 ConvertHalfVec = true; 13042 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13043 break; 13044 case BO_Shl: 13045 case BO_Shr: 13046 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13047 break; 13048 case BO_LE: 13049 case BO_LT: 13050 case BO_GE: 13051 case BO_GT: 13052 ConvertHalfVec = true; 13053 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13054 break; 13055 case BO_EQ: 13056 case BO_NE: 13057 ConvertHalfVec = true; 13058 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13059 break; 13060 case BO_Cmp: 13061 ConvertHalfVec = true; 13062 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13063 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13064 break; 13065 case BO_And: 13066 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13067 LLVM_FALLTHROUGH; 13068 case BO_Xor: 13069 case BO_Or: 13070 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13071 break; 13072 case BO_LAnd: 13073 case BO_LOr: 13074 ConvertHalfVec = true; 13075 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13076 break; 13077 case BO_MulAssign: 13078 case BO_DivAssign: 13079 ConvertHalfVec = true; 13080 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13081 Opc == BO_DivAssign); 13082 CompLHSTy = CompResultTy; 13083 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13084 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13085 break; 13086 case BO_RemAssign: 13087 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13088 CompLHSTy = CompResultTy; 13089 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13090 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13091 break; 13092 case BO_AddAssign: 13093 ConvertHalfVec = true; 13094 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13095 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13096 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13097 break; 13098 case BO_SubAssign: 13099 ConvertHalfVec = true; 13100 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13101 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13102 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13103 break; 13104 case BO_ShlAssign: 13105 case BO_ShrAssign: 13106 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13107 CompLHSTy = CompResultTy; 13108 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13109 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13110 break; 13111 case BO_AndAssign: 13112 case BO_OrAssign: // fallthrough 13113 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13114 LLVM_FALLTHROUGH; 13115 case BO_XorAssign: 13116 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13117 CompLHSTy = CompResultTy; 13118 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13119 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13120 break; 13121 case BO_Comma: 13122 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13123 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13124 VK = RHS.get()->getValueKind(); 13125 OK = RHS.get()->getObjectKind(); 13126 } 13127 break; 13128 } 13129 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13130 return ExprError(); 13131 13132 if (ResultTy->isRealFloatingType() && 13133 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13134 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13135 // Mark the current function as usng floating point constrained intrinsics 13136 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13137 F->setUsesFPIntrin(true); 13138 } 13139 13140 // Some of the binary operations require promoting operands of half vector to 13141 // float vectors and truncating the result back to half vector. For now, we do 13142 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13143 // arm64). 13144 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13145 isVector(LHS.get()->getType(), Context.HalfTy) && 13146 "both sides are half vectors or neither sides are"); 13147 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13148 LHS.get()->getType()); 13149 13150 // Check for array bounds violations for both sides of the BinaryOperator 13151 CheckArrayAccess(LHS.get()); 13152 CheckArrayAccess(RHS.get()); 13153 13154 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13155 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13156 &Context.Idents.get("object_setClass"), 13157 SourceLocation(), LookupOrdinaryName); 13158 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13159 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13160 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13161 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13162 "object_setClass(") 13163 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13164 ",") 13165 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13166 } 13167 else 13168 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13169 } 13170 else if (const ObjCIvarRefExpr *OIRE = 13171 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13172 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13173 13174 // Opc is not a compound assignment if CompResultTy is null. 13175 if (CompResultTy.isNull()) { 13176 if (ConvertHalfVec) 13177 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13178 OpLoc, FPFeatures); 13179 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13180 OK, OpLoc, FPFeatures); 13181 } 13182 13183 // Handle compound assignments. 13184 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13185 OK_ObjCProperty) { 13186 VK = VK_LValue; 13187 OK = LHS.get()->getObjectKind(); 13188 } 13189 13190 if (ConvertHalfVec) 13191 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13192 OpLoc, FPFeatures); 13193 13194 return new (Context) CompoundAssignOperator( 13195 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13196 OpLoc, FPFeatures); 13197 } 13198 13199 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13200 /// operators are mixed in a way that suggests that the programmer forgot that 13201 /// comparison operators have higher precedence. The most typical example of 13202 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13203 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13204 SourceLocation OpLoc, Expr *LHSExpr, 13205 Expr *RHSExpr) { 13206 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13207 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13208 13209 // Check that one of the sides is a comparison operator and the other isn't. 13210 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13211 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13212 if (isLeftComp == isRightComp) 13213 return; 13214 13215 // Bitwise operations are sometimes used as eager logical ops. 13216 // Don't diagnose this. 13217 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13218 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13219 if (isLeftBitwise || isRightBitwise) 13220 return; 13221 13222 SourceRange DiagRange = isLeftComp 13223 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13224 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13225 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13226 SourceRange ParensRange = 13227 isLeftComp 13228 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13229 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13230 13231 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13232 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13233 SuggestParentheses(Self, OpLoc, 13234 Self.PDiag(diag::note_precedence_silence) << OpStr, 13235 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13236 SuggestParentheses(Self, OpLoc, 13237 Self.PDiag(diag::note_precedence_bitwise_first) 13238 << BinaryOperator::getOpcodeStr(Opc), 13239 ParensRange); 13240 } 13241 13242 /// It accepts a '&&' expr that is inside a '||' one. 13243 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13244 /// in parentheses. 13245 static void 13246 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13247 BinaryOperator *Bop) { 13248 assert(Bop->getOpcode() == BO_LAnd); 13249 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13250 << Bop->getSourceRange() << OpLoc; 13251 SuggestParentheses(Self, Bop->getOperatorLoc(), 13252 Self.PDiag(diag::note_precedence_silence) 13253 << Bop->getOpcodeStr(), 13254 Bop->getSourceRange()); 13255 } 13256 13257 /// Returns true if the given expression can be evaluated as a constant 13258 /// 'true'. 13259 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13260 bool Res; 13261 return !E->isValueDependent() && 13262 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13263 } 13264 13265 /// Returns true if the given expression can be evaluated as a constant 13266 /// 'false'. 13267 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13268 bool Res; 13269 return !E->isValueDependent() && 13270 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13271 } 13272 13273 /// Look for '&&' in the left hand of a '||' expr. 13274 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13275 Expr *LHSExpr, Expr *RHSExpr) { 13276 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13277 if (Bop->getOpcode() == BO_LAnd) { 13278 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13279 if (EvaluatesAsFalse(S, RHSExpr)) 13280 return; 13281 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13282 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13283 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13284 } else if (Bop->getOpcode() == BO_LOr) { 13285 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13286 // If it's "a || b && 1 || c" we didn't warn earlier for 13287 // "a || b && 1", but warn now. 13288 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13289 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13290 } 13291 } 13292 } 13293 } 13294 13295 /// Look for '&&' in the right hand of a '||' expr. 13296 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13297 Expr *LHSExpr, Expr *RHSExpr) { 13298 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13299 if (Bop->getOpcode() == BO_LAnd) { 13300 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13301 if (EvaluatesAsFalse(S, LHSExpr)) 13302 return; 13303 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13304 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13305 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13306 } 13307 } 13308 } 13309 13310 /// Look for bitwise op in the left or right hand of a bitwise op with 13311 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13312 /// the '&' expression in parentheses. 13313 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13314 SourceLocation OpLoc, Expr *SubExpr) { 13315 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13316 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13317 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13318 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13319 << Bop->getSourceRange() << OpLoc; 13320 SuggestParentheses(S, Bop->getOperatorLoc(), 13321 S.PDiag(diag::note_precedence_silence) 13322 << Bop->getOpcodeStr(), 13323 Bop->getSourceRange()); 13324 } 13325 } 13326 } 13327 13328 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13329 Expr *SubExpr, StringRef Shift) { 13330 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13331 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13332 StringRef Op = Bop->getOpcodeStr(); 13333 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13334 << Bop->getSourceRange() << OpLoc << Shift << Op; 13335 SuggestParentheses(S, Bop->getOperatorLoc(), 13336 S.PDiag(diag::note_precedence_silence) << Op, 13337 Bop->getSourceRange()); 13338 } 13339 } 13340 } 13341 13342 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13343 Expr *LHSExpr, Expr *RHSExpr) { 13344 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13345 if (!OCE) 13346 return; 13347 13348 FunctionDecl *FD = OCE->getDirectCallee(); 13349 if (!FD || !FD->isOverloadedOperator()) 13350 return; 13351 13352 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13353 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13354 return; 13355 13356 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13357 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13358 << (Kind == OO_LessLess); 13359 SuggestParentheses(S, OCE->getOperatorLoc(), 13360 S.PDiag(diag::note_precedence_silence) 13361 << (Kind == OO_LessLess ? "<<" : ">>"), 13362 OCE->getSourceRange()); 13363 SuggestParentheses( 13364 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13365 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13366 } 13367 13368 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13369 /// precedence. 13370 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13371 SourceLocation OpLoc, Expr *LHSExpr, 13372 Expr *RHSExpr){ 13373 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13374 if (BinaryOperator::isBitwiseOp(Opc)) 13375 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13376 13377 // Diagnose "arg1 & arg2 | arg3" 13378 if ((Opc == BO_Or || Opc == BO_Xor) && 13379 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13380 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13381 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13382 } 13383 13384 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13385 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13386 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13387 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13388 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13389 } 13390 13391 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13392 || Opc == BO_Shr) { 13393 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13394 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13395 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13396 } 13397 13398 // Warn on overloaded shift operators and comparisons, such as: 13399 // cout << 5 == 4; 13400 if (BinaryOperator::isComparisonOp(Opc)) 13401 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13402 } 13403 13404 // Binary Operators. 'Tok' is the token for the operator. 13405 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13406 tok::TokenKind Kind, 13407 Expr *LHSExpr, Expr *RHSExpr) { 13408 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13409 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13410 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13411 13412 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13413 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13414 13415 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13416 } 13417 13418 /// Build an overloaded binary operator expression in the given scope. 13419 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13420 BinaryOperatorKind Opc, 13421 Expr *LHS, Expr *RHS) { 13422 switch (Opc) { 13423 case BO_Assign: 13424 case BO_DivAssign: 13425 case BO_RemAssign: 13426 case BO_SubAssign: 13427 case BO_AndAssign: 13428 case BO_OrAssign: 13429 case BO_XorAssign: 13430 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13431 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13432 break; 13433 default: 13434 break; 13435 } 13436 13437 // Find all of the overloaded operators visible from this 13438 // point. We perform both an operator-name lookup from the local 13439 // scope and an argument-dependent lookup based on the types of 13440 // the arguments. 13441 UnresolvedSet<16> Functions; 13442 OverloadedOperatorKind OverOp 13443 = BinaryOperator::getOverloadedOperator(Opc); 13444 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13445 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13446 RHS->getType(), Functions); 13447 13448 // In C++20 onwards, we may have a second operator to look up. 13449 if (S.getLangOpts().CPlusPlus2a) { 13450 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13451 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13452 RHS->getType(), Functions); 13453 } 13454 13455 // Build the (potentially-overloaded, potentially-dependent) 13456 // binary operation. 13457 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13458 } 13459 13460 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13461 BinaryOperatorKind Opc, 13462 Expr *LHSExpr, Expr *RHSExpr) { 13463 ExprResult LHS, RHS; 13464 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13465 if (!LHS.isUsable() || !RHS.isUsable()) 13466 return ExprError(); 13467 LHSExpr = LHS.get(); 13468 RHSExpr = RHS.get(); 13469 13470 // We want to end up calling one of checkPseudoObjectAssignment 13471 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13472 // both expressions are overloadable or either is type-dependent), 13473 // or CreateBuiltinBinOp (in any other case). We also want to get 13474 // any placeholder types out of the way. 13475 13476 // Handle pseudo-objects in the LHS. 13477 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13478 // Assignments with a pseudo-object l-value need special analysis. 13479 if (pty->getKind() == BuiltinType::PseudoObject && 13480 BinaryOperator::isAssignmentOp(Opc)) 13481 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13482 13483 // Don't resolve overloads if the other type is overloadable. 13484 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13485 // We can't actually test that if we still have a placeholder, 13486 // though. Fortunately, none of the exceptions we see in that 13487 // code below are valid when the LHS is an overload set. Note 13488 // that an overload set can be dependently-typed, but it never 13489 // instantiates to having an overloadable type. 13490 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13491 if (resolvedRHS.isInvalid()) return ExprError(); 13492 RHSExpr = resolvedRHS.get(); 13493 13494 if (RHSExpr->isTypeDependent() || 13495 RHSExpr->getType()->isOverloadableType()) 13496 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13497 } 13498 13499 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13500 // template, diagnose the missing 'template' keyword instead of diagnosing 13501 // an invalid use of a bound member function. 13502 // 13503 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13504 // to C++1z [over.over]/1.4, but we already checked for that case above. 13505 if (Opc == BO_LT && inTemplateInstantiation() && 13506 (pty->getKind() == BuiltinType::BoundMember || 13507 pty->getKind() == BuiltinType::Overload)) { 13508 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13509 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13510 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13511 return isa<FunctionTemplateDecl>(ND); 13512 })) { 13513 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13514 : OE->getNameLoc(), 13515 diag::err_template_kw_missing) 13516 << OE->getName().getAsString() << ""; 13517 return ExprError(); 13518 } 13519 } 13520 13521 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13522 if (LHS.isInvalid()) return ExprError(); 13523 LHSExpr = LHS.get(); 13524 } 13525 13526 // Handle pseudo-objects in the RHS. 13527 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13528 // An overload in the RHS can potentially be resolved by the type 13529 // being assigned to. 13530 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13531 if (getLangOpts().CPlusPlus && 13532 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13533 LHSExpr->getType()->isOverloadableType())) 13534 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13535 13536 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13537 } 13538 13539 // Don't resolve overloads if the other type is overloadable. 13540 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13541 LHSExpr->getType()->isOverloadableType()) 13542 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13543 13544 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13545 if (!resolvedRHS.isUsable()) return ExprError(); 13546 RHSExpr = resolvedRHS.get(); 13547 } 13548 13549 if (getLangOpts().CPlusPlus) { 13550 // If either expression is type-dependent, always build an 13551 // overloaded op. 13552 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13553 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13554 13555 // Otherwise, build an overloaded op if either expression has an 13556 // overloadable type. 13557 if (LHSExpr->getType()->isOverloadableType() || 13558 RHSExpr->getType()->isOverloadableType()) 13559 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13560 } 13561 13562 // Build a built-in binary operation. 13563 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13564 } 13565 13566 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13567 if (T.isNull() || T->isDependentType()) 13568 return false; 13569 13570 if (!T->isPromotableIntegerType()) 13571 return true; 13572 13573 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13574 } 13575 13576 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13577 UnaryOperatorKind Opc, 13578 Expr *InputExpr) { 13579 ExprResult Input = InputExpr; 13580 ExprValueKind VK = VK_RValue; 13581 ExprObjectKind OK = OK_Ordinary; 13582 QualType resultType; 13583 bool CanOverflow = false; 13584 13585 bool ConvertHalfVec = false; 13586 if (getLangOpts().OpenCL) { 13587 QualType Ty = InputExpr->getType(); 13588 // The only legal unary operation for atomics is '&'. 13589 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13590 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13591 // only with a builtin functions and therefore should be disallowed here. 13592 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13593 || Ty->isBlockPointerType())) { 13594 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13595 << InputExpr->getType() 13596 << Input.get()->getSourceRange()); 13597 } 13598 } 13599 // Diagnose operations on the unsupported types for OpenMP device compilation. 13600 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13601 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13602 UnaryOperator::isArithmeticOp(Opc)) 13603 checkOpenMPDeviceExpr(InputExpr); 13604 } 13605 13606 switch (Opc) { 13607 case UO_PreInc: 13608 case UO_PreDec: 13609 case UO_PostInc: 13610 case UO_PostDec: 13611 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13612 OpLoc, 13613 Opc == UO_PreInc || 13614 Opc == UO_PostInc, 13615 Opc == UO_PreInc || 13616 Opc == UO_PreDec); 13617 CanOverflow = isOverflowingIntegerType(Context, resultType); 13618 break; 13619 case UO_AddrOf: 13620 resultType = CheckAddressOfOperand(Input, OpLoc); 13621 CheckAddressOfNoDeref(InputExpr); 13622 RecordModifiableNonNullParam(*this, InputExpr); 13623 break; 13624 case UO_Deref: { 13625 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13626 if (Input.isInvalid()) return ExprError(); 13627 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13628 break; 13629 } 13630 case UO_Plus: 13631 case UO_Minus: 13632 CanOverflow = Opc == UO_Minus && 13633 isOverflowingIntegerType(Context, Input.get()->getType()); 13634 Input = UsualUnaryConversions(Input.get()); 13635 if (Input.isInvalid()) return ExprError(); 13636 // Unary plus and minus require promoting an operand of half vector to a 13637 // float vector and truncating the result back to a half vector. For now, we 13638 // do this only when HalfArgsAndReturns is set (that is, when the target is 13639 // arm or arm64). 13640 ConvertHalfVec = 13641 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13642 13643 // If the operand is a half vector, promote it to a float vector. 13644 if (ConvertHalfVec) 13645 Input = convertVector(Input.get(), Context.FloatTy, *this); 13646 resultType = Input.get()->getType(); 13647 if (resultType->isDependentType()) 13648 break; 13649 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13650 break; 13651 else if (resultType->isVectorType() && 13652 // The z vector extensions don't allow + or - with bool vectors. 13653 (!Context.getLangOpts().ZVector || 13654 resultType->castAs<VectorType>()->getVectorKind() != 13655 VectorType::AltiVecBool)) 13656 break; 13657 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13658 Opc == UO_Plus && 13659 resultType->isPointerType()) 13660 break; 13661 13662 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13663 << resultType << Input.get()->getSourceRange()); 13664 13665 case UO_Not: // bitwise complement 13666 Input = UsualUnaryConversions(Input.get()); 13667 if (Input.isInvalid()) 13668 return ExprError(); 13669 resultType = Input.get()->getType(); 13670 if (resultType->isDependentType()) 13671 break; 13672 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13673 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13674 // C99 does not support '~' for complex conjugation. 13675 Diag(OpLoc, diag::ext_integer_complement_complex) 13676 << resultType << Input.get()->getSourceRange(); 13677 else if (resultType->hasIntegerRepresentation()) 13678 break; 13679 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13680 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13681 // on vector float types. 13682 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13683 if (!T->isIntegerType()) 13684 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13685 << resultType << Input.get()->getSourceRange()); 13686 } else { 13687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13688 << resultType << Input.get()->getSourceRange()); 13689 } 13690 break; 13691 13692 case UO_LNot: // logical negation 13693 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13694 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13695 if (Input.isInvalid()) return ExprError(); 13696 resultType = Input.get()->getType(); 13697 13698 // Though we still have to promote half FP to float... 13699 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13700 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13701 resultType = Context.FloatTy; 13702 } 13703 13704 if (resultType->isDependentType()) 13705 break; 13706 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13707 // C99 6.5.3.3p1: ok, fallthrough; 13708 if (Context.getLangOpts().CPlusPlus) { 13709 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13710 // operand contextually converted to bool. 13711 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13712 ScalarTypeToBooleanCastKind(resultType)); 13713 } else if (Context.getLangOpts().OpenCL && 13714 Context.getLangOpts().OpenCLVersion < 120) { 13715 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13716 // operate on scalar float types. 13717 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13718 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13719 << resultType << Input.get()->getSourceRange()); 13720 } 13721 } else if (resultType->isExtVectorType()) { 13722 if (Context.getLangOpts().OpenCL && 13723 Context.getLangOpts().OpenCLVersion < 120 && 13724 !Context.getLangOpts().OpenCLCPlusPlus) { 13725 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13726 // operate on vector float types. 13727 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13728 if (!T->isIntegerType()) 13729 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13730 << resultType << Input.get()->getSourceRange()); 13731 } 13732 // Vector logical not returns the signed variant of the operand type. 13733 resultType = GetSignedVectorType(resultType); 13734 break; 13735 } else { 13736 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13737 // type in C++. We should allow that here too. 13738 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13739 << resultType << Input.get()->getSourceRange()); 13740 } 13741 13742 // LNot always has type int. C99 6.5.3.3p5. 13743 // In C++, it's bool. C++ 5.3.1p8 13744 resultType = Context.getLogicalOperationType(); 13745 break; 13746 case UO_Real: 13747 case UO_Imag: 13748 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13749 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13750 // complex l-values to ordinary l-values and all other values to r-values. 13751 if (Input.isInvalid()) return ExprError(); 13752 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13753 if (Input.get()->getValueKind() != VK_RValue && 13754 Input.get()->getObjectKind() == OK_Ordinary) 13755 VK = Input.get()->getValueKind(); 13756 } else if (!getLangOpts().CPlusPlus) { 13757 // In C, a volatile scalar is read by __imag. In C++, it is not. 13758 Input = DefaultLvalueConversion(Input.get()); 13759 } 13760 break; 13761 case UO_Extension: 13762 resultType = Input.get()->getType(); 13763 VK = Input.get()->getValueKind(); 13764 OK = Input.get()->getObjectKind(); 13765 break; 13766 case UO_Coawait: 13767 // It's unnecessary to represent the pass-through operator co_await in the 13768 // AST; just return the input expression instead. 13769 assert(!Input.get()->getType()->isDependentType() && 13770 "the co_await expression must be non-dependant before " 13771 "building operator co_await"); 13772 return Input; 13773 } 13774 if (resultType.isNull() || Input.isInvalid()) 13775 return ExprError(); 13776 13777 // Check for array bounds violations in the operand of the UnaryOperator, 13778 // except for the '*' and '&' operators that have to be handled specially 13779 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13780 // that are explicitly defined as valid by the standard). 13781 if (Opc != UO_AddrOf && Opc != UO_Deref) 13782 CheckArrayAccess(Input.get()); 13783 13784 auto *UO = new (Context) 13785 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13786 13787 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13788 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13789 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13790 13791 // Convert the result back to a half vector. 13792 if (ConvertHalfVec) 13793 return convertVector(UO, Context.HalfTy, *this); 13794 return UO; 13795 } 13796 13797 /// Determine whether the given expression is a qualified member 13798 /// access expression, of a form that could be turned into a pointer to member 13799 /// with the address-of operator. 13800 bool Sema::isQualifiedMemberAccess(Expr *E) { 13801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13802 if (!DRE->getQualifier()) 13803 return false; 13804 13805 ValueDecl *VD = DRE->getDecl(); 13806 if (!VD->isCXXClassMember()) 13807 return false; 13808 13809 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13810 return true; 13811 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13812 return Method->isInstance(); 13813 13814 return false; 13815 } 13816 13817 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13818 if (!ULE->getQualifier()) 13819 return false; 13820 13821 for (NamedDecl *D : ULE->decls()) { 13822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13823 if (Method->isInstance()) 13824 return true; 13825 } else { 13826 // Overload set does not contain methods. 13827 break; 13828 } 13829 } 13830 13831 return false; 13832 } 13833 13834 return false; 13835 } 13836 13837 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13838 UnaryOperatorKind Opc, Expr *Input) { 13839 // First things first: handle placeholders so that the 13840 // overloaded-operator check considers the right type. 13841 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13842 // Increment and decrement of pseudo-object references. 13843 if (pty->getKind() == BuiltinType::PseudoObject && 13844 UnaryOperator::isIncrementDecrementOp(Opc)) 13845 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13846 13847 // extension is always a builtin operator. 13848 if (Opc == UO_Extension) 13849 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13850 13851 // & gets special logic for several kinds of placeholder. 13852 // The builtin code knows what to do. 13853 if (Opc == UO_AddrOf && 13854 (pty->getKind() == BuiltinType::Overload || 13855 pty->getKind() == BuiltinType::UnknownAny || 13856 pty->getKind() == BuiltinType::BoundMember)) 13857 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13858 13859 // Anything else needs to be handled now. 13860 ExprResult Result = CheckPlaceholderExpr(Input); 13861 if (Result.isInvalid()) return ExprError(); 13862 Input = Result.get(); 13863 } 13864 13865 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13866 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13867 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13868 // Find all of the overloaded operators visible from this 13869 // point. We perform both an operator-name lookup from the local 13870 // scope and an argument-dependent lookup based on the types of 13871 // the arguments. 13872 UnresolvedSet<16> Functions; 13873 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13874 if (S && OverOp != OO_None) 13875 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13876 Functions); 13877 13878 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13879 } 13880 13881 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13882 } 13883 13884 // Unary Operators. 'Tok' is the token for the operator. 13885 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13886 tok::TokenKind Op, Expr *Input) { 13887 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13888 } 13889 13890 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13891 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13892 LabelDecl *TheDecl) { 13893 TheDecl->markUsed(Context); 13894 // Create the AST node. The address of a label always has type 'void*'. 13895 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13896 Context.getPointerType(Context.VoidTy)); 13897 } 13898 13899 void Sema::ActOnStartStmtExpr() { 13900 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13901 } 13902 13903 void Sema::ActOnStmtExprError() { 13904 // Note that function is also called by TreeTransform when leaving a 13905 // StmtExpr scope without rebuilding anything. 13906 13907 DiscardCleanupsInEvaluationContext(); 13908 PopExpressionEvaluationContext(); 13909 } 13910 13911 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 13912 SourceLocation RPLoc) { 13913 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 13914 } 13915 13916 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13917 SourceLocation RPLoc, unsigned TemplateDepth) { 13918 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13919 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13920 13921 if (hasAnyUnrecoverableErrorsInThisFunction()) 13922 DiscardCleanupsInEvaluationContext(); 13923 assert(!Cleanup.exprNeedsCleanups() && 13924 "cleanups within StmtExpr not correctly bound!"); 13925 PopExpressionEvaluationContext(); 13926 13927 // FIXME: there are a variety of strange constraints to enforce here, for 13928 // example, it is not possible to goto into a stmt expression apparently. 13929 // More semantic analysis is needed. 13930 13931 // If there are sub-stmts in the compound stmt, take the type of the last one 13932 // as the type of the stmtexpr. 13933 QualType Ty = Context.VoidTy; 13934 bool StmtExprMayBindToTemp = false; 13935 if (!Compound->body_empty()) { 13936 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13937 if (const auto *LastStmt = 13938 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13939 if (const Expr *Value = LastStmt->getExprStmt()) { 13940 StmtExprMayBindToTemp = true; 13941 Ty = Value->getType(); 13942 } 13943 } 13944 } 13945 13946 // FIXME: Check that expression type is complete/non-abstract; statement 13947 // expressions are not lvalues. 13948 Expr *ResStmtExpr = 13949 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 13950 if (StmtExprMayBindToTemp) 13951 return MaybeBindToTemporary(ResStmtExpr); 13952 return ResStmtExpr; 13953 } 13954 13955 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13956 if (ER.isInvalid()) 13957 return ExprError(); 13958 13959 // Do function/array conversion on the last expression, but not 13960 // lvalue-to-rvalue. However, initialize an unqualified type. 13961 ER = DefaultFunctionArrayConversion(ER.get()); 13962 if (ER.isInvalid()) 13963 return ExprError(); 13964 Expr *E = ER.get(); 13965 13966 if (E->isTypeDependent()) 13967 return E; 13968 13969 // In ARC, if the final expression ends in a consume, splice 13970 // the consume out and bind it later. In the alternate case 13971 // (when dealing with a retainable type), the result 13972 // initialization will create a produce. In both cases the 13973 // result will be +1, and we'll need to balance that out with 13974 // a bind. 13975 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13976 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13977 return Cast->getSubExpr(); 13978 13979 // FIXME: Provide a better location for the initialization. 13980 return PerformCopyInitialization( 13981 InitializedEntity::InitializeStmtExprResult( 13982 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13983 SourceLocation(), E); 13984 } 13985 13986 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13987 TypeSourceInfo *TInfo, 13988 ArrayRef<OffsetOfComponent> Components, 13989 SourceLocation RParenLoc) { 13990 QualType ArgTy = TInfo->getType(); 13991 bool Dependent = ArgTy->isDependentType(); 13992 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13993 13994 // We must have at least one component that refers to the type, and the first 13995 // one is known to be a field designator. Verify that the ArgTy represents 13996 // a struct/union/class. 13997 if (!Dependent && !ArgTy->isRecordType()) 13998 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13999 << ArgTy << TypeRange); 14000 14001 // Type must be complete per C99 7.17p3 because a declaring a variable 14002 // with an incomplete type would be ill-formed. 14003 if (!Dependent 14004 && RequireCompleteType(BuiltinLoc, ArgTy, 14005 diag::err_offsetof_incomplete_type, TypeRange)) 14006 return ExprError(); 14007 14008 bool DidWarnAboutNonPOD = false; 14009 QualType CurrentType = ArgTy; 14010 SmallVector<OffsetOfNode, 4> Comps; 14011 SmallVector<Expr*, 4> Exprs; 14012 for (const OffsetOfComponent &OC : Components) { 14013 if (OC.isBrackets) { 14014 // Offset of an array sub-field. TODO: Should we allow vector elements? 14015 if (!CurrentType->isDependentType()) { 14016 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14017 if(!AT) 14018 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14019 << CurrentType); 14020 CurrentType = AT->getElementType(); 14021 } else 14022 CurrentType = Context.DependentTy; 14023 14024 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14025 if (IdxRval.isInvalid()) 14026 return ExprError(); 14027 Expr *Idx = IdxRval.get(); 14028 14029 // The expression must be an integral expression. 14030 // FIXME: An integral constant expression? 14031 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14032 !Idx->getType()->isIntegerType()) 14033 return ExprError( 14034 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14035 << Idx->getSourceRange()); 14036 14037 // Record this array index. 14038 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14039 Exprs.push_back(Idx); 14040 continue; 14041 } 14042 14043 // Offset of a field. 14044 if (CurrentType->isDependentType()) { 14045 // We have the offset of a field, but we can't look into the dependent 14046 // type. Just record the identifier of the field. 14047 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14048 CurrentType = Context.DependentTy; 14049 continue; 14050 } 14051 14052 // We need to have a complete type to look into. 14053 if (RequireCompleteType(OC.LocStart, CurrentType, 14054 diag::err_offsetof_incomplete_type)) 14055 return ExprError(); 14056 14057 // Look for the designated field. 14058 const RecordType *RC = CurrentType->getAs<RecordType>(); 14059 if (!RC) 14060 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14061 << CurrentType); 14062 RecordDecl *RD = RC->getDecl(); 14063 14064 // C++ [lib.support.types]p5: 14065 // The macro offsetof accepts a restricted set of type arguments in this 14066 // International Standard. type shall be a POD structure or a POD union 14067 // (clause 9). 14068 // C++11 [support.types]p4: 14069 // If type is not a standard-layout class (Clause 9), the results are 14070 // undefined. 14071 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14072 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14073 unsigned DiagID = 14074 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14075 : diag::ext_offsetof_non_pod_type; 14076 14077 if (!IsSafe && !DidWarnAboutNonPOD && 14078 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14079 PDiag(DiagID) 14080 << SourceRange(Components[0].LocStart, OC.LocEnd) 14081 << CurrentType)) 14082 DidWarnAboutNonPOD = true; 14083 } 14084 14085 // Look for the field. 14086 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14087 LookupQualifiedName(R, RD); 14088 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14089 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14090 if (!MemberDecl) { 14091 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14092 MemberDecl = IndirectMemberDecl->getAnonField(); 14093 } 14094 14095 if (!MemberDecl) 14096 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14097 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14098 OC.LocEnd)); 14099 14100 // C99 7.17p3: 14101 // (If the specified member is a bit-field, the behavior is undefined.) 14102 // 14103 // We diagnose this as an error. 14104 if (MemberDecl->isBitField()) { 14105 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14106 << MemberDecl->getDeclName() 14107 << SourceRange(BuiltinLoc, RParenLoc); 14108 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14109 return ExprError(); 14110 } 14111 14112 RecordDecl *Parent = MemberDecl->getParent(); 14113 if (IndirectMemberDecl) 14114 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14115 14116 // If the member was found in a base class, introduce OffsetOfNodes for 14117 // the base class indirections. 14118 CXXBasePaths Paths; 14119 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14120 Paths)) { 14121 if (Paths.getDetectedVirtual()) { 14122 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14123 << MemberDecl->getDeclName() 14124 << SourceRange(BuiltinLoc, RParenLoc); 14125 return ExprError(); 14126 } 14127 14128 CXXBasePath &Path = Paths.front(); 14129 for (const CXXBasePathElement &B : Path) 14130 Comps.push_back(OffsetOfNode(B.Base)); 14131 } 14132 14133 if (IndirectMemberDecl) { 14134 for (auto *FI : IndirectMemberDecl->chain()) { 14135 assert(isa<FieldDecl>(FI)); 14136 Comps.push_back(OffsetOfNode(OC.LocStart, 14137 cast<FieldDecl>(FI), OC.LocEnd)); 14138 } 14139 } else 14140 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14141 14142 CurrentType = MemberDecl->getType().getNonReferenceType(); 14143 } 14144 14145 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14146 Comps, Exprs, RParenLoc); 14147 } 14148 14149 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14150 SourceLocation BuiltinLoc, 14151 SourceLocation TypeLoc, 14152 ParsedType ParsedArgTy, 14153 ArrayRef<OffsetOfComponent> Components, 14154 SourceLocation RParenLoc) { 14155 14156 TypeSourceInfo *ArgTInfo; 14157 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14158 if (ArgTy.isNull()) 14159 return ExprError(); 14160 14161 if (!ArgTInfo) 14162 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14163 14164 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14165 } 14166 14167 14168 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14169 Expr *CondExpr, 14170 Expr *LHSExpr, Expr *RHSExpr, 14171 SourceLocation RPLoc) { 14172 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14173 14174 ExprValueKind VK = VK_RValue; 14175 ExprObjectKind OK = OK_Ordinary; 14176 QualType resType; 14177 bool ValueDependent = false; 14178 bool CondIsTrue = false; 14179 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14180 resType = Context.DependentTy; 14181 ValueDependent = true; 14182 } else { 14183 // The conditional expression is required to be a constant expression. 14184 llvm::APSInt condEval(32); 14185 ExprResult CondICE 14186 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14187 diag::err_typecheck_choose_expr_requires_constant, false); 14188 if (CondICE.isInvalid()) 14189 return ExprError(); 14190 CondExpr = CondICE.get(); 14191 CondIsTrue = condEval.getZExtValue(); 14192 14193 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14194 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14195 14196 resType = ActiveExpr->getType(); 14197 ValueDependent = ActiveExpr->isValueDependent(); 14198 VK = ActiveExpr->getValueKind(); 14199 OK = ActiveExpr->getObjectKind(); 14200 } 14201 14202 return new (Context) 14203 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14204 CondIsTrue, resType->isDependentType(), ValueDependent); 14205 } 14206 14207 //===----------------------------------------------------------------------===// 14208 // Clang Extensions. 14209 //===----------------------------------------------------------------------===// 14210 14211 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14212 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14213 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14214 14215 if (LangOpts.CPlusPlus) { 14216 MangleNumberingContext *MCtx; 14217 Decl *ManglingContextDecl; 14218 std::tie(MCtx, ManglingContextDecl) = 14219 getCurrentMangleNumberContext(Block->getDeclContext()); 14220 if (MCtx) { 14221 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14222 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14223 } 14224 } 14225 14226 PushBlockScope(CurScope, Block); 14227 CurContext->addDecl(Block); 14228 if (CurScope) 14229 PushDeclContext(CurScope, Block); 14230 else 14231 CurContext = Block; 14232 14233 getCurBlock()->HasImplicitReturnType = true; 14234 14235 // Enter a new evaluation context to insulate the block from any 14236 // cleanups from the enclosing full-expression. 14237 PushExpressionEvaluationContext( 14238 ExpressionEvaluationContext::PotentiallyEvaluated); 14239 } 14240 14241 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14242 Scope *CurScope) { 14243 assert(ParamInfo.getIdentifier() == nullptr && 14244 "block-id should have no identifier!"); 14245 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14246 BlockScopeInfo *CurBlock = getCurBlock(); 14247 14248 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14249 QualType T = Sig->getType(); 14250 14251 // FIXME: We should allow unexpanded parameter packs here, but that would, 14252 // in turn, make the block expression contain unexpanded parameter packs. 14253 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14254 // Drop the parameters. 14255 FunctionProtoType::ExtProtoInfo EPI; 14256 EPI.HasTrailingReturn = false; 14257 EPI.TypeQuals.addConst(); 14258 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14259 Sig = Context.getTrivialTypeSourceInfo(T); 14260 } 14261 14262 // GetTypeForDeclarator always produces a function type for a block 14263 // literal signature. Furthermore, it is always a FunctionProtoType 14264 // unless the function was written with a typedef. 14265 assert(T->isFunctionType() && 14266 "GetTypeForDeclarator made a non-function block signature"); 14267 14268 // Look for an explicit signature in that function type. 14269 FunctionProtoTypeLoc ExplicitSignature; 14270 14271 if ((ExplicitSignature = Sig->getTypeLoc() 14272 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14273 14274 // Check whether that explicit signature was synthesized by 14275 // GetTypeForDeclarator. If so, don't save that as part of the 14276 // written signature. 14277 if (ExplicitSignature.getLocalRangeBegin() == 14278 ExplicitSignature.getLocalRangeEnd()) { 14279 // This would be much cheaper if we stored TypeLocs instead of 14280 // TypeSourceInfos. 14281 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14282 unsigned Size = Result.getFullDataSize(); 14283 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14284 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14285 14286 ExplicitSignature = FunctionProtoTypeLoc(); 14287 } 14288 } 14289 14290 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14291 CurBlock->FunctionType = T; 14292 14293 const FunctionType *Fn = T->getAs<FunctionType>(); 14294 QualType RetTy = Fn->getReturnType(); 14295 bool isVariadic = 14296 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14297 14298 CurBlock->TheDecl->setIsVariadic(isVariadic); 14299 14300 // Context.DependentTy is used as a placeholder for a missing block 14301 // return type. TODO: what should we do with declarators like: 14302 // ^ * { ... } 14303 // If the answer is "apply template argument deduction".... 14304 if (RetTy != Context.DependentTy) { 14305 CurBlock->ReturnType = RetTy; 14306 CurBlock->TheDecl->setBlockMissingReturnType(false); 14307 CurBlock->HasImplicitReturnType = false; 14308 } 14309 14310 // Push block parameters from the declarator if we had them. 14311 SmallVector<ParmVarDecl*, 8> Params; 14312 if (ExplicitSignature) { 14313 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14314 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14315 if (Param->getIdentifier() == nullptr && 14316 !Param->isImplicit() && 14317 !Param->isInvalidDecl() && 14318 !getLangOpts().CPlusPlus) 14319 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14320 Params.push_back(Param); 14321 } 14322 14323 // Fake up parameter variables if we have a typedef, like 14324 // ^ fntype { ... } 14325 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14326 for (const auto &I : Fn->param_types()) { 14327 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14328 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14329 Params.push_back(Param); 14330 } 14331 } 14332 14333 // Set the parameters on the block decl. 14334 if (!Params.empty()) { 14335 CurBlock->TheDecl->setParams(Params); 14336 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14337 /*CheckParameterNames=*/false); 14338 } 14339 14340 // Finally we can process decl attributes. 14341 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14342 14343 // Put the parameter variables in scope. 14344 for (auto AI : CurBlock->TheDecl->parameters()) { 14345 AI->setOwningFunction(CurBlock->TheDecl); 14346 14347 // If this has an identifier, add it to the scope stack. 14348 if (AI->getIdentifier()) { 14349 CheckShadow(CurBlock->TheScope, AI); 14350 14351 PushOnScopeChains(AI, CurBlock->TheScope); 14352 } 14353 } 14354 } 14355 14356 /// ActOnBlockError - If there is an error parsing a block, this callback 14357 /// is invoked to pop the information about the block from the action impl. 14358 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14359 // Leave the expression-evaluation context. 14360 DiscardCleanupsInEvaluationContext(); 14361 PopExpressionEvaluationContext(); 14362 14363 // Pop off CurBlock, handle nested blocks. 14364 PopDeclContext(); 14365 PopFunctionScopeInfo(); 14366 } 14367 14368 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14369 /// literal was successfully completed. ^(int x){...} 14370 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14371 Stmt *Body, Scope *CurScope) { 14372 // If blocks are disabled, emit an error. 14373 if (!LangOpts.Blocks) 14374 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14375 14376 // Leave the expression-evaluation context. 14377 if (hasAnyUnrecoverableErrorsInThisFunction()) 14378 DiscardCleanupsInEvaluationContext(); 14379 assert(!Cleanup.exprNeedsCleanups() && 14380 "cleanups within block not correctly bound!"); 14381 PopExpressionEvaluationContext(); 14382 14383 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14384 BlockDecl *BD = BSI->TheDecl; 14385 14386 if (BSI->HasImplicitReturnType) 14387 deduceClosureReturnType(*BSI); 14388 14389 QualType RetTy = Context.VoidTy; 14390 if (!BSI->ReturnType.isNull()) 14391 RetTy = BSI->ReturnType; 14392 14393 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14394 QualType BlockTy; 14395 14396 // If the user wrote a function type in some form, try to use that. 14397 if (!BSI->FunctionType.isNull()) { 14398 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14399 14400 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14401 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14402 14403 // Turn protoless block types into nullary block types. 14404 if (isa<FunctionNoProtoType>(FTy)) { 14405 FunctionProtoType::ExtProtoInfo EPI; 14406 EPI.ExtInfo = Ext; 14407 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14408 14409 // Otherwise, if we don't need to change anything about the function type, 14410 // preserve its sugar structure. 14411 } else if (FTy->getReturnType() == RetTy && 14412 (!NoReturn || FTy->getNoReturnAttr())) { 14413 BlockTy = BSI->FunctionType; 14414 14415 // Otherwise, make the minimal modifications to the function type. 14416 } else { 14417 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14418 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14419 EPI.TypeQuals = Qualifiers(); 14420 EPI.ExtInfo = Ext; 14421 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14422 } 14423 14424 // If we don't have a function type, just build one from nothing. 14425 } else { 14426 FunctionProtoType::ExtProtoInfo EPI; 14427 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14428 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14429 } 14430 14431 DiagnoseUnusedParameters(BD->parameters()); 14432 BlockTy = Context.getBlockPointerType(BlockTy); 14433 14434 // If needed, diagnose invalid gotos and switches in the block. 14435 if (getCurFunction()->NeedsScopeChecking() && 14436 !PP.isCodeCompletionEnabled()) 14437 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14438 14439 BD->setBody(cast<CompoundStmt>(Body)); 14440 14441 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14442 DiagnoseUnguardedAvailabilityViolations(BD); 14443 14444 // Try to apply the named return value optimization. We have to check again 14445 // if we can do this, though, because blocks keep return statements around 14446 // to deduce an implicit return type. 14447 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14448 !BD->isDependentContext()) 14449 computeNRVO(Body, BSI); 14450 14451 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14452 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14453 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14454 NTCUK_Destruct|NTCUK_Copy); 14455 14456 PopDeclContext(); 14457 14458 // Pop the block scope now but keep it alive to the end of this function. 14459 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14460 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14461 14462 // Set the captured variables on the block. 14463 SmallVector<BlockDecl::Capture, 4> Captures; 14464 for (Capture &Cap : BSI->Captures) { 14465 if (Cap.isInvalid() || Cap.isThisCapture()) 14466 continue; 14467 14468 VarDecl *Var = Cap.getVariable(); 14469 Expr *CopyExpr = nullptr; 14470 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14471 if (const RecordType *Record = 14472 Cap.getCaptureType()->getAs<RecordType>()) { 14473 // The capture logic needs the destructor, so make sure we mark it. 14474 // Usually this is unnecessary because most local variables have 14475 // their destructors marked at declaration time, but parameters are 14476 // an exception because it's technically only the call site that 14477 // actually requires the destructor. 14478 if (isa<ParmVarDecl>(Var)) 14479 FinalizeVarWithDestructor(Var, Record); 14480 14481 // Enter a separate potentially-evaluated context while building block 14482 // initializers to isolate their cleanups from those of the block 14483 // itself. 14484 // FIXME: Is this appropriate even when the block itself occurs in an 14485 // unevaluated operand? 14486 EnterExpressionEvaluationContext EvalContext( 14487 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14488 14489 SourceLocation Loc = Cap.getLocation(); 14490 14491 ExprResult Result = BuildDeclarationNameExpr( 14492 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14493 14494 // According to the blocks spec, the capture of a variable from 14495 // the stack requires a const copy constructor. This is not true 14496 // of the copy/move done to move a __block variable to the heap. 14497 if (!Result.isInvalid() && 14498 !Result.get()->getType().isConstQualified()) { 14499 Result = ImpCastExprToType(Result.get(), 14500 Result.get()->getType().withConst(), 14501 CK_NoOp, VK_LValue); 14502 } 14503 14504 if (!Result.isInvalid()) { 14505 Result = PerformCopyInitialization( 14506 InitializedEntity::InitializeBlock(Var->getLocation(), 14507 Cap.getCaptureType(), false), 14508 Loc, Result.get()); 14509 } 14510 14511 // Build a full-expression copy expression if initialization 14512 // succeeded and used a non-trivial constructor. Recover from 14513 // errors by pretending that the copy isn't necessary. 14514 if (!Result.isInvalid() && 14515 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14516 ->isTrivial()) { 14517 Result = MaybeCreateExprWithCleanups(Result); 14518 CopyExpr = Result.get(); 14519 } 14520 } 14521 } 14522 14523 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14524 CopyExpr); 14525 Captures.push_back(NewCap); 14526 } 14527 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14528 14529 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14530 14531 // If the block isn't obviously global, i.e. it captures anything at 14532 // all, then we need to do a few things in the surrounding context: 14533 if (Result->getBlockDecl()->hasCaptures()) { 14534 // First, this expression has a new cleanup object. 14535 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14536 Cleanup.setExprNeedsCleanups(true); 14537 14538 // It also gets a branch-protected scope if any of the captured 14539 // variables needs destruction. 14540 for (const auto &CI : Result->getBlockDecl()->captures()) { 14541 const VarDecl *var = CI.getVariable(); 14542 if (var->getType().isDestructedType() != QualType::DK_none) { 14543 setFunctionHasBranchProtectedScope(); 14544 break; 14545 } 14546 } 14547 } 14548 14549 if (getCurFunction()) 14550 getCurFunction()->addBlock(BD); 14551 14552 return Result; 14553 } 14554 14555 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14556 SourceLocation RPLoc) { 14557 TypeSourceInfo *TInfo; 14558 GetTypeFromParser(Ty, &TInfo); 14559 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14560 } 14561 14562 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14563 Expr *E, TypeSourceInfo *TInfo, 14564 SourceLocation RPLoc) { 14565 Expr *OrigExpr = E; 14566 bool IsMS = false; 14567 14568 // CUDA device code does not support varargs. 14569 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14570 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14571 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14572 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14573 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14574 } 14575 } 14576 14577 // NVPTX does not support va_arg expression. 14578 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14579 Context.getTargetInfo().getTriple().isNVPTX()) 14580 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14581 14582 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14583 // as Microsoft ABI on an actual Microsoft platform, where 14584 // __builtin_ms_va_list and __builtin_va_list are the same.) 14585 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14586 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14587 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14588 if (Context.hasSameType(MSVaListType, E->getType())) { 14589 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14590 return ExprError(); 14591 IsMS = true; 14592 } 14593 } 14594 14595 // Get the va_list type 14596 QualType VaListType = Context.getBuiltinVaListType(); 14597 if (!IsMS) { 14598 if (VaListType->isArrayType()) { 14599 // Deal with implicit array decay; for example, on x86-64, 14600 // va_list is an array, but it's supposed to decay to 14601 // a pointer for va_arg. 14602 VaListType = Context.getArrayDecayedType(VaListType); 14603 // Make sure the input expression also decays appropriately. 14604 ExprResult Result = UsualUnaryConversions(E); 14605 if (Result.isInvalid()) 14606 return ExprError(); 14607 E = Result.get(); 14608 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14609 // If va_list is a record type and we are compiling in C++ mode, 14610 // check the argument using reference binding. 14611 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14612 Context, Context.getLValueReferenceType(VaListType), false); 14613 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14614 if (Init.isInvalid()) 14615 return ExprError(); 14616 E = Init.getAs<Expr>(); 14617 } else { 14618 // Otherwise, the va_list argument must be an l-value because 14619 // it is modified by va_arg. 14620 if (!E->isTypeDependent() && 14621 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14622 return ExprError(); 14623 } 14624 } 14625 14626 if (!IsMS && !E->isTypeDependent() && 14627 !Context.hasSameType(VaListType, E->getType())) 14628 return ExprError( 14629 Diag(E->getBeginLoc(), 14630 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14631 << OrigExpr->getType() << E->getSourceRange()); 14632 14633 if (!TInfo->getType()->isDependentType()) { 14634 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14635 diag::err_second_parameter_to_va_arg_incomplete, 14636 TInfo->getTypeLoc())) 14637 return ExprError(); 14638 14639 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14640 TInfo->getType(), 14641 diag::err_second_parameter_to_va_arg_abstract, 14642 TInfo->getTypeLoc())) 14643 return ExprError(); 14644 14645 if (!TInfo->getType().isPODType(Context)) { 14646 Diag(TInfo->getTypeLoc().getBeginLoc(), 14647 TInfo->getType()->isObjCLifetimeType() 14648 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14649 : diag::warn_second_parameter_to_va_arg_not_pod) 14650 << TInfo->getType() 14651 << TInfo->getTypeLoc().getSourceRange(); 14652 } 14653 14654 // Check for va_arg where arguments of the given type will be promoted 14655 // (i.e. this va_arg is guaranteed to have undefined behavior). 14656 QualType PromoteType; 14657 if (TInfo->getType()->isPromotableIntegerType()) { 14658 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14659 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14660 PromoteType = QualType(); 14661 } 14662 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14663 PromoteType = Context.DoubleTy; 14664 if (!PromoteType.isNull()) 14665 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14666 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14667 << TInfo->getType() 14668 << PromoteType 14669 << TInfo->getTypeLoc().getSourceRange()); 14670 } 14671 14672 QualType T = TInfo->getType().getNonLValueExprType(Context); 14673 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14674 } 14675 14676 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14677 // The type of __null will be int or long, depending on the size of 14678 // pointers on the target. 14679 QualType Ty; 14680 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14681 if (pw == Context.getTargetInfo().getIntWidth()) 14682 Ty = Context.IntTy; 14683 else if (pw == Context.getTargetInfo().getLongWidth()) 14684 Ty = Context.LongTy; 14685 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14686 Ty = Context.LongLongTy; 14687 else { 14688 llvm_unreachable("I don't know size of pointer!"); 14689 } 14690 14691 return new (Context) GNUNullExpr(Ty, TokenLoc); 14692 } 14693 14694 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14695 SourceLocation BuiltinLoc, 14696 SourceLocation RPLoc) { 14697 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14698 } 14699 14700 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14701 SourceLocation BuiltinLoc, 14702 SourceLocation RPLoc, 14703 DeclContext *ParentContext) { 14704 return new (Context) 14705 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14706 } 14707 14708 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14709 bool Diagnose) { 14710 if (!getLangOpts().ObjC) 14711 return false; 14712 14713 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14714 if (!PT) 14715 return false; 14716 14717 if (!PT->isObjCIdType()) { 14718 // Check if the destination is the 'NSString' interface. 14719 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14720 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14721 return false; 14722 } 14723 14724 // Ignore any parens, implicit casts (should only be 14725 // array-to-pointer decays), and not-so-opaque values. The last is 14726 // important for making this trigger for property assignments. 14727 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14728 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14729 if (OV->getSourceExpr()) 14730 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14731 14732 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14733 if (!SL || !SL->isAscii()) 14734 return false; 14735 if (Diagnose) { 14736 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14737 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14738 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14739 } 14740 return true; 14741 } 14742 14743 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14744 const Expr *SrcExpr) { 14745 if (!DstType->isFunctionPointerType() || 14746 !SrcExpr->getType()->isFunctionType()) 14747 return false; 14748 14749 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14750 if (!DRE) 14751 return false; 14752 14753 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14754 if (!FD) 14755 return false; 14756 14757 return !S.checkAddressOfFunctionIsAvailable(FD, 14758 /*Complain=*/true, 14759 SrcExpr->getBeginLoc()); 14760 } 14761 14762 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14763 SourceLocation Loc, 14764 QualType DstType, QualType SrcType, 14765 Expr *SrcExpr, AssignmentAction Action, 14766 bool *Complained) { 14767 if (Complained) 14768 *Complained = false; 14769 14770 // Decode the result (notice that AST's are still created for extensions). 14771 bool CheckInferredResultType = false; 14772 bool isInvalid = false; 14773 unsigned DiagKind = 0; 14774 FixItHint Hint; 14775 ConversionFixItGenerator ConvHints; 14776 bool MayHaveConvFixit = false; 14777 bool MayHaveFunctionDiff = false; 14778 const ObjCInterfaceDecl *IFace = nullptr; 14779 const ObjCProtocolDecl *PDecl = nullptr; 14780 14781 switch (ConvTy) { 14782 case Compatible: 14783 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14784 return false; 14785 14786 case PointerToInt: 14787 DiagKind = diag::ext_typecheck_convert_pointer_int; 14788 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14789 MayHaveConvFixit = true; 14790 break; 14791 case IntToPointer: 14792 DiagKind = diag::ext_typecheck_convert_int_pointer; 14793 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14794 MayHaveConvFixit = true; 14795 break; 14796 case IncompatiblePointer: 14797 if (Action == AA_Passing_CFAudited) 14798 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14799 else if (SrcType->isFunctionPointerType() && 14800 DstType->isFunctionPointerType()) 14801 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14802 else 14803 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14804 14805 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14806 SrcType->isObjCObjectPointerType(); 14807 if (Hint.isNull() && !CheckInferredResultType) { 14808 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14809 } 14810 else if (CheckInferredResultType) { 14811 SrcType = SrcType.getUnqualifiedType(); 14812 DstType = DstType.getUnqualifiedType(); 14813 } 14814 MayHaveConvFixit = true; 14815 break; 14816 case IncompatiblePointerSign: 14817 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14818 break; 14819 case FunctionVoidPointer: 14820 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14821 break; 14822 case IncompatiblePointerDiscardsQualifiers: { 14823 // Perform array-to-pointer decay if necessary. 14824 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14825 14826 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14827 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14828 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14829 DiagKind = diag::err_typecheck_incompatible_address_space; 14830 break; 14831 14832 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14833 DiagKind = diag::err_typecheck_incompatible_ownership; 14834 break; 14835 } 14836 14837 llvm_unreachable("unknown error case for discarding qualifiers!"); 14838 // fallthrough 14839 } 14840 case CompatiblePointerDiscardsQualifiers: 14841 // If the qualifiers lost were because we were applying the 14842 // (deprecated) C++ conversion from a string literal to a char* 14843 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14844 // Ideally, this check would be performed in 14845 // checkPointerTypesForAssignment. However, that would require a 14846 // bit of refactoring (so that the second argument is an 14847 // expression, rather than a type), which should be done as part 14848 // of a larger effort to fix checkPointerTypesForAssignment for 14849 // C++ semantics. 14850 if (getLangOpts().CPlusPlus && 14851 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14852 return false; 14853 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14854 break; 14855 case IncompatibleNestedPointerQualifiers: 14856 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14857 break; 14858 case IncompatibleNestedPointerAddressSpaceMismatch: 14859 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14860 break; 14861 case IntToBlockPointer: 14862 DiagKind = diag::err_int_to_block_pointer; 14863 break; 14864 case IncompatibleBlockPointer: 14865 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14866 break; 14867 case IncompatibleObjCQualifiedId: { 14868 if (SrcType->isObjCQualifiedIdType()) { 14869 const ObjCObjectPointerType *srcOPT = 14870 SrcType->castAs<ObjCObjectPointerType>(); 14871 for (auto *srcProto : srcOPT->quals()) { 14872 PDecl = srcProto; 14873 break; 14874 } 14875 if (const ObjCInterfaceType *IFaceT = 14876 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14877 IFace = IFaceT->getDecl(); 14878 } 14879 else if (DstType->isObjCQualifiedIdType()) { 14880 const ObjCObjectPointerType *dstOPT = 14881 DstType->castAs<ObjCObjectPointerType>(); 14882 for (auto *dstProto : dstOPT->quals()) { 14883 PDecl = dstProto; 14884 break; 14885 } 14886 if (const ObjCInterfaceType *IFaceT = 14887 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14888 IFace = IFaceT->getDecl(); 14889 } 14890 DiagKind = diag::warn_incompatible_qualified_id; 14891 break; 14892 } 14893 case IncompatibleVectors: 14894 DiagKind = diag::warn_incompatible_vectors; 14895 break; 14896 case IncompatibleObjCWeakRef: 14897 DiagKind = diag::err_arc_weak_unavailable_assign; 14898 break; 14899 case Incompatible: 14900 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14901 if (Complained) 14902 *Complained = true; 14903 return true; 14904 } 14905 14906 DiagKind = diag::err_typecheck_convert_incompatible; 14907 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14908 MayHaveConvFixit = true; 14909 isInvalid = true; 14910 MayHaveFunctionDiff = true; 14911 break; 14912 } 14913 14914 QualType FirstType, SecondType; 14915 switch (Action) { 14916 case AA_Assigning: 14917 case AA_Initializing: 14918 // The destination type comes first. 14919 FirstType = DstType; 14920 SecondType = SrcType; 14921 break; 14922 14923 case AA_Returning: 14924 case AA_Passing: 14925 case AA_Passing_CFAudited: 14926 case AA_Converting: 14927 case AA_Sending: 14928 case AA_Casting: 14929 // The source type comes first. 14930 FirstType = SrcType; 14931 SecondType = DstType; 14932 break; 14933 } 14934 14935 PartialDiagnostic FDiag = PDiag(DiagKind); 14936 if (Action == AA_Passing_CFAudited) 14937 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14938 else 14939 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14940 14941 // If we can fix the conversion, suggest the FixIts. 14942 assert(ConvHints.isNull() || Hint.isNull()); 14943 if (!ConvHints.isNull()) { 14944 for (FixItHint &H : ConvHints.Hints) 14945 FDiag << H; 14946 } else { 14947 FDiag << Hint; 14948 } 14949 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14950 14951 if (MayHaveFunctionDiff) 14952 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14953 14954 Diag(Loc, FDiag); 14955 if (DiagKind == diag::warn_incompatible_qualified_id && 14956 PDecl && IFace && !IFace->hasDefinition()) 14957 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14958 << IFace << PDecl; 14959 14960 if (SecondType == Context.OverloadTy) 14961 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14962 FirstType, /*TakingAddress=*/true); 14963 14964 if (CheckInferredResultType) 14965 EmitRelatedResultTypeNote(SrcExpr); 14966 14967 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14968 EmitRelatedResultTypeNoteForReturn(DstType); 14969 14970 if (Complained) 14971 *Complained = true; 14972 return isInvalid; 14973 } 14974 14975 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14976 llvm::APSInt *Result) { 14977 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14978 public: 14979 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14980 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14981 } 14982 } Diagnoser; 14983 14984 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14985 } 14986 14987 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14988 llvm::APSInt *Result, 14989 unsigned DiagID, 14990 bool AllowFold) { 14991 class IDDiagnoser : public VerifyICEDiagnoser { 14992 unsigned DiagID; 14993 14994 public: 14995 IDDiagnoser(unsigned DiagID) 14996 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14997 14998 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14999 S.Diag(Loc, DiagID) << SR; 15000 } 15001 } Diagnoser(DiagID); 15002 15003 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15004 } 15005 15006 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15007 SourceRange SR) { 15008 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15009 } 15010 15011 ExprResult 15012 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15013 VerifyICEDiagnoser &Diagnoser, 15014 bool AllowFold) { 15015 SourceLocation DiagLoc = E->getBeginLoc(); 15016 15017 if (getLangOpts().CPlusPlus11) { 15018 // C++11 [expr.const]p5: 15019 // If an expression of literal class type is used in a context where an 15020 // integral constant expression is required, then that class type shall 15021 // have a single non-explicit conversion function to an integral or 15022 // unscoped enumeration type 15023 ExprResult Converted; 15024 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15025 public: 15026 CXX11ConvertDiagnoser(bool Silent) 15027 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15028 Silent, true) {} 15029 15030 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15031 QualType T) override { 15032 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15033 } 15034 15035 SemaDiagnosticBuilder diagnoseIncomplete( 15036 Sema &S, SourceLocation Loc, QualType T) override { 15037 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15038 } 15039 15040 SemaDiagnosticBuilder diagnoseExplicitConv( 15041 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15042 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15043 } 15044 15045 SemaDiagnosticBuilder noteExplicitConv( 15046 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15047 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15048 << ConvTy->isEnumeralType() << ConvTy; 15049 } 15050 15051 SemaDiagnosticBuilder diagnoseAmbiguous( 15052 Sema &S, SourceLocation Loc, QualType T) override { 15053 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15054 } 15055 15056 SemaDiagnosticBuilder noteAmbiguous( 15057 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15058 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15059 << ConvTy->isEnumeralType() << ConvTy; 15060 } 15061 15062 SemaDiagnosticBuilder diagnoseConversion( 15063 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15064 llvm_unreachable("conversion functions are permitted"); 15065 } 15066 } ConvertDiagnoser(Diagnoser.Suppress); 15067 15068 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15069 ConvertDiagnoser); 15070 if (Converted.isInvalid()) 15071 return Converted; 15072 E = Converted.get(); 15073 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15074 return ExprError(); 15075 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15076 // An ICE must be of integral or unscoped enumeration type. 15077 if (!Diagnoser.Suppress) 15078 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15079 return ExprError(); 15080 } 15081 15082 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15083 // in the non-ICE case. 15084 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15085 if (Result) 15086 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15087 if (!isa<ConstantExpr>(E)) 15088 E = ConstantExpr::Create(Context, E); 15089 return E; 15090 } 15091 15092 Expr::EvalResult EvalResult; 15093 SmallVector<PartialDiagnosticAt, 8> Notes; 15094 EvalResult.Diag = &Notes; 15095 15096 // Try to evaluate the expression, and produce diagnostics explaining why it's 15097 // not a constant expression as a side-effect. 15098 bool Folded = 15099 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15100 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15101 15102 if (!isa<ConstantExpr>(E)) 15103 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15104 15105 // In C++11, we can rely on diagnostics being produced for any expression 15106 // which is not a constant expression. If no diagnostics were produced, then 15107 // this is a constant expression. 15108 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15109 if (Result) 15110 *Result = EvalResult.Val.getInt(); 15111 return E; 15112 } 15113 15114 // If our only note is the usual "invalid subexpression" note, just point 15115 // the caret at its location rather than producing an essentially 15116 // redundant note. 15117 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15118 diag::note_invalid_subexpr_in_const_expr) { 15119 DiagLoc = Notes[0].first; 15120 Notes.clear(); 15121 } 15122 15123 if (!Folded || !AllowFold) { 15124 if (!Diagnoser.Suppress) { 15125 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15126 for (const PartialDiagnosticAt &Note : Notes) 15127 Diag(Note.first, Note.second); 15128 } 15129 15130 return ExprError(); 15131 } 15132 15133 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15134 for (const PartialDiagnosticAt &Note : Notes) 15135 Diag(Note.first, Note.second); 15136 15137 if (Result) 15138 *Result = EvalResult.Val.getInt(); 15139 return E; 15140 } 15141 15142 namespace { 15143 // Handle the case where we conclude a expression which we speculatively 15144 // considered to be unevaluated is actually evaluated. 15145 class TransformToPE : public TreeTransform<TransformToPE> { 15146 typedef TreeTransform<TransformToPE> BaseTransform; 15147 15148 public: 15149 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15150 15151 // Make sure we redo semantic analysis 15152 bool AlwaysRebuild() { return true; } 15153 bool ReplacingOriginal() { return true; } 15154 15155 // We need to special-case DeclRefExprs referring to FieldDecls which 15156 // are not part of a member pointer formation; normal TreeTransforming 15157 // doesn't catch this case because of the way we represent them in the AST. 15158 // FIXME: This is a bit ugly; is it really the best way to handle this 15159 // case? 15160 // 15161 // Error on DeclRefExprs referring to FieldDecls. 15162 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15163 if (isa<FieldDecl>(E->getDecl()) && 15164 !SemaRef.isUnevaluatedContext()) 15165 return SemaRef.Diag(E->getLocation(), 15166 diag::err_invalid_non_static_member_use) 15167 << E->getDecl() << E->getSourceRange(); 15168 15169 return BaseTransform::TransformDeclRefExpr(E); 15170 } 15171 15172 // Exception: filter out member pointer formation 15173 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15174 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15175 return E; 15176 15177 return BaseTransform::TransformUnaryOperator(E); 15178 } 15179 15180 // The body of a lambda-expression is in a separate expression evaluation 15181 // context so never needs to be transformed. 15182 // FIXME: Ideally we wouldn't transform the closure type either, and would 15183 // just recreate the capture expressions and lambda expression. 15184 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15185 return SkipLambdaBody(E, Body); 15186 } 15187 }; 15188 } 15189 15190 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15191 assert(isUnevaluatedContext() && 15192 "Should only transform unevaluated expressions"); 15193 ExprEvalContexts.back().Context = 15194 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15195 if (isUnevaluatedContext()) 15196 return E; 15197 return TransformToPE(*this).TransformExpr(E); 15198 } 15199 15200 void 15201 Sema::PushExpressionEvaluationContext( 15202 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15203 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15204 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15205 LambdaContextDecl, ExprContext); 15206 Cleanup.reset(); 15207 if (!MaybeODRUseExprs.empty()) 15208 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15209 } 15210 15211 void 15212 Sema::PushExpressionEvaluationContext( 15213 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15214 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15215 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15216 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15217 } 15218 15219 namespace { 15220 15221 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15222 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15223 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15224 if (E->getOpcode() == UO_Deref) 15225 return CheckPossibleDeref(S, E->getSubExpr()); 15226 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15227 return CheckPossibleDeref(S, E->getBase()); 15228 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15229 return CheckPossibleDeref(S, E->getBase()); 15230 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15231 QualType Inner; 15232 QualType Ty = E->getType(); 15233 if (const auto *Ptr = Ty->getAs<PointerType>()) 15234 Inner = Ptr->getPointeeType(); 15235 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15236 Inner = Arr->getElementType(); 15237 else 15238 return nullptr; 15239 15240 if (Inner->hasAttr(attr::NoDeref)) 15241 return E; 15242 } 15243 return nullptr; 15244 } 15245 15246 } // namespace 15247 15248 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15249 for (const Expr *E : Rec.PossibleDerefs) { 15250 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15251 if (DeclRef) { 15252 const ValueDecl *Decl = DeclRef->getDecl(); 15253 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15254 << Decl->getName() << E->getSourceRange(); 15255 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15256 } else { 15257 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15258 << E->getSourceRange(); 15259 } 15260 } 15261 Rec.PossibleDerefs.clear(); 15262 } 15263 15264 /// Check whether E, which is either a discarded-value expression or an 15265 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15266 /// and if so, remove it from the list of volatile-qualified assignments that 15267 /// we are going to warn are deprecated. 15268 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15269 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15270 return; 15271 15272 // Note: ignoring parens here is not justified by the standard rules, but 15273 // ignoring parentheses seems like a more reasonable approach, and this only 15274 // drives a deprecation warning so doesn't affect conformance. 15275 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15276 if (BO->getOpcode() == BO_Assign) { 15277 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15278 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15279 LHSs.end()); 15280 } 15281 } 15282 } 15283 15284 void Sema::PopExpressionEvaluationContext() { 15285 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15286 unsigned NumTypos = Rec.NumTypos; 15287 15288 if (!Rec.Lambdas.empty()) { 15289 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15290 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15291 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15292 unsigned D; 15293 if (Rec.isUnevaluated()) { 15294 // C++11 [expr.prim.lambda]p2: 15295 // A lambda-expression shall not appear in an unevaluated operand 15296 // (Clause 5). 15297 D = diag::err_lambda_unevaluated_operand; 15298 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15299 // C++1y [expr.const]p2: 15300 // A conditional-expression e is a core constant expression unless the 15301 // evaluation of e, following the rules of the abstract machine, would 15302 // evaluate [...] a lambda-expression. 15303 D = diag::err_lambda_in_constant_expression; 15304 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15305 // C++17 [expr.prim.lamda]p2: 15306 // A lambda-expression shall not appear [...] in a template-argument. 15307 D = diag::err_lambda_in_invalid_context; 15308 } else 15309 llvm_unreachable("Couldn't infer lambda error message."); 15310 15311 for (const auto *L : Rec.Lambdas) 15312 Diag(L->getBeginLoc(), D); 15313 } 15314 } 15315 15316 WarnOnPendingNoDerefs(Rec); 15317 15318 // Warn on any volatile-qualified simple-assignments that are not discarded- 15319 // value expressions nor unevaluated operands (those cases get removed from 15320 // this list by CheckUnusedVolatileAssignment). 15321 for (auto *BO : Rec.VolatileAssignmentLHSs) 15322 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15323 << BO->getType(); 15324 15325 // When are coming out of an unevaluated context, clear out any 15326 // temporaries that we may have created as part of the evaluation of 15327 // the expression in that context: they aren't relevant because they 15328 // will never be constructed. 15329 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15330 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15331 ExprCleanupObjects.end()); 15332 Cleanup = Rec.ParentCleanup; 15333 CleanupVarDeclMarking(); 15334 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15335 // Otherwise, merge the contexts together. 15336 } else { 15337 Cleanup.mergeFrom(Rec.ParentCleanup); 15338 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15339 Rec.SavedMaybeODRUseExprs.end()); 15340 } 15341 15342 // Pop the current expression evaluation context off the stack. 15343 ExprEvalContexts.pop_back(); 15344 15345 // The global expression evaluation context record is never popped. 15346 ExprEvalContexts.back().NumTypos += NumTypos; 15347 } 15348 15349 void Sema::DiscardCleanupsInEvaluationContext() { 15350 ExprCleanupObjects.erase( 15351 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15352 ExprCleanupObjects.end()); 15353 Cleanup.reset(); 15354 MaybeODRUseExprs.clear(); 15355 } 15356 15357 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15358 ExprResult Result = CheckPlaceholderExpr(E); 15359 if (Result.isInvalid()) 15360 return ExprError(); 15361 E = Result.get(); 15362 if (!E->getType()->isVariablyModifiedType()) 15363 return E; 15364 return TransformToPotentiallyEvaluated(E); 15365 } 15366 15367 /// Are we in a context that is potentially constant evaluated per C++20 15368 /// [expr.const]p12? 15369 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15370 /// C++2a [expr.const]p12: 15371 // An expression or conversion is potentially constant evaluated if it is 15372 switch (SemaRef.ExprEvalContexts.back().Context) { 15373 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15374 // -- a manifestly constant-evaluated expression, 15375 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15376 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15377 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15378 // -- a potentially-evaluated expression, 15379 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15380 // -- an immediate subexpression of a braced-init-list, 15381 15382 // -- [FIXME] an expression of the form & cast-expression that occurs 15383 // within a templated entity 15384 // -- a subexpression of one of the above that is not a subexpression of 15385 // a nested unevaluated operand. 15386 return true; 15387 15388 case Sema::ExpressionEvaluationContext::Unevaluated: 15389 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15390 // Expressions in this context are never evaluated. 15391 return false; 15392 } 15393 llvm_unreachable("Invalid context"); 15394 } 15395 15396 /// Return true if this function has a calling convention that requires mangling 15397 /// in the size of the parameter pack. 15398 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15399 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15400 // we don't need parameter type sizes. 15401 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15402 if (!TT.isOSWindows() || !TT.isX86()) 15403 return false; 15404 15405 // If this is C++ and this isn't an extern "C" function, parameters do not 15406 // need to be complete. In this case, C++ mangling will apply, which doesn't 15407 // use the size of the parameters. 15408 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15409 return false; 15410 15411 // Stdcall, fastcall, and vectorcall need this special treatment. 15412 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15413 switch (CC) { 15414 case CC_X86StdCall: 15415 case CC_X86FastCall: 15416 case CC_X86VectorCall: 15417 return true; 15418 default: 15419 break; 15420 } 15421 return false; 15422 } 15423 15424 /// Require that all of the parameter types of function be complete. Normally, 15425 /// parameter types are only required to be complete when a function is called 15426 /// or defined, but to mangle functions with certain calling conventions, the 15427 /// mangler needs to know the size of the parameter list. In this situation, 15428 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15429 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15430 /// result in a linker error. Clang doesn't implement this behavior, and instead 15431 /// attempts to error at compile time. 15432 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15433 SourceLocation Loc) { 15434 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15435 FunctionDecl *FD; 15436 ParmVarDecl *Param; 15437 15438 public: 15439 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15440 : FD(FD), Param(Param) {} 15441 15442 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15443 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15444 StringRef CCName; 15445 switch (CC) { 15446 case CC_X86StdCall: 15447 CCName = "stdcall"; 15448 break; 15449 case CC_X86FastCall: 15450 CCName = "fastcall"; 15451 break; 15452 case CC_X86VectorCall: 15453 CCName = "vectorcall"; 15454 break; 15455 default: 15456 llvm_unreachable("CC does not need mangling"); 15457 } 15458 15459 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15460 << Param->getDeclName() << FD->getDeclName() << CCName; 15461 } 15462 }; 15463 15464 for (ParmVarDecl *Param : FD->parameters()) { 15465 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15466 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15467 } 15468 } 15469 15470 namespace { 15471 enum class OdrUseContext { 15472 /// Declarations in this context are not odr-used. 15473 None, 15474 /// Declarations in this context are formally odr-used, but this is a 15475 /// dependent context. 15476 Dependent, 15477 /// Declarations in this context are odr-used but not actually used (yet). 15478 FormallyOdrUsed, 15479 /// Declarations in this context are used. 15480 Used 15481 }; 15482 } 15483 15484 /// Are we within a context in which references to resolved functions or to 15485 /// variables result in odr-use? 15486 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15487 OdrUseContext Result; 15488 15489 switch (SemaRef.ExprEvalContexts.back().Context) { 15490 case Sema::ExpressionEvaluationContext::Unevaluated: 15491 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15492 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15493 return OdrUseContext::None; 15494 15495 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15496 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15497 Result = OdrUseContext::Used; 15498 break; 15499 15500 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15501 Result = OdrUseContext::FormallyOdrUsed; 15502 break; 15503 15504 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15505 // A default argument formally results in odr-use, but doesn't actually 15506 // result in a use in any real sense until it itself is used. 15507 Result = OdrUseContext::FormallyOdrUsed; 15508 break; 15509 } 15510 15511 if (SemaRef.CurContext->isDependentContext()) 15512 return OdrUseContext::Dependent; 15513 15514 return Result; 15515 } 15516 15517 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15518 return Func->isConstexpr() && 15519 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15520 } 15521 15522 /// Mark a function referenced, and check whether it is odr-used 15523 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15524 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15525 bool MightBeOdrUse) { 15526 assert(Func && "No function?"); 15527 15528 Func->setReferenced(); 15529 15530 // Recursive functions aren't really used until they're used from some other 15531 // context. 15532 bool IsRecursiveCall = CurContext == Func; 15533 15534 // C++11 [basic.def.odr]p3: 15535 // A function whose name appears as a potentially-evaluated expression is 15536 // odr-used if it is the unique lookup result or the selected member of a 15537 // set of overloaded functions [...]. 15538 // 15539 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15540 // can just check that here. 15541 OdrUseContext OdrUse = 15542 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15543 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15544 OdrUse = OdrUseContext::FormallyOdrUsed; 15545 15546 // Trivial default constructors and destructors are never actually used. 15547 // FIXME: What about other special members? 15548 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15549 OdrUse == OdrUseContext::Used) { 15550 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15551 if (Constructor->isDefaultConstructor()) 15552 OdrUse = OdrUseContext::FormallyOdrUsed; 15553 if (isa<CXXDestructorDecl>(Func)) 15554 OdrUse = OdrUseContext::FormallyOdrUsed; 15555 } 15556 15557 // C++20 [expr.const]p12: 15558 // A function [...] is needed for constant evaluation if it is [...] a 15559 // constexpr function that is named by an expression that is potentially 15560 // constant evaluated 15561 bool NeededForConstantEvaluation = 15562 isPotentiallyConstantEvaluatedContext(*this) && 15563 isImplicitlyDefinableConstexprFunction(Func); 15564 15565 // Determine whether we require a function definition to exist, per 15566 // C++11 [temp.inst]p3: 15567 // Unless a function template specialization has been explicitly 15568 // instantiated or explicitly specialized, the function template 15569 // specialization is implicitly instantiated when the specialization is 15570 // referenced in a context that requires a function definition to exist. 15571 // C++20 [temp.inst]p7: 15572 // The existence of a definition of a [...] function is considered to 15573 // affect the semantics of the program if the [...] function is needed for 15574 // constant evaluation by an expression 15575 // C++20 [basic.def.odr]p10: 15576 // Every program shall contain exactly one definition of every non-inline 15577 // function or variable that is odr-used in that program outside of a 15578 // discarded statement 15579 // C++20 [special]p1: 15580 // The implementation will implicitly define [defaulted special members] 15581 // if they are odr-used or needed for constant evaluation. 15582 // 15583 // Note that we skip the implicit instantiation of templates that are only 15584 // used in unused default arguments or by recursive calls to themselves. 15585 // This is formally non-conforming, but seems reasonable in practice. 15586 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15587 NeededForConstantEvaluation); 15588 15589 // C++14 [temp.expl.spec]p6: 15590 // If a template [...] is explicitly specialized then that specialization 15591 // shall be declared before the first use of that specialization that would 15592 // cause an implicit instantiation to take place, in every translation unit 15593 // in which such a use occurs 15594 if (NeedDefinition && 15595 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15596 Func->getMemberSpecializationInfo())) 15597 checkSpecializationVisibility(Loc, Func); 15598 15599 if (getLangOpts().CUDA) 15600 CheckCUDACall(Loc, Func); 15601 15602 // If we need a definition, try to create one. 15603 if (NeedDefinition && !Func->getBody()) { 15604 runWithSufficientStackSpace(Loc, [&] { 15605 if (CXXConstructorDecl *Constructor = 15606 dyn_cast<CXXConstructorDecl>(Func)) { 15607 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15608 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15609 if (Constructor->isDefaultConstructor()) { 15610 if (Constructor->isTrivial() && 15611 !Constructor->hasAttr<DLLExportAttr>()) 15612 return; 15613 DefineImplicitDefaultConstructor(Loc, Constructor); 15614 } else if (Constructor->isCopyConstructor()) { 15615 DefineImplicitCopyConstructor(Loc, Constructor); 15616 } else if (Constructor->isMoveConstructor()) { 15617 DefineImplicitMoveConstructor(Loc, Constructor); 15618 } 15619 } else if (Constructor->getInheritedConstructor()) { 15620 DefineInheritingConstructor(Loc, Constructor); 15621 } 15622 } else if (CXXDestructorDecl *Destructor = 15623 dyn_cast<CXXDestructorDecl>(Func)) { 15624 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15625 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15626 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15627 return; 15628 DefineImplicitDestructor(Loc, Destructor); 15629 } 15630 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15631 MarkVTableUsed(Loc, Destructor->getParent()); 15632 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15633 if (MethodDecl->isOverloadedOperator() && 15634 MethodDecl->getOverloadedOperator() == OO_Equal) { 15635 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15636 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15637 if (MethodDecl->isCopyAssignmentOperator()) 15638 DefineImplicitCopyAssignment(Loc, MethodDecl); 15639 else if (MethodDecl->isMoveAssignmentOperator()) 15640 DefineImplicitMoveAssignment(Loc, MethodDecl); 15641 } 15642 } else if (isa<CXXConversionDecl>(MethodDecl) && 15643 MethodDecl->getParent()->isLambda()) { 15644 CXXConversionDecl *Conversion = 15645 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15646 if (Conversion->isLambdaToBlockPointerConversion()) 15647 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15648 else 15649 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15650 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15651 MarkVTableUsed(Loc, MethodDecl->getParent()); 15652 } 15653 15654 if (Func->isDefaulted() && !Func->isDeleted()) { 15655 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15656 if (DCK != DefaultedComparisonKind::None) 15657 DefineDefaultedComparison(Loc, Func, DCK); 15658 } 15659 15660 // Implicit instantiation of function templates and member functions of 15661 // class templates. 15662 if (Func->isImplicitlyInstantiable()) { 15663 TemplateSpecializationKind TSK = 15664 Func->getTemplateSpecializationKindForInstantiation(); 15665 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15666 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15667 if (FirstInstantiation) { 15668 PointOfInstantiation = Loc; 15669 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15670 } else if (TSK != TSK_ImplicitInstantiation) { 15671 // Use the point of use as the point of instantiation, instead of the 15672 // point of explicit instantiation (which we track as the actual point 15673 // of instantiation). This gives better backtraces in diagnostics. 15674 PointOfInstantiation = Loc; 15675 } 15676 15677 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15678 Func->isConstexpr()) { 15679 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15680 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15681 CodeSynthesisContexts.size()) 15682 PendingLocalImplicitInstantiations.push_back( 15683 std::make_pair(Func, PointOfInstantiation)); 15684 else if (Func->isConstexpr()) 15685 // Do not defer instantiations of constexpr functions, to avoid the 15686 // expression evaluator needing to call back into Sema if it sees a 15687 // call to such a function. 15688 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15689 else { 15690 Func->setInstantiationIsPending(true); 15691 PendingInstantiations.push_back( 15692 std::make_pair(Func, PointOfInstantiation)); 15693 // Notify the consumer that a function was implicitly instantiated. 15694 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15695 } 15696 } 15697 } else { 15698 // Walk redefinitions, as some of them may be instantiable. 15699 for (auto i : Func->redecls()) { 15700 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15701 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15702 } 15703 } 15704 }); 15705 } 15706 15707 // C++14 [except.spec]p17: 15708 // An exception-specification is considered to be needed when: 15709 // - the function is odr-used or, if it appears in an unevaluated operand, 15710 // would be odr-used if the expression were potentially-evaluated; 15711 // 15712 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15713 // function is a pure virtual function we're calling, and in that case the 15714 // function was selected by overload resolution and we need to resolve its 15715 // exception specification for a different reason. 15716 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15717 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15718 ResolveExceptionSpec(Loc, FPT); 15719 15720 // If this is the first "real" use, act on that. 15721 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15722 // Keep track of used but undefined functions. 15723 if (!Func->isDefined()) { 15724 if (mightHaveNonExternalLinkage(Func)) 15725 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15726 else if (Func->getMostRecentDecl()->isInlined() && 15727 !LangOpts.GNUInline && 15728 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15729 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15730 else if (isExternalWithNoLinkageType(Func)) 15731 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15732 } 15733 15734 // Some x86 Windows calling conventions mangle the size of the parameter 15735 // pack into the name. Computing the size of the parameters requires the 15736 // parameter types to be complete. Check that now. 15737 if (funcHasParameterSizeMangling(*this, Func)) 15738 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15739 15740 Func->markUsed(Context); 15741 } 15742 15743 if (LangOpts.OpenMP) { 15744 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15745 if (LangOpts.OpenMPIsDevice) 15746 checkOpenMPDeviceFunction(Loc, Func); 15747 else 15748 checkOpenMPHostFunction(Loc, Func); 15749 } 15750 } 15751 15752 /// Directly mark a variable odr-used. Given a choice, prefer to use 15753 /// MarkVariableReferenced since it does additional checks and then 15754 /// calls MarkVarDeclODRUsed. 15755 /// If the variable must be captured: 15756 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15757 /// - else capture it in the DeclContext that maps to the 15758 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15759 static void 15760 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15761 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15762 // Keep track of used but undefined variables. 15763 // FIXME: We shouldn't suppress this warning for static data members. 15764 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15765 (!Var->isExternallyVisible() || Var->isInline() || 15766 SemaRef.isExternalWithNoLinkageType(Var)) && 15767 !(Var->isStaticDataMember() && Var->hasInit())) { 15768 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15769 if (old.isInvalid()) 15770 old = Loc; 15771 } 15772 QualType CaptureType, DeclRefType; 15773 if (SemaRef.LangOpts.OpenMP) 15774 SemaRef.tryCaptureOpenMPLambdas(Var); 15775 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15776 /*EllipsisLoc*/ SourceLocation(), 15777 /*BuildAndDiagnose*/ true, 15778 CaptureType, DeclRefType, 15779 FunctionScopeIndexToStopAt); 15780 15781 Var->markUsed(SemaRef.Context); 15782 } 15783 15784 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15785 SourceLocation Loc, 15786 unsigned CapturingScopeIndex) { 15787 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15788 } 15789 15790 static void 15791 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15792 ValueDecl *var, DeclContext *DC) { 15793 DeclContext *VarDC = var->getDeclContext(); 15794 15795 // If the parameter still belongs to the translation unit, then 15796 // we're actually just using one parameter in the declaration of 15797 // the next. 15798 if (isa<ParmVarDecl>(var) && 15799 isa<TranslationUnitDecl>(VarDC)) 15800 return; 15801 15802 // For C code, don't diagnose about capture if we're not actually in code 15803 // right now; it's impossible to write a non-constant expression outside of 15804 // function context, so we'll get other (more useful) diagnostics later. 15805 // 15806 // For C++, things get a bit more nasty... it would be nice to suppress this 15807 // diagnostic for certain cases like using a local variable in an array bound 15808 // for a member of a local class, but the correct predicate is not obvious. 15809 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15810 return; 15811 15812 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15813 unsigned ContextKind = 3; // unknown 15814 if (isa<CXXMethodDecl>(VarDC) && 15815 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15816 ContextKind = 2; 15817 } else if (isa<FunctionDecl>(VarDC)) { 15818 ContextKind = 0; 15819 } else if (isa<BlockDecl>(VarDC)) { 15820 ContextKind = 1; 15821 } 15822 15823 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15824 << var << ValueKind << ContextKind << VarDC; 15825 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15826 << var; 15827 15828 // FIXME: Add additional diagnostic info about class etc. which prevents 15829 // capture. 15830 } 15831 15832 15833 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15834 bool &SubCapturesAreNested, 15835 QualType &CaptureType, 15836 QualType &DeclRefType) { 15837 // Check whether we've already captured it. 15838 if (CSI->CaptureMap.count(Var)) { 15839 // If we found a capture, any subcaptures are nested. 15840 SubCapturesAreNested = true; 15841 15842 // Retrieve the capture type for this variable. 15843 CaptureType = CSI->getCapture(Var).getCaptureType(); 15844 15845 // Compute the type of an expression that refers to this variable. 15846 DeclRefType = CaptureType.getNonReferenceType(); 15847 15848 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15849 // are mutable in the sense that user can change their value - they are 15850 // private instances of the captured declarations. 15851 const Capture &Cap = CSI->getCapture(Var); 15852 if (Cap.isCopyCapture() && 15853 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15854 !(isa<CapturedRegionScopeInfo>(CSI) && 15855 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15856 DeclRefType.addConst(); 15857 return true; 15858 } 15859 return false; 15860 } 15861 15862 // Only block literals, captured statements, and lambda expressions can 15863 // capture; other scopes don't work. 15864 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15865 SourceLocation Loc, 15866 const bool Diagnose, Sema &S) { 15867 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15868 return getLambdaAwareParentOfDeclContext(DC); 15869 else if (Var->hasLocalStorage()) { 15870 if (Diagnose) 15871 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15872 } 15873 return nullptr; 15874 } 15875 15876 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15877 // certain types of variables (unnamed, variably modified types etc.) 15878 // so check for eligibility. 15879 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15880 SourceLocation Loc, 15881 const bool Diagnose, Sema &S) { 15882 15883 bool IsBlock = isa<BlockScopeInfo>(CSI); 15884 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15885 15886 // Lambdas are not allowed to capture unnamed variables 15887 // (e.g. anonymous unions). 15888 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15889 // assuming that's the intent. 15890 if (IsLambda && !Var->getDeclName()) { 15891 if (Diagnose) { 15892 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15893 S.Diag(Var->getLocation(), diag::note_declared_at); 15894 } 15895 return false; 15896 } 15897 15898 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15899 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15900 if (Diagnose) { 15901 S.Diag(Loc, diag::err_ref_vm_type); 15902 S.Diag(Var->getLocation(), diag::note_previous_decl) 15903 << Var->getDeclName(); 15904 } 15905 return false; 15906 } 15907 // Prohibit structs with flexible array members too. 15908 // We cannot capture what is in the tail end of the struct. 15909 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15910 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15911 if (Diagnose) { 15912 if (IsBlock) 15913 S.Diag(Loc, diag::err_ref_flexarray_type); 15914 else 15915 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15916 << Var->getDeclName(); 15917 S.Diag(Var->getLocation(), diag::note_previous_decl) 15918 << Var->getDeclName(); 15919 } 15920 return false; 15921 } 15922 } 15923 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15924 // Lambdas and captured statements are not allowed to capture __block 15925 // variables; they don't support the expected semantics. 15926 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15927 if (Diagnose) { 15928 S.Diag(Loc, diag::err_capture_block_variable) 15929 << Var->getDeclName() << !IsLambda; 15930 S.Diag(Var->getLocation(), diag::note_previous_decl) 15931 << Var->getDeclName(); 15932 } 15933 return false; 15934 } 15935 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15936 if (S.getLangOpts().OpenCL && IsBlock && 15937 Var->getType()->isBlockPointerType()) { 15938 if (Diagnose) 15939 S.Diag(Loc, diag::err_opencl_block_ref_block); 15940 return false; 15941 } 15942 15943 return true; 15944 } 15945 15946 // Returns true if the capture by block was successful. 15947 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15948 SourceLocation Loc, 15949 const bool BuildAndDiagnose, 15950 QualType &CaptureType, 15951 QualType &DeclRefType, 15952 const bool Nested, 15953 Sema &S, bool Invalid) { 15954 bool ByRef = false; 15955 15956 // Blocks are not allowed to capture arrays, excepting OpenCL. 15957 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15958 // (decayed to pointers). 15959 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15960 if (BuildAndDiagnose) { 15961 S.Diag(Loc, diag::err_ref_array_type); 15962 S.Diag(Var->getLocation(), diag::note_previous_decl) 15963 << Var->getDeclName(); 15964 Invalid = true; 15965 } else { 15966 return false; 15967 } 15968 } 15969 15970 // Forbid the block-capture of autoreleasing variables. 15971 if (!Invalid && 15972 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15973 if (BuildAndDiagnose) { 15974 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15975 << /*block*/ 0; 15976 S.Diag(Var->getLocation(), diag::note_previous_decl) 15977 << Var->getDeclName(); 15978 Invalid = true; 15979 } else { 15980 return false; 15981 } 15982 } 15983 15984 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15985 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15986 QualType PointeeTy = PT->getPointeeType(); 15987 15988 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15989 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15990 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15991 if (BuildAndDiagnose) { 15992 SourceLocation VarLoc = Var->getLocation(); 15993 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15994 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15995 } 15996 } 15997 } 15998 15999 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16000 if (HasBlocksAttr || CaptureType->isReferenceType() || 16001 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16002 // Block capture by reference does not change the capture or 16003 // declaration reference types. 16004 ByRef = true; 16005 } else { 16006 // Block capture by copy introduces 'const'. 16007 CaptureType = CaptureType.getNonReferenceType().withConst(); 16008 DeclRefType = CaptureType; 16009 } 16010 16011 // Actually capture the variable. 16012 if (BuildAndDiagnose) 16013 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16014 CaptureType, Invalid); 16015 16016 return !Invalid; 16017 } 16018 16019 16020 /// Capture the given variable in the captured region. 16021 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16022 VarDecl *Var, 16023 SourceLocation Loc, 16024 const bool BuildAndDiagnose, 16025 QualType &CaptureType, 16026 QualType &DeclRefType, 16027 const bool RefersToCapturedVariable, 16028 Sema &S, bool Invalid) { 16029 // By default, capture variables by reference. 16030 bool ByRef = true; 16031 // Using an LValue reference type is consistent with Lambdas (see below). 16032 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16033 if (S.isOpenMPCapturedDecl(Var)) { 16034 bool HasConst = DeclRefType.isConstQualified(); 16035 DeclRefType = DeclRefType.getUnqualifiedType(); 16036 // Don't lose diagnostics about assignments to const. 16037 if (HasConst) 16038 DeclRefType.addConst(); 16039 } 16040 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16041 RSI->OpenMPCaptureLevel); 16042 } 16043 16044 if (ByRef) 16045 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16046 else 16047 CaptureType = DeclRefType; 16048 16049 // Actually capture the variable. 16050 if (BuildAndDiagnose) 16051 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16052 Loc, SourceLocation(), CaptureType, Invalid); 16053 16054 return !Invalid; 16055 } 16056 16057 /// Capture the given variable in the lambda. 16058 static bool captureInLambda(LambdaScopeInfo *LSI, 16059 VarDecl *Var, 16060 SourceLocation Loc, 16061 const bool BuildAndDiagnose, 16062 QualType &CaptureType, 16063 QualType &DeclRefType, 16064 const bool RefersToCapturedVariable, 16065 const Sema::TryCaptureKind Kind, 16066 SourceLocation EllipsisLoc, 16067 const bool IsTopScope, 16068 Sema &S, bool Invalid) { 16069 // Determine whether we are capturing by reference or by value. 16070 bool ByRef = false; 16071 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16072 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16073 } else { 16074 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16075 } 16076 16077 // Compute the type of the field that will capture this variable. 16078 if (ByRef) { 16079 // C++11 [expr.prim.lambda]p15: 16080 // An entity is captured by reference if it is implicitly or 16081 // explicitly captured but not captured by copy. It is 16082 // unspecified whether additional unnamed non-static data 16083 // members are declared in the closure type for entities 16084 // captured by reference. 16085 // 16086 // FIXME: It is not clear whether we want to build an lvalue reference 16087 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16088 // to do the former, while EDG does the latter. Core issue 1249 will 16089 // clarify, but for now we follow GCC because it's a more permissive and 16090 // easily defensible position. 16091 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16092 } else { 16093 // C++11 [expr.prim.lambda]p14: 16094 // For each entity captured by copy, an unnamed non-static 16095 // data member is declared in the closure type. The 16096 // declaration order of these members is unspecified. The type 16097 // of such a data member is the type of the corresponding 16098 // captured entity if the entity is not a reference to an 16099 // object, or the referenced type otherwise. [Note: If the 16100 // captured entity is a reference to a function, the 16101 // corresponding data member is also a reference to a 16102 // function. - end note ] 16103 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16104 if (!RefType->getPointeeType()->isFunctionType()) 16105 CaptureType = RefType->getPointeeType(); 16106 } 16107 16108 // Forbid the lambda copy-capture of autoreleasing variables. 16109 if (!Invalid && 16110 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16111 if (BuildAndDiagnose) { 16112 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16113 S.Diag(Var->getLocation(), diag::note_previous_decl) 16114 << Var->getDeclName(); 16115 Invalid = true; 16116 } else { 16117 return false; 16118 } 16119 } 16120 16121 // Make sure that by-copy captures are of a complete and non-abstract type. 16122 if (!Invalid && BuildAndDiagnose) { 16123 if (!CaptureType->isDependentType() && 16124 S.RequireCompleteType(Loc, CaptureType, 16125 diag::err_capture_of_incomplete_type, 16126 Var->getDeclName())) 16127 Invalid = true; 16128 else if (S.RequireNonAbstractType(Loc, CaptureType, 16129 diag::err_capture_of_abstract_type)) 16130 Invalid = true; 16131 } 16132 } 16133 16134 // Compute the type of a reference to this captured variable. 16135 if (ByRef) 16136 DeclRefType = CaptureType.getNonReferenceType(); 16137 else { 16138 // C++ [expr.prim.lambda]p5: 16139 // The closure type for a lambda-expression has a public inline 16140 // function call operator [...]. This function call operator is 16141 // declared const (9.3.1) if and only if the lambda-expression's 16142 // parameter-declaration-clause is not followed by mutable. 16143 DeclRefType = CaptureType.getNonReferenceType(); 16144 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16145 DeclRefType.addConst(); 16146 } 16147 16148 // Add the capture. 16149 if (BuildAndDiagnose) 16150 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16151 Loc, EllipsisLoc, CaptureType, Invalid); 16152 16153 return !Invalid; 16154 } 16155 16156 bool Sema::tryCaptureVariable( 16157 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16158 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16159 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16160 // An init-capture is notionally from the context surrounding its 16161 // declaration, but its parent DC is the lambda class. 16162 DeclContext *VarDC = Var->getDeclContext(); 16163 if (Var->isInitCapture()) 16164 VarDC = VarDC->getParent(); 16165 16166 DeclContext *DC = CurContext; 16167 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16168 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16169 // We need to sync up the Declaration Context with the 16170 // FunctionScopeIndexToStopAt 16171 if (FunctionScopeIndexToStopAt) { 16172 unsigned FSIndex = FunctionScopes.size() - 1; 16173 while (FSIndex != MaxFunctionScopesIndex) { 16174 DC = getLambdaAwareParentOfDeclContext(DC); 16175 --FSIndex; 16176 } 16177 } 16178 16179 16180 // If the variable is declared in the current context, there is no need to 16181 // capture it. 16182 if (VarDC == DC) return true; 16183 16184 // Capture global variables if it is required to use private copy of this 16185 // variable. 16186 bool IsGlobal = !Var->hasLocalStorage(); 16187 if (IsGlobal && 16188 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16189 MaxFunctionScopesIndex))) 16190 return true; 16191 Var = Var->getCanonicalDecl(); 16192 16193 // Walk up the stack to determine whether we can capture the variable, 16194 // performing the "simple" checks that don't depend on type. We stop when 16195 // we've either hit the declared scope of the variable or find an existing 16196 // capture of that variable. We start from the innermost capturing-entity 16197 // (the DC) and ensure that all intervening capturing-entities 16198 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16199 // declcontext can either capture the variable or have already captured 16200 // the variable. 16201 CaptureType = Var->getType(); 16202 DeclRefType = CaptureType.getNonReferenceType(); 16203 bool Nested = false; 16204 bool Explicit = (Kind != TryCapture_Implicit); 16205 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16206 do { 16207 // Only block literals, captured statements, and lambda expressions can 16208 // capture; other scopes don't work. 16209 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16210 ExprLoc, 16211 BuildAndDiagnose, 16212 *this); 16213 // We need to check for the parent *first* because, if we *have* 16214 // private-captured a global variable, we need to recursively capture it in 16215 // intermediate blocks, lambdas, etc. 16216 if (!ParentDC) { 16217 if (IsGlobal) { 16218 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16219 break; 16220 } 16221 return true; 16222 } 16223 16224 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16225 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16226 16227 16228 // Check whether we've already captured it. 16229 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16230 DeclRefType)) { 16231 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16232 break; 16233 } 16234 // If we are instantiating a generic lambda call operator body, 16235 // we do not want to capture new variables. What was captured 16236 // during either a lambdas transformation or initial parsing 16237 // should be used. 16238 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16239 if (BuildAndDiagnose) { 16240 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16241 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16242 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16243 Diag(Var->getLocation(), diag::note_previous_decl) 16244 << Var->getDeclName(); 16245 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16246 } else 16247 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16248 } 16249 return true; 16250 } 16251 16252 // Try to capture variable-length arrays types. 16253 if (Var->getType()->isVariablyModifiedType()) { 16254 // We're going to walk down into the type and look for VLA 16255 // expressions. 16256 QualType QTy = Var->getType(); 16257 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16258 QTy = PVD->getOriginalType(); 16259 captureVariablyModifiedType(Context, QTy, CSI); 16260 } 16261 16262 if (getLangOpts().OpenMP) { 16263 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16264 // OpenMP private variables should not be captured in outer scope, so 16265 // just break here. Similarly, global variables that are captured in a 16266 // target region should not be captured outside the scope of the region. 16267 if (RSI->CapRegionKind == CR_OpenMP) { 16268 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16269 // If the variable is private (i.e. not captured) and has variably 16270 // modified type, we still need to capture the type for correct 16271 // codegen in all regions, associated with the construct. Currently, 16272 // it is captured in the innermost captured region only. 16273 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16274 QualType QTy = Var->getType(); 16275 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16276 QTy = PVD->getOriginalType(); 16277 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16278 I < E; ++I) { 16279 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16280 FunctionScopes[FunctionScopesIndex - I]); 16281 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16282 "Wrong number of captured regions associated with the " 16283 "OpenMP construct."); 16284 captureVariablyModifiedType(Context, QTy, OuterRSI); 16285 } 16286 } 16287 bool IsTargetCap = !IsOpenMPPrivateDecl && 16288 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16289 // When we detect target captures we are looking from inside the 16290 // target region, therefore we need to propagate the capture from the 16291 // enclosing region. Therefore, the capture is not initially nested. 16292 if (IsTargetCap) 16293 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16294 16295 if (IsTargetCap || IsOpenMPPrivateDecl) { 16296 Nested = !IsTargetCap; 16297 DeclRefType = DeclRefType.getUnqualifiedType(); 16298 CaptureType = Context.getLValueReferenceType(DeclRefType); 16299 break; 16300 } 16301 } 16302 } 16303 } 16304 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16305 // No capture-default, and this is not an explicit capture 16306 // so cannot capture this variable. 16307 if (BuildAndDiagnose) { 16308 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16309 Diag(Var->getLocation(), diag::note_previous_decl) 16310 << Var->getDeclName(); 16311 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16312 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16313 diag::note_lambda_decl); 16314 // FIXME: If we error out because an outer lambda can not implicitly 16315 // capture a variable that an inner lambda explicitly captures, we 16316 // should have the inner lambda do the explicit capture - because 16317 // it makes for cleaner diagnostics later. This would purely be done 16318 // so that the diagnostic does not misleadingly claim that a variable 16319 // can not be captured by a lambda implicitly even though it is captured 16320 // explicitly. Suggestion: 16321 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16322 // at the function head 16323 // - cache the StartingDeclContext - this must be a lambda 16324 // - captureInLambda in the innermost lambda the variable. 16325 } 16326 return true; 16327 } 16328 16329 FunctionScopesIndex--; 16330 DC = ParentDC; 16331 Explicit = false; 16332 } while (!VarDC->Equals(DC)); 16333 16334 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16335 // computing the type of the capture at each step, checking type-specific 16336 // requirements, and adding captures if requested. 16337 // If the variable had already been captured previously, we start capturing 16338 // at the lambda nested within that one. 16339 bool Invalid = false; 16340 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16341 ++I) { 16342 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16343 16344 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16345 // certain types of variables (unnamed, variably modified types etc.) 16346 // so check for eligibility. 16347 if (!Invalid) 16348 Invalid = 16349 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16350 16351 // After encountering an error, if we're actually supposed to capture, keep 16352 // capturing in nested contexts to suppress any follow-on diagnostics. 16353 if (Invalid && !BuildAndDiagnose) 16354 return true; 16355 16356 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16357 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16358 DeclRefType, Nested, *this, Invalid); 16359 Nested = true; 16360 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16361 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16362 CaptureType, DeclRefType, Nested, 16363 *this, Invalid); 16364 Nested = true; 16365 } else { 16366 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16367 Invalid = 16368 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16369 DeclRefType, Nested, Kind, EllipsisLoc, 16370 /*IsTopScope*/ I == N - 1, *this, Invalid); 16371 Nested = true; 16372 } 16373 16374 if (Invalid && !BuildAndDiagnose) 16375 return true; 16376 } 16377 return Invalid; 16378 } 16379 16380 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16381 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16382 QualType CaptureType; 16383 QualType DeclRefType; 16384 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16385 /*BuildAndDiagnose=*/true, CaptureType, 16386 DeclRefType, nullptr); 16387 } 16388 16389 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16390 QualType CaptureType; 16391 QualType DeclRefType; 16392 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16393 /*BuildAndDiagnose=*/false, CaptureType, 16394 DeclRefType, nullptr); 16395 } 16396 16397 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16398 QualType CaptureType; 16399 QualType DeclRefType; 16400 16401 // Determine whether we can capture this variable. 16402 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16403 /*BuildAndDiagnose=*/false, CaptureType, 16404 DeclRefType, nullptr)) 16405 return QualType(); 16406 16407 return DeclRefType; 16408 } 16409 16410 namespace { 16411 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16412 // The produced TemplateArgumentListInfo* points to data stored within this 16413 // object, so should only be used in contexts where the pointer will not be 16414 // used after the CopiedTemplateArgs object is destroyed. 16415 class CopiedTemplateArgs { 16416 bool HasArgs; 16417 TemplateArgumentListInfo TemplateArgStorage; 16418 public: 16419 template<typename RefExpr> 16420 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16421 if (HasArgs) 16422 E->copyTemplateArgumentsInto(TemplateArgStorage); 16423 } 16424 operator TemplateArgumentListInfo*() 16425 #ifdef __has_cpp_attribute 16426 #if __has_cpp_attribute(clang::lifetimebound) 16427 [[clang::lifetimebound]] 16428 #endif 16429 #endif 16430 { 16431 return HasArgs ? &TemplateArgStorage : nullptr; 16432 } 16433 }; 16434 } 16435 16436 /// Walk the set of potential results of an expression and mark them all as 16437 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16438 /// 16439 /// \return A new expression if we found any potential results, ExprEmpty() if 16440 /// not, and ExprError() if we diagnosed an error. 16441 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16442 NonOdrUseReason NOUR) { 16443 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16444 // an object that satisfies the requirements for appearing in a 16445 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16446 // is immediately applied." This function handles the lvalue-to-rvalue 16447 // conversion part. 16448 // 16449 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16450 // transform it into the relevant kind of non-odr-use node and rebuild the 16451 // tree of nodes leading to it. 16452 // 16453 // This is a mini-TreeTransform that only transforms a restricted subset of 16454 // nodes (and only certain operands of them). 16455 16456 // Rebuild a subexpression. 16457 auto Rebuild = [&](Expr *Sub) { 16458 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16459 }; 16460 16461 // Check whether a potential result satisfies the requirements of NOUR. 16462 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16463 // Any entity other than a VarDecl is always odr-used whenever it's named 16464 // in a potentially-evaluated expression. 16465 auto *VD = dyn_cast<VarDecl>(D); 16466 if (!VD) 16467 return true; 16468 16469 // C++2a [basic.def.odr]p4: 16470 // A variable x whose name appears as a potentially-evalauted expression 16471 // e is odr-used by e unless 16472 // -- x is a reference that is usable in constant expressions, or 16473 // -- x is a variable of non-reference type that is usable in constant 16474 // expressions and has no mutable subobjects, and e is an element of 16475 // the set of potential results of an expression of 16476 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16477 // conversion is applied, or 16478 // -- x is a variable of non-reference type, and e is an element of the 16479 // set of potential results of a discarded-value expression to which 16480 // the lvalue-to-rvalue conversion is not applied 16481 // 16482 // We check the first bullet and the "potentially-evaluated" condition in 16483 // BuildDeclRefExpr. We check the type requirements in the second bullet 16484 // in CheckLValueToRValueConversionOperand below. 16485 switch (NOUR) { 16486 case NOUR_None: 16487 case NOUR_Unevaluated: 16488 llvm_unreachable("unexpected non-odr-use-reason"); 16489 16490 case NOUR_Constant: 16491 // Constant references were handled when they were built. 16492 if (VD->getType()->isReferenceType()) 16493 return true; 16494 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16495 if (RD->hasMutableFields()) 16496 return true; 16497 if (!VD->isUsableInConstantExpressions(S.Context)) 16498 return true; 16499 break; 16500 16501 case NOUR_Discarded: 16502 if (VD->getType()->isReferenceType()) 16503 return true; 16504 break; 16505 } 16506 return false; 16507 }; 16508 16509 // Mark that this expression does not constitute an odr-use. 16510 auto MarkNotOdrUsed = [&] { 16511 S.MaybeODRUseExprs.erase(E); 16512 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16513 LSI->markVariableExprAsNonODRUsed(E); 16514 }; 16515 16516 // C++2a [basic.def.odr]p2: 16517 // The set of potential results of an expression e is defined as follows: 16518 switch (E->getStmtClass()) { 16519 // -- If e is an id-expression, ... 16520 case Expr::DeclRefExprClass: { 16521 auto *DRE = cast<DeclRefExpr>(E); 16522 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16523 break; 16524 16525 // Rebuild as a non-odr-use DeclRefExpr. 16526 MarkNotOdrUsed(); 16527 return DeclRefExpr::Create( 16528 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16529 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16530 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16531 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16532 } 16533 16534 case Expr::FunctionParmPackExprClass: { 16535 auto *FPPE = cast<FunctionParmPackExpr>(E); 16536 // If any of the declarations in the pack is odr-used, then the expression 16537 // as a whole constitutes an odr-use. 16538 for (VarDecl *D : *FPPE) 16539 if (IsPotentialResultOdrUsed(D)) 16540 return ExprEmpty(); 16541 16542 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16543 // nothing cares about whether we marked this as an odr-use, but it might 16544 // be useful for non-compiler tools. 16545 MarkNotOdrUsed(); 16546 break; 16547 } 16548 16549 // -- If e is a subscripting operation with an array operand... 16550 case Expr::ArraySubscriptExprClass: { 16551 auto *ASE = cast<ArraySubscriptExpr>(E); 16552 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16553 if (!OldBase->getType()->isArrayType()) 16554 break; 16555 ExprResult Base = Rebuild(OldBase); 16556 if (!Base.isUsable()) 16557 return Base; 16558 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16559 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16560 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16561 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16562 ASE->getRBracketLoc()); 16563 } 16564 16565 case Expr::MemberExprClass: { 16566 auto *ME = cast<MemberExpr>(E); 16567 // -- If e is a class member access expression [...] naming a non-static 16568 // data member... 16569 if (isa<FieldDecl>(ME->getMemberDecl())) { 16570 ExprResult Base = Rebuild(ME->getBase()); 16571 if (!Base.isUsable()) 16572 return Base; 16573 return MemberExpr::Create( 16574 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16575 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16576 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16577 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16578 ME->getObjectKind(), ME->isNonOdrUse()); 16579 } 16580 16581 if (ME->getMemberDecl()->isCXXInstanceMember()) 16582 break; 16583 16584 // -- If e is a class member access expression naming a static data member, 16585 // ... 16586 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16587 break; 16588 16589 // Rebuild as a non-odr-use MemberExpr. 16590 MarkNotOdrUsed(); 16591 return MemberExpr::Create( 16592 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16593 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16594 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16595 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16596 return ExprEmpty(); 16597 } 16598 16599 case Expr::BinaryOperatorClass: { 16600 auto *BO = cast<BinaryOperator>(E); 16601 Expr *LHS = BO->getLHS(); 16602 Expr *RHS = BO->getRHS(); 16603 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16604 if (BO->getOpcode() == BO_PtrMemD) { 16605 ExprResult Sub = Rebuild(LHS); 16606 if (!Sub.isUsable()) 16607 return Sub; 16608 LHS = Sub.get(); 16609 // -- If e is a comma expression, ... 16610 } else if (BO->getOpcode() == BO_Comma) { 16611 ExprResult Sub = Rebuild(RHS); 16612 if (!Sub.isUsable()) 16613 return Sub; 16614 RHS = Sub.get(); 16615 } else { 16616 break; 16617 } 16618 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16619 LHS, RHS); 16620 } 16621 16622 // -- If e has the form (e1)... 16623 case Expr::ParenExprClass: { 16624 auto *PE = cast<ParenExpr>(E); 16625 ExprResult Sub = Rebuild(PE->getSubExpr()); 16626 if (!Sub.isUsable()) 16627 return Sub; 16628 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16629 } 16630 16631 // -- If e is a glvalue conditional expression, ... 16632 // We don't apply this to a binary conditional operator. FIXME: Should we? 16633 case Expr::ConditionalOperatorClass: { 16634 auto *CO = cast<ConditionalOperator>(E); 16635 ExprResult LHS = Rebuild(CO->getLHS()); 16636 if (LHS.isInvalid()) 16637 return ExprError(); 16638 ExprResult RHS = Rebuild(CO->getRHS()); 16639 if (RHS.isInvalid()) 16640 return ExprError(); 16641 if (!LHS.isUsable() && !RHS.isUsable()) 16642 return ExprEmpty(); 16643 if (!LHS.isUsable()) 16644 LHS = CO->getLHS(); 16645 if (!RHS.isUsable()) 16646 RHS = CO->getRHS(); 16647 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16648 CO->getCond(), LHS.get(), RHS.get()); 16649 } 16650 16651 // [Clang extension] 16652 // -- If e has the form __extension__ e1... 16653 case Expr::UnaryOperatorClass: { 16654 auto *UO = cast<UnaryOperator>(E); 16655 if (UO->getOpcode() != UO_Extension) 16656 break; 16657 ExprResult Sub = Rebuild(UO->getSubExpr()); 16658 if (!Sub.isUsable()) 16659 return Sub; 16660 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16661 Sub.get()); 16662 } 16663 16664 // [Clang extension] 16665 // -- If e has the form _Generic(...), the set of potential results is the 16666 // union of the sets of potential results of the associated expressions. 16667 case Expr::GenericSelectionExprClass: { 16668 auto *GSE = cast<GenericSelectionExpr>(E); 16669 16670 SmallVector<Expr *, 4> AssocExprs; 16671 bool AnyChanged = false; 16672 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16673 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16674 if (AssocExpr.isInvalid()) 16675 return ExprError(); 16676 if (AssocExpr.isUsable()) { 16677 AssocExprs.push_back(AssocExpr.get()); 16678 AnyChanged = true; 16679 } else { 16680 AssocExprs.push_back(OrigAssocExpr); 16681 } 16682 } 16683 16684 return AnyChanged ? S.CreateGenericSelectionExpr( 16685 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16686 GSE->getRParenLoc(), GSE->getControllingExpr(), 16687 GSE->getAssocTypeSourceInfos(), AssocExprs) 16688 : ExprEmpty(); 16689 } 16690 16691 // [Clang extension] 16692 // -- If e has the form __builtin_choose_expr(...), the set of potential 16693 // results is the union of the sets of potential results of the 16694 // second and third subexpressions. 16695 case Expr::ChooseExprClass: { 16696 auto *CE = cast<ChooseExpr>(E); 16697 16698 ExprResult LHS = Rebuild(CE->getLHS()); 16699 if (LHS.isInvalid()) 16700 return ExprError(); 16701 16702 ExprResult RHS = Rebuild(CE->getLHS()); 16703 if (RHS.isInvalid()) 16704 return ExprError(); 16705 16706 if (!LHS.get() && !RHS.get()) 16707 return ExprEmpty(); 16708 if (!LHS.isUsable()) 16709 LHS = CE->getLHS(); 16710 if (!RHS.isUsable()) 16711 RHS = CE->getRHS(); 16712 16713 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16714 RHS.get(), CE->getRParenLoc()); 16715 } 16716 16717 // Step through non-syntactic nodes. 16718 case Expr::ConstantExprClass: { 16719 auto *CE = cast<ConstantExpr>(E); 16720 ExprResult Sub = Rebuild(CE->getSubExpr()); 16721 if (!Sub.isUsable()) 16722 return Sub; 16723 return ConstantExpr::Create(S.Context, Sub.get()); 16724 } 16725 16726 // We could mostly rely on the recursive rebuilding to rebuild implicit 16727 // casts, but not at the top level, so rebuild them here. 16728 case Expr::ImplicitCastExprClass: { 16729 auto *ICE = cast<ImplicitCastExpr>(E); 16730 // Only step through the narrow set of cast kinds we expect to encounter. 16731 // Anything else suggests we've left the region in which potential results 16732 // can be found. 16733 switch (ICE->getCastKind()) { 16734 case CK_NoOp: 16735 case CK_DerivedToBase: 16736 case CK_UncheckedDerivedToBase: { 16737 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16738 if (!Sub.isUsable()) 16739 return Sub; 16740 CXXCastPath Path(ICE->path()); 16741 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16742 ICE->getValueKind(), &Path); 16743 } 16744 16745 default: 16746 break; 16747 } 16748 break; 16749 } 16750 16751 default: 16752 break; 16753 } 16754 16755 // Can't traverse through this node. Nothing to do. 16756 return ExprEmpty(); 16757 } 16758 16759 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16760 // Check whether the operand is or contains an object of non-trivial C union 16761 // type. 16762 if (E->getType().isVolatileQualified() && 16763 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16764 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16765 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16766 Sema::NTCUC_LValueToRValueVolatile, 16767 NTCUK_Destruct|NTCUK_Copy); 16768 16769 // C++2a [basic.def.odr]p4: 16770 // [...] an expression of non-volatile-qualified non-class type to which 16771 // the lvalue-to-rvalue conversion is applied [...] 16772 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16773 return E; 16774 16775 ExprResult Result = 16776 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16777 if (Result.isInvalid()) 16778 return ExprError(); 16779 return Result.get() ? Result : E; 16780 } 16781 16782 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16783 Res = CorrectDelayedTyposInExpr(Res); 16784 16785 if (!Res.isUsable()) 16786 return Res; 16787 16788 // If a constant-expression is a reference to a variable where we delay 16789 // deciding whether it is an odr-use, just assume we will apply the 16790 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16791 // (a non-type template argument), we have special handling anyway. 16792 return CheckLValueToRValueConversionOperand(Res.get()); 16793 } 16794 16795 void Sema::CleanupVarDeclMarking() { 16796 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16797 // call. 16798 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16799 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16800 16801 for (Expr *E : LocalMaybeODRUseExprs) { 16802 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16803 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16804 DRE->getLocation(), *this); 16805 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16806 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16807 *this); 16808 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16809 for (VarDecl *VD : *FP) 16810 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16811 } else { 16812 llvm_unreachable("Unexpected expression"); 16813 } 16814 } 16815 16816 assert(MaybeODRUseExprs.empty() && 16817 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16818 } 16819 16820 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16821 VarDecl *Var, Expr *E) { 16822 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16823 isa<FunctionParmPackExpr>(E)) && 16824 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16825 Var->setReferenced(); 16826 16827 if (Var->isInvalidDecl()) 16828 return; 16829 16830 auto *MSI = Var->getMemberSpecializationInfo(); 16831 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16832 : Var->getTemplateSpecializationKind(); 16833 16834 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16835 bool UsableInConstantExpr = 16836 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16837 16838 // C++20 [expr.const]p12: 16839 // A variable [...] is needed for constant evaluation if it is [...] a 16840 // variable whose name appears as a potentially constant evaluated 16841 // expression that is either a contexpr variable or is of non-volatile 16842 // const-qualified integral type or of reference type 16843 bool NeededForConstantEvaluation = 16844 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16845 16846 bool NeedDefinition = 16847 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16848 16849 VarTemplateSpecializationDecl *VarSpec = 16850 dyn_cast<VarTemplateSpecializationDecl>(Var); 16851 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16852 "Can't instantiate a partial template specialization."); 16853 16854 // If this might be a member specialization of a static data member, check 16855 // the specialization is visible. We already did the checks for variable 16856 // template specializations when we created them. 16857 if (NeedDefinition && TSK != TSK_Undeclared && 16858 !isa<VarTemplateSpecializationDecl>(Var)) 16859 SemaRef.checkSpecializationVisibility(Loc, Var); 16860 16861 // Perform implicit instantiation of static data members, static data member 16862 // templates of class templates, and variable template specializations. Delay 16863 // instantiations of variable templates, except for those that could be used 16864 // in a constant expression. 16865 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16866 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16867 // instantiation declaration if a variable is usable in a constant 16868 // expression (among other cases). 16869 bool TryInstantiating = 16870 TSK == TSK_ImplicitInstantiation || 16871 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16872 16873 if (TryInstantiating) { 16874 SourceLocation PointOfInstantiation = 16875 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16876 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16877 if (FirstInstantiation) { 16878 PointOfInstantiation = Loc; 16879 if (MSI) 16880 MSI->setPointOfInstantiation(PointOfInstantiation); 16881 else 16882 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16883 } 16884 16885 bool InstantiationDependent = false; 16886 bool IsNonDependent = 16887 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16888 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16889 : true; 16890 16891 // Do not instantiate specializations that are still type-dependent. 16892 if (IsNonDependent) { 16893 if (UsableInConstantExpr) { 16894 // Do not defer instantiations of variables that could be used in a 16895 // constant expression. 16896 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16897 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16898 }); 16899 } else if (FirstInstantiation || 16900 isa<VarTemplateSpecializationDecl>(Var)) { 16901 // FIXME: For a specialization of a variable template, we don't 16902 // distinguish between "declaration and type implicitly instantiated" 16903 // and "implicit instantiation of definition requested", so we have 16904 // no direct way to avoid enqueueing the pending instantiation 16905 // multiple times. 16906 SemaRef.PendingInstantiations 16907 .push_back(std::make_pair(Var, PointOfInstantiation)); 16908 } 16909 } 16910 } 16911 } 16912 16913 // C++2a [basic.def.odr]p4: 16914 // A variable x whose name appears as a potentially-evaluated expression e 16915 // is odr-used by e unless 16916 // -- x is a reference that is usable in constant expressions 16917 // -- x is a variable of non-reference type that is usable in constant 16918 // expressions and has no mutable subobjects [FIXME], and e is an 16919 // element of the set of potential results of an expression of 16920 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16921 // conversion is applied 16922 // -- x is a variable of non-reference type, and e is an element of the set 16923 // of potential results of a discarded-value expression to which the 16924 // lvalue-to-rvalue conversion is not applied [FIXME] 16925 // 16926 // We check the first part of the second bullet here, and 16927 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16928 // FIXME: To get the third bullet right, we need to delay this even for 16929 // variables that are not usable in constant expressions. 16930 16931 // If we already know this isn't an odr-use, there's nothing more to do. 16932 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16933 if (DRE->isNonOdrUse()) 16934 return; 16935 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16936 if (ME->isNonOdrUse()) 16937 return; 16938 16939 switch (OdrUse) { 16940 case OdrUseContext::None: 16941 assert((!E || isa<FunctionParmPackExpr>(E)) && 16942 "missing non-odr-use marking for unevaluated decl ref"); 16943 break; 16944 16945 case OdrUseContext::FormallyOdrUsed: 16946 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16947 // behavior. 16948 break; 16949 16950 case OdrUseContext::Used: 16951 // If we might later find that this expression isn't actually an odr-use, 16952 // delay the marking. 16953 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16954 SemaRef.MaybeODRUseExprs.insert(E); 16955 else 16956 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16957 break; 16958 16959 case OdrUseContext::Dependent: 16960 // If this is a dependent context, we don't need to mark variables as 16961 // odr-used, but we may still need to track them for lambda capture. 16962 // FIXME: Do we also need to do this inside dependent typeid expressions 16963 // (which are modeled as unevaluated at this point)? 16964 const bool RefersToEnclosingScope = 16965 (SemaRef.CurContext != Var->getDeclContext() && 16966 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16967 if (RefersToEnclosingScope) { 16968 LambdaScopeInfo *const LSI = 16969 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16970 if (LSI && (!LSI->CallOperator || 16971 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16972 // If a variable could potentially be odr-used, defer marking it so 16973 // until we finish analyzing the full expression for any 16974 // lvalue-to-rvalue 16975 // or discarded value conversions that would obviate odr-use. 16976 // Add it to the list of potential captures that will be analyzed 16977 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16978 // unless the variable is a reference that was initialized by a constant 16979 // expression (this will never need to be captured or odr-used). 16980 // 16981 // FIXME: We can simplify this a lot after implementing P0588R1. 16982 assert(E && "Capture variable should be used in an expression."); 16983 if (!Var->getType()->isReferenceType() || 16984 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16985 LSI->addPotentialCapture(E->IgnoreParens()); 16986 } 16987 } 16988 break; 16989 } 16990 } 16991 16992 /// Mark a variable referenced, and check whether it is odr-used 16993 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16994 /// used directly for normal expressions referring to VarDecl. 16995 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16996 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16997 } 16998 16999 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17000 Decl *D, Expr *E, bool MightBeOdrUse) { 17001 if (SemaRef.isInOpenMPDeclareTargetContext()) 17002 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17003 17004 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17005 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17006 return; 17007 } 17008 17009 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17010 17011 // If this is a call to a method via a cast, also mark the method in the 17012 // derived class used in case codegen can devirtualize the call. 17013 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17014 if (!ME) 17015 return; 17016 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17017 if (!MD) 17018 return; 17019 // Only attempt to devirtualize if this is truly a virtual call. 17020 bool IsVirtualCall = MD->isVirtual() && 17021 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17022 if (!IsVirtualCall) 17023 return; 17024 17025 // If it's possible to devirtualize the call, mark the called function 17026 // referenced. 17027 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17028 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17029 if (DM) 17030 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17031 } 17032 17033 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17034 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17035 // TODO: update this with DR# once a defect report is filed. 17036 // C++11 defect. The address of a pure member should not be an ODR use, even 17037 // if it's a qualified reference. 17038 bool OdrUse = true; 17039 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17040 if (Method->isVirtual() && 17041 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17042 OdrUse = false; 17043 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17044 } 17045 17046 /// Perform reference-marking and odr-use handling for a MemberExpr. 17047 void Sema::MarkMemberReferenced(MemberExpr *E) { 17048 // C++11 [basic.def.odr]p2: 17049 // A non-overloaded function whose name appears as a potentially-evaluated 17050 // expression or a member of a set of candidate functions, if selected by 17051 // overload resolution when referred to from a potentially-evaluated 17052 // expression, is odr-used, unless it is a pure virtual function and its 17053 // name is not explicitly qualified. 17054 bool MightBeOdrUse = true; 17055 if (E->performsVirtualDispatch(getLangOpts())) { 17056 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17057 if (Method->isPure()) 17058 MightBeOdrUse = false; 17059 } 17060 SourceLocation Loc = 17061 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17062 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17063 } 17064 17065 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17066 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17067 for (VarDecl *VD : *E) 17068 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17069 } 17070 17071 /// Perform marking for a reference to an arbitrary declaration. It 17072 /// marks the declaration referenced, and performs odr-use checking for 17073 /// functions and variables. This method should not be used when building a 17074 /// normal expression which refers to a variable. 17075 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17076 bool MightBeOdrUse) { 17077 if (MightBeOdrUse) { 17078 if (auto *VD = dyn_cast<VarDecl>(D)) { 17079 MarkVariableReferenced(Loc, VD); 17080 return; 17081 } 17082 } 17083 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17084 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17085 return; 17086 } 17087 D->setReferenced(); 17088 } 17089 17090 namespace { 17091 // Mark all of the declarations used by a type as referenced. 17092 // FIXME: Not fully implemented yet! We need to have a better understanding 17093 // of when we're entering a context we should not recurse into. 17094 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17095 // TreeTransforms rebuilding the type in a new context. Rather than 17096 // duplicating the TreeTransform logic, we should consider reusing it here. 17097 // Currently that causes problems when rebuilding LambdaExprs. 17098 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17099 Sema &S; 17100 SourceLocation Loc; 17101 17102 public: 17103 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17104 17105 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17106 17107 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17108 }; 17109 } 17110 17111 bool MarkReferencedDecls::TraverseTemplateArgument( 17112 const TemplateArgument &Arg) { 17113 { 17114 // A non-type template argument is a constant-evaluated context. 17115 EnterExpressionEvaluationContext Evaluated( 17116 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17117 if (Arg.getKind() == TemplateArgument::Declaration) { 17118 if (Decl *D = Arg.getAsDecl()) 17119 S.MarkAnyDeclReferenced(Loc, D, true); 17120 } else if (Arg.getKind() == TemplateArgument::Expression) { 17121 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17122 } 17123 } 17124 17125 return Inherited::TraverseTemplateArgument(Arg); 17126 } 17127 17128 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17129 MarkReferencedDecls Marker(*this, Loc); 17130 Marker.TraverseType(T); 17131 } 17132 17133 namespace { 17134 /// Helper class that marks all of the declarations referenced by 17135 /// potentially-evaluated subexpressions as "referenced". 17136 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17137 Sema &S; 17138 bool SkipLocalVariables; 17139 17140 public: 17141 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17142 17143 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17144 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17145 17146 void VisitDeclRefExpr(DeclRefExpr *E) { 17147 // If we were asked not to visit local variables, don't. 17148 if (SkipLocalVariables) { 17149 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17150 if (VD->hasLocalStorage()) 17151 return; 17152 } 17153 17154 S.MarkDeclRefReferenced(E); 17155 } 17156 17157 void VisitMemberExpr(MemberExpr *E) { 17158 S.MarkMemberReferenced(E); 17159 Inherited::VisitMemberExpr(E); 17160 } 17161 17162 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17163 S.MarkFunctionReferenced( 17164 E->getBeginLoc(), 17165 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17166 Visit(E->getSubExpr()); 17167 } 17168 17169 void VisitCXXNewExpr(CXXNewExpr *E) { 17170 if (E->getOperatorNew()) 17171 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17172 if (E->getOperatorDelete()) 17173 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17174 Inherited::VisitCXXNewExpr(E); 17175 } 17176 17177 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17178 if (E->getOperatorDelete()) 17179 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17180 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17181 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17182 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17183 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17184 } 17185 17186 Inherited::VisitCXXDeleteExpr(E); 17187 } 17188 17189 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17190 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17191 Inherited::VisitCXXConstructExpr(E); 17192 } 17193 17194 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17195 Visit(E->getExpr()); 17196 } 17197 }; 17198 } 17199 17200 /// Mark any declarations that appear within this expression or any 17201 /// potentially-evaluated subexpressions as "referenced". 17202 /// 17203 /// \param SkipLocalVariables If true, don't mark local variables as 17204 /// 'referenced'. 17205 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17206 bool SkipLocalVariables) { 17207 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17208 } 17209 17210 /// Emit a diagnostic that describes an effect on the run-time behavior 17211 /// of the program being compiled. 17212 /// 17213 /// This routine emits the given diagnostic when the code currently being 17214 /// type-checked is "potentially evaluated", meaning that there is a 17215 /// possibility that the code will actually be executable. Code in sizeof() 17216 /// expressions, code used only during overload resolution, etc., are not 17217 /// potentially evaluated. This routine will suppress such diagnostics or, 17218 /// in the absolutely nutty case of potentially potentially evaluated 17219 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17220 /// later. 17221 /// 17222 /// This routine should be used for all diagnostics that describe the run-time 17223 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17224 /// Failure to do so will likely result in spurious diagnostics or failures 17225 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17226 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17227 const PartialDiagnostic &PD) { 17228 switch (ExprEvalContexts.back().Context) { 17229 case ExpressionEvaluationContext::Unevaluated: 17230 case ExpressionEvaluationContext::UnevaluatedList: 17231 case ExpressionEvaluationContext::UnevaluatedAbstract: 17232 case ExpressionEvaluationContext::DiscardedStatement: 17233 // The argument will never be evaluated, so don't complain. 17234 break; 17235 17236 case ExpressionEvaluationContext::ConstantEvaluated: 17237 // Relevant diagnostics should be produced by constant evaluation. 17238 break; 17239 17240 case ExpressionEvaluationContext::PotentiallyEvaluated: 17241 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17242 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17243 FunctionScopes.back()->PossiblyUnreachableDiags. 17244 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17245 return true; 17246 } 17247 17248 // The initializer of a constexpr variable or of the first declaration of a 17249 // static data member is not syntactically a constant evaluated constant, 17250 // but nonetheless is always required to be a constant expression, so we 17251 // can skip diagnosing. 17252 // FIXME: Using the mangling context here is a hack. 17253 if (auto *VD = dyn_cast_or_null<VarDecl>( 17254 ExprEvalContexts.back().ManglingContextDecl)) { 17255 if (VD->isConstexpr() || 17256 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17257 break; 17258 // FIXME: For any other kind of variable, we should build a CFG for its 17259 // initializer and check whether the context in question is reachable. 17260 } 17261 17262 Diag(Loc, PD); 17263 return true; 17264 } 17265 17266 return false; 17267 } 17268 17269 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17270 const PartialDiagnostic &PD) { 17271 return DiagRuntimeBehavior( 17272 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17273 } 17274 17275 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17276 CallExpr *CE, FunctionDecl *FD) { 17277 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17278 return false; 17279 17280 // If we're inside a decltype's expression, don't check for a valid return 17281 // type or construct temporaries until we know whether this is the last call. 17282 if (ExprEvalContexts.back().ExprContext == 17283 ExpressionEvaluationContextRecord::EK_Decltype) { 17284 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17285 return false; 17286 } 17287 17288 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17289 FunctionDecl *FD; 17290 CallExpr *CE; 17291 17292 public: 17293 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17294 : FD(FD), CE(CE) { } 17295 17296 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17297 if (!FD) { 17298 S.Diag(Loc, diag::err_call_incomplete_return) 17299 << T << CE->getSourceRange(); 17300 return; 17301 } 17302 17303 S.Diag(Loc, diag::err_call_function_incomplete_return) 17304 << CE->getSourceRange() << FD->getDeclName() << T; 17305 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17306 << FD->getDeclName(); 17307 } 17308 } Diagnoser(FD, CE); 17309 17310 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17311 return true; 17312 17313 return false; 17314 } 17315 17316 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17317 // will prevent this condition from triggering, which is what we want. 17318 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17319 SourceLocation Loc; 17320 17321 unsigned diagnostic = diag::warn_condition_is_assignment; 17322 bool IsOrAssign = false; 17323 17324 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17325 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17326 return; 17327 17328 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17329 17330 // Greylist some idioms by putting them into a warning subcategory. 17331 if (ObjCMessageExpr *ME 17332 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17333 Selector Sel = ME->getSelector(); 17334 17335 // self = [<foo> init...] 17336 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17337 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17338 17339 // <foo> = [<bar> nextObject] 17340 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17341 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17342 } 17343 17344 Loc = Op->getOperatorLoc(); 17345 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17346 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17347 return; 17348 17349 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17350 Loc = Op->getOperatorLoc(); 17351 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17352 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17353 else { 17354 // Not an assignment. 17355 return; 17356 } 17357 17358 Diag(Loc, diagnostic) << E->getSourceRange(); 17359 17360 SourceLocation Open = E->getBeginLoc(); 17361 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17362 Diag(Loc, diag::note_condition_assign_silence) 17363 << FixItHint::CreateInsertion(Open, "(") 17364 << FixItHint::CreateInsertion(Close, ")"); 17365 17366 if (IsOrAssign) 17367 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17368 << FixItHint::CreateReplacement(Loc, "!="); 17369 else 17370 Diag(Loc, diag::note_condition_assign_to_comparison) 17371 << FixItHint::CreateReplacement(Loc, "=="); 17372 } 17373 17374 /// Redundant parentheses over an equality comparison can indicate 17375 /// that the user intended an assignment used as condition. 17376 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17377 // Don't warn if the parens came from a macro. 17378 SourceLocation parenLoc = ParenE->getBeginLoc(); 17379 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17380 return; 17381 // Don't warn for dependent expressions. 17382 if (ParenE->isTypeDependent()) 17383 return; 17384 17385 Expr *E = ParenE->IgnoreParens(); 17386 17387 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17388 if (opE->getOpcode() == BO_EQ && 17389 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17390 == Expr::MLV_Valid) { 17391 SourceLocation Loc = opE->getOperatorLoc(); 17392 17393 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17394 SourceRange ParenERange = ParenE->getSourceRange(); 17395 Diag(Loc, diag::note_equality_comparison_silence) 17396 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17397 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17398 Diag(Loc, diag::note_equality_comparison_to_assign) 17399 << FixItHint::CreateReplacement(Loc, "="); 17400 } 17401 } 17402 17403 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17404 bool IsConstexpr) { 17405 DiagnoseAssignmentAsCondition(E); 17406 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17407 DiagnoseEqualityWithExtraParens(parenE); 17408 17409 ExprResult result = CheckPlaceholderExpr(E); 17410 if (result.isInvalid()) return ExprError(); 17411 E = result.get(); 17412 17413 if (!E->isTypeDependent()) { 17414 if (getLangOpts().CPlusPlus) 17415 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17416 17417 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17418 if (ERes.isInvalid()) 17419 return ExprError(); 17420 E = ERes.get(); 17421 17422 QualType T = E->getType(); 17423 if (!T->isScalarType()) { // C99 6.8.4.1p1 17424 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17425 << T << E->getSourceRange(); 17426 return ExprError(); 17427 } 17428 CheckBoolLikeConversion(E, Loc); 17429 } 17430 17431 return E; 17432 } 17433 17434 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17435 Expr *SubExpr, ConditionKind CK) { 17436 // Empty conditions are valid in for-statements. 17437 if (!SubExpr) 17438 return ConditionResult(); 17439 17440 ExprResult Cond; 17441 switch (CK) { 17442 case ConditionKind::Boolean: 17443 Cond = CheckBooleanCondition(Loc, SubExpr); 17444 break; 17445 17446 case ConditionKind::ConstexprIf: 17447 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17448 break; 17449 17450 case ConditionKind::Switch: 17451 Cond = CheckSwitchCondition(Loc, SubExpr); 17452 break; 17453 } 17454 if (Cond.isInvalid()) 17455 return ConditionError(); 17456 17457 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17458 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17459 if (!FullExpr.get()) 17460 return ConditionError(); 17461 17462 return ConditionResult(*this, nullptr, FullExpr, 17463 CK == ConditionKind::ConstexprIf); 17464 } 17465 17466 namespace { 17467 /// A visitor for rebuilding a call to an __unknown_any expression 17468 /// to have an appropriate type. 17469 struct RebuildUnknownAnyFunction 17470 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17471 17472 Sema &S; 17473 17474 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17475 17476 ExprResult VisitStmt(Stmt *S) { 17477 llvm_unreachable("unexpected statement!"); 17478 } 17479 17480 ExprResult VisitExpr(Expr *E) { 17481 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17482 << E->getSourceRange(); 17483 return ExprError(); 17484 } 17485 17486 /// Rebuild an expression which simply semantically wraps another 17487 /// expression which it shares the type and value kind of. 17488 template <class T> ExprResult rebuildSugarExpr(T *E) { 17489 ExprResult SubResult = Visit(E->getSubExpr()); 17490 if (SubResult.isInvalid()) return ExprError(); 17491 17492 Expr *SubExpr = SubResult.get(); 17493 E->setSubExpr(SubExpr); 17494 E->setType(SubExpr->getType()); 17495 E->setValueKind(SubExpr->getValueKind()); 17496 assert(E->getObjectKind() == OK_Ordinary); 17497 return E; 17498 } 17499 17500 ExprResult VisitParenExpr(ParenExpr *E) { 17501 return rebuildSugarExpr(E); 17502 } 17503 17504 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17505 return rebuildSugarExpr(E); 17506 } 17507 17508 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17509 ExprResult SubResult = Visit(E->getSubExpr()); 17510 if (SubResult.isInvalid()) return ExprError(); 17511 17512 Expr *SubExpr = SubResult.get(); 17513 E->setSubExpr(SubExpr); 17514 E->setType(S.Context.getPointerType(SubExpr->getType())); 17515 assert(E->getValueKind() == VK_RValue); 17516 assert(E->getObjectKind() == OK_Ordinary); 17517 return E; 17518 } 17519 17520 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17521 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17522 17523 E->setType(VD->getType()); 17524 17525 assert(E->getValueKind() == VK_RValue); 17526 if (S.getLangOpts().CPlusPlus && 17527 !(isa<CXXMethodDecl>(VD) && 17528 cast<CXXMethodDecl>(VD)->isInstance())) 17529 E->setValueKind(VK_LValue); 17530 17531 return E; 17532 } 17533 17534 ExprResult VisitMemberExpr(MemberExpr *E) { 17535 return resolveDecl(E, E->getMemberDecl()); 17536 } 17537 17538 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17539 return resolveDecl(E, E->getDecl()); 17540 } 17541 }; 17542 } 17543 17544 /// Given a function expression of unknown-any type, try to rebuild it 17545 /// to have a function type. 17546 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17547 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17548 if (Result.isInvalid()) return ExprError(); 17549 return S.DefaultFunctionArrayConversion(Result.get()); 17550 } 17551 17552 namespace { 17553 /// A visitor for rebuilding an expression of type __unknown_anytype 17554 /// into one which resolves the type directly on the referring 17555 /// expression. Strict preservation of the original source 17556 /// structure is not a goal. 17557 struct RebuildUnknownAnyExpr 17558 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17559 17560 Sema &S; 17561 17562 /// The current destination type. 17563 QualType DestType; 17564 17565 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17566 : S(S), DestType(CastType) {} 17567 17568 ExprResult VisitStmt(Stmt *S) { 17569 llvm_unreachable("unexpected statement!"); 17570 } 17571 17572 ExprResult VisitExpr(Expr *E) { 17573 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17574 << E->getSourceRange(); 17575 return ExprError(); 17576 } 17577 17578 ExprResult VisitCallExpr(CallExpr *E); 17579 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17580 17581 /// Rebuild an expression which simply semantically wraps another 17582 /// expression which it shares the type and value kind of. 17583 template <class T> ExprResult rebuildSugarExpr(T *E) { 17584 ExprResult SubResult = Visit(E->getSubExpr()); 17585 if (SubResult.isInvalid()) return ExprError(); 17586 Expr *SubExpr = SubResult.get(); 17587 E->setSubExpr(SubExpr); 17588 E->setType(SubExpr->getType()); 17589 E->setValueKind(SubExpr->getValueKind()); 17590 assert(E->getObjectKind() == OK_Ordinary); 17591 return E; 17592 } 17593 17594 ExprResult VisitParenExpr(ParenExpr *E) { 17595 return rebuildSugarExpr(E); 17596 } 17597 17598 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17599 return rebuildSugarExpr(E); 17600 } 17601 17602 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17603 const PointerType *Ptr = DestType->getAs<PointerType>(); 17604 if (!Ptr) { 17605 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17606 << E->getSourceRange(); 17607 return ExprError(); 17608 } 17609 17610 if (isa<CallExpr>(E->getSubExpr())) { 17611 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17612 << E->getSourceRange(); 17613 return ExprError(); 17614 } 17615 17616 assert(E->getValueKind() == VK_RValue); 17617 assert(E->getObjectKind() == OK_Ordinary); 17618 E->setType(DestType); 17619 17620 // Build the sub-expression as if it were an object of the pointee type. 17621 DestType = Ptr->getPointeeType(); 17622 ExprResult SubResult = Visit(E->getSubExpr()); 17623 if (SubResult.isInvalid()) return ExprError(); 17624 E->setSubExpr(SubResult.get()); 17625 return E; 17626 } 17627 17628 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17629 17630 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17631 17632 ExprResult VisitMemberExpr(MemberExpr *E) { 17633 return resolveDecl(E, E->getMemberDecl()); 17634 } 17635 17636 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17637 return resolveDecl(E, E->getDecl()); 17638 } 17639 }; 17640 } 17641 17642 /// Rebuilds a call expression which yielded __unknown_anytype. 17643 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17644 Expr *CalleeExpr = E->getCallee(); 17645 17646 enum FnKind { 17647 FK_MemberFunction, 17648 FK_FunctionPointer, 17649 FK_BlockPointer 17650 }; 17651 17652 FnKind Kind; 17653 QualType CalleeType = CalleeExpr->getType(); 17654 if (CalleeType == S.Context.BoundMemberTy) { 17655 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17656 Kind = FK_MemberFunction; 17657 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17658 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17659 CalleeType = Ptr->getPointeeType(); 17660 Kind = FK_FunctionPointer; 17661 } else { 17662 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17663 Kind = FK_BlockPointer; 17664 } 17665 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17666 17667 // Verify that this is a legal result type of a function. 17668 if (DestType->isArrayType() || DestType->isFunctionType()) { 17669 unsigned diagID = diag::err_func_returning_array_function; 17670 if (Kind == FK_BlockPointer) 17671 diagID = diag::err_block_returning_array_function; 17672 17673 S.Diag(E->getExprLoc(), diagID) 17674 << DestType->isFunctionType() << DestType; 17675 return ExprError(); 17676 } 17677 17678 // Otherwise, go ahead and set DestType as the call's result. 17679 E->setType(DestType.getNonLValueExprType(S.Context)); 17680 E->setValueKind(Expr::getValueKindForType(DestType)); 17681 assert(E->getObjectKind() == OK_Ordinary); 17682 17683 // Rebuild the function type, replacing the result type with DestType. 17684 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17685 if (Proto) { 17686 // __unknown_anytype(...) is a special case used by the debugger when 17687 // it has no idea what a function's signature is. 17688 // 17689 // We want to build this call essentially under the K&R 17690 // unprototyped rules, but making a FunctionNoProtoType in C++ 17691 // would foul up all sorts of assumptions. However, we cannot 17692 // simply pass all arguments as variadic arguments, nor can we 17693 // portably just call the function under a non-variadic type; see 17694 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17695 // However, it turns out that in practice it is generally safe to 17696 // call a function declared as "A foo(B,C,D);" under the prototype 17697 // "A foo(B,C,D,...);". The only known exception is with the 17698 // Windows ABI, where any variadic function is implicitly cdecl 17699 // regardless of its normal CC. Therefore we change the parameter 17700 // types to match the types of the arguments. 17701 // 17702 // This is a hack, but it is far superior to moving the 17703 // corresponding target-specific code from IR-gen to Sema/AST. 17704 17705 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17706 SmallVector<QualType, 8> ArgTypes; 17707 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17708 ArgTypes.reserve(E->getNumArgs()); 17709 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17710 Expr *Arg = E->getArg(i); 17711 QualType ArgType = Arg->getType(); 17712 if (E->isLValue()) { 17713 ArgType = S.Context.getLValueReferenceType(ArgType); 17714 } else if (E->isXValue()) { 17715 ArgType = S.Context.getRValueReferenceType(ArgType); 17716 } 17717 ArgTypes.push_back(ArgType); 17718 } 17719 ParamTypes = ArgTypes; 17720 } 17721 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17722 Proto->getExtProtoInfo()); 17723 } else { 17724 DestType = S.Context.getFunctionNoProtoType(DestType, 17725 FnType->getExtInfo()); 17726 } 17727 17728 // Rebuild the appropriate pointer-to-function type. 17729 switch (Kind) { 17730 case FK_MemberFunction: 17731 // Nothing to do. 17732 break; 17733 17734 case FK_FunctionPointer: 17735 DestType = S.Context.getPointerType(DestType); 17736 break; 17737 17738 case FK_BlockPointer: 17739 DestType = S.Context.getBlockPointerType(DestType); 17740 break; 17741 } 17742 17743 // Finally, we can recurse. 17744 ExprResult CalleeResult = Visit(CalleeExpr); 17745 if (!CalleeResult.isUsable()) return ExprError(); 17746 E->setCallee(CalleeResult.get()); 17747 17748 // Bind a temporary if necessary. 17749 return S.MaybeBindToTemporary(E); 17750 } 17751 17752 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17753 // Verify that this is a legal result type of a call. 17754 if (DestType->isArrayType() || DestType->isFunctionType()) { 17755 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17756 << DestType->isFunctionType() << DestType; 17757 return ExprError(); 17758 } 17759 17760 // Rewrite the method result type if available. 17761 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17762 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17763 Method->setReturnType(DestType); 17764 } 17765 17766 // Change the type of the message. 17767 E->setType(DestType.getNonReferenceType()); 17768 E->setValueKind(Expr::getValueKindForType(DestType)); 17769 17770 return S.MaybeBindToTemporary(E); 17771 } 17772 17773 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17774 // The only case we should ever see here is a function-to-pointer decay. 17775 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17776 assert(E->getValueKind() == VK_RValue); 17777 assert(E->getObjectKind() == OK_Ordinary); 17778 17779 E->setType(DestType); 17780 17781 // Rebuild the sub-expression as the pointee (function) type. 17782 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17783 17784 ExprResult Result = Visit(E->getSubExpr()); 17785 if (!Result.isUsable()) return ExprError(); 17786 17787 E->setSubExpr(Result.get()); 17788 return E; 17789 } else if (E->getCastKind() == CK_LValueToRValue) { 17790 assert(E->getValueKind() == VK_RValue); 17791 assert(E->getObjectKind() == OK_Ordinary); 17792 17793 assert(isa<BlockPointerType>(E->getType())); 17794 17795 E->setType(DestType); 17796 17797 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17798 DestType = S.Context.getLValueReferenceType(DestType); 17799 17800 ExprResult Result = Visit(E->getSubExpr()); 17801 if (!Result.isUsable()) return ExprError(); 17802 17803 E->setSubExpr(Result.get()); 17804 return E; 17805 } else { 17806 llvm_unreachable("Unhandled cast type!"); 17807 } 17808 } 17809 17810 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17811 ExprValueKind ValueKind = VK_LValue; 17812 QualType Type = DestType; 17813 17814 // We know how to make this work for certain kinds of decls: 17815 17816 // - functions 17817 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17818 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17819 DestType = Ptr->getPointeeType(); 17820 ExprResult Result = resolveDecl(E, VD); 17821 if (Result.isInvalid()) return ExprError(); 17822 return S.ImpCastExprToType(Result.get(), Type, 17823 CK_FunctionToPointerDecay, VK_RValue); 17824 } 17825 17826 if (!Type->isFunctionType()) { 17827 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17828 << VD << E->getSourceRange(); 17829 return ExprError(); 17830 } 17831 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17832 // We must match the FunctionDecl's type to the hack introduced in 17833 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17834 // type. See the lengthy commentary in that routine. 17835 QualType FDT = FD->getType(); 17836 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17837 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17838 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17839 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17840 SourceLocation Loc = FD->getLocation(); 17841 FunctionDecl *NewFD = FunctionDecl::Create( 17842 S.Context, FD->getDeclContext(), Loc, Loc, 17843 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17844 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17845 /*ConstexprKind*/ CSK_unspecified); 17846 17847 if (FD->getQualifier()) 17848 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17849 17850 SmallVector<ParmVarDecl*, 16> Params; 17851 for (const auto &AI : FT->param_types()) { 17852 ParmVarDecl *Param = 17853 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17854 Param->setScopeInfo(0, Params.size()); 17855 Params.push_back(Param); 17856 } 17857 NewFD->setParams(Params); 17858 DRE->setDecl(NewFD); 17859 VD = DRE->getDecl(); 17860 } 17861 } 17862 17863 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17864 if (MD->isInstance()) { 17865 ValueKind = VK_RValue; 17866 Type = S.Context.BoundMemberTy; 17867 } 17868 17869 // Function references aren't l-values in C. 17870 if (!S.getLangOpts().CPlusPlus) 17871 ValueKind = VK_RValue; 17872 17873 // - variables 17874 } else if (isa<VarDecl>(VD)) { 17875 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17876 Type = RefTy->getPointeeType(); 17877 } else if (Type->isFunctionType()) { 17878 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17879 << VD << E->getSourceRange(); 17880 return ExprError(); 17881 } 17882 17883 // - nothing else 17884 } else { 17885 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17886 << VD << E->getSourceRange(); 17887 return ExprError(); 17888 } 17889 17890 // Modifying the declaration like this is friendly to IR-gen but 17891 // also really dangerous. 17892 VD->setType(DestType); 17893 E->setType(Type); 17894 E->setValueKind(ValueKind); 17895 return E; 17896 } 17897 17898 /// Check a cast of an unknown-any type. We intentionally only 17899 /// trigger this for C-style casts. 17900 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17901 Expr *CastExpr, CastKind &CastKind, 17902 ExprValueKind &VK, CXXCastPath &Path) { 17903 // The type we're casting to must be either void or complete. 17904 if (!CastType->isVoidType() && 17905 RequireCompleteType(TypeRange.getBegin(), CastType, 17906 diag::err_typecheck_cast_to_incomplete)) 17907 return ExprError(); 17908 17909 // Rewrite the casted expression from scratch. 17910 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17911 if (!result.isUsable()) return ExprError(); 17912 17913 CastExpr = result.get(); 17914 VK = CastExpr->getValueKind(); 17915 CastKind = CK_NoOp; 17916 17917 return CastExpr; 17918 } 17919 17920 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17921 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17922 } 17923 17924 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17925 Expr *arg, QualType ¶mType) { 17926 // If the syntactic form of the argument is not an explicit cast of 17927 // any sort, just do default argument promotion. 17928 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17929 if (!castArg) { 17930 ExprResult result = DefaultArgumentPromotion(arg); 17931 if (result.isInvalid()) return ExprError(); 17932 paramType = result.get()->getType(); 17933 return result; 17934 } 17935 17936 // Otherwise, use the type that was written in the explicit cast. 17937 assert(!arg->hasPlaceholderType()); 17938 paramType = castArg->getTypeAsWritten(); 17939 17940 // Copy-initialize a parameter of that type. 17941 InitializedEntity entity = 17942 InitializedEntity::InitializeParameter(Context, paramType, 17943 /*consumed*/ false); 17944 return PerformCopyInitialization(entity, callLoc, arg); 17945 } 17946 17947 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17948 Expr *orig = E; 17949 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17950 while (true) { 17951 E = E->IgnoreParenImpCasts(); 17952 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17953 E = call->getCallee(); 17954 diagID = diag::err_uncasted_call_of_unknown_any; 17955 } else { 17956 break; 17957 } 17958 } 17959 17960 SourceLocation loc; 17961 NamedDecl *d; 17962 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17963 loc = ref->getLocation(); 17964 d = ref->getDecl(); 17965 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17966 loc = mem->getMemberLoc(); 17967 d = mem->getMemberDecl(); 17968 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17969 diagID = diag::err_uncasted_call_of_unknown_any; 17970 loc = msg->getSelectorStartLoc(); 17971 d = msg->getMethodDecl(); 17972 if (!d) { 17973 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17974 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17975 << orig->getSourceRange(); 17976 return ExprError(); 17977 } 17978 } else { 17979 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17980 << E->getSourceRange(); 17981 return ExprError(); 17982 } 17983 17984 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17985 17986 // Never recoverable. 17987 return ExprError(); 17988 } 17989 17990 /// Check for operands with placeholder types and complain if found. 17991 /// Returns ExprError() if there was an error and no recovery was possible. 17992 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17993 if (!getLangOpts().CPlusPlus) { 17994 // C cannot handle TypoExpr nodes on either side of a binop because it 17995 // doesn't handle dependent types properly, so make sure any TypoExprs have 17996 // been dealt with before checking the operands. 17997 ExprResult Result = CorrectDelayedTyposInExpr(E); 17998 if (!Result.isUsable()) return ExprError(); 17999 E = Result.get(); 18000 } 18001 18002 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18003 if (!placeholderType) return E; 18004 18005 switch (placeholderType->getKind()) { 18006 18007 // Overloaded expressions. 18008 case BuiltinType::Overload: { 18009 // Try to resolve a single function template specialization. 18010 // This is obligatory. 18011 ExprResult Result = E; 18012 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18013 return Result; 18014 18015 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18016 // leaves Result unchanged on failure. 18017 Result = E; 18018 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18019 return Result; 18020 18021 // If that failed, try to recover with a call. 18022 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18023 /*complain*/ true); 18024 return Result; 18025 } 18026 18027 // Bound member functions. 18028 case BuiltinType::BoundMember: { 18029 ExprResult result = E; 18030 const Expr *BME = E->IgnoreParens(); 18031 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18032 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18033 if (isa<CXXPseudoDestructorExpr>(BME)) { 18034 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18035 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18036 if (ME->getMemberNameInfo().getName().getNameKind() == 18037 DeclarationName::CXXDestructorName) 18038 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18039 } 18040 tryToRecoverWithCall(result, PD, 18041 /*complain*/ true); 18042 return result; 18043 } 18044 18045 // ARC unbridged casts. 18046 case BuiltinType::ARCUnbridgedCast: { 18047 Expr *realCast = stripARCUnbridgedCast(E); 18048 diagnoseARCUnbridgedCast(realCast); 18049 return realCast; 18050 } 18051 18052 // Expressions of unknown type. 18053 case BuiltinType::UnknownAny: 18054 return diagnoseUnknownAnyExpr(*this, E); 18055 18056 // Pseudo-objects. 18057 case BuiltinType::PseudoObject: 18058 return checkPseudoObjectRValue(E); 18059 18060 case BuiltinType::BuiltinFn: { 18061 // Accept __noop without parens by implicitly converting it to a call expr. 18062 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18063 if (DRE) { 18064 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18065 if (FD->getBuiltinID() == Builtin::BI__noop) { 18066 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18067 CK_BuiltinFnToFnPtr) 18068 .get(); 18069 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18070 VK_RValue, SourceLocation()); 18071 } 18072 } 18073 18074 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18075 return ExprError(); 18076 } 18077 18078 // Expressions of unknown type. 18079 case BuiltinType::OMPArraySection: 18080 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18081 return ExprError(); 18082 18083 // Everything else should be impossible. 18084 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18085 case BuiltinType::Id: 18086 #include "clang/Basic/OpenCLImageTypes.def" 18087 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18088 case BuiltinType::Id: 18089 #include "clang/Basic/OpenCLExtensionTypes.def" 18090 #define SVE_TYPE(Name, Id, SingletonId) \ 18091 case BuiltinType::Id: 18092 #include "clang/Basic/AArch64SVEACLETypes.def" 18093 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18094 #define PLACEHOLDER_TYPE(Id, SingletonId) 18095 #include "clang/AST/BuiltinTypes.def" 18096 break; 18097 } 18098 18099 llvm_unreachable("invalid placeholder type!"); 18100 } 18101 18102 bool Sema::CheckCaseExpression(Expr *E) { 18103 if (E->isTypeDependent()) 18104 return true; 18105 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18106 return E->getType()->isIntegralOrEnumerationType(); 18107 return false; 18108 } 18109 18110 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18111 ExprResult 18112 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18113 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18114 "Unknown Objective-C Boolean value!"); 18115 QualType BoolT = Context.ObjCBuiltinBoolTy; 18116 if (!Context.getBOOLDecl()) { 18117 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18118 Sema::LookupOrdinaryName); 18119 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18120 NamedDecl *ND = Result.getFoundDecl(); 18121 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18122 Context.setBOOLDecl(TD); 18123 } 18124 } 18125 if (Context.getBOOLDecl()) 18126 BoolT = Context.getBOOLType(); 18127 return new (Context) 18128 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18129 } 18130 18131 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18132 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18133 SourceLocation RParen) { 18134 18135 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18136 18137 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18138 return Spec.getPlatform() == Platform; 18139 }); 18140 18141 VersionTuple Version; 18142 if (Spec != AvailSpecs.end()) 18143 Version = Spec->getVersion(); 18144 18145 // The use of `@available` in the enclosing function should be analyzed to 18146 // warn when it's used inappropriately (i.e. not if(@available)). 18147 if (getCurFunctionOrMethodDecl()) 18148 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18149 else if (getCurBlock() || getCurLambda()) 18150 getCurFunction()->HasPotentialAvailabilityViolations = true; 18151 18152 return new (Context) 18153 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18154 } 18155 18156 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18157 assert(E->isTypeDependent()); 18158 return isa<UnresolvedLookupExpr>(E); 18159 } 18160