1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 344 isa<VarDecl>(D)) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << DMD->getVarName().getAsString(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) 359 if (const auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 363 !isUnevaluatedContext()) { 364 // C++ [expr.prim.req.nested] p3 365 // A local parameter shall only appear as an unevaluated operand 366 // (Clause 8) within the constraint-expression. 367 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 368 << D; 369 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 370 return true; 371 } 372 373 return false; 374 } 375 376 /// DiagnoseSentinelCalls - This routine checks whether a call or 377 /// message-send is to a declaration with the sentinel attribute, and 378 /// if so, it checks that the requirements of the sentinel are 379 /// satisfied. 380 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 381 ArrayRef<Expr *> Args) { 382 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 383 if (!attr) 384 return; 385 386 // The number of formal parameters of the declaration. 387 unsigned numFormalParams; 388 389 // The kind of declaration. This is also an index into a %select in 390 // the diagnostic. 391 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 392 393 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 394 numFormalParams = MD->param_size(); 395 calleeType = CT_Method; 396 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 397 numFormalParams = FD->param_size(); 398 calleeType = CT_Function; 399 } else if (isa<VarDecl>(D)) { 400 QualType type = cast<ValueDecl>(D)->getType(); 401 const FunctionType *fn = nullptr; 402 if (const PointerType *ptr = type->getAs<PointerType>()) { 403 fn = ptr->getPointeeType()->getAs<FunctionType>(); 404 if (!fn) return; 405 calleeType = CT_Function; 406 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 407 fn = ptr->getPointeeType()->castAs<FunctionType>(); 408 calleeType = CT_Block; 409 } else { 410 return; 411 } 412 413 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 414 numFormalParams = proto->getNumParams(); 415 } else { 416 numFormalParams = 0; 417 } 418 } else { 419 return; 420 } 421 422 // "nullPos" is the number of formal parameters at the end which 423 // effectively count as part of the variadic arguments. This is 424 // useful if you would prefer to not have *any* formal parameters, 425 // but the language forces you to have at least one. 426 unsigned nullPos = attr->getNullPos(); 427 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 428 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 429 430 // The number of arguments which should follow the sentinel. 431 unsigned numArgsAfterSentinel = attr->getSentinel(); 432 433 // If there aren't enough arguments for all the formal parameters, 434 // the sentinel, and the args after the sentinel, complain. 435 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 436 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 437 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 438 return; 439 } 440 441 // Otherwise, find the sentinel expression. 442 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 443 if (!sentinelExpr) return; 444 if (sentinelExpr->isValueDependent()) return; 445 if (Context.isSentinelNullExpr(sentinelExpr)) return; 446 447 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 448 // or 'NULL' if those are actually defined in the context. Only use 449 // 'nil' for ObjC methods, where it's much more likely that the 450 // variadic arguments form a list of object pointers. 451 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 452 std::string NullValue; 453 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 454 NullValue = "nil"; 455 else if (getLangOpts().CPlusPlus11) 456 NullValue = "nullptr"; 457 else if (PP.isMacroDefined("NULL")) 458 NullValue = "NULL"; 459 else 460 NullValue = "(void*) 0"; 461 462 if (MissingNilLoc.isInvalid()) 463 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 464 else 465 Diag(MissingNilLoc, diag::warn_missing_sentinel) 466 << int(calleeType) 467 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 468 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 469 } 470 471 SourceRange Sema::getExprRange(Expr *E) const { 472 return E ? E->getSourceRange() : SourceRange(); 473 } 474 475 //===----------------------------------------------------------------------===// 476 // Standard Promotions and Conversions 477 //===----------------------------------------------------------------------===// 478 479 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 480 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 481 // Handle any placeholder expressions which made it here. 482 if (E->getType()->isPlaceholderType()) { 483 ExprResult result = CheckPlaceholderExpr(E); 484 if (result.isInvalid()) return ExprError(); 485 E = result.get(); 486 } 487 488 QualType Ty = E->getType(); 489 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 490 491 if (Ty->isFunctionType()) { 492 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 493 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 494 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 495 return ExprError(); 496 497 E = ImpCastExprToType(E, Context.getPointerType(Ty), 498 CK_FunctionToPointerDecay).get(); 499 } else if (Ty->isArrayType()) { 500 // In C90 mode, arrays only promote to pointers if the array expression is 501 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 502 // type 'array of type' is converted to an expression that has type 'pointer 503 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 504 // that has type 'array of type' ...". The relevant change is "an lvalue" 505 // (C90) to "an expression" (C99). 506 // 507 // C++ 4.2p1: 508 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 509 // T" can be converted to an rvalue of type "pointer to T". 510 // 511 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 512 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 513 CK_ArrayToPointerDecay).get(); 514 } 515 return E; 516 } 517 518 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 519 // Check to see if we are dereferencing a null pointer. If so, 520 // and if not volatile-qualified, this is undefined behavior that the 521 // optimizer will delete, so warn about it. People sometimes try to use this 522 // to get a deterministic trap and are surprised by clang's behavior. This 523 // only handles the pattern "*null", which is a very syntactic check. 524 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 525 if (UO && UO->getOpcode() == UO_Deref && 526 UO->getSubExpr()->getType()->isPointerType()) { 527 const LangAS AS = 528 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 529 if ((!isTargetAddressSpace(AS) || 530 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 531 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 532 S.Context, Expr::NPC_ValueDependentIsNotNull) && 533 !UO->getType().isVolatileQualified()) { 534 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 535 S.PDiag(diag::warn_indirection_through_null) 536 << UO->getSubExpr()->getSourceRange()); 537 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 538 S.PDiag(diag::note_indirection_through_null)); 539 } 540 } 541 } 542 543 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 544 SourceLocation AssignLoc, 545 const Expr* RHS) { 546 const ObjCIvarDecl *IV = OIRE->getDecl(); 547 if (!IV) 548 return; 549 550 DeclarationName MemberName = IV->getDeclName(); 551 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 552 if (!Member || !Member->isStr("isa")) 553 return; 554 555 const Expr *Base = OIRE->getBase(); 556 QualType BaseType = Base->getType(); 557 if (OIRE->isArrow()) 558 BaseType = BaseType->getPointeeType(); 559 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 560 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 561 ObjCInterfaceDecl *ClassDeclared = nullptr; 562 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 563 if (!ClassDeclared->getSuperClass() 564 && (*ClassDeclared->ivar_begin()) == IV) { 565 if (RHS) { 566 NamedDecl *ObjectSetClass = 567 S.LookupSingleName(S.TUScope, 568 &S.Context.Idents.get("object_setClass"), 569 SourceLocation(), S.LookupOrdinaryName); 570 if (ObjectSetClass) { 571 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 572 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 573 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 574 "object_setClass(") 575 << FixItHint::CreateReplacement( 576 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 577 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 578 } 579 else 580 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 581 } else { 582 NamedDecl *ObjectGetClass = 583 S.LookupSingleName(S.TUScope, 584 &S.Context.Idents.get("object_getClass"), 585 SourceLocation(), S.LookupOrdinaryName); 586 if (ObjectGetClass) 587 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 588 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 589 "object_getClass(") 590 << FixItHint::CreateReplacement( 591 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 592 else 593 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 594 } 595 S.Diag(IV->getLocation(), diag::note_ivar_decl); 596 } 597 } 598 } 599 600 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 601 // Handle any placeholder expressions which made it here. 602 if (E->getType()->isPlaceholderType()) { 603 ExprResult result = CheckPlaceholderExpr(E); 604 if (result.isInvalid()) return ExprError(); 605 E = result.get(); 606 } 607 608 // C++ [conv.lval]p1: 609 // A glvalue of a non-function, non-array type T can be 610 // converted to a prvalue. 611 if (!E->isGLValue()) return E; 612 613 QualType T = E->getType(); 614 assert(!T.isNull() && "r-value conversion on typeless expression?"); 615 616 // lvalue-to-rvalue conversion cannot be applied to function or array types. 617 if (T->isFunctionType() || T->isArrayType()) 618 return E; 619 620 // We don't want to throw lvalue-to-rvalue casts on top of 621 // expressions of certain types in C++. 622 if (getLangOpts().CPlusPlus && 623 (E->getType() == Context.OverloadTy || 624 T->isDependentType() || 625 T->isRecordType())) 626 return E; 627 628 // The C standard is actually really unclear on this point, and 629 // DR106 tells us what the result should be but not why. It's 630 // generally best to say that void types just doesn't undergo 631 // lvalue-to-rvalue at all. Note that expressions of unqualified 632 // 'void' type are never l-values, but qualified void can be. 633 if (T->isVoidType()) 634 return E; 635 636 // OpenCL usually rejects direct accesses to values of 'half' type. 637 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 638 T->isHalfType()) { 639 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 640 << 0 << T; 641 return ExprError(); 642 } 643 644 CheckForNullPointerDereference(*this, E); 645 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 646 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 647 &Context.Idents.get("object_getClass"), 648 SourceLocation(), LookupOrdinaryName); 649 if (ObjectGetClass) 650 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 651 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 652 << FixItHint::CreateReplacement( 653 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 654 else 655 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 656 } 657 else if (const ObjCIvarRefExpr *OIRE = 658 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 659 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 660 661 // C++ [conv.lval]p1: 662 // [...] If T is a non-class type, the type of the prvalue is the 663 // cv-unqualified version of T. Otherwise, the type of the 664 // rvalue is T. 665 // 666 // C99 6.3.2.1p2: 667 // If the lvalue has qualified type, the value has the unqualified 668 // version of the type of the lvalue; otherwise, the value has the 669 // type of the lvalue. 670 if (T.hasQualifiers()) 671 T = T.getUnqualifiedType(); 672 673 // Under the MS ABI, lock down the inheritance model now. 674 if (T->isMemberPointerType() && 675 Context.getTargetInfo().getCXXABI().isMicrosoft()) 676 (void)isCompleteType(E->getExprLoc(), T); 677 678 ExprResult Res = CheckLValueToRValueConversionOperand(E); 679 if (Res.isInvalid()) 680 return Res; 681 E = Res.get(); 682 683 // Loading a __weak object implicitly retains the value, so we need a cleanup to 684 // balance that. 685 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 686 Cleanup.setExprNeedsCleanups(true); 687 688 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 689 Cleanup.setExprNeedsCleanups(true); 690 691 // C++ [conv.lval]p3: 692 // If T is cv std::nullptr_t, the result is a null pointer constant. 693 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 694 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 695 696 // C11 6.3.2.1p2: 697 // ... if the lvalue has atomic type, the value has the non-atomic version 698 // of the type of the lvalue ... 699 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 700 T = Atomic->getValueType().getUnqualifiedType(); 701 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 702 nullptr, VK_RValue); 703 } 704 705 return Res; 706 } 707 708 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 709 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 710 if (Res.isInvalid()) 711 return ExprError(); 712 Res = DefaultLvalueConversion(Res.get()); 713 if (Res.isInvalid()) 714 return ExprError(); 715 return Res; 716 } 717 718 /// CallExprUnaryConversions - a special case of an unary conversion 719 /// performed on a function designator of a call expression. 720 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 721 QualType Ty = E->getType(); 722 ExprResult Res = E; 723 // Only do implicit cast for a function type, but not for a pointer 724 // to function type. 725 if (Ty->isFunctionType()) { 726 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 727 CK_FunctionToPointerDecay).get(); 728 if (Res.isInvalid()) 729 return ExprError(); 730 } 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res.get(); 735 } 736 737 /// UsualUnaryConversions - Performs various conversions that are common to most 738 /// operators (C99 6.3). The conversions of array and function types are 739 /// sometimes suppressed. For example, the array->pointer conversion doesn't 740 /// apply if the array is an argument to the sizeof or address (&) operators. 741 /// In these instances, this routine should *not* be called. 742 ExprResult Sema::UsualUnaryConversions(Expr *E) { 743 // First, convert to an r-value. 744 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 745 if (Res.isInvalid()) 746 return ExprError(); 747 E = Res.get(); 748 749 QualType Ty = E->getType(); 750 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 751 752 // Half FP have to be promoted to float unless it is natively supported 753 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 754 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 755 756 // Try to perform integral promotions if the object has a theoretically 757 // promotable type. 758 if (Ty->isIntegralOrUnscopedEnumerationType()) { 759 // C99 6.3.1.1p2: 760 // 761 // The following may be used in an expression wherever an int or 762 // unsigned int may be used: 763 // - an object or expression with an integer type whose integer 764 // conversion rank is less than or equal to the rank of int 765 // and unsigned int. 766 // - A bit-field of type _Bool, int, signed int, or unsigned int. 767 // 768 // If an int can represent all values of the original type, the 769 // value is converted to an int; otherwise, it is converted to an 770 // unsigned int. These are called the integer promotions. All 771 // other types are unchanged by the integer promotions. 772 773 QualType PTy = Context.isPromotableBitField(E); 774 if (!PTy.isNull()) { 775 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 776 return E; 777 } 778 if (Ty->isPromotableIntegerType()) { 779 QualType PT = Context.getPromotedIntegerType(Ty); 780 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 781 return E; 782 } 783 } 784 return E; 785 } 786 787 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 788 /// do not have a prototype. Arguments that have type float or __fp16 789 /// are promoted to double. All other argument types are converted by 790 /// UsualUnaryConversions(). 791 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 792 QualType Ty = E->getType(); 793 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 794 795 ExprResult Res = UsualUnaryConversions(E); 796 if (Res.isInvalid()) 797 return ExprError(); 798 E = Res.get(); 799 800 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 801 // promote to double. 802 // Note that default argument promotion applies only to float (and 803 // half/fp16); it does not apply to _Float16. 804 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 805 if (BTy && (BTy->getKind() == BuiltinType::Half || 806 BTy->getKind() == BuiltinType::Float)) { 807 if (getLangOpts().OpenCL && 808 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 809 if (BTy->getKind() == BuiltinType::Half) { 810 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 811 } 812 } else { 813 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 814 } 815 } 816 817 // C++ performs lvalue-to-rvalue conversion as a default argument 818 // promotion, even on class types, but note: 819 // C++11 [conv.lval]p2: 820 // When an lvalue-to-rvalue conversion occurs in an unevaluated 821 // operand or a subexpression thereof the value contained in the 822 // referenced object is not accessed. Otherwise, if the glvalue 823 // has a class type, the conversion copy-initializes a temporary 824 // of type T from the glvalue and the result of the conversion 825 // is a prvalue for the temporary. 826 // FIXME: add some way to gate this entire thing for correctness in 827 // potentially potentially evaluated contexts. 828 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 829 ExprResult Temp = PerformCopyInitialization( 830 InitializedEntity::InitializeTemporary(E->getType()), 831 E->getExprLoc(), E); 832 if (Temp.isInvalid()) 833 return ExprError(); 834 E = Temp.get(); 835 } 836 837 return E; 838 } 839 840 /// Determine the degree of POD-ness for an expression. 841 /// Incomplete types are considered POD, since this check can be performed 842 /// when we're in an unevaluated context. 843 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 844 if (Ty->isIncompleteType()) { 845 // C++11 [expr.call]p7: 846 // After these conversions, if the argument does not have arithmetic, 847 // enumeration, pointer, pointer to member, or class type, the program 848 // is ill-formed. 849 // 850 // Since we've already performed array-to-pointer and function-to-pointer 851 // decay, the only such type in C++ is cv void. This also handles 852 // initializer lists as variadic arguments. 853 if (Ty->isVoidType()) 854 return VAK_Invalid; 855 856 if (Ty->isObjCObjectType()) 857 return VAK_Invalid; 858 return VAK_Valid; 859 } 860 861 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 862 return VAK_Invalid; 863 864 if (Ty.isCXX98PODType(Context)) 865 return VAK_Valid; 866 867 // C++11 [expr.call]p7: 868 // Passing a potentially-evaluated argument of class type (Clause 9) 869 // having a non-trivial copy constructor, a non-trivial move constructor, 870 // or a non-trivial destructor, with no corresponding parameter, 871 // is conditionally-supported with implementation-defined semantics. 872 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 873 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 874 if (!Record->hasNonTrivialCopyConstructor() && 875 !Record->hasNonTrivialMoveConstructor() && 876 !Record->hasNonTrivialDestructor()) 877 return VAK_ValidInCXX11; 878 879 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 880 return VAK_Valid; 881 882 if (Ty->isObjCObjectType()) 883 return VAK_Invalid; 884 885 if (getLangOpts().MSVCCompat) 886 return VAK_MSVCUndefined; 887 888 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 889 // permitted to reject them. We should consider doing so. 890 return VAK_Undefined; 891 } 892 893 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 894 // Don't allow one to pass an Objective-C interface to a vararg. 895 const QualType &Ty = E->getType(); 896 VarArgKind VAK = isValidVarArgType(Ty); 897 898 // Complain about passing non-POD types through varargs. 899 switch (VAK) { 900 case VAK_ValidInCXX11: 901 DiagRuntimeBehavior( 902 E->getBeginLoc(), nullptr, 903 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 904 LLVM_FALLTHROUGH; 905 case VAK_Valid: 906 if (Ty->isRecordType()) { 907 // This is unlikely to be what the user intended. If the class has a 908 // 'c_str' member function, the user probably meant to call that. 909 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 910 PDiag(diag::warn_pass_class_arg_to_vararg) 911 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 912 } 913 break; 914 915 case VAK_Undefined: 916 case VAK_MSVCUndefined: 917 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 918 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 919 << getLangOpts().CPlusPlus11 << Ty << CT); 920 break; 921 922 case VAK_Invalid: 923 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 924 Diag(E->getBeginLoc(), 925 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 926 << Ty << CT; 927 else if (Ty->isObjCObjectType()) 928 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 929 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 930 << Ty << CT); 931 else 932 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 933 << isa<InitListExpr>(E) << Ty << CT; 934 break; 935 } 936 } 937 938 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 939 /// will create a trap if the resulting type is not a POD type. 940 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 941 FunctionDecl *FDecl) { 942 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 943 // Strip the unbridged-cast placeholder expression off, if applicable. 944 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 945 (CT == VariadicMethod || 946 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 947 E = stripARCUnbridgedCast(E); 948 949 // Otherwise, do normal placeholder checking. 950 } else { 951 ExprResult ExprRes = CheckPlaceholderExpr(E); 952 if (ExprRes.isInvalid()) 953 return ExprError(); 954 E = ExprRes.get(); 955 } 956 } 957 958 ExprResult ExprRes = DefaultArgumentPromotion(E); 959 if (ExprRes.isInvalid()) 960 return ExprError(); 961 E = ExprRes.get(); 962 963 // Diagnostics regarding non-POD argument types are 964 // emitted along with format string checking in Sema::CheckFunctionCall(). 965 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 966 // Turn this into a trap. 967 CXXScopeSpec SS; 968 SourceLocation TemplateKWLoc; 969 UnqualifiedId Name; 970 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 971 E->getBeginLoc()); 972 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 973 /*HasTrailingLParen=*/true, 974 /*IsAddressOfOperand=*/false); 975 if (TrapFn.isInvalid()) 976 return ExprError(); 977 978 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 979 None, E->getEndLoc()); 980 if (Call.isInvalid()) 981 return ExprError(); 982 983 ExprResult Comma = 984 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 985 if (Comma.isInvalid()) 986 return ExprError(); 987 return Comma.get(); 988 } 989 990 if (!getLangOpts().CPlusPlus && 991 RequireCompleteType(E->getExprLoc(), E->getType(), 992 diag::err_call_incomplete_argument)) 993 return ExprError(); 994 995 return E; 996 } 997 998 /// Converts an integer to complex float type. Helper function of 999 /// UsualArithmeticConversions() 1000 /// 1001 /// \return false if the integer expression is an integer type and is 1002 /// successfully converted to the complex type. 1003 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1004 ExprResult &ComplexExpr, 1005 QualType IntTy, 1006 QualType ComplexTy, 1007 bool SkipCast) { 1008 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1009 if (SkipCast) return false; 1010 if (IntTy->isIntegerType()) { 1011 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1012 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1013 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1014 CK_FloatingRealToComplex); 1015 } else { 1016 assert(IntTy->isComplexIntegerType()); 1017 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1018 CK_IntegralComplexToFloatingComplex); 1019 } 1020 return false; 1021 } 1022 1023 /// Handle arithmetic conversion with complex types. Helper function of 1024 /// UsualArithmeticConversions() 1025 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1026 ExprResult &RHS, QualType LHSType, 1027 QualType RHSType, 1028 bool IsCompAssign) { 1029 // if we have an integer operand, the result is the complex type. 1030 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1031 /*skipCast*/false)) 1032 return LHSType; 1033 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1034 /*skipCast*/IsCompAssign)) 1035 return RHSType; 1036 1037 // This handles complex/complex, complex/float, or float/complex. 1038 // When both operands are complex, the shorter operand is converted to the 1039 // type of the longer, and that is the type of the result. This corresponds 1040 // to what is done when combining two real floating-point operands. 1041 // The fun begins when size promotion occur across type domains. 1042 // From H&S 6.3.4: When one operand is complex and the other is a real 1043 // floating-point type, the less precise type is converted, within it's 1044 // real or complex domain, to the precision of the other type. For example, 1045 // when combining a "long double" with a "double _Complex", the 1046 // "double _Complex" is promoted to "long double _Complex". 1047 1048 // Compute the rank of the two types, regardless of whether they are complex. 1049 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1050 1051 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1052 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1053 QualType LHSElementType = 1054 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1055 QualType RHSElementType = 1056 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1057 1058 QualType ResultType = S.Context.getComplexType(LHSElementType); 1059 if (Order < 0) { 1060 // Promote the precision of the LHS if not an assignment. 1061 ResultType = S.Context.getComplexType(RHSElementType); 1062 if (!IsCompAssign) { 1063 if (LHSComplexType) 1064 LHS = 1065 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1066 else 1067 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1068 } 1069 } else if (Order > 0) { 1070 // Promote the precision of the RHS. 1071 if (RHSComplexType) 1072 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1073 else 1074 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1075 } 1076 return ResultType; 1077 } 1078 1079 /// Handle arithmetic conversion from integer to float. Helper function 1080 /// of UsualArithmeticConversions() 1081 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1082 ExprResult &IntExpr, 1083 QualType FloatTy, QualType IntTy, 1084 bool ConvertFloat, bool ConvertInt) { 1085 if (IntTy->isIntegerType()) { 1086 if (ConvertInt) 1087 // Convert intExpr to the lhs floating point type. 1088 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1089 CK_IntegralToFloating); 1090 return FloatTy; 1091 } 1092 1093 // Convert both sides to the appropriate complex float. 1094 assert(IntTy->isComplexIntegerType()); 1095 QualType result = S.Context.getComplexType(FloatTy); 1096 1097 // _Complex int -> _Complex float 1098 if (ConvertInt) 1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1100 CK_IntegralComplexToFloatingComplex); 1101 1102 // float -> _Complex float 1103 if (ConvertFloat) 1104 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1105 CK_FloatingRealToComplex); 1106 1107 return result; 1108 } 1109 1110 /// Handle arithmethic conversion with floating point types. Helper 1111 /// function of UsualArithmeticConversions() 1112 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1113 ExprResult &RHS, QualType LHSType, 1114 QualType RHSType, bool IsCompAssign) { 1115 bool LHSFloat = LHSType->isRealFloatingType(); 1116 bool RHSFloat = RHSType->isRealFloatingType(); 1117 1118 // If we have two real floating types, convert the smaller operand 1119 // to the bigger result. 1120 if (LHSFloat && RHSFloat) { 1121 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1122 if (order > 0) { 1123 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1124 return LHSType; 1125 } 1126 1127 assert(order < 0 && "illegal float comparison"); 1128 if (!IsCompAssign) 1129 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1130 return RHSType; 1131 } 1132 1133 if (LHSFloat) { 1134 // Half FP has to be promoted to float unless it is natively supported 1135 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1136 LHSType = S.Context.FloatTy; 1137 1138 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1139 /*ConvertFloat=*/!IsCompAssign, 1140 /*ConvertInt=*/ true); 1141 } 1142 assert(RHSFloat); 1143 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1144 /*convertInt=*/ true, 1145 /*convertFloat=*/!IsCompAssign); 1146 } 1147 1148 /// Diagnose attempts to convert between __float128 and long double if 1149 /// there is no support for such conversion. Helper function of 1150 /// UsualArithmeticConversions(). 1151 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1152 QualType RHSType) { 1153 /* No issue converting if at least one of the types is not a floating point 1154 type or the two types have the same rank. 1155 */ 1156 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1157 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1158 return false; 1159 1160 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1161 "The remaining types must be floating point types."); 1162 1163 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1164 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1165 1166 QualType LHSElemType = LHSComplex ? 1167 LHSComplex->getElementType() : LHSType; 1168 QualType RHSElemType = RHSComplex ? 1169 RHSComplex->getElementType() : RHSType; 1170 1171 // No issue if the two types have the same representation 1172 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1173 &S.Context.getFloatTypeSemantics(RHSElemType)) 1174 return false; 1175 1176 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1177 RHSElemType == S.Context.LongDoubleTy); 1178 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1179 RHSElemType == S.Context.Float128Ty); 1180 1181 // We've handled the situation where __float128 and long double have the same 1182 // representation. We allow all conversions for all possible long double types 1183 // except PPC's double double. 1184 return Float128AndLongDouble && 1185 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1186 &llvm::APFloat::PPCDoubleDouble()); 1187 } 1188 1189 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1190 1191 namespace { 1192 /// These helper callbacks are placed in an anonymous namespace to 1193 /// permit their use as function template parameters. 1194 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1195 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1196 } 1197 1198 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1199 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1200 CK_IntegralComplexCast); 1201 } 1202 } 1203 1204 /// Handle integer arithmetic conversions. Helper function of 1205 /// UsualArithmeticConversions() 1206 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1207 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1208 ExprResult &RHS, QualType LHSType, 1209 QualType RHSType, bool IsCompAssign) { 1210 // The rules for this case are in C99 6.3.1.8 1211 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1212 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1213 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1214 if (LHSSigned == RHSSigned) { 1215 // Same signedness; use the higher-ranked type 1216 if (order >= 0) { 1217 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1218 return LHSType; 1219 } else if (!IsCompAssign) 1220 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1221 return RHSType; 1222 } else if (order != (LHSSigned ? 1 : -1)) { 1223 // The unsigned type has greater than or equal rank to the 1224 // signed type, so use the unsigned type 1225 if (RHSSigned) { 1226 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1227 return LHSType; 1228 } else if (!IsCompAssign) 1229 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1230 return RHSType; 1231 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1232 // The two types are different widths; if we are here, that 1233 // means the signed type is larger than the unsigned type, so 1234 // use the signed type. 1235 if (LHSSigned) { 1236 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1237 return LHSType; 1238 } else if (!IsCompAssign) 1239 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1240 return RHSType; 1241 } else { 1242 // The signed type is higher-ranked than the unsigned type, 1243 // but isn't actually any bigger (like unsigned int and long 1244 // on most 32-bit systems). Use the unsigned type corresponding 1245 // to the signed type. 1246 QualType result = 1247 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1248 RHS = (*doRHSCast)(S, RHS.get(), result); 1249 if (!IsCompAssign) 1250 LHS = (*doLHSCast)(S, LHS.get(), result); 1251 return result; 1252 } 1253 } 1254 1255 /// Handle conversions with GCC complex int extension. Helper function 1256 /// of UsualArithmeticConversions() 1257 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1258 ExprResult &RHS, QualType LHSType, 1259 QualType RHSType, 1260 bool IsCompAssign) { 1261 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1262 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1263 1264 if (LHSComplexInt && RHSComplexInt) { 1265 QualType LHSEltType = LHSComplexInt->getElementType(); 1266 QualType RHSEltType = RHSComplexInt->getElementType(); 1267 QualType ScalarType = 1268 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1269 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1270 1271 return S.Context.getComplexType(ScalarType); 1272 } 1273 1274 if (LHSComplexInt) { 1275 QualType LHSEltType = LHSComplexInt->getElementType(); 1276 QualType ScalarType = 1277 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1278 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1279 QualType ComplexType = S.Context.getComplexType(ScalarType); 1280 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1281 CK_IntegralRealToComplex); 1282 1283 return ComplexType; 1284 } 1285 1286 assert(RHSComplexInt); 1287 1288 QualType RHSEltType = RHSComplexInt->getElementType(); 1289 QualType ScalarType = 1290 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1291 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1292 QualType ComplexType = S.Context.getComplexType(ScalarType); 1293 1294 if (!IsCompAssign) 1295 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1296 CK_IntegralRealToComplex); 1297 return ComplexType; 1298 } 1299 1300 /// Return the rank of a given fixed point or integer type. The value itself 1301 /// doesn't matter, but the values must be increasing with proper increasing 1302 /// rank as described in N1169 4.1.1. 1303 static unsigned GetFixedPointRank(QualType Ty) { 1304 const auto *BTy = Ty->getAs<BuiltinType>(); 1305 assert(BTy && "Expected a builtin type."); 1306 1307 switch (BTy->getKind()) { 1308 case BuiltinType::ShortFract: 1309 case BuiltinType::UShortFract: 1310 case BuiltinType::SatShortFract: 1311 case BuiltinType::SatUShortFract: 1312 return 1; 1313 case BuiltinType::Fract: 1314 case BuiltinType::UFract: 1315 case BuiltinType::SatFract: 1316 case BuiltinType::SatUFract: 1317 return 2; 1318 case BuiltinType::LongFract: 1319 case BuiltinType::ULongFract: 1320 case BuiltinType::SatLongFract: 1321 case BuiltinType::SatULongFract: 1322 return 3; 1323 case BuiltinType::ShortAccum: 1324 case BuiltinType::UShortAccum: 1325 case BuiltinType::SatShortAccum: 1326 case BuiltinType::SatUShortAccum: 1327 return 4; 1328 case BuiltinType::Accum: 1329 case BuiltinType::UAccum: 1330 case BuiltinType::SatAccum: 1331 case BuiltinType::SatUAccum: 1332 return 5; 1333 case BuiltinType::LongAccum: 1334 case BuiltinType::ULongAccum: 1335 case BuiltinType::SatLongAccum: 1336 case BuiltinType::SatULongAccum: 1337 return 6; 1338 default: 1339 if (BTy->isInteger()) 1340 return 0; 1341 llvm_unreachable("Unexpected fixed point or integer type"); 1342 } 1343 } 1344 1345 /// handleFixedPointConversion - Fixed point operations between fixed 1346 /// point types and integers or other fixed point types do not fall under 1347 /// usual arithmetic conversion since these conversions could result in loss 1348 /// of precsision (N1169 4.1.4). These operations should be calculated with 1349 /// the full precision of their result type (N1169 4.1.6.2.1). 1350 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1351 QualType RHSTy) { 1352 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1353 "Expected at least one of the operands to be a fixed point type"); 1354 assert((LHSTy->isFixedPointOrIntegerType() || 1355 RHSTy->isFixedPointOrIntegerType()) && 1356 "Special fixed point arithmetic operation conversions are only " 1357 "applied to ints or other fixed point types"); 1358 1359 // If one operand has signed fixed-point type and the other operand has 1360 // unsigned fixed-point type, then the unsigned fixed-point operand is 1361 // converted to its corresponding signed fixed-point type and the resulting 1362 // type is the type of the converted operand. 1363 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1364 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1365 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1366 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1367 1368 // The result type is the type with the highest rank, whereby a fixed-point 1369 // conversion rank is always greater than an integer conversion rank; if the 1370 // type of either of the operands is a saturating fixedpoint type, the result 1371 // type shall be the saturating fixed-point type corresponding to the type 1372 // with the highest rank; the resulting value is converted (taking into 1373 // account rounding and overflow) to the precision of the resulting type. 1374 // Same ranks between signed and unsigned types are resolved earlier, so both 1375 // types are either signed or both unsigned at this point. 1376 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1377 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1378 1379 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1380 1381 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1382 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1383 1384 return ResultTy; 1385 } 1386 1387 /// Check that the usual arithmetic conversions can be performed on this pair of 1388 /// expressions that might be of enumeration type. 1389 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1390 SourceLocation Loc, 1391 Sema::ArithConvKind ACK) { 1392 // C++2a [expr.arith.conv]p1: 1393 // If one operand is of enumeration type and the other operand is of a 1394 // different enumeration type or a floating-point type, this behavior is 1395 // deprecated ([depr.arith.conv.enum]). 1396 // 1397 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1398 // Eventually we will presumably reject these cases (in C++23 onwards?). 1399 QualType L = LHS->getType(), R = RHS->getType(); 1400 bool LEnum = L->isUnscopedEnumerationType(), 1401 REnum = R->isUnscopedEnumerationType(); 1402 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1403 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1404 (REnum && L->isFloatingType())) { 1405 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1406 ? diag::warn_arith_conv_enum_float_cxx20 1407 : diag::warn_arith_conv_enum_float) 1408 << LHS->getSourceRange() << RHS->getSourceRange() 1409 << (int)ACK << LEnum << L << R; 1410 } else if (!IsCompAssign && LEnum && REnum && 1411 !S.Context.hasSameUnqualifiedType(L, R)) { 1412 unsigned DiagID; 1413 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1414 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1415 // If either enumeration type is unnamed, it's less likely that the 1416 // user cares about this, but this situation is still deprecated in 1417 // C++2a. Use a different warning group. 1418 DiagID = S.getLangOpts().CPlusPlus20 1419 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1420 : diag::warn_arith_conv_mixed_anon_enum_types; 1421 } else if (ACK == Sema::ACK_Conditional) { 1422 // Conditional expressions are separated out because they have 1423 // historically had a different warning flag. 1424 DiagID = S.getLangOpts().CPlusPlus20 1425 ? diag::warn_conditional_mixed_enum_types_cxx20 1426 : diag::warn_conditional_mixed_enum_types; 1427 } else if (ACK == Sema::ACK_Comparison) { 1428 // Comparison expressions are separated out because they have 1429 // historically had a different warning flag. 1430 DiagID = S.getLangOpts().CPlusPlus20 1431 ? diag::warn_comparison_mixed_enum_types_cxx20 1432 : diag::warn_comparison_mixed_enum_types; 1433 } else { 1434 DiagID = S.getLangOpts().CPlusPlus20 1435 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1436 : diag::warn_arith_conv_mixed_enum_types; 1437 } 1438 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1439 << (int)ACK << L << R; 1440 } 1441 } 1442 1443 /// UsualArithmeticConversions - Performs various conversions that are common to 1444 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1445 /// routine returns the first non-arithmetic type found. The client is 1446 /// responsible for emitting appropriate error diagnostics. 1447 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1448 SourceLocation Loc, 1449 ArithConvKind ACK) { 1450 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1451 1452 if (ACK != ACK_CompAssign) { 1453 LHS = UsualUnaryConversions(LHS.get()); 1454 if (LHS.isInvalid()) 1455 return QualType(); 1456 } 1457 1458 RHS = UsualUnaryConversions(RHS.get()); 1459 if (RHS.isInvalid()) 1460 return QualType(); 1461 1462 // For conversion purposes, we ignore any qualifiers. 1463 // For example, "const float" and "float" are equivalent. 1464 QualType LHSType = 1465 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1466 QualType RHSType = 1467 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1468 1469 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1470 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1471 LHSType = AtomicLHS->getValueType(); 1472 1473 // If both types are identical, no conversion is needed. 1474 if (LHSType == RHSType) 1475 return LHSType; 1476 1477 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1478 // The caller can deal with this (e.g. pointer + int). 1479 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1480 return QualType(); 1481 1482 // Apply unary and bitfield promotions to the LHS's type. 1483 QualType LHSUnpromotedType = LHSType; 1484 if (LHSType->isPromotableIntegerType()) 1485 LHSType = Context.getPromotedIntegerType(LHSType); 1486 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1487 if (!LHSBitfieldPromoteTy.isNull()) 1488 LHSType = LHSBitfieldPromoteTy; 1489 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1490 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1491 1492 // If both types are identical, no conversion is needed. 1493 if (LHSType == RHSType) 1494 return LHSType; 1495 1496 // ExtInt types aren't subject to conversions between them or normal integers, 1497 // so this fails. 1498 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1499 return QualType(); 1500 1501 // At this point, we have two different arithmetic types. 1502 1503 // Diagnose attempts to convert between __float128 and long double where 1504 // such conversions currently can't be handled. 1505 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1506 return QualType(); 1507 1508 // Handle complex types first (C99 6.3.1.8p1). 1509 if (LHSType->isComplexType() || RHSType->isComplexType()) 1510 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1511 ACK == ACK_CompAssign); 1512 1513 // Now handle "real" floating types (i.e. float, double, long double). 1514 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1515 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1516 ACK == ACK_CompAssign); 1517 1518 // Handle GCC complex int extension. 1519 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1520 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1521 ACK == ACK_CompAssign); 1522 1523 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1524 return handleFixedPointConversion(*this, LHSType, RHSType); 1525 1526 // Finally, we have two differing integer types. 1527 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1528 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1529 } 1530 1531 //===----------------------------------------------------------------------===// 1532 // Semantic Analysis for various Expression Types 1533 //===----------------------------------------------------------------------===// 1534 1535 1536 ExprResult 1537 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1538 SourceLocation DefaultLoc, 1539 SourceLocation RParenLoc, 1540 Expr *ControllingExpr, 1541 ArrayRef<ParsedType> ArgTypes, 1542 ArrayRef<Expr *> ArgExprs) { 1543 unsigned NumAssocs = ArgTypes.size(); 1544 assert(NumAssocs == ArgExprs.size()); 1545 1546 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1547 for (unsigned i = 0; i < NumAssocs; ++i) { 1548 if (ArgTypes[i]) 1549 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1550 else 1551 Types[i] = nullptr; 1552 } 1553 1554 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1555 ControllingExpr, 1556 llvm::makeArrayRef(Types, NumAssocs), 1557 ArgExprs); 1558 delete [] Types; 1559 return ER; 1560 } 1561 1562 ExprResult 1563 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1564 SourceLocation DefaultLoc, 1565 SourceLocation RParenLoc, 1566 Expr *ControllingExpr, 1567 ArrayRef<TypeSourceInfo *> Types, 1568 ArrayRef<Expr *> Exprs) { 1569 unsigned NumAssocs = Types.size(); 1570 assert(NumAssocs == Exprs.size()); 1571 1572 // Decay and strip qualifiers for the controlling expression type, and handle 1573 // placeholder type replacement. See committee discussion from WG14 DR423. 1574 { 1575 EnterExpressionEvaluationContext Unevaluated( 1576 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1577 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1578 if (R.isInvalid()) 1579 return ExprError(); 1580 ControllingExpr = R.get(); 1581 } 1582 1583 // The controlling expression is an unevaluated operand, so side effects are 1584 // likely unintended. 1585 if (!inTemplateInstantiation() && 1586 ControllingExpr->HasSideEffects(Context, false)) 1587 Diag(ControllingExpr->getExprLoc(), 1588 diag::warn_side_effects_unevaluated_context); 1589 1590 bool TypeErrorFound = false, 1591 IsResultDependent = ControllingExpr->isTypeDependent(), 1592 ContainsUnexpandedParameterPack 1593 = ControllingExpr->containsUnexpandedParameterPack(); 1594 1595 for (unsigned i = 0; i < NumAssocs; ++i) { 1596 if (Exprs[i]->containsUnexpandedParameterPack()) 1597 ContainsUnexpandedParameterPack = true; 1598 1599 if (Types[i]) { 1600 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1601 ContainsUnexpandedParameterPack = true; 1602 1603 if (Types[i]->getType()->isDependentType()) { 1604 IsResultDependent = true; 1605 } else { 1606 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1607 // complete object type other than a variably modified type." 1608 unsigned D = 0; 1609 if (Types[i]->getType()->isIncompleteType()) 1610 D = diag::err_assoc_type_incomplete; 1611 else if (!Types[i]->getType()->isObjectType()) 1612 D = diag::err_assoc_type_nonobject; 1613 else if (Types[i]->getType()->isVariablyModifiedType()) 1614 D = diag::err_assoc_type_variably_modified; 1615 1616 if (D != 0) { 1617 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1618 << Types[i]->getTypeLoc().getSourceRange() 1619 << Types[i]->getType(); 1620 TypeErrorFound = true; 1621 } 1622 1623 // C11 6.5.1.1p2 "No two generic associations in the same generic 1624 // selection shall specify compatible types." 1625 for (unsigned j = i+1; j < NumAssocs; ++j) 1626 if (Types[j] && !Types[j]->getType()->isDependentType() && 1627 Context.typesAreCompatible(Types[i]->getType(), 1628 Types[j]->getType())) { 1629 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1630 diag::err_assoc_compatible_types) 1631 << Types[j]->getTypeLoc().getSourceRange() 1632 << Types[j]->getType() 1633 << Types[i]->getType(); 1634 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1635 diag::note_compat_assoc) 1636 << Types[i]->getTypeLoc().getSourceRange() 1637 << Types[i]->getType(); 1638 TypeErrorFound = true; 1639 } 1640 } 1641 } 1642 } 1643 if (TypeErrorFound) 1644 return ExprError(); 1645 1646 // If we determined that the generic selection is result-dependent, don't 1647 // try to compute the result expression. 1648 if (IsResultDependent) 1649 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1650 Exprs, DefaultLoc, RParenLoc, 1651 ContainsUnexpandedParameterPack); 1652 1653 SmallVector<unsigned, 1> CompatIndices; 1654 unsigned DefaultIndex = -1U; 1655 for (unsigned i = 0; i < NumAssocs; ++i) { 1656 if (!Types[i]) 1657 DefaultIndex = i; 1658 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1659 Types[i]->getType())) 1660 CompatIndices.push_back(i); 1661 } 1662 1663 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1664 // type compatible with at most one of the types named in its generic 1665 // association list." 1666 if (CompatIndices.size() > 1) { 1667 // We strip parens here because the controlling expression is typically 1668 // parenthesized in macro definitions. 1669 ControllingExpr = ControllingExpr->IgnoreParens(); 1670 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1671 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1672 << (unsigned)CompatIndices.size(); 1673 for (unsigned I : CompatIndices) { 1674 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1675 diag::note_compat_assoc) 1676 << Types[I]->getTypeLoc().getSourceRange() 1677 << Types[I]->getType(); 1678 } 1679 return ExprError(); 1680 } 1681 1682 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1683 // its controlling expression shall have type compatible with exactly one of 1684 // the types named in its generic association list." 1685 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1686 // We strip parens here because the controlling expression is typically 1687 // parenthesized in macro definitions. 1688 ControllingExpr = ControllingExpr->IgnoreParens(); 1689 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1690 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1691 return ExprError(); 1692 } 1693 1694 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1695 // type name that is compatible with the type of the controlling expression, 1696 // then the result expression of the generic selection is the expression 1697 // in that generic association. Otherwise, the result expression of the 1698 // generic selection is the expression in the default generic association." 1699 unsigned ResultIndex = 1700 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1701 1702 return GenericSelectionExpr::Create( 1703 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1704 ContainsUnexpandedParameterPack, ResultIndex); 1705 } 1706 1707 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1708 /// location of the token and the offset of the ud-suffix within it. 1709 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1710 unsigned Offset) { 1711 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1712 S.getLangOpts()); 1713 } 1714 1715 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1716 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1717 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1718 IdentifierInfo *UDSuffix, 1719 SourceLocation UDSuffixLoc, 1720 ArrayRef<Expr*> Args, 1721 SourceLocation LitEndLoc) { 1722 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1723 1724 QualType ArgTy[2]; 1725 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1726 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1727 if (ArgTy[ArgIdx]->isArrayType()) 1728 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1729 } 1730 1731 DeclarationName OpName = 1732 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1733 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1734 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1735 1736 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1737 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1738 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1739 /*AllowStringTemplate*/ false, 1740 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1741 return ExprError(); 1742 1743 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1744 } 1745 1746 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1747 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1748 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1749 /// multiple tokens. However, the common case is that StringToks points to one 1750 /// string. 1751 /// 1752 ExprResult 1753 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1754 assert(!StringToks.empty() && "Must have at least one string!"); 1755 1756 StringLiteralParser Literal(StringToks, PP); 1757 if (Literal.hadError) 1758 return ExprError(); 1759 1760 SmallVector<SourceLocation, 4> StringTokLocs; 1761 for (const Token &Tok : StringToks) 1762 StringTokLocs.push_back(Tok.getLocation()); 1763 1764 QualType CharTy = Context.CharTy; 1765 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1766 if (Literal.isWide()) { 1767 CharTy = Context.getWideCharType(); 1768 Kind = StringLiteral::Wide; 1769 } else if (Literal.isUTF8()) { 1770 if (getLangOpts().Char8) 1771 CharTy = Context.Char8Ty; 1772 Kind = StringLiteral::UTF8; 1773 } else if (Literal.isUTF16()) { 1774 CharTy = Context.Char16Ty; 1775 Kind = StringLiteral::UTF16; 1776 } else if (Literal.isUTF32()) { 1777 CharTy = Context.Char32Ty; 1778 Kind = StringLiteral::UTF32; 1779 } else if (Literal.isPascal()) { 1780 CharTy = Context.UnsignedCharTy; 1781 } 1782 1783 // Warn on initializing an array of char from a u8 string literal; this 1784 // becomes ill-formed in C++2a. 1785 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1786 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1787 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1788 1789 // Create removals for all 'u8' prefixes in the string literal(s). This 1790 // ensures C++2a compatibility (but may change the program behavior when 1791 // built by non-Clang compilers for which the execution character set is 1792 // not always UTF-8). 1793 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1794 SourceLocation RemovalDiagLoc; 1795 for (const Token &Tok : StringToks) { 1796 if (Tok.getKind() == tok::utf8_string_literal) { 1797 if (RemovalDiagLoc.isInvalid()) 1798 RemovalDiagLoc = Tok.getLocation(); 1799 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1800 Tok.getLocation(), 1801 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1802 getSourceManager(), getLangOpts()))); 1803 } 1804 } 1805 Diag(RemovalDiagLoc, RemovalDiag); 1806 } 1807 1808 QualType StrTy = 1809 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1810 1811 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1812 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1813 Kind, Literal.Pascal, StrTy, 1814 &StringTokLocs[0], 1815 StringTokLocs.size()); 1816 if (Literal.getUDSuffix().empty()) 1817 return Lit; 1818 1819 // We're building a user-defined literal. 1820 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1821 SourceLocation UDSuffixLoc = 1822 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1823 Literal.getUDSuffixOffset()); 1824 1825 // Make sure we're allowed user-defined literals here. 1826 if (!UDLScope) 1827 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1828 1829 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1830 // operator "" X (str, len) 1831 QualType SizeType = Context.getSizeType(); 1832 1833 DeclarationName OpName = 1834 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1835 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1836 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1837 1838 QualType ArgTy[] = { 1839 Context.getArrayDecayedType(StrTy), SizeType 1840 }; 1841 1842 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1843 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1844 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1845 /*AllowStringTemplate*/ true, 1846 /*DiagnoseMissing*/ true)) { 1847 1848 case LOLR_Cooked: { 1849 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1850 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1851 StringTokLocs[0]); 1852 Expr *Args[] = { Lit, LenArg }; 1853 1854 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1855 } 1856 1857 case LOLR_StringTemplate: { 1858 TemplateArgumentListInfo ExplicitArgs; 1859 1860 unsigned CharBits = Context.getIntWidth(CharTy); 1861 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1862 llvm::APSInt Value(CharBits, CharIsUnsigned); 1863 1864 TemplateArgument TypeArg(CharTy); 1865 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1866 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1867 1868 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1869 Value = Lit->getCodeUnit(I); 1870 TemplateArgument Arg(Context, Value, CharTy); 1871 TemplateArgumentLocInfo ArgInfo; 1872 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1873 } 1874 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1875 &ExplicitArgs); 1876 } 1877 case LOLR_Raw: 1878 case LOLR_Template: 1879 case LOLR_ErrorNoDiagnostic: 1880 llvm_unreachable("unexpected literal operator lookup result"); 1881 case LOLR_Error: 1882 return ExprError(); 1883 } 1884 llvm_unreachable("unexpected literal operator lookup result"); 1885 } 1886 1887 DeclRefExpr * 1888 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1889 SourceLocation Loc, 1890 const CXXScopeSpec *SS) { 1891 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1892 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1893 } 1894 1895 DeclRefExpr * 1896 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1897 const DeclarationNameInfo &NameInfo, 1898 const CXXScopeSpec *SS, NamedDecl *FoundD, 1899 SourceLocation TemplateKWLoc, 1900 const TemplateArgumentListInfo *TemplateArgs) { 1901 NestedNameSpecifierLoc NNS = 1902 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1903 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1904 TemplateArgs); 1905 } 1906 1907 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1908 // A declaration named in an unevaluated operand never constitutes an odr-use. 1909 if (isUnevaluatedContext()) 1910 return NOUR_Unevaluated; 1911 1912 // C++2a [basic.def.odr]p4: 1913 // A variable x whose name appears as a potentially-evaluated expression e 1914 // is odr-used by e unless [...] x is a reference that is usable in 1915 // constant expressions. 1916 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1917 if (VD->getType()->isReferenceType() && 1918 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1919 VD->isUsableInConstantExpressions(Context)) 1920 return NOUR_Constant; 1921 } 1922 1923 // All remaining non-variable cases constitute an odr-use. For variables, we 1924 // need to wait and see how the expression is used. 1925 return NOUR_None; 1926 } 1927 1928 /// BuildDeclRefExpr - Build an expression that references a 1929 /// declaration that does not require a closure capture. 1930 DeclRefExpr * 1931 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1932 const DeclarationNameInfo &NameInfo, 1933 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1934 SourceLocation TemplateKWLoc, 1935 const TemplateArgumentListInfo *TemplateArgs) { 1936 bool RefersToCapturedVariable = 1937 isa<VarDecl>(D) && 1938 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1939 1940 DeclRefExpr *E = DeclRefExpr::Create( 1941 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1942 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1943 MarkDeclRefReferenced(E); 1944 1945 // C++ [except.spec]p17: 1946 // An exception-specification is considered to be needed when: 1947 // - in an expression, the function is the unique lookup result or 1948 // the selected member of a set of overloaded functions. 1949 // 1950 // We delay doing this until after we've built the function reference and 1951 // marked it as used so that: 1952 // a) if the function is defaulted, we get errors from defining it before / 1953 // instead of errors from computing its exception specification, and 1954 // b) if the function is a defaulted comparison, we can use the body we 1955 // build when defining it as input to the exception specification 1956 // computation rather than computing a new body. 1957 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1958 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1959 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1960 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1961 } 1962 } 1963 1964 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1965 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1966 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1967 getCurFunction()->recordUseOfWeak(E); 1968 1969 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1970 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1971 FD = IFD->getAnonField(); 1972 if (FD) { 1973 UnusedPrivateFields.remove(FD); 1974 // Just in case we're building an illegal pointer-to-member. 1975 if (FD->isBitField()) 1976 E->setObjectKind(OK_BitField); 1977 } 1978 1979 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1980 // designates a bit-field. 1981 if (auto *BD = dyn_cast<BindingDecl>(D)) 1982 if (auto *BE = BD->getBinding()) 1983 E->setObjectKind(BE->getObjectKind()); 1984 1985 return E; 1986 } 1987 1988 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1989 /// possibly a list of template arguments. 1990 /// 1991 /// If this produces template arguments, it is permitted to call 1992 /// DecomposeTemplateName. 1993 /// 1994 /// This actually loses a lot of source location information for 1995 /// non-standard name kinds; we should consider preserving that in 1996 /// some way. 1997 void 1998 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1999 TemplateArgumentListInfo &Buffer, 2000 DeclarationNameInfo &NameInfo, 2001 const TemplateArgumentListInfo *&TemplateArgs) { 2002 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2003 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2004 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2005 2006 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2007 Id.TemplateId->NumArgs); 2008 translateTemplateArguments(TemplateArgsPtr, Buffer); 2009 2010 TemplateName TName = Id.TemplateId->Template.get(); 2011 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2012 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2013 TemplateArgs = &Buffer; 2014 } else { 2015 NameInfo = GetNameFromUnqualifiedId(Id); 2016 TemplateArgs = nullptr; 2017 } 2018 } 2019 2020 static void emitEmptyLookupTypoDiagnostic( 2021 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2022 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2023 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2024 DeclContext *Ctx = 2025 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2026 if (!TC) { 2027 // Emit a special diagnostic for failed member lookups. 2028 // FIXME: computing the declaration context might fail here (?) 2029 if (Ctx) 2030 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2031 << SS.getRange(); 2032 else 2033 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2034 return; 2035 } 2036 2037 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2038 bool DroppedSpecifier = 2039 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2040 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2041 ? diag::note_implicit_param_decl 2042 : diag::note_previous_decl; 2043 if (!Ctx) 2044 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2045 SemaRef.PDiag(NoteID)); 2046 else 2047 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2048 << Typo << Ctx << DroppedSpecifier 2049 << SS.getRange(), 2050 SemaRef.PDiag(NoteID)); 2051 } 2052 2053 /// Diagnose an empty lookup. 2054 /// 2055 /// \return false if new lookup candidates were found 2056 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2057 CorrectionCandidateCallback &CCC, 2058 TemplateArgumentListInfo *ExplicitTemplateArgs, 2059 ArrayRef<Expr *> Args, TypoExpr **Out) { 2060 DeclarationName Name = R.getLookupName(); 2061 2062 unsigned diagnostic = diag::err_undeclared_var_use; 2063 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2064 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2065 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2066 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2067 diagnostic = diag::err_undeclared_use; 2068 diagnostic_suggest = diag::err_undeclared_use_suggest; 2069 } 2070 2071 // If the original lookup was an unqualified lookup, fake an 2072 // unqualified lookup. This is useful when (for example) the 2073 // original lookup would not have found something because it was a 2074 // dependent name. 2075 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2076 while (DC) { 2077 if (isa<CXXRecordDecl>(DC)) { 2078 LookupQualifiedName(R, DC); 2079 2080 if (!R.empty()) { 2081 // Don't give errors about ambiguities in this lookup. 2082 R.suppressDiagnostics(); 2083 2084 // During a default argument instantiation the CurContext points 2085 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2086 // function parameter list, hence add an explicit check. 2087 bool isDefaultArgument = 2088 !CodeSynthesisContexts.empty() && 2089 CodeSynthesisContexts.back().Kind == 2090 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2091 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2092 bool isInstance = CurMethod && 2093 CurMethod->isInstance() && 2094 DC == CurMethod->getParent() && !isDefaultArgument; 2095 2096 // Give a code modification hint to insert 'this->'. 2097 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2098 // Actually quite difficult! 2099 if (getLangOpts().MSVCCompat) 2100 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2101 if (isInstance) { 2102 Diag(R.getNameLoc(), diagnostic) << Name 2103 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2104 CheckCXXThisCapture(R.getNameLoc()); 2105 } else { 2106 Diag(R.getNameLoc(), diagnostic) << Name; 2107 } 2108 2109 // Do we really want to note all of these? 2110 for (NamedDecl *D : R) 2111 Diag(D->getLocation(), diag::note_dependent_var_use); 2112 2113 // Return true if we are inside a default argument instantiation 2114 // and the found name refers to an instance member function, otherwise 2115 // the function calling DiagnoseEmptyLookup will try to create an 2116 // implicit member call and this is wrong for default argument. 2117 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2118 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2119 return true; 2120 } 2121 2122 // Tell the callee to try to recover. 2123 return false; 2124 } 2125 2126 R.clear(); 2127 } 2128 2129 DC = DC->getLookupParent(); 2130 } 2131 2132 // We didn't find anything, so try to correct for a typo. 2133 TypoCorrection Corrected; 2134 if (S && Out) { 2135 SourceLocation TypoLoc = R.getNameLoc(); 2136 assert(!ExplicitTemplateArgs && 2137 "Diagnosing an empty lookup with explicit template args!"); 2138 *Out = CorrectTypoDelayed( 2139 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2140 [=](const TypoCorrection &TC) { 2141 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2142 diagnostic, diagnostic_suggest); 2143 }, 2144 nullptr, CTK_ErrorRecovery); 2145 if (*Out) 2146 return true; 2147 } else if (S && 2148 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2149 S, &SS, CCC, CTK_ErrorRecovery))) { 2150 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2151 bool DroppedSpecifier = 2152 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2153 R.setLookupName(Corrected.getCorrection()); 2154 2155 bool AcceptableWithRecovery = false; 2156 bool AcceptableWithoutRecovery = false; 2157 NamedDecl *ND = Corrected.getFoundDecl(); 2158 if (ND) { 2159 if (Corrected.isOverloaded()) { 2160 OverloadCandidateSet OCS(R.getNameLoc(), 2161 OverloadCandidateSet::CSK_Normal); 2162 OverloadCandidateSet::iterator Best; 2163 for (NamedDecl *CD : Corrected) { 2164 if (FunctionTemplateDecl *FTD = 2165 dyn_cast<FunctionTemplateDecl>(CD)) 2166 AddTemplateOverloadCandidate( 2167 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2168 Args, OCS); 2169 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2170 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2171 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2172 Args, OCS); 2173 } 2174 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2175 case OR_Success: 2176 ND = Best->FoundDecl; 2177 Corrected.setCorrectionDecl(ND); 2178 break; 2179 default: 2180 // FIXME: Arbitrarily pick the first declaration for the note. 2181 Corrected.setCorrectionDecl(ND); 2182 break; 2183 } 2184 } 2185 R.addDecl(ND); 2186 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2187 CXXRecordDecl *Record = nullptr; 2188 if (Corrected.getCorrectionSpecifier()) { 2189 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2190 Record = Ty->getAsCXXRecordDecl(); 2191 } 2192 if (!Record) 2193 Record = cast<CXXRecordDecl>( 2194 ND->getDeclContext()->getRedeclContext()); 2195 R.setNamingClass(Record); 2196 } 2197 2198 auto *UnderlyingND = ND->getUnderlyingDecl(); 2199 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2200 isa<FunctionTemplateDecl>(UnderlyingND); 2201 // FIXME: If we ended up with a typo for a type name or 2202 // Objective-C class name, we're in trouble because the parser 2203 // is in the wrong place to recover. Suggest the typo 2204 // correction, but don't make it a fix-it since we're not going 2205 // to recover well anyway. 2206 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2207 getAsTypeTemplateDecl(UnderlyingND) || 2208 isa<ObjCInterfaceDecl>(UnderlyingND); 2209 } else { 2210 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2211 // because we aren't able to recover. 2212 AcceptableWithoutRecovery = true; 2213 } 2214 2215 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2216 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2217 ? diag::note_implicit_param_decl 2218 : diag::note_previous_decl; 2219 if (SS.isEmpty()) 2220 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2221 PDiag(NoteID), AcceptableWithRecovery); 2222 else 2223 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2224 << Name << computeDeclContext(SS, false) 2225 << DroppedSpecifier << SS.getRange(), 2226 PDiag(NoteID), AcceptableWithRecovery); 2227 2228 // Tell the callee whether to try to recover. 2229 return !AcceptableWithRecovery; 2230 } 2231 } 2232 R.clear(); 2233 2234 // Emit a special diagnostic for failed member lookups. 2235 // FIXME: computing the declaration context might fail here (?) 2236 if (!SS.isEmpty()) { 2237 Diag(R.getNameLoc(), diag::err_no_member) 2238 << Name << computeDeclContext(SS, false) 2239 << SS.getRange(); 2240 return true; 2241 } 2242 2243 // Give up, we can't recover. 2244 Diag(R.getNameLoc(), diagnostic) << Name; 2245 return true; 2246 } 2247 2248 /// In Microsoft mode, if we are inside a template class whose parent class has 2249 /// dependent base classes, and we can't resolve an unqualified identifier, then 2250 /// assume the identifier is a member of a dependent base class. We can only 2251 /// recover successfully in static methods, instance methods, and other contexts 2252 /// where 'this' is available. This doesn't precisely match MSVC's 2253 /// instantiation model, but it's close enough. 2254 static Expr * 2255 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2256 DeclarationNameInfo &NameInfo, 2257 SourceLocation TemplateKWLoc, 2258 const TemplateArgumentListInfo *TemplateArgs) { 2259 // Only try to recover from lookup into dependent bases in static methods or 2260 // contexts where 'this' is available. 2261 QualType ThisType = S.getCurrentThisType(); 2262 const CXXRecordDecl *RD = nullptr; 2263 if (!ThisType.isNull()) 2264 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2265 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2266 RD = MD->getParent(); 2267 if (!RD || !RD->hasAnyDependentBases()) 2268 return nullptr; 2269 2270 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2271 // is available, suggest inserting 'this->' as a fixit. 2272 SourceLocation Loc = NameInfo.getLoc(); 2273 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2274 DB << NameInfo.getName() << RD; 2275 2276 if (!ThisType.isNull()) { 2277 DB << FixItHint::CreateInsertion(Loc, "this->"); 2278 return CXXDependentScopeMemberExpr::Create( 2279 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2280 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2281 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2282 } 2283 2284 // Synthesize a fake NNS that points to the derived class. This will 2285 // perform name lookup during template instantiation. 2286 CXXScopeSpec SS; 2287 auto *NNS = 2288 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2289 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2290 return DependentScopeDeclRefExpr::Create( 2291 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2292 TemplateArgs); 2293 } 2294 2295 ExprResult 2296 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2297 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2298 bool HasTrailingLParen, bool IsAddressOfOperand, 2299 CorrectionCandidateCallback *CCC, 2300 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2301 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2302 "cannot be direct & operand and have a trailing lparen"); 2303 if (SS.isInvalid()) 2304 return ExprError(); 2305 2306 TemplateArgumentListInfo TemplateArgsBuffer; 2307 2308 // Decompose the UnqualifiedId into the following data. 2309 DeclarationNameInfo NameInfo; 2310 const TemplateArgumentListInfo *TemplateArgs; 2311 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2312 2313 DeclarationName Name = NameInfo.getName(); 2314 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2315 SourceLocation NameLoc = NameInfo.getLoc(); 2316 2317 if (II && II->isEditorPlaceholder()) { 2318 // FIXME: When typed placeholders are supported we can create a typed 2319 // placeholder expression node. 2320 return ExprError(); 2321 } 2322 2323 // C++ [temp.dep.expr]p3: 2324 // An id-expression is type-dependent if it contains: 2325 // -- an identifier that was declared with a dependent type, 2326 // (note: handled after lookup) 2327 // -- a template-id that is dependent, 2328 // (note: handled in BuildTemplateIdExpr) 2329 // -- a conversion-function-id that specifies a dependent type, 2330 // -- a nested-name-specifier that contains a class-name that 2331 // names a dependent type. 2332 // Determine whether this is a member of an unknown specialization; 2333 // we need to handle these differently. 2334 bool DependentID = false; 2335 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2336 Name.getCXXNameType()->isDependentType()) { 2337 DependentID = true; 2338 } else if (SS.isSet()) { 2339 if (DeclContext *DC = computeDeclContext(SS, false)) { 2340 if (RequireCompleteDeclContext(SS, DC)) 2341 return ExprError(); 2342 } else { 2343 DependentID = true; 2344 } 2345 } 2346 2347 if (DependentID) 2348 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2349 IsAddressOfOperand, TemplateArgs); 2350 2351 // Perform the required lookup. 2352 LookupResult R(*this, NameInfo, 2353 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2354 ? LookupObjCImplicitSelfParam 2355 : LookupOrdinaryName); 2356 if (TemplateKWLoc.isValid() || TemplateArgs) { 2357 // Lookup the template name again to correctly establish the context in 2358 // which it was found. This is really unfortunate as we already did the 2359 // lookup to determine that it was a template name in the first place. If 2360 // this becomes a performance hit, we can work harder to preserve those 2361 // results until we get here but it's likely not worth it. 2362 bool MemberOfUnknownSpecialization; 2363 AssumedTemplateKind AssumedTemplate; 2364 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2365 MemberOfUnknownSpecialization, TemplateKWLoc, 2366 &AssumedTemplate)) 2367 return ExprError(); 2368 2369 if (MemberOfUnknownSpecialization || 2370 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2371 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2372 IsAddressOfOperand, TemplateArgs); 2373 } else { 2374 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2375 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2376 2377 // If the result might be in a dependent base class, this is a dependent 2378 // id-expression. 2379 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2380 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2381 IsAddressOfOperand, TemplateArgs); 2382 2383 // If this reference is in an Objective-C method, then we need to do 2384 // some special Objective-C lookup, too. 2385 if (IvarLookupFollowUp) { 2386 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2387 if (E.isInvalid()) 2388 return ExprError(); 2389 2390 if (Expr *Ex = E.getAs<Expr>()) 2391 return Ex; 2392 } 2393 } 2394 2395 if (R.isAmbiguous()) 2396 return ExprError(); 2397 2398 // This could be an implicitly declared function reference (legal in C90, 2399 // extension in C99, forbidden in C++). 2400 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2401 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2402 if (D) R.addDecl(D); 2403 } 2404 2405 // Determine whether this name might be a candidate for 2406 // argument-dependent lookup. 2407 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2408 2409 if (R.empty() && !ADL) { 2410 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2411 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2412 TemplateKWLoc, TemplateArgs)) 2413 return E; 2414 } 2415 2416 // Don't diagnose an empty lookup for inline assembly. 2417 if (IsInlineAsmIdentifier) 2418 return ExprError(); 2419 2420 // If this name wasn't predeclared and if this is not a function 2421 // call, diagnose the problem. 2422 TypoExpr *TE = nullptr; 2423 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2424 : nullptr); 2425 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2426 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2427 "Typo correction callback misconfigured"); 2428 if (CCC) { 2429 // Make sure the callback knows what the typo being diagnosed is. 2430 CCC->setTypoName(II); 2431 if (SS.isValid()) 2432 CCC->setTypoNNS(SS.getScopeRep()); 2433 } 2434 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2435 // a template name, but we happen to have always already looked up the name 2436 // before we get here if it must be a template name. 2437 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2438 None, &TE)) { 2439 if (TE && KeywordReplacement) { 2440 auto &State = getTypoExprState(TE); 2441 auto BestTC = State.Consumer->getNextCorrection(); 2442 if (BestTC.isKeyword()) { 2443 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2444 if (State.DiagHandler) 2445 State.DiagHandler(BestTC); 2446 KeywordReplacement->startToken(); 2447 KeywordReplacement->setKind(II->getTokenID()); 2448 KeywordReplacement->setIdentifierInfo(II); 2449 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2450 // Clean up the state associated with the TypoExpr, since it has 2451 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2452 clearDelayedTypo(TE); 2453 // Signal that a correction to a keyword was performed by returning a 2454 // valid-but-null ExprResult. 2455 return (Expr*)nullptr; 2456 } 2457 State.Consumer->resetCorrectionStream(); 2458 } 2459 return TE ? TE : ExprError(); 2460 } 2461 2462 assert(!R.empty() && 2463 "DiagnoseEmptyLookup returned false but added no results"); 2464 2465 // If we found an Objective-C instance variable, let 2466 // LookupInObjCMethod build the appropriate expression to 2467 // reference the ivar. 2468 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2469 R.clear(); 2470 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2471 // In a hopelessly buggy code, Objective-C instance variable 2472 // lookup fails and no expression will be built to reference it. 2473 if (!E.isInvalid() && !E.get()) 2474 return ExprError(); 2475 return E; 2476 } 2477 } 2478 2479 // This is guaranteed from this point on. 2480 assert(!R.empty() || ADL); 2481 2482 // Check whether this might be a C++ implicit instance member access. 2483 // C++ [class.mfct.non-static]p3: 2484 // When an id-expression that is not part of a class member access 2485 // syntax and not used to form a pointer to member is used in the 2486 // body of a non-static member function of class X, if name lookup 2487 // resolves the name in the id-expression to a non-static non-type 2488 // member of some class C, the id-expression is transformed into a 2489 // class member access expression using (*this) as the 2490 // postfix-expression to the left of the . operator. 2491 // 2492 // But we don't actually need to do this for '&' operands if R 2493 // resolved to a function or overloaded function set, because the 2494 // expression is ill-formed if it actually works out to be a 2495 // non-static member function: 2496 // 2497 // C++ [expr.ref]p4: 2498 // Otherwise, if E1.E2 refers to a non-static member function. . . 2499 // [t]he expression can be used only as the left-hand operand of a 2500 // member function call. 2501 // 2502 // There are other safeguards against such uses, but it's important 2503 // to get this right here so that we don't end up making a 2504 // spuriously dependent expression if we're inside a dependent 2505 // instance method. 2506 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2507 bool MightBeImplicitMember; 2508 if (!IsAddressOfOperand) 2509 MightBeImplicitMember = true; 2510 else if (!SS.isEmpty()) 2511 MightBeImplicitMember = false; 2512 else if (R.isOverloadedResult()) 2513 MightBeImplicitMember = false; 2514 else if (R.isUnresolvableResult()) 2515 MightBeImplicitMember = true; 2516 else 2517 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2518 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2519 isa<MSPropertyDecl>(R.getFoundDecl()); 2520 2521 if (MightBeImplicitMember) 2522 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2523 R, TemplateArgs, S); 2524 } 2525 2526 if (TemplateArgs || TemplateKWLoc.isValid()) { 2527 2528 // In C++1y, if this is a variable template id, then check it 2529 // in BuildTemplateIdExpr(). 2530 // The single lookup result must be a variable template declaration. 2531 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2532 Id.TemplateId->Kind == TNK_Var_template) { 2533 assert(R.getAsSingle<VarTemplateDecl>() && 2534 "There should only be one declaration found."); 2535 } 2536 2537 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2538 } 2539 2540 return BuildDeclarationNameExpr(SS, R, ADL); 2541 } 2542 2543 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2544 /// declaration name, generally during template instantiation. 2545 /// There's a large number of things which don't need to be done along 2546 /// this path. 2547 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2548 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2549 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2550 DeclContext *DC = computeDeclContext(SS, false); 2551 if (!DC) 2552 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2553 NameInfo, /*TemplateArgs=*/nullptr); 2554 2555 if (RequireCompleteDeclContext(SS, DC)) 2556 return ExprError(); 2557 2558 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2559 LookupQualifiedName(R, DC); 2560 2561 if (R.isAmbiguous()) 2562 return ExprError(); 2563 2564 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2565 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2566 NameInfo, /*TemplateArgs=*/nullptr); 2567 2568 if (R.empty()) { 2569 Diag(NameInfo.getLoc(), diag::err_no_member) 2570 << NameInfo.getName() << DC << SS.getRange(); 2571 return ExprError(); 2572 } 2573 2574 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2575 // Diagnose a missing typename if this resolved unambiguously to a type in 2576 // a dependent context. If we can recover with a type, downgrade this to 2577 // a warning in Microsoft compatibility mode. 2578 unsigned DiagID = diag::err_typename_missing; 2579 if (RecoveryTSI && getLangOpts().MSVCCompat) 2580 DiagID = diag::ext_typename_missing; 2581 SourceLocation Loc = SS.getBeginLoc(); 2582 auto D = Diag(Loc, DiagID); 2583 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2584 << SourceRange(Loc, NameInfo.getEndLoc()); 2585 2586 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2587 // context. 2588 if (!RecoveryTSI) 2589 return ExprError(); 2590 2591 // Only issue the fixit if we're prepared to recover. 2592 D << FixItHint::CreateInsertion(Loc, "typename "); 2593 2594 // Recover by pretending this was an elaborated type. 2595 QualType Ty = Context.getTypeDeclType(TD); 2596 TypeLocBuilder TLB; 2597 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2598 2599 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2600 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2601 QTL.setElaboratedKeywordLoc(SourceLocation()); 2602 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2603 2604 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2605 2606 return ExprEmpty(); 2607 } 2608 2609 // Defend against this resolving to an implicit member access. We usually 2610 // won't get here if this might be a legitimate a class member (we end up in 2611 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2612 // a pointer-to-member or in an unevaluated context in C++11. 2613 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2614 return BuildPossibleImplicitMemberExpr(SS, 2615 /*TemplateKWLoc=*/SourceLocation(), 2616 R, /*TemplateArgs=*/nullptr, S); 2617 2618 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2619 } 2620 2621 /// The parser has read a name in, and Sema has detected that we're currently 2622 /// inside an ObjC method. Perform some additional checks and determine if we 2623 /// should form a reference to an ivar. 2624 /// 2625 /// Ideally, most of this would be done by lookup, but there's 2626 /// actually quite a lot of extra work involved. 2627 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2628 IdentifierInfo *II) { 2629 SourceLocation Loc = Lookup.getNameLoc(); 2630 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2631 2632 // Check for error condition which is already reported. 2633 if (!CurMethod) 2634 return DeclResult(true); 2635 2636 // There are two cases to handle here. 1) scoped lookup could have failed, 2637 // in which case we should look for an ivar. 2) scoped lookup could have 2638 // found a decl, but that decl is outside the current instance method (i.e. 2639 // a global variable). In these two cases, we do a lookup for an ivar with 2640 // this name, if the lookup sucedes, we replace it our current decl. 2641 2642 // If we're in a class method, we don't normally want to look for 2643 // ivars. But if we don't find anything else, and there's an 2644 // ivar, that's an error. 2645 bool IsClassMethod = CurMethod->isClassMethod(); 2646 2647 bool LookForIvars; 2648 if (Lookup.empty()) 2649 LookForIvars = true; 2650 else if (IsClassMethod) 2651 LookForIvars = false; 2652 else 2653 LookForIvars = (Lookup.isSingleResult() && 2654 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2655 ObjCInterfaceDecl *IFace = nullptr; 2656 if (LookForIvars) { 2657 IFace = CurMethod->getClassInterface(); 2658 ObjCInterfaceDecl *ClassDeclared; 2659 ObjCIvarDecl *IV = nullptr; 2660 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2661 // Diagnose using an ivar in a class method. 2662 if (IsClassMethod) { 2663 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2664 return DeclResult(true); 2665 } 2666 2667 // Diagnose the use of an ivar outside of the declaring class. 2668 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2669 !declaresSameEntity(ClassDeclared, IFace) && 2670 !getLangOpts().DebuggerSupport) 2671 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2672 2673 // Success. 2674 return IV; 2675 } 2676 } else if (CurMethod->isInstanceMethod()) { 2677 // We should warn if a local variable hides an ivar. 2678 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2679 ObjCInterfaceDecl *ClassDeclared; 2680 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2681 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2682 declaresSameEntity(IFace, ClassDeclared)) 2683 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2684 } 2685 } 2686 } else if (Lookup.isSingleResult() && 2687 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2688 // If accessing a stand-alone ivar in a class method, this is an error. 2689 if (const ObjCIvarDecl *IV = 2690 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2691 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2692 return DeclResult(true); 2693 } 2694 } 2695 2696 // Didn't encounter an error, didn't find an ivar. 2697 return DeclResult(false); 2698 } 2699 2700 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2701 ObjCIvarDecl *IV) { 2702 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2703 assert(CurMethod && CurMethod->isInstanceMethod() && 2704 "should not reference ivar from this context"); 2705 2706 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2707 assert(IFace && "should not reference ivar from this context"); 2708 2709 // If we're referencing an invalid decl, just return this as a silent 2710 // error node. The error diagnostic was already emitted on the decl. 2711 if (IV->isInvalidDecl()) 2712 return ExprError(); 2713 2714 // Check if referencing a field with __attribute__((deprecated)). 2715 if (DiagnoseUseOfDecl(IV, Loc)) 2716 return ExprError(); 2717 2718 // FIXME: This should use a new expr for a direct reference, don't 2719 // turn this into Self->ivar, just return a BareIVarExpr or something. 2720 IdentifierInfo &II = Context.Idents.get("self"); 2721 UnqualifiedId SelfName; 2722 SelfName.setIdentifier(&II, SourceLocation()); 2723 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2724 CXXScopeSpec SelfScopeSpec; 2725 SourceLocation TemplateKWLoc; 2726 ExprResult SelfExpr = 2727 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2728 /*HasTrailingLParen=*/false, 2729 /*IsAddressOfOperand=*/false); 2730 if (SelfExpr.isInvalid()) 2731 return ExprError(); 2732 2733 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2734 if (SelfExpr.isInvalid()) 2735 return ExprError(); 2736 2737 MarkAnyDeclReferenced(Loc, IV, true); 2738 2739 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2740 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2741 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2742 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2743 2744 ObjCIvarRefExpr *Result = new (Context) 2745 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2746 IV->getLocation(), SelfExpr.get(), true, true); 2747 2748 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2749 if (!isUnevaluatedContext() && 2750 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2751 getCurFunction()->recordUseOfWeak(Result); 2752 } 2753 if (getLangOpts().ObjCAutoRefCount) 2754 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2755 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2756 2757 return Result; 2758 } 2759 2760 /// The parser has read a name in, and Sema has detected that we're currently 2761 /// inside an ObjC method. Perform some additional checks and determine if we 2762 /// should form a reference to an ivar. If so, build an expression referencing 2763 /// that ivar. 2764 ExprResult 2765 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2766 IdentifierInfo *II, bool AllowBuiltinCreation) { 2767 // FIXME: Integrate this lookup step into LookupParsedName. 2768 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2769 if (Ivar.isInvalid()) 2770 return ExprError(); 2771 if (Ivar.isUsable()) 2772 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2773 cast<ObjCIvarDecl>(Ivar.get())); 2774 2775 if (Lookup.empty() && II && AllowBuiltinCreation) 2776 LookupBuiltin(Lookup); 2777 2778 // Sentinel value saying that we didn't do anything special. 2779 return ExprResult(false); 2780 } 2781 2782 /// Cast a base object to a member's actual type. 2783 /// 2784 /// Logically this happens in three phases: 2785 /// 2786 /// * First we cast from the base type to the naming class. 2787 /// The naming class is the class into which we were looking 2788 /// when we found the member; it's the qualifier type if a 2789 /// qualifier was provided, and otherwise it's the base type. 2790 /// 2791 /// * Next we cast from the naming class to the declaring class. 2792 /// If the member we found was brought into a class's scope by 2793 /// a using declaration, this is that class; otherwise it's 2794 /// the class declaring the member. 2795 /// 2796 /// * Finally we cast from the declaring class to the "true" 2797 /// declaring class of the member. This conversion does not 2798 /// obey access control. 2799 ExprResult 2800 Sema::PerformObjectMemberConversion(Expr *From, 2801 NestedNameSpecifier *Qualifier, 2802 NamedDecl *FoundDecl, 2803 NamedDecl *Member) { 2804 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2805 if (!RD) 2806 return From; 2807 2808 QualType DestRecordType; 2809 QualType DestType; 2810 QualType FromRecordType; 2811 QualType FromType = From->getType(); 2812 bool PointerConversions = false; 2813 if (isa<FieldDecl>(Member)) { 2814 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2815 auto FromPtrType = FromType->getAs<PointerType>(); 2816 DestRecordType = Context.getAddrSpaceQualType( 2817 DestRecordType, FromPtrType 2818 ? FromType->getPointeeType().getAddressSpace() 2819 : FromType.getAddressSpace()); 2820 2821 if (FromPtrType) { 2822 DestType = Context.getPointerType(DestRecordType); 2823 FromRecordType = FromPtrType->getPointeeType(); 2824 PointerConversions = true; 2825 } else { 2826 DestType = DestRecordType; 2827 FromRecordType = FromType; 2828 } 2829 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2830 if (Method->isStatic()) 2831 return From; 2832 2833 DestType = Method->getThisType(); 2834 DestRecordType = DestType->getPointeeType(); 2835 2836 if (FromType->getAs<PointerType>()) { 2837 FromRecordType = FromType->getPointeeType(); 2838 PointerConversions = true; 2839 } else { 2840 FromRecordType = FromType; 2841 DestType = DestRecordType; 2842 } 2843 2844 LangAS FromAS = FromRecordType.getAddressSpace(); 2845 LangAS DestAS = DestRecordType.getAddressSpace(); 2846 if (FromAS != DestAS) { 2847 QualType FromRecordTypeWithoutAS = 2848 Context.removeAddrSpaceQualType(FromRecordType); 2849 QualType FromTypeWithDestAS = 2850 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2851 if (PointerConversions) 2852 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2853 From = ImpCastExprToType(From, FromTypeWithDestAS, 2854 CK_AddressSpaceConversion, From->getValueKind()) 2855 .get(); 2856 } 2857 } else { 2858 // No conversion necessary. 2859 return From; 2860 } 2861 2862 if (DestType->isDependentType() || FromType->isDependentType()) 2863 return From; 2864 2865 // If the unqualified types are the same, no conversion is necessary. 2866 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2867 return From; 2868 2869 SourceRange FromRange = From->getSourceRange(); 2870 SourceLocation FromLoc = FromRange.getBegin(); 2871 2872 ExprValueKind VK = From->getValueKind(); 2873 2874 // C++ [class.member.lookup]p8: 2875 // [...] Ambiguities can often be resolved by qualifying a name with its 2876 // class name. 2877 // 2878 // If the member was a qualified name and the qualified referred to a 2879 // specific base subobject type, we'll cast to that intermediate type 2880 // first and then to the object in which the member is declared. That allows 2881 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2882 // 2883 // class Base { public: int x; }; 2884 // class Derived1 : public Base { }; 2885 // class Derived2 : public Base { }; 2886 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2887 // 2888 // void VeryDerived::f() { 2889 // x = 17; // error: ambiguous base subobjects 2890 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2891 // } 2892 if (Qualifier && Qualifier->getAsType()) { 2893 QualType QType = QualType(Qualifier->getAsType(), 0); 2894 assert(QType->isRecordType() && "lookup done with non-record type"); 2895 2896 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2897 2898 // In C++98, the qualifier type doesn't actually have to be a base 2899 // type of the object type, in which case we just ignore it. 2900 // Otherwise build the appropriate casts. 2901 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2902 CXXCastPath BasePath; 2903 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2904 FromLoc, FromRange, &BasePath)) 2905 return ExprError(); 2906 2907 if (PointerConversions) 2908 QType = Context.getPointerType(QType); 2909 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2910 VK, &BasePath).get(); 2911 2912 FromType = QType; 2913 FromRecordType = QRecordType; 2914 2915 // If the qualifier type was the same as the destination type, 2916 // we're done. 2917 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2918 return From; 2919 } 2920 } 2921 2922 bool IgnoreAccess = false; 2923 2924 // If we actually found the member through a using declaration, cast 2925 // down to the using declaration's type. 2926 // 2927 // Pointer equality is fine here because only one declaration of a 2928 // class ever has member declarations. 2929 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2930 assert(isa<UsingShadowDecl>(FoundDecl)); 2931 QualType URecordType = Context.getTypeDeclType( 2932 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2933 2934 // We only need to do this if the naming-class to declaring-class 2935 // conversion is non-trivial. 2936 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2937 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2938 CXXCastPath BasePath; 2939 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2940 FromLoc, FromRange, &BasePath)) 2941 return ExprError(); 2942 2943 QualType UType = URecordType; 2944 if (PointerConversions) 2945 UType = Context.getPointerType(UType); 2946 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2947 VK, &BasePath).get(); 2948 FromType = UType; 2949 FromRecordType = URecordType; 2950 } 2951 2952 // We don't do access control for the conversion from the 2953 // declaring class to the true declaring class. 2954 IgnoreAccess = true; 2955 } 2956 2957 CXXCastPath BasePath; 2958 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2959 FromLoc, FromRange, &BasePath, 2960 IgnoreAccess)) 2961 return ExprError(); 2962 2963 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2964 VK, &BasePath); 2965 } 2966 2967 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2968 const LookupResult &R, 2969 bool HasTrailingLParen) { 2970 // Only when used directly as the postfix-expression of a call. 2971 if (!HasTrailingLParen) 2972 return false; 2973 2974 // Never if a scope specifier was provided. 2975 if (SS.isSet()) 2976 return false; 2977 2978 // Only in C++ or ObjC++. 2979 if (!getLangOpts().CPlusPlus) 2980 return false; 2981 2982 // Turn off ADL when we find certain kinds of declarations during 2983 // normal lookup: 2984 for (NamedDecl *D : R) { 2985 // C++0x [basic.lookup.argdep]p3: 2986 // -- a declaration of a class member 2987 // Since using decls preserve this property, we check this on the 2988 // original decl. 2989 if (D->isCXXClassMember()) 2990 return false; 2991 2992 // C++0x [basic.lookup.argdep]p3: 2993 // -- a block-scope function declaration that is not a 2994 // using-declaration 2995 // NOTE: we also trigger this for function templates (in fact, we 2996 // don't check the decl type at all, since all other decl types 2997 // turn off ADL anyway). 2998 if (isa<UsingShadowDecl>(D)) 2999 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3000 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3001 return false; 3002 3003 // C++0x [basic.lookup.argdep]p3: 3004 // -- a declaration that is neither a function or a function 3005 // template 3006 // And also for builtin functions. 3007 if (isa<FunctionDecl>(D)) { 3008 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3009 3010 // But also builtin functions. 3011 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3012 return false; 3013 } else if (!isa<FunctionTemplateDecl>(D)) 3014 return false; 3015 } 3016 3017 return true; 3018 } 3019 3020 3021 /// Diagnoses obvious problems with the use of the given declaration 3022 /// as an expression. This is only actually called for lookups that 3023 /// were not overloaded, and it doesn't promise that the declaration 3024 /// will in fact be used. 3025 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3026 if (D->isInvalidDecl()) 3027 return true; 3028 3029 if (isa<TypedefNameDecl>(D)) { 3030 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3031 return true; 3032 } 3033 3034 if (isa<ObjCInterfaceDecl>(D)) { 3035 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3036 return true; 3037 } 3038 3039 if (isa<NamespaceDecl>(D)) { 3040 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3041 return true; 3042 } 3043 3044 return false; 3045 } 3046 3047 // Certain multiversion types should be treated as overloaded even when there is 3048 // only one result. 3049 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3050 assert(R.isSingleResult() && "Expected only a single result"); 3051 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3052 return FD && 3053 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3054 } 3055 3056 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3057 LookupResult &R, bool NeedsADL, 3058 bool AcceptInvalidDecl) { 3059 // If this is a single, fully-resolved result and we don't need ADL, 3060 // just build an ordinary singleton decl ref. 3061 if (!NeedsADL && R.isSingleResult() && 3062 !R.getAsSingle<FunctionTemplateDecl>() && 3063 !ShouldLookupResultBeMultiVersionOverload(R)) 3064 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3065 R.getRepresentativeDecl(), nullptr, 3066 AcceptInvalidDecl); 3067 3068 // We only need to check the declaration if there's exactly one 3069 // result, because in the overloaded case the results can only be 3070 // functions and function templates. 3071 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3072 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3073 return ExprError(); 3074 3075 // Otherwise, just build an unresolved lookup expression. Suppress 3076 // any lookup-related diagnostics; we'll hash these out later, when 3077 // we've picked a target. 3078 R.suppressDiagnostics(); 3079 3080 UnresolvedLookupExpr *ULE 3081 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3082 SS.getWithLocInContext(Context), 3083 R.getLookupNameInfo(), 3084 NeedsADL, R.isOverloadedResult(), 3085 R.begin(), R.end()); 3086 3087 return ULE; 3088 } 3089 3090 static void 3091 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3092 ValueDecl *var, DeclContext *DC); 3093 3094 /// Complete semantic analysis for a reference to the given declaration. 3095 ExprResult Sema::BuildDeclarationNameExpr( 3096 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3097 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3098 bool AcceptInvalidDecl) { 3099 assert(D && "Cannot refer to a NULL declaration"); 3100 assert(!isa<FunctionTemplateDecl>(D) && 3101 "Cannot refer unambiguously to a function template"); 3102 3103 SourceLocation Loc = NameInfo.getLoc(); 3104 if (CheckDeclInExpr(*this, Loc, D)) 3105 return ExprError(); 3106 3107 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3108 // Specifically diagnose references to class templates that are missing 3109 // a template argument list. 3110 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3111 return ExprError(); 3112 } 3113 3114 // Make sure that we're referring to a value. 3115 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3116 if (!VD) { 3117 Diag(Loc, diag::err_ref_non_value) 3118 << D << SS.getRange(); 3119 Diag(D->getLocation(), diag::note_declared_at); 3120 return ExprError(); 3121 } 3122 3123 // Check whether this declaration can be used. Note that we suppress 3124 // this check when we're going to perform argument-dependent lookup 3125 // on this function name, because this might not be the function 3126 // that overload resolution actually selects. 3127 if (DiagnoseUseOfDecl(VD, Loc)) 3128 return ExprError(); 3129 3130 // Only create DeclRefExpr's for valid Decl's. 3131 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3132 return ExprError(); 3133 3134 // Handle members of anonymous structs and unions. If we got here, 3135 // and the reference is to a class member indirect field, then this 3136 // must be the subject of a pointer-to-member expression. 3137 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3138 if (!indirectField->isCXXClassMember()) 3139 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3140 indirectField); 3141 3142 { 3143 QualType type = VD->getType(); 3144 if (type.isNull()) 3145 return ExprError(); 3146 ExprValueKind valueKind = VK_RValue; 3147 3148 switch (D->getKind()) { 3149 // Ignore all the non-ValueDecl kinds. 3150 #define ABSTRACT_DECL(kind) 3151 #define VALUE(type, base) 3152 #define DECL(type, base) \ 3153 case Decl::type: 3154 #include "clang/AST/DeclNodes.inc" 3155 llvm_unreachable("invalid value decl kind"); 3156 3157 // These shouldn't make it here. 3158 case Decl::ObjCAtDefsField: 3159 llvm_unreachable("forming non-member reference to ivar?"); 3160 3161 // Enum constants are always r-values and never references. 3162 // Unresolved using declarations are dependent. 3163 case Decl::EnumConstant: 3164 case Decl::UnresolvedUsingValue: 3165 case Decl::OMPDeclareReduction: 3166 case Decl::OMPDeclareMapper: 3167 valueKind = VK_RValue; 3168 break; 3169 3170 // Fields and indirect fields that got here must be for 3171 // pointer-to-member expressions; we just call them l-values for 3172 // internal consistency, because this subexpression doesn't really 3173 // exist in the high-level semantics. 3174 case Decl::Field: 3175 case Decl::IndirectField: 3176 case Decl::ObjCIvar: 3177 assert(getLangOpts().CPlusPlus && 3178 "building reference to field in C?"); 3179 3180 // These can't have reference type in well-formed programs, but 3181 // for internal consistency we do this anyway. 3182 type = type.getNonReferenceType(); 3183 valueKind = VK_LValue; 3184 break; 3185 3186 // Non-type template parameters are either l-values or r-values 3187 // depending on the type. 3188 case Decl::NonTypeTemplateParm: { 3189 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3190 type = reftype->getPointeeType(); 3191 valueKind = VK_LValue; // even if the parameter is an r-value reference 3192 break; 3193 } 3194 3195 // For non-references, we need to strip qualifiers just in case 3196 // the template parameter was declared as 'const int' or whatever. 3197 valueKind = VK_RValue; 3198 type = type.getUnqualifiedType(); 3199 break; 3200 } 3201 3202 case Decl::Var: 3203 case Decl::VarTemplateSpecialization: 3204 case Decl::VarTemplatePartialSpecialization: 3205 case Decl::Decomposition: 3206 case Decl::OMPCapturedExpr: 3207 // In C, "extern void blah;" is valid and is an r-value. 3208 if (!getLangOpts().CPlusPlus && 3209 !type.hasQualifiers() && 3210 type->isVoidType()) { 3211 valueKind = VK_RValue; 3212 break; 3213 } 3214 LLVM_FALLTHROUGH; 3215 3216 case Decl::ImplicitParam: 3217 case Decl::ParmVar: { 3218 // These are always l-values. 3219 valueKind = VK_LValue; 3220 type = type.getNonReferenceType(); 3221 3222 // FIXME: Does the addition of const really only apply in 3223 // potentially-evaluated contexts? Since the variable isn't actually 3224 // captured in an unevaluated context, it seems that the answer is no. 3225 if (!isUnevaluatedContext()) { 3226 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3227 if (!CapturedType.isNull()) 3228 type = CapturedType; 3229 } 3230 3231 break; 3232 } 3233 3234 case Decl::Binding: { 3235 // These are always lvalues. 3236 valueKind = VK_LValue; 3237 type = type.getNonReferenceType(); 3238 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3239 // decides how that's supposed to work. 3240 auto *BD = cast<BindingDecl>(VD); 3241 if (BD->getDeclContext() != CurContext) { 3242 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3243 if (DD && DD->hasLocalStorage()) 3244 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3245 } 3246 break; 3247 } 3248 3249 case Decl::Function: { 3250 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3251 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3252 type = Context.BuiltinFnTy; 3253 valueKind = VK_RValue; 3254 break; 3255 } 3256 } 3257 3258 const FunctionType *fty = type->castAs<FunctionType>(); 3259 3260 // If we're referring to a function with an __unknown_anytype 3261 // result type, make the entire expression __unknown_anytype. 3262 if (fty->getReturnType() == Context.UnknownAnyTy) { 3263 type = Context.UnknownAnyTy; 3264 valueKind = VK_RValue; 3265 break; 3266 } 3267 3268 // Functions are l-values in C++. 3269 if (getLangOpts().CPlusPlus) { 3270 valueKind = VK_LValue; 3271 break; 3272 } 3273 3274 // C99 DR 316 says that, if a function type comes from a 3275 // function definition (without a prototype), that type is only 3276 // used for checking compatibility. Therefore, when referencing 3277 // the function, we pretend that we don't have the full function 3278 // type. 3279 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3280 isa<FunctionProtoType>(fty)) 3281 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3282 fty->getExtInfo()); 3283 3284 // Functions are r-values in C. 3285 valueKind = VK_RValue; 3286 break; 3287 } 3288 3289 case Decl::CXXDeductionGuide: 3290 llvm_unreachable("building reference to deduction guide"); 3291 3292 case Decl::MSProperty: 3293 case Decl::MSGuid: 3294 // FIXME: Should MSGuidDecl be subject to capture in OpenMP, 3295 // or duplicated between host and device? 3296 valueKind = VK_LValue; 3297 break; 3298 3299 case Decl::CXXMethod: 3300 // If we're referring to a method with an __unknown_anytype 3301 // result type, make the entire expression __unknown_anytype. 3302 // This should only be possible with a type written directly. 3303 if (const FunctionProtoType *proto 3304 = dyn_cast<FunctionProtoType>(VD->getType())) 3305 if (proto->getReturnType() == Context.UnknownAnyTy) { 3306 type = Context.UnknownAnyTy; 3307 valueKind = VK_RValue; 3308 break; 3309 } 3310 3311 // C++ methods are l-values if static, r-values if non-static. 3312 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3313 valueKind = VK_LValue; 3314 break; 3315 } 3316 LLVM_FALLTHROUGH; 3317 3318 case Decl::CXXConversion: 3319 case Decl::CXXDestructor: 3320 case Decl::CXXConstructor: 3321 valueKind = VK_RValue; 3322 break; 3323 } 3324 3325 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3326 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3327 TemplateArgs); 3328 } 3329 } 3330 3331 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3332 SmallString<32> &Target) { 3333 Target.resize(CharByteWidth * (Source.size() + 1)); 3334 char *ResultPtr = &Target[0]; 3335 const llvm::UTF8 *ErrorPtr; 3336 bool success = 3337 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3338 (void)success; 3339 assert(success); 3340 Target.resize(ResultPtr - &Target[0]); 3341 } 3342 3343 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3344 PredefinedExpr::IdentKind IK) { 3345 // Pick the current block, lambda, captured statement or function. 3346 Decl *currentDecl = nullptr; 3347 if (const BlockScopeInfo *BSI = getCurBlock()) 3348 currentDecl = BSI->TheDecl; 3349 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3350 currentDecl = LSI->CallOperator; 3351 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3352 currentDecl = CSI->TheCapturedDecl; 3353 else 3354 currentDecl = getCurFunctionOrMethodDecl(); 3355 3356 if (!currentDecl) { 3357 Diag(Loc, diag::ext_predef_outside_function); 3358 currentDecl = Context.getTranslationUnitDecl(); 3359 } 3360 3361 QualType ResTy; 3362 StringLiteral *SL = nullptr; 3363 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3364 ResTy = Context.DependentTy; 3365 else { 3366 // Pre-defined identifiers are of type char[x], where x is the length of 3367 // the string. 3368 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3369 unsigned Length = Str.length(); 3370 3371 llvm::APInt LengthI(32, Length + 1); 3372 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3373 ResTy = 3374 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3375 SmallString<32> RawChars; 3376 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3377 Str, RawChars); 3378 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3379 ArrayType::Normal, 3380 /*IndexTypeQuals*/ 0); 3381 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3382 /*Pascal*/ false, ResTy, Loc); 3383 } else { 3384 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3385 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3386 ArrayType::Normal, 3387 /*IndexTypeQuals*/ 0); 3388 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3389 /*Pascal*/ false, ResTy, Loc); 3390 } 3391 } 3392 3393 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3394 } 3395 3396 static std::pair<QualType, StringLiteral *> 3397 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3398 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3399 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3400 3401 if (OpType->isDependentType()) { 3402 Result.first = Context.DependentTy; 3403 return Result; 3404 } 3405 3406 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3407 llvm::APInt Length(32, Str.length() + 1); 3408 Result.first = 3409 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3410 Result.first = Context.getConstantArrayType( 3411 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3412 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3413 /*Pascal*/ false, Result.first, OpLoc); 3414 return Result; 3415 } 3416 3417 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3418 TypeSourceInfo *Operand) { 3419 QualType ResultTy; 3420 StringLiteral *SL; 3421 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3422 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3423 3424 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3425 PredefinedExpr::UniqueStableNameType, SL, 3426 Operand); 3427 } 3428 3429 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3430 Expr *E) { 3431 QualType ResultTy; 3432 StringLiteral *SL; 3433 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3434 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3435 3436 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3437 PredefinedExpr::UniqueStableNameExpr, SL, E); 3438 } 3439 3440 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3441 SourceLocation L, SourceLocation R, 3442 ParsedType Ty) { 3443 TypeSourceInfo *TInfo = nullptr; 3444 QualType T = GetTypeFromParser(Ty, &TInfo); 3445 3446 if (T.isNull()) 3447 return ExprError(); 3448 if (!TInfo) 3449 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3450 3451 return BuildUniqueStableName(OpLoc, TInfo); 3452 } 3453 3454 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3455 SourceLocation L, SourceLocation R, 3456 Expr *E) { 3457 return BuildUniqueStableName(OpLoc, E); 3458 } 3459 3460 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3461 PredefinedExpr::IdentKind IK; 3462 3463 switch (Kind) { 3464 default: llvm_unreachable("Unknown simple primary expr!"); 3465 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3466 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3467 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3468 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3469 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3470 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3471 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3472 } 3473 3474 return BuildPredefinedExpr(Loc, IK); 3475 } 3476 3477 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3478 SmallString<16> CharBuffer; 3479 bool Invalid = false; 3480 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3481 if (Invalid) 3482 return ExprError(); 3483 3484 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3485 PP, Tok.getKind()); 3486 if (Literal.hadError()) 3487 return ExprError(); 3488 3489 QualType Ty; 3490 if (Literal.isWide()) 3491 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3492 else if (Literal.isUTF8() && getLangOpts().Char8) 3493 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3494 else if (Literal.isUTF16()) 3495 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3496 else if (Literal.isUTF32()) 3497 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3498 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3499 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3500 else 3501 Ty = Context.CharTy; // 'x' -> char in C++ 3502 3503 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3504 if (Literal.isWide()) 3505 Kind = CharacterLiteral::Wide; 3506 else if (Literal.isUTF16()) 3507 Kind = CharacterLiteral::UTF16; 3508 else if (Literal.isUTF32()) 3509 Kind = CharacterLiteral::UTF32; 3510 else if (Literal.isUTF8()) 3511 Kind = CharacterLiteral::UTF8; 3512 3513 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3514 Tok.getLocation()); 3515 3516 if (Literal.getUDSuffix().empty()) 3517 return Lit; 3518 3519 // We're building a user-defined literal. 3520 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3521 SourceLocation UDSuffixLoc = 3522 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3523 3524 // Make sure we're allowed user-defined literals here. 3525 if (!UDLScope) 3526 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3527 3528 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3529 // operator "" X (ch) 3530 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3531 Lit, Tok.getLocation()); 3532 } 3533 3534 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3535 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3536 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3537 Context.IntTy, Loc); 3538 } 3539 3540 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3541 QualType Ty, SourceLocation Loc) { 3542 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3543 3544 using llvm::APFloat; 3545 APFloat Val(Format); 3546 3547 APFloat::opStatus result = Literal.GetFloatValue(Val); 3548 3549 // Overflow is always an error, but underflow is only an error if 3550 // we underflowed to zero (APFloat reports denormals as underflow). 3551 if ((result & APFloat::opOverflow) || 3552 ((result & APFloat::opUnderflow) && Val.isZero())) { 3553 unsigned diagnostic; 3554 SmallString<20> buffer; 3555 if (result & APFloat::opOverflow) { 3556 diagnostic = diag::warn_float_overflow; 3557 APFloat::getLargest(Format).toString(buffer); 3558 } else { 3559 diagnostic = diag::warn_float_underflow; 3560 APFloat::getSmallest(Format).toString(buffer); 3561 } 3562 3563 S.Diag(Loc, diagnostic) 3564 << Ty 3565 << StringRef(buffer.data(), buffer.size()); 3566 } 3567 3568 bool isExact = (result == APFloat::opOK); 3569 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3570 } 3571 3572 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3573 assert(E && "Invalid expression"); 3574 3575 if (E->isValueDependent()) 3576 return false; 3577 3578 QualType QT = E->getType(); 3579 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3580 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3581 return true; 3582 } 3583 3584 llvm::APSInt ValueAPS; 3585 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3586 3587 if (R.isInvalid()) 3588 return true; 3589 3590 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3591 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3592 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3593 << ValueAPS.toString(10) << ValueIsPositive; 3594 return true; 3595 } 3596 3597 return false; 3598 } 3599 3600 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3601 // Fast path for a single digit (which is quite common). A single digit 3602 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3603 if (Tok.getLength() == 1) { 3604 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3605 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3606 } 3607 3608 SmallString<128> SpellingBuffer; 3609 // NumericLiteralParser wants to overread by one character. Add padding to 3610 // the buffer in case the token is copied to the buffer. If getSpelling() 3611 // returns a StringRef to the memory buffer, it should have a null char at 3612 // the EOF, so it is also safe. 3613 SpellingBuffer.resize(Tok.getLength() + 1); 3614 3615 // Get the spelling of the token, which eliminates trigraphs, etc. 3616 bool Invalid = false; 3617 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3618 if (Invalid) 3619 return ExprError(); 3620 3621 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3622 if (Literal.hadError) 3623 return ExprError(); 3624 3625 if (Literal.hasUDSuffix()) { 3626 // We're building a user-defined literal. 3627 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3628 SourceLocation UDSuffixLoc = 3629 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3630 3631 // Make sure we're allowed user-defined literals here. 3632 if (!UDLScope) 3633 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3634 3635 QualType CookedTy; 3636 if (Literal.isFloatingLiteral()) { 3637 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3638 // long double, the literal is treated as a call of the form 3639 // operator "" X (f L) 3640 CookedTy = Context.LongDoubleTy; 3641 } else { 3642 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3643 // unsigned long long, the literal is treated as a call of the form 3644 // operator "" X (n ULL) 3645 CookedTy = Context.UnsignedLongLongTy; 3646 } 3647 3648 DeclarationName OpName = 3649 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3650 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3651 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3652 3653 SourceLocation TokLoc = Tok.getLocation(); 3654 3655 // Perform literal operator lookup to determine if we're building a raw 3656 // literal or a cooked one. 3657 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3658 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3659 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3660 /*AllowStringTemplate*/ false, 3661 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3662 case LOLR_ErrorNoDiagnostic: 3663 // Lookup failure for imaginary constants isn't fatal, there's still the 3664 // GNU extension producing _Complex types. 3665 break; 3666 case LOLR_Error: 3667 return ExprError(); 3668 case LOLR_Cooked: { 3669 Expr *Lit; 3670 if (Literal.isFloatingLiteral()) { 3671 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3672 } else { 3673 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3674 if (Literal.GetIntegerValue(ResultVal)) 3675 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3676 << /* Unsigned */ 1; 3677 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3678 Tok.getLocation()); 3679 } 3680 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3681 } 3682 3683 case LOLR_Raw: { 3684 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3685 // literal is treated as a call of the form 3686 // operator "" X ("n") 3687 unsigned Length = Literal.getUDSuffixOffset(); 3688 QualType StrTy = Context.getConstantArrayType( 3689 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3690 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3691 Expr *Lit = StringLiteral::Create( 3692 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3693 /*Pascal*/false, StrTy, &TokLoc, 1); 3694 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3695 } 3696 3697 case LOLR_Template: { 3698 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3699 // template), L is treated as a call fo the form 3700 // operator "" X <'c1', 'c2', ... 'ck'>() 3701 // where n is the source character sequence c1 c2 ... ck. 3702 TemplateArgumentListInfo ExplicitArgs; 3703 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3704 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3705 llvm::APSInt Value(CharBits, CharIsUnsigned); 3706 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3707 Value = TokSpelling[I]; 3708 TemplateArgument Arg(Context, Value, Context.CharTy); 3709 TemplateArgumentLocInfo ArgInfo; 3710 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3711 } 3712 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3713 &ExplicitArgs); 3714 } 3715 case LOLR_StringTemplate: 3716 llvm_unreachable("unexpected literal operator lookup result"); 3717 } 3718 } 3719 3720 Expr *Res; 3721 3722 if (Literal.isFixedPointLiteral()) { 3723 QualType Ty; 3724 3725 if (Literal.isAccum) { 3726 if (Literal.isHalf) { 3727 Ty = Context.ShortAccumTy; 3728 } else if (Literal.isLong) { 3729 Ty = Context.LongAccumTy; 3730 } else { 3731 Ty = Context.AccumTy; 3732 } 3733 } else if (Literal.isFract) { 3734 if (Literal.isHalf) { 3735 Ty = Context.ShortFractTy; 3736 } else if (Literal.isLong) { 3737 Ty = Context.LongFractTy; 3738 } else { 3739 Ty = Context.FractTy; 3740 } 3741 } 3742 3743 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3744 3745 bool isSigned = !Literal.isUnsigned; 3746 unsigned scale = Context.getFixedPointScale(Ty); 3747 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3748 3749 llvm::APInt Val(bit_width, 0, isSigned); 3750 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3751 bool ValIsZero = Val.isNullValue() && !Overflowed; 3752 3753 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3754 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3755 // Clause 6.4.4 - The value of a constant shall be in the range of 3756 // representable values for its type, with exception for constants of a 3757 // fract type with a value of exactly 1; such a constant shall denote 3758 // the maximal value for the type. 3759 --Val; 3760 else if (Val.ugt(MaxVal) || Overflowed) 3761 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3762 3763 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3764 Tok.getLocation(), scale); 3765 } else if (Literal.isFloatingLiteral()) { 3766 QualType Ty; 3767 if (Literal.isHalf){ 3768 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3769 Ty = Context.HalfTy; 3770 else { 3771 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3772 return ExprError(); 3773 } 3774 } else if (Literal.isFloat) 3775 Ty = Context.FloatTy; 3776 else if (Literal.isLong) 3777 Ty = Context.LongDoubleTy; 3778 else if (Literal.isFloat16) 3779 Ty = Context.Float16Ty; 3780 else if (Literal.isFloat128) 3781 Ty = Context.Float128Ty; 3782 else 3783 Ty = Context.DoubleTy; 3784 3785 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3786 3787 if (Ty == Context.DoubleTy) { 3788 if (getLangOpts().SinglePrecisionConstants) { 3789 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3790 if (BTy->getKind() != BuiltinType::Float) { 3791 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3792 } 3793 } else if (getLangOpts().OpenCL && 3794 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3795 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3796 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3797 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3798 } 3799 } 3800 } else if (!Literal.isIntegerLiteral()) { 3801 return ExprError(); 3802 } else { 3803 QualType Ty; 3804 3805 // 'long long' is a C99 or C++11 feature. 3806 if (!getLangOpts().C99 && Literal.isLongLong) { 3807 if (getLangOpts().CPlusPlus) 3808 Diag(Tok.getLocation(), 3809 getLangOpts().CPlusPlus11 ? 3810 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3811 else 3812 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3813 } 3814 3815 // Get the value in the widest-possible width. 3816 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3817 llvm::APInt ResultVal(MaxWidth, 0); 3818 3819 if (Literal.GetIntegerValue(ResultVal)) { 3820 // If this value didn't fit into uintmax_t, error and force to ull. 3821 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3822 << /* Unsigned */ 1; 3823 Ty = Context.UnsignedLongLongTy; 3824 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3825 "long long is not intmax_t?"); 3826 } else { 3827 // If this value fits into a ULL, try to figure out what else it fits into 3828 // according to the rules of C99 6.4.4.1p5. 3829 3830 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3831 // be an unsigned int. 3832 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3833 3834 // Check from smallest to largest, picking the smallest type we can. 3835 unsigned Width = 0; 3836 3837 // Microsoft specific integer suffixes are explicitly sized. 3838 if (Literal.MicrosoftInteger) { 3839 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3840 Width = 8; 3841 Ty = Context.CharTy; 3842 } else { 3843 Width = Literal.MicrosoftInteger; 3844 Ty = Context.getIntTypeForBitwidth(Width, 3845 /*Signed=*/!Literal.isUnsigned); 3846 } 3847 } 3848 3849 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3850 // Are int/unsigned possibilities? 3851 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3852 3853 // Does it fit in a unsigned int? 3854 if (ResultVal.isIntN(IntSize)) { 3855 // Does it fit in a signed int? 3856 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3857 Ty = Context.IntTy; 3858 else if (AllowUnsigned) 3859 Ty = Context.UnsignedIntTy; 3860 Width = IntSize; 3861 } 3862 } 3863 3864 // Are long/unsigned long possibilities? 3865 if (Ty.isNull() && !Literal.isLongLong) { 3866 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3867 3868 // Does it fit in a unsigned long? 3869 if (ResultVal.isIntN(LongSize)) { 3870 // Does it fit in a signed long? 3871 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3872 Ty = Context.LongTy; 3873 else if (AllowUnsigned) 3874 Ty = Context.UnsignedLongTy; 3875 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3876 // is compatible. 3877 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3878 const unsigned LongLongSize = 3879 Context.getTargetInfo().getLongLongWidth(); 3880 Diag(Tok.getLocation(), 3881 getLangOpts().CPlusPlus 3882 ? Literal.isLong 3883 ? diag::warn_old_implicitly_unsigned_long_cxx 3884 : /*C++98 UB*/ diag:: 3885 ext_old_implicitly_unsigned_long_cxx 3886 : diag::warn_old_implicitly_unsigned_long) 3887 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3888 : /*will be ill-formed*/ 1); 3889 Ty = Context.UnsignedLongTy; 3890 } 3891 Width = LongSize; 3892 } 3893 } 3894 3895 // Check long long if needed. 3896 if (Ty.isNull()) { 3897 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3898 3899 // Does it fit in a unsigned long long? 3900 if (ResultVal.isIntN(LongLongSize)) { 3901 // Does it fit in a signed long long? 3902 // To be compatible with MSVC, hex integer literals ending with the 3903 // LL or i64 suffix are always signed in Microsoft mode. 3904 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3905 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3906 Ty = Context.LongLongTy; 3907 else if (AllowUnsigned) 3908 Ty = Context.UnsignedLongLongTy; 3909 Width = LongLongSize; 3910 } 3911 } 3912 3913 // If we still couldn't decide a type, we probably have something that 3914 // does not fit in a signed long long, but has no U suffix. 3915 if (Ty.isNull()) { 3916 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3917 Ty = Context.UnsignedLongLongTy; 3918 Width = Context.getTargetInfo().getLongLongWidth(); 3919 } 3920 3921 if (ResultVal.getBitWidth() != Width) 3922 ResultVal = ResultVal.trunc(Width); 3923 } 3924 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3925 } 3926 3927 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3928 if (Literal.isImaginary) { 3929 Res = new (Context) ImaginaryLiteral(Res, 3930 Context.getComplexType(Res->getType())); 3931 3932 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3933 } 3934 return Res; 3935 } 3936 3937 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3938 assert(E && "ActOnParenExpr() missing expr"); 3939 return new (Context) ParenExpr(L, R, E); 3940 } 3941 3942 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3943 SourceLocation Loc, 3944 SourceRange ArgRange) { 3945 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3946 // scalar or vector data type argument..." 3947 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3948 // type (C99 6.2.5p18) or void. 3949 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3950 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3951 << T << ArgRange; 3952 return true; 3953 } 3954 3955 assert((T->isVoidType() || !T->isIncompleteType()) && 3956 "Scalar types should always be complete"); 3957 return false; 3958 } 3959 3960 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3961 SourceLocation Loc, 3962 SourceRange ArgRange, 3963 UnaryExprOrTypeTrait TraitKind) { 3964 // Invalid types must be hard errors for SFINAE in C++. 3965 if (S.LangOpts.CPlusPlus) 3966 return true; 3967 3968 // C99 6.5.3.4p1: 3969 if (T->isFunctionType() && 3970 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3971 TraitKind == UETT_PreferredAlignOf)) { 3972 // sizeof(function)/alignof(function) is allowed as an extension. 3973 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3974 << TraitKind << ArgRange; 3975 return false; 3976 } 3977 3978 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3979 // this is an error (OpenCL v1.1 s6.3.k) 3980 if (T->isVoidType()) { 3981 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3982 : diag::ext_sizeof_alignof_void_type; 3983 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3984 return false; 3985 } 3986 3987 return true; 3988 } 3989 3990 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3991 SourceLocation Loc, 3992 SourceRange ArgRange, 3993 UnaryExprOrTypeTrait TraitKind) { 3994 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3995 // runtime doesn't allow it. 3996 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3997 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3998 << T << (TraitKind == UETT_SizeOf) 3999 << ArgRange; 4000 return true; 4001 } 4002 4003 return false; 4004 } 4005 4006 /// Check whether E is a pointer from a decayed array type (the decayed 4007 /// pointer type is equal to T) and emit a warning if it is. 4008 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4009 Expr *E) { 4010 // Don't warn if the operation changed the type. 4011 if (T != E->getType()) 4012 return; 4013 4014 // Now look for array decays. 4015 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4016 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4017 return; 4018 4019 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4020 << ICE->getType() 4021 << ICE->getSubExpr()->getType(); 4022 } 4023 4024 /// Check the constraints on expression operands to unary type expression 4025 /// and type traits. 4026 /// 4027 /// Completes any types necessary and validates the constraints on the operand 4028 /// expression. The logic mostly mirrors the type-based overload, but may modify 4029 /// the expression as it completes the type for that expression through template 4030 /// instantiation, etc. 4031 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4032 UnaryExprOrTypeTrait ExprKind) { 4033 QualType ExprTy = E->getType(); 4034 assert(!ExprTy->isReferenceType()); 4035 4036 bool IsUnevaluatedOperand = 4037 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4038 ExprKind == UETT_PreferredAlignOf); 4039 if (IsUnevaluatedOperand) { 4040 ExprResult Result = CheckUnevaluatedOperand(E); 4041 if (Result.isInvalid()) 4042 return true; 4043 E = Result.get(); 4044 } 4045 4046 if (ExprKind == UETT_VecStep) 4047 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4048 E->getSourceRange()); 4049 4050 // Whitelist some types as extensions 4051 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4052 E->getSourceRange(), ExprKind)) 4053 return false; 4054 4055 // 'alignof' applied to an expression only requires the base element type of 4056 // the expression to be complete. 'sizeof' requires the expression's type to 4057 // be complete (and will attempt to complete it if it's an array of unknown 4058 // bound). 4059 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4060 if (RequireCompleteSizedType( 4061 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4062 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4063 E->getSourceRange())) 4064 return true; 4065 } else { 4066 if (RequireCompleteSizedExprType( 4067 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4068 E->getSourceRange())) 4069 return true; 4070 } 4071 4072 // Completing the expression's type may have changed it. 4073 ExprTy = E->getType(); 4074 assert(!ExprTy->isReferenceType()); 4075 4076 if (ExprTy->isFunctionType()) { 4077 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4078 << ExprKind << E->getSourceRange(); 4079 return true; 4080 } 4081 4082 // The operand for sizeof and alignof is in an unevaluated expression context, 4083 // so side effects could result in unintended consequences. 4084 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4085 E->HasSideEffects(Context, false)) 4086 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4087 4088 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4089 E->getSourceRange(), ExprKind)) 4090 return true; 4091 4092 if (ExprKind == UETT_SizeOf) { 4093 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4094 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4095 QualType OType = PVD->getOriginalType(); 4096 QualType Type = PVD->getType(); 4097 if (Type->isPointerType() && OType->isArrayType()) { 4098 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4099 << Type << OType; 4100 Diag(PVD->getLocation(), diag::note_declared_at); 4101 } 4102 } 4103 } 4104 4105 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4106 // decays into a pointer and returns an unintended result. This is most 4107 // likely a typo for "sizeof(array) op x". 4108 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4109 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4110 BO->getLHS()); 4111 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4112 BO->getRHS()); 4113 } 4114 } 4115 4116 return false; 4117 } 4118 4119 /// Check the constraints on operands to unary expression and type 4120 /// traits. 4121 /// 4122 /// This will complete any types necessary, and validate the various constraints 4123 /// on those operands. 4124 /// 4125 /// The UsualUnaryConversions() function is *not* called by this routine. 4126 /// C99 6.3.2.1p[2-4] all state: 4127 /// Except when it is the operand of the sizeof operator ... 4128 /// 4129 /// C++ [expr.sizeof]p4 4130 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4131 /// standard conversions are not applied to the operand of sizeof. 4132 /// 4133 /// This policy is followed for all of the unary trait expressions. 4134 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4135 SourceLocation OpLoc, 4136 SourceRange ExprRange, 4137 UnaryExprOrTypeTrait ExprKind) { 4138 if (ExprType->isDependentType()) 4139 return false; 4140 4141 // C++ [expr.sizeof]p2: 4142 // When applied to a reference or a reference type, the result 4143 // is the size of the referenced type. 4144 // C++11 [expr.alignof]p3: 4145 // When alignof is applied to a reference type, the result 4146 // shall be the alignment of the referenced type. 4147 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4148 ExprType = Ref->getPointeeType(); 4149 4150 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4151 // When alignof or _Alignof is applied to an array type, the result 4152 // is the alignment of the element type. 4153 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4154 ExprKind == UETT_OpenMPRequiredSimdAlign) 4155 ExprType = Context.getBaseElementType(ExprType); 4156 4157 if (ExprKind == UETT_VecStep) 4158 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4159 4160 // Whitelist some types as extensions 4161 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4162 ExprKind)) 4163 return false; 4164 4165 if (RequireCompleteSizedType( 4166 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4167 ExprKind, ExprRange)) 4168 return true; 4169 4170 if (ExprType->isFunctionType()) { 4171 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4172 << ExprKind << ExprRange; 4173 return true; 4174 } 4175 4176 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4177 ExprKind)) 4178 return true; 4179 4180 return false; 4181 } 4182 4183 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4184 // Cannot know anything else if the expression is dependent. 4185 if (E->isTypeDependent()) 4186 return false; 4187 4188 if (E->getObjectKind() == OK_BitField) { 4189 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4190 << 1 << E->getSourceRange(); 4191 return true; 4192 } 4193 4194 ValueDecl *D = nullptr; 4195 Expr *Inner = E->IgnoreParens(); 4196 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4197 D = DRE->getDecl(); 4198 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4199 D = ME->getMemberDecl(); 4200 } 4201 4202 // If it's a field, require the containing struct to have a 4203 // complete definition so that we can compute the layout. 4204 // 4205 // This can happen in C++11 onwards, either by naming the member 4206 // in a way that is not transformed into a member access expression 4207 // (in an unevaluated operand, for instance), or by naming the member 4208 // in a trailing-return-type. 4209 // 4210 // For the record, since __alignof__ on expressions is a GCC 4211 // extension, GCC seems to permit this but always gives the 4212 // nonsensical answer 0. 4213 // 4214 // We don't really need the layout here --- we could instead just 4215 // directly check for all the appropriate alignment-lowing 4216 // attributes --- but that would require duplicating a lot of 4217 // logic that just isn't worth duplicating for such a marginal 4218 // use-case. 4219 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4220 // Fast path this check, since we at least know the record has a 4221 // definition if we can find a member of it. 4222 if (!FD->getParent()->isCompleteDefinition()) { 4223 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4224 << E->getSourceRange(); 4225 return true; 4226 } 4227 4228 // Otherwise, if it's a field, and the field doesn't have 4229 // reference type, then it must have a complete type (or be a 4230 // flexible array member, which we explicitly want to 4231 // white-list anyway), which makes the following checks trivial. 4232 if (!FD->getType()->isReferenceType()) 4233 return false; 4234 } 4235 4236 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4237 } 4238 4239 bool Sema::CheckVecStepExpr(Expr *E) { 4240 E = E->IgnoreParens(); 4241 4242 // Cannot know anything else if the expression is dependent. 4243 if (E->isTypeDependent()) 4244 return false; 4245 4246 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4247 } 4248 4249 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4250 CapturingScopeInfo *CSI) { 4251 assert(T->isVariablyModifiedType()); 4252 assert(CSI != nullptr); 4253 4254 // We're going to walk down into the type and look for VLA expressions. 4255 do { 4256 const Type *Ty = T.getTypePtr(); 4257 switch (Ty->getTypeClass()) { 4258 #define TYPE(Class, Base) 4259 #define ABSTRACT_TYPE(Class, Base) 4260 #define NON_CANONICAL_TYPE(Class, Base) 4261 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4262 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4263 #include "clang/AST/TypeNodes.inc" 4264 T = QualType(); 4265 break; 4266 // These types are never variably-modified. 4267 case Type::Builtin: 4268 case Type::Complex: 4269 case Type::Vector: 4270 case Type::ExtVector: 4271 case Type::ConstantMatrix: 4272 case Type::Record: 4273 case Type::Enum: 4274 case Type::Elaborated: 4275 case Type::TemplateSpecialization: 4276 case Type::ObjCObject: 4277 case Type::ObjCInterface: 4278 case Type::ObjCObjectPointer: 4279 case Type::ObjCTypeParam: 4280 case Type::Pipe: 4281 case Type::ExtInt: 4282 llvm_unreachable("type class is never variably-modified!"); 4283 case Type::Adjusted: 4284 T = cast<AdjustedType>(Ty)->getOriginalType(); 4285 break; 4286 case Type::Decayed: 4287 T = cast<DecayedType>(Ty)->getPointeeType(); 4288 break; 4289 case Type::Pointer: 4290 T = cast<PointerType>(Ty)->getPointeeType(); 4291 break; 4292 case Type::BlockPointer: 4293 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4294 break; 4295 case Type::LValueReference: 4296 case Type::RValueReference: 4297 T = cast<ReferenceType>(Ty)->getPointeeType(); 4298 break; 4299 case Type::MemberPointer: 4300 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4301 break; 4302 case Type::ConstantArray: 4303 case Type::IncompleteArray: 4304 // Losing element qualification here is fine. 4305 T = cast<ArrayType>(Ty)->getElementType(); 4306 break; 4307 case Type::VariableArray: { 4308 // Losing element qualification here is fine. 4309 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4310 4311 // Unknown size indication requires no size computation. 4312 // Otherwise, evaluate and record it. 4313 auto Size = VAT->getSizeExpr(); 4314 if (Size && !CSI->isVLATypeCaptured(VAT) && 4315 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4316 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4317 4318 T = VAT->getElementType(); 4319 break; 4320 } 4321 case Type::FunctionProto: 4322 case Type::FunctionNoProto: 4323 T = cast<FunctionType>(Ty)->getReturnType(); 4324 break; 4325 case Type::Paren: 4326 case Type::TypeOf: 4327 case Type::UnaryTransform: 4328 case Type::Attributed: 4329 case Type::SubstTemplateTypeParm: 4330 case Type::PackExpansion: 4331 case Type::MacroQualified: 4332 // Keep walking after single level desugaring. 4333 T = T.getSingleStepDesugaredType(Context); 4334 break; 4335 case Type::Typedef: 4336 T = cast<TypedefType>(Ty)->desugar(); 4337 break; 4338 case Type::Decltype: 4339 T = cast<DecltypeType>(Ty)->desugar(); 4340 break; 4341 case Type::Auto: 4342 case Type::DeducedTemplateSpecialization: 4343 T = cast<DeducedType>(Ty)->getDeducedType(); 4344 break; 4345 case Type::TypeOfExpr: 4346 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4347 break; 4348 case Type::Atomic: 4349 T = cast<AtomicType>(Ty)->getValueType(); 4350 break; 4351 } 4352 } while (!T.isNull() && T->isVariablyModifiedType()); 4353 } 4354 4355 /// Build a sizeof or alignof expression given a type operand. 4356 ExprResult 4357 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4358 SourceLocation OpLoc, 4359 UnaryExprOrTypeTrait ExprKind, 4360 SourceRange R) { 4361 if (!TInfo) 4362 return ExprError(); 4363 4364 QualType T = TInfo->getType(); 4365 4366 if (!T->isDependentType() && 4367 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4368 return ExprError(); 4369 4370 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4371 if (auto *TT = T->getAs<TypedefType>()) { 4372 for (auto I = FunctionScopes.rbegin(), 4373 E = std::prev(FunctionScopes.rend()); 4374 I != E; ++I) { 4375 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4376 if (CSI == nullptr) 4377 break; 4378 DeclContext *DC = nullptr; 4379 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4380 DC = LSI->CallOperator; 4381 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4382 DC = CRSI->TheCapturedDecl; 4383 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4384 DC = BSI->TheDecl; 4385 if (DC) { 4386 if (DC->containsDecl(TT->getDecl())) 4387 break; 4388 captureVariablyModifiedType(Context, T, CSI); 4389 } 4390 } 4391 } 4392 } 4393 4394 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4395 return new (Context) UnaryExprOrTypeTraitExpr( 4396 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4397 } 4398 4399 /// Build a sizeof or alignof expression given an expression 4400 /// operand. 4401 ExprResult 4402 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4403 UnaryExprOrTypeTrait ExprKind) { 4404 ExprResult PE = CheckPlaceholderExpr(E); 4405 if (PE.isInvalid()) 4406 return ExprError(); 4407 4408 E = PE.get(); 4409 4410 // Verify that the operand is valid. 4411 bool isInvalid = false; 4412 if (E->isTypeDependent()) { 4413 // Delay type-checking for type-dependent expressions. 4414 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4415 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4416 } else if (ExprKind == UETT_VecStep) { 4417 isInvalid = CheckVecStepExpr(E); 4418 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4419 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4420 isInvalid = true; 4421 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4422 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4423 isInvalid = true; 4424 } else { 4425 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4426 } 4427 4428 if (isInvalid) 4429 return ExprError(); 4430 4431 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4432 PE = TransformToPotentiallyEvaluated(E); 4433 if (PE.isInvalid()) return ExprError(); 4434 E = PE.get(); 4435 } 4436 4437 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4438 return new (Context) UnaryExprOrTypeTraitExpr( 4439 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4440 } 4441 4442 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4443 /// expr and the same for @c alignof and @c __alignof 4444 /// Note that the ArgRange is invalid if isType is false. 4445 ExprResult 4446 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4447 UnaryExprOrTypeTrait ExprKind, bool IsType, 4448 void *TyOrEx, SourceRange ArgRange) { 4449 // If error parsing type, ignore. 4450 if (!TyOrEx) return ExprError(); 4451 4452 if (IsType) { 4453 TypeSourceInfo *TInfo; 4454 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4455 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4456 } 4457 4458 Expr *ArgEx = (Expr *)TyOrEx; 4459 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4460 return Result; 4461 } 4462 4463 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4464 bool IsReal) { 4465 if (V.get()->isTypeDependent()) 4466 return S.Context.DependentTy; 4467 4468 // _Real and _Imag are only l-values for normal l-values. 4469 if (V.get()->getObjectKind() != OK_Ordinary) { 4470 V = S.DefaultLvalueConversion(V.get()); 4471 if (V.isInvalid()) 4472 return QualType(); 4473 } 4474 4475 // These operators return the element type of a complex type. 4476 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4477 return CT->getElementType(); 4478 4479 // Otherwise they pass through real integer and floating point types here. 4480 if (V.get()->getType()->isArithmeticType()) 4481 return V.get()->getType(); 4482 4483 // Test for placeholders. 4484 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4485 if (PR.isInvalid()) return QualType(); 4486 if (PR.get() != V.get()) { 4487 V = PR; 4488 return CheckRealImagOperand(S, V, Loc, IsReal); 4489 } 4490 4491 // Reject anything else. 4492 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4493 << (IsReal ? "__real" : "__imag"); 4494 return QualType(); 4495 } 4496 4497 4498 4499 ExprResult 4500 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4501 tok::TokenKind Kind, Expr *Input) { 4502 UnaryOperatorKind Opc; 4503 switch (Kind) { 4504 default: llvm_unreachable("Unknown unary op!"); 4505 case tok::plusplus: Opc = UO_PostInc; break; 4506 case tok::minusminus: Opc = UO_PostDec; break; 4507 } 4508 4509 // Since this might is a postfix expression, get rid of ParenListExprs. 4510 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4511 if (Result.isInvalid()) return ExprError(); 4512 Input = Result.get(); 4513 4514 return BuildUnaryOp(S, OpLoc, Opc, Input); 4515 } 4516 4517 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4518 /// 4519 /// \return true on error 4520 static bool checkArithmeticOnObjCPointer(Sema &S, 4521 SourceLocation opLoc, 4522 Expr *op) { 4523 assert(op->getType()->isObjCObjectPointerType()); 4524 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4525 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4526 return false; 4527 4528 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4529 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4530 << op->getSourceRange(); 4531 return true; 4532 } 4533 4534 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4535 auto *BaseNoParens = Base->IgnoreParens(); 4536 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4537 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4538 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4539 } 4540 4541 ExprResult 4542 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4543 Expr *idx, SourceLocation rbLoc) { 4544 if (base && !base->getType().isNull() && 4545 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4546 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4547 /*Length=*/nullptr, rbLoc); 4548 4549 // Since this might be a postfix expression, get rid of ParenListExprs. 4550 if (isa<ParenListExpr>(base)) { 4551 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4552 if (result.isInvalid()) return ExprError(); 4553 base = result.get(); 4554 } 4555 4556 // Check if base and idx form a MatrixSubscriptExpr. 4557 // 4558 // Helper to check for comma expressions, which are not allowed as indices for 4559 // matrix subscript expressions. 4560 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4561 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4562 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4563 << SourceRange(base->getBeginLoc(), rbLoc); 4564 return true; 4565 } 4566 return false; 4567 }; 4568 // The matrix subscript operator ([][])is considered a single operator. 4569 // Separating the index expressions by parenthesis is not allowed. 4570 if (base->getType()->isSpecificPlaceholderType( 4571 BuiltinType::IncompleteMatrixIdx) && 4572 !isa<MatrixSubscriptExpr>(base)) { 4573 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4574 << SourceRange(base->getBeginLoc(), rbLoc); 4575 return ExprError(); 4576 } 4577 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create 4578 // a new MatrixSubscriptExpr. 4579 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4580 if (matSubscriptE) { 4581 if (CheckAndReportCommaError(idx)) 4582 return ExprError(); 4583 4584 assert(matSubscriptE->isIncomplete() && 4585 "base has to be an incomplete matrix subscript"); 4586 return CreateBuiltinMatrixSubscriptExpr( 4587 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4588 } 4589 Expr *matrixBase = base; 4590 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4591 if (!IsMSPropertySubscript) { 4592 ExprResult result = CheckPlaceholderExpr(base); 4593 if (!result.isInvalid()) 4594 matrixBase = result.get(); 4595 } 4596 if (matrixBase->getType()->isMatrixType()) { 4597 if (CheckAndReportCommaError(idx)) 4598 return ExprError(); 4599 4600 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc); 4601 } 4602 4603 // A comma-expression as the index is deprecated in C++2a onwards. 4604 if (getLangOpts().CPlusPlus20 && 4605 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4606 (isa<CXXOperatorCallExpr>(idx) && 4607 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4608 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4609 << SourceRange(base->getBeginLoc(), rbLoc); 4610 } 4611 4612 // Handle any non-overload placeholder types in the base and index 4613 // expressions. We can't handle overloads here because the other 4614 // operand might be an overloadable type, in which case the overload 4615 // resolution for the operator overload should get the first crack 4616 // at the overload. 4617 if (base->getType()->isNonOverloadPlaceholderType()) { 4618 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4619 if (!IsMSPropertySubscript) { 4620 ExprResult result = CheckPlaceholderExpr(base); 4621 if (result.isInvalid()) 4622 return ExprError(); 4623 base = result.get(); 4624 } 4625 } 4626 if (idx->getType()->isNonOverloadPlaceholderType()) { 4627 ExprResult result = CheckPlaceholderExpr(idx); 4628 if (result.isInvalid()) return ExprError(); 4629 idx = result.get(); 4630 } 4631 4632 // Build an unanalyzed expression if either operand is type-dependent. 4633 if (getLangOpts().CPlusPlus && 4634 (base->isTypeDependent() || idx->isTypeDependent())) { 4635 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4636 VK_LValue, OK_Ordinary, rbLoc); 4637 } 4638 4639 // MSDN, property (C++) 4640 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4641 // This attribute can also be used in the declaration of an empty array in a 4642 // class or structure definition. For example: 4643 // __declspec(property(get=GetX, put=PutX)) int x[]; 4644 // The above statement indicates that x[] can be used with one or more array 4645 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4646 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4647 if (IsMSPropertySubscript) { 4648 // Build MS property subscript expression if base is MS property reference 4649 // or MS property subscript. 4650 return new (Context) MSPropertySubscriptExpr( 4651 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4652 } 4653 4654 // Use C++ overloaded-operator rules if either operand has record 4655 // type. The spec says to do this if either type is *overloadable*, 4656 // but enum types can't declare subscript operators or conversion 4657 // operators, so there's nothing interesting for overload resolution 4658 // to do if there aren't any record types involved. 4659 // 4660 // ObjC pointers have their own subscripting logic that is not tied 4661 // to overload resolution and so should not take this path. 4662 if (getLangOpts().CPlusPlus && 4663 (base->getType()->isRecordType() || 4664 (!base->getType()->isObjCObjectPointerType() && 4665 idx->getType()->isRecordType()))) { 4666 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4667 } 4668 4669 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4670 4671 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4672 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4673 4674 return Res; 4675 } 4676 4677 static bool tryConvertToTy(Sema &S, QualType ElementType, ExprResult *Scalar) { 4678 InitializedEntity Entity = 4679 InitializedEntity::InitializeTemporary(ElementType); 4680 InitializationKind Kind = InitializationKind::CreateCopy( 4681 Scalar->get()->getBeginLoc(), SourceLocation()); 4682 Expr *Arg = Scalar->get(); 4683 InitializationSequence InitSeq(S, Entity, Kind, Arg); 4684 *Scalar = InitSeq.Perform(S, Entity, Kind, Arg); 4685 return !Scalar->isInvalid(); 4686 } 4687 4688 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4689 Expr *ColumnIdx, 4690 SourceLocation RBLoc) { 4691 ExprResult BaseR = CheckPlaceholderExpr(Base); 4692 if (BaseR.isInvalid()) 4693 return BaseR; 4694 Base = BaseR.get(); 4695 4696 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4697 if (RowR.isInvalid()) 4698 return RowR; 4699 RowIdx = RowR.get(); 4700 4701 if (!ColumnIdx) 4702 return new (Context) MatrixSubscriptExpr( 4703 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4704 4705 // Build an unanalyzed expression if any of the operands is type-dependent. 4706 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4707 ColumnIdx->isTypeDependent()) 4708 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4709 Context.DependentTy, RBLoc); 4710 4711 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4712 if (ColumnR.isInvalid()) 4713 return ColumnR; 4714 ColumnIdx = ColumnR.get(); 4715 4716 // Check that IndexExpr is an integer expression. If it is a constant 4717 // expression, check that it is less than Dim (= the number of elements in the 4718 // corresponding dimension). 4719 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4720 bool IsColumnIdx) -> Expr * { 4721 if (!IndexExpr->getType()->isIntegerType() && 4722 !IndexExpr->isTypeDependent()) { 4723 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4724 << IsColumnIdx; 4725 return nullptr; 4726 } 4727 4728 llvm::APSInt Idx; 4729 if (IndexExpr->isIntegerConstantExpr(Idx, Context) && 4730 (Idx < 0 || Idx >= Dim)) { 4731 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4732 << IsColumnIdx << Dim; 4733 return nullptr; 4734 } 4735 4736 ExprResult ConvExpr = IndexExpr; 4737 bool ConversionOk = tryConvertToTy(*this, Context.getSizeType(), &ConvExpr); 4738 assert(ConversionOk && 4739 "should be able to convert any integer type to size type"); 4740 return ConvExpr.get(); 4741 }; 4742 4743 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4744 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4745 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4746 if (!RowIdx || !ColumnIdx) 4747 return ExprError(); 4748 4749 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4750 MTy->getElementType(), RBLoc); 4751 } 4752 4753 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4754 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4755 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4756 4757 // For expressions like `&(*s).b`, the base is recorded and what should be 4758 // checked. 4759 const MemberExpr *Member = nullptr; 4760 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4761 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4762 4763 LastRecord.PossibleDerefs.erase(StrippedExpr); 4764 } 4765 4766 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4767 QualType ResultTy = E->getType(); 4768 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4769 4770 // Bail if the element is an array since it is not memory access. 4771 if (isa<ArrayType>(ResultTy)) 4772 return; 4773 4774 if (ResultTy->hasAttr(attr::NoDeref)) { 4775 LastRecord.PossibleDerefs.insert(E); 4776 return; 4777 } 4778 4779 // Check if the base type is a pointer to a member access of a struct 4780 // marked with noderef. 4781 const Expr *Base = E->getBase(); 4782 QualType BaseTy = Base->getType(); 4783 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4784 // Not a pointer access 4785 return; 4786 4787 const MemberExpr *Member = nullptr; 4788 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4789 Member->isArrow()) 4790 Base = Member->getBase(); 4791 4792 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4793 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4794 LastRecord.PossibleDerefs.insert(E); 4795 } 4796 } 4797 4798 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4799 Expr *LowerBound, 4800 SourceLocation ColonLoc, Expr *Length, 4801 SourceLocation RBLoc) { 4802 if (Base->getType()->isPlaceholderType() && 4803 !Base->getType()->isSpecificPlaceholderType( 4804 BuiltinType::OMPArraySection)) { 4805 ExprResult Result = CheckPlaceholderExpr(Base); 4806 if (Result.isInvalid()) 4807 return ExprError(); 4808 Base = Result.get(); 4809 } 4810 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4811 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4812 if (Result.isInvalid()) 4813 return ExprError(); 4814 Result = DefaultLvalueConversion(Result.get()); 4815 if (Result.isInvalid()) 4816 return ExprError(); 4817 LowerBound = Result.get(); 4818 } 4819 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4820 ExprResult Result = CheckPlaceholderExpr(Length); 4821 if (Result.isInvalid()) 4822 return ExprError(); 4823 Result = DefaultLvalueConversion(Result.get()); 4824 if (Result.isInvalid()) 4825 return ExprError(); 4826 Length = Result.get(); 4827 } 4828 4829 // Build an unanalyzed expression if either operand is type-dependent. 4830 if (Base->isTypeDependent() || 4831 (LowerBound && 4832 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4833 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4834 return new (Context) 4835 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4836 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4837 } 4838 4839 // Perform default conversions. 4840 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4841 QualType ResultTy; 4842 if (OriginalTy->isAnyPointerType()) { 4843 ResultTy = OriginalTy->getPointeeType(); 4844 } else if (OriginalTy->isArrayType()) { 4845 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4846 } else { 4847 return ExprError( 4848 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4849 << Base->getSourceRange()); 4850 } 4851 // C99 6.5.2.1p1 4852 if (LowerBound) { 4853 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4854 LowerBound); 4855 if (Res.isInvalid()) 4856 return ExprError(Diag(LowerBound->getExprLoc(), 4857 diag::err_omp_typecheck_section_not_integer) 4858 << 0 << LowerBound->getSourceRange()); 4859 LowerBound = Res.get(); 4860 4861 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4862 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4863 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4864 << 0 << LowerBound->getSourceRange(); 4865 } 4866 if (Length) { 4867 auto Res = 4868 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4869 if (Res.isInvalid()) 4870 return ExprError(Diag(Length->getExprLoc(), 4871 diag::err_omp_typecheck_section_not_integer) 4872 << 1 << Length->getSourceRange()); 4873 Length = Res.get(); 4874 4875 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4876 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4877 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4878 << 1 << Length->getSourceRange(); 4879 } 4880 4881 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4882 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4883 // type. Note that functions are not objects, and that (in C99 parlance) 4884 // incomplete types are not object types. 4885 if (ResultTy->isFunctionType()) { 4886 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4887 << ResultTy << Base->getSourceRange(); 4888 return ExprError(); 4889 } 4890 4891 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4892 diag::err_omp_section_incomplete_type, Base)) 4893 return ExprError(); 4894 4895 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4896 Expr::EvalResult Result; 4897 if (LowerBound->EvaluateAsInt(Result, Context)) { 4898 // OpenMP 4.5, [2.4 Array Sections] 4899 // The array section must be a subset of the original array. 4900 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4901 if (LowerBoundValue.isNegative()) { 4902 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4903 << LowerBound->getSourceRange(); 4904 return ExprError(); 4905 } 4906 } 4907 } 4908 4909 if (Length) { 4910 Expr::EvalResult Result; 4911 if (Length->EvaluateAsInt(Result, Context)) { 4912 // OpenMP 4.5, [2.4 Array Sections] 4913 // The length must evaluate to non-negative integers. 4914 llvm::APSInt LengthValue = Result.Val.getInt(); 4915 if (LengthValue.isNegative()) { 4916 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4917 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4918 << Length->getSourceRange(); 4919 return ExprError(); 4920 } 4921 } 4922 } else if (ColonLoc.isValid() && 4923 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4924 !OriginalTy->isVariableArrayType()))) { 4925 // OpenMP 4.5, [2.4 Array Sections] 4926 // When the size of the array dimension is not known, the length must be 4927 // specified explicitly. 4928 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4929 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4930 return ExprError(); 4931 } 4932 4933 if (!Base->getType()->isSpecificPlaceholderType( 4934 BuiltinType::OMPArraySection)) { 4935 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4936 if (Result.isInvalid()) 4937 return ExprError(); 4938 Base = Result.get(); 4939 } 4940 return new (Context) 4941 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4942 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4943 } 4944 4945 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4946 SourceLocation RParenLoc, 4947 ArrayRef<Expr *> Dims, 4948 ArrayRef<SourceRange> Brackets) { 4949 if (Base->getType()->isPlaceholderType()) { 4950 ExprResult Result = CheckPlaceholderExpr(Base); 4951 if (Result.isInvalid()) 4952 return ExprError(); 4953 Result = DefaultLvalueConversion(Result.get()); 4954 if (Result.isInvalid()) 4955 return ExprError(); 4956 Base = Result.get(); 4957 } 4958 QualType BaseTy = Base->getType(); 4959 // Delay analysis of the types/expressions if instantiation/specialization is 4960 // required. 4961 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 4962 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 4963 LParenLoc, RParenLoc, Dims, Brackets); 4964 if (!BaseTy->isPointerType() || 4965 (!Base->isTypeDependent() && 4966 BaseTy->getPointeeType()->isIncompleteType())) 4967 return ExprError(Diag(Base->getExprLoc(), 4968 diag::err_omp_non_pointer_type_array_shaping_base) 4969 << Base->getSourceRange()); 4970 4971 SmallVector<Expr *, 4> NewDims; 4972 bool ErrorFound = false; 4973 for (Expr *Dim : Dims) { 4974 if (Dim->getType()->isPlaceholderType()) { 4975 ExprResult Result = CheckPlaceholderExpr(Dim); 4976 if (Result.isInvalid()) { 4977 ErrorFound = true; 4978 continue; 4979 } 4980 Result = DefaultLvalueConversion(Result.get()); 4981 if (Result.isInvalid()) { 4982 ErrorFound = true; 4983 continue; 4984 } 4985 Dim = Result.get(); 4986 } 4987 if (!Dim->isTypeDependent()) { 4988 ExprResult Result = 4989 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 4990 if (Result.isInvalid()) { 4991 ErrorFound = true; 4992 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 4993 << Dim->getSourceRange(); 4994 continue; 4995 } 4996 Dim = Result.get(); 4997 Expr::EvalResult EvResult; 4998 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 4999 // OpenMP 5.0, [2.1.4 Array Shaping] 5000 // Each si is an integral type expression that must evaluate to a 5001 // positive integer. 5002 llvm::APSInt Value = EvResult.Val.getInt(); 5003 if (!Value.isStrictlyPositive()) { 5004 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5005 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5006 << Dim->getSourceRange(); 5007 ErrorFound = true; 5008 continue; 5009 } 5010 } 5011 } 5012 NewDims.push_back(Dim); 5013 } 5014 if (ErrorFound) 5015 return ExprError(); 5016 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5017 LParenLoc, RParenLoc, NewDims, Brackets); 5018 } 5019 5020 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5021 SourceLocation LLoc, SourceLocation RLoc, 5022 ArrayRef<OMPIteratorData> Data) { 5023 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5024 bool IsCorrect = true; 5025 for (const OMPIteratorData &D : Data) { 5026 TypeSourceInfo *TInfo = nullptr; 5027 SourceLocation StartLoc; 5028 QualType DeclTy; 5029 if (!D.Type.getAsOpaquePtr()) { 5030 // OpenMP 5.0, 2.1.6 Iterators 5031 // In an iterator-specifier, if the iterator-type is not specified then 5032 // the type of that iterator is of int type. 5033 DeclTy = Context.IntTy; 5034 StartLoc = D.DeclIdentLoc; 5035 } else { 5036 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5037 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5038 } 5039 5040 bool IsDeclTyDependent = DeclTy->isDependentType() || 5041 DeclTy->containsUnexpandedParameterPack() || 5042 DeclTy->isInstantiationDependentType(); 5043 if (!IsDeclTyDependent) { 5044 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5045 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5046 // The iterator-type must be an integral or pointer type. 5047 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5048 << DeclTy; 5049 IsCorrect = false; 5050 continue; 5051 } 5052 if (DeclTy.isConstant(Context)) { 5053 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5054 // The iterator-type must not be const qualified. 5055 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5056 << DeclTy; 5057 IsCorrect = false; 5058 continue; 5059 } 5060 } 5061 5062 // Iterator declaration. 5063 assert(D.DeclIdent && "Identifier expected."); 5064 // Always try to create iterator declarator to avoid extra error messages 5065 // about unknown declarations use. 5066 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5067 D.DeclIdent, DeclTy, TInfo, SC_None); 5068 VD->setImplicit(); 5069 if (S) { 5070 // Check for conflicting previous declaration. 5071 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5072 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5073 ForVisibleRedeclaration); 5074 Previous.suppressDiagnostics(); 5075 LookupName(Previous, S); 5076 5077 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5078 /*AllowInlineNamespace=*/false); 5079 if (!Previous.empty()) { 5080 NamedDecl *Old = Previous.getRepresentativeDecl(); 5081 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5082 Diag(Old->getLocation(), diag::note_previous_definition); 5083 } else { 5084 PushOnScopeChains(VD, S); 5085 } 5086 } else { 5087 CurContext->addDecl(VD); 5088 } 5089 Expr *Begin = D.Range.Begin; 5090 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5091 ExprResult BeginRes = 5092 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5093 Begin = BeginRes.get(); 5094 } 5095 Expr *End = D.Range.End; 5096 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5097 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5098 End = EndRes.get(); 5099 } 5100 Expr *Step = D.Range.Step; 5101 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5102 if (!Step->getType()->isIntegralType(Context)) { 5103 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5104 << Step << Step->getSourceRange(); 5105 IsCorrect = false; 5106 continue; 5107 } 5108 llvm::APSInt Result; 5109 bool IsConstant = Step->isIntegerConstantExpr(Result, Context); 5110 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5111 // If the step expression of a range-specification equals zero, the 5112 // behavior is unspecified. 5113 if (IsConstant && Result.isNullValue()) { 5114 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5115 << Step << Step->getSourceRange(); 5116 IsCorrect = false; 5117 continue; 5118 } 5119 } 5120 if (!Begin || !End || !IsCorrect) { 5121 IsCorrect = false; 5122 continue; 5123 } 5124 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5125 IDElem.IteratorDecl = VD; 5126 IDElem.AssignmentLoc = D.AssignLoc; 5127 IDElem.Range.Begin = Begin; 5128 IDElem.Range.End = End; 5129 IDElem.Range.Step = Step; 5130 IDElem.ColonLoc = D.ColonLoc; 5131 IDElem.SecondColonLoc = D.SecColonLoc; 5132 } 5133 if (!IsCorrect) { 5134 // Invalidate all created iterator declarations if error is found. 5135 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5136 if (Decl *ID = D.IteratorDecl) 5137 ID->setInvalidDecl(); 5138 } 5139 return ExprError(); 5140 } 5141 SmallVector<OMPIteratorHelperData, 4> Helpers; 5142 if (!CurContext->isDependentContext()) { 5143 // Build number of ityeration for each iteration range. 5144 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5145 // ((Begini-Stepi-1-Endi) / -Stepi); 5146 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5147 // (Endi - Begini) 5148 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5149 D.Range.Begin); 5150 if(!Res.isUsable()) { 5151 IsCorrect = false; 5152 continue; 5153 } 5154 ExprResult St, St1; 5155 if (D.Range.Step) { 5156 St = D.Range.Step; 5157 // (Endi - Begini) + Stepi 5158 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5159 if (!Res.isUsable()) { 5160 IsCorrect = false; 5161 continue; 5162 } 5163 // (Endi - Begini) + Stepi - 1 5164 Res = 5165 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5166 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5167 if (!Res.isUsable()) { 5168 IsCorrect = false; 5169 continue; 5170 } 5171 // ((Endi - Begini) + Stepi - 1) / Stepi 5172 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5173 if (!Res.isUsable()) { 5174 IsCorrect = false; 5175 continue; 5176 } 5177 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5178 // (Begini - Endi) 5179 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5180 D.Range.Begin, D.Range.End); 5181 if (!Res1.isUsable()) { 5182 IsCorrect = false; 5183 continue; 5184 } 5185 // (Begini - Endi) - Stepi 5186 Res1 = 5187 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5188 if (!Res1.isUsable()) { 5189 IsCorrect = false; 5190 continue; 5191 } 5192 // (Begini - Endi) - Stepi - 1 5193 Res1 = 5194 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5195 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5196 if (!Res1.isUsable()) { 5197 IsCorrect = false; 5198 continue; 5199 } 5200 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5201 Res1 = 5202 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5203 if (!Res1.isUsable()) { 5204 IsCorrect = false; 5205 continue; 5206 } 5207 // Stepi > 0. 5208 ExprResult CmpRes = 5209 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5210 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5211 if (!CmpRes.isUsable()) { 5212 IsCorrect = false; 5213 continue; 5214 } 5215 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5216 Res.get(), Res1.get()); 5217 if (!Res.isUsable()) { 5218 IsCorrect = false; 5219 continue; 5220 } 5221 } 5222 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5223 if (!Res.isUsable()) { 5224 IsCorrect = false; 5225 continue; 5226 } 5227 5228 // Build counter update. 5229 // Build counter. 5230 auto *CounterVD = 5231 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5232 D.IteratorDecl->getBeginLoc(), nullptr, 5233 Res.get()->getType(), nullptr, SC_None); 5234 CounterVD->setImplicit(); 5235 ExprResult RefRes = 5236 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5237 D.IteratorDecl->getBeginLoc()); 5238 // Build counter update. 5239 // I = Begini + counter * Stepi; 5240 ExprResult UpdateRes; 5241 if (D.Range.Step) { 5242 UpdateRes = CreateBuiltinBinOp( 5243 D.AssignmentLoc, BO_Mul, 5244 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5245 } else { 5246 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5247 } 5248 if (!UpdateRes.isUsable()) { 5249 IsCorrect = false; 5250 continue; 5251 } 5252 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5253 UpdateRes.get()); 5254 if (!UpdateRes.isUsable()) { 5255 IsCorrect = false; 5256 continue; 5257 } 5258 ExprResult VDRes = 5259 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5260 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5261 D.IteratorDecl->getBeginLoc()); 5262 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5263 UpdateRes.get()); 5264 if (!UpdateRes.isUsable()) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 UpdateRes = 5269 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5270 if (!UpdateRes.isUsable()) { 5271 IsCorrect = false; 5272 continue; 5273 } 5274 ExprResult CounterUpdateRes = 5275 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5276 if (!CounterUpdateRes.isUsable()) { 5277 IsCorrect = false; 5278 continue; 5279 } 5280 CounterUpdateRes = 5281 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5282 if (!CounterUpdateRes.isUsable()) { 5283 IsCorrect = false; 5284 continue; 5285 } 5286 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5287 HD.CounterVD = CounterVD; 5288 HD.Upper = Res.get(); 5289 HD.Update = UpdateRes.get(); 5290 HD.CounterUpdate = CounterUpdateRes.get(); 5291 } 5292 } else { 5293 Helpers.assign(ID.size(), {}); 5294 } 5295 if (!IsCorrect) { 5296 // Invalidate all created iterator declarations if error is found. 5297 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5298 if (Decl *ID = D.IteratorDecl) 5299 ID->setInvalidDecl(); 5300 } 5301 return ExprError(); 5302 } 5303 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5304 LLoc, RLoc, ID, Helpers); 5305 } 5306 5307 ExprResult 5308 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5309 Expr *Idx, SourceLocation RLoc) { 5310 Expr *LHSExp = Base; 5311 Expr *RHSExp = Idx; 5312 5313 ExprValueKind VK = VK_LValue; 5314 ExprObjectKind OK = OK_Ordinary; 5315 5316 // Per C++ core issue 1213, the result is an xvalue if either operand is 5317 // a non-lvalue array, and an lvalue otherwise. 5318 if (getLangOpts().CPlusPlus11) { 5319 for (auto *Op : {LHSExp, RHSExp}) { 5320 Op = Op->IgnoreImplicit(); 5321 if (Op->getType()->isArrayType() && !Op->isLValue()) 5322 VK = VK_XValue; 5323 } 5324 } 5325 5326 // Perform default conversions. 5327 if (!LHSExp->getType()->getAs<VectorType>()) { 5328 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5329 if (Result.isInvalid()) 5330 return ExprError(); 5331 LHSExp = Result.get(); 5332 } 5333 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5334 if (Result.isInvalid()) 5335 return ExprError(); 5336 RHSExp = Result.get(); 5337 5338 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5339 5340 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5341 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5342 // in the subscript position. As a result, we need to derive the array base 5343 // and index from the expression types. 5344 Expr *BaseExpr, *IndexExpr; 5345 QualType ResultType; 5346 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5347 BaseExpr = LHSExp; 5348 IndexExpr = RHSExp; 5349 ResultType = Context.DependentTy; 5350 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5351 BaseExpr = LHSExp; 5352 IndexExpr = RHSExp; 5353 ResultType = PTy->getPointeeType(); 5354 } else if (const ObjCObjectPointerType *PTy = 5355 LHSTy->getAs<ObjCObjectPointerType>()) { 5356 BaseExpr = LHSExp; 5357 IndexExpr = RHSExp; 5358 5359 // Use custom logic if this should be the pseudo-object subscript 5360 // expression. 5361 if (!LangOpts.isSubscriptPointerArithmetic()) 5362 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5363 nullptr); 5364 5365 ResultType = PTy->getPointeeType(); 5366 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5367 // Handle the uncommon case of "123[Ptr]". 5368 BaseExpr = RHSExp; 5369 IndexExpr = LHSExp; 5370 ResultType = PTy->getPointeeType(); 5371 } else if (const ObjCObjectPointerType *PTy = 5372 RHSTy->getAs<ObjCObjectPointerType>()) { 5373 // Handle the uncommon case of "123[Ptr]". 5374 BaseExpr = RHSExp; 5375 IndexExpr = LHSExp; 5376 ResultType = PTy->getPointeeType(); 5377 if (!LangOpts.isSubscriptPointerArithmetic()) { 5378 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5379 << ResultType << BaseExpr->getSourceRange(); 5380 return ExprError(); 5381 } 5382 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5383 BaseExpr = LHSExp; // vectors: V[123] 5384 IndexExpr = RHSExp; 5385 // We apply C++ DR1213 to vector subscripting too. 5386 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5387 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5388 if (Materialized.isInvalid()) 5389 return ExprError(); 5390 LHSExp = Materialized.get(); 5391 } 5392 VK = LHSExp->getValueKind(); 5393 if (VK != VK_RValue) 5394 OK = OK_VectorComponent; 5395 5396 ResultType = VTy->getElementType(); 5397 QualType BaseType = BaseExpr->getType(); 5398 Qualifiers BaseQuals = BaseType.getQualifiers(); 5399 Qualifiers MemberQuals = ResultType.getQualifiers(); 5400 Qualifiers Combined = BaseQuals + MemberQuals; 5401 if (Combined != MemberQuals) 5402 ResultType = Context.getQualifiedType(ResultType, Combined); 5403 } else if (LHSTy->isArrayType()) { 5404 // If we see an array that wasn't promoted by 5405 // DefaultFunctionArrayLvalueConversion, it must be an array that 5406 // wasn't promoted because of the C90 rule that doesn't 5407 // allow promoting non-lvalue arrays. Warn, then 5408 // force the promotion here. 5409 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5410 << LHSExp->getSourceRange(); 5411 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5412 CK_ArrayToPointerDecay).get(); 5413 LHSTy = LHSExp->getType(); 5414 5415 BaseExpr = LHSExp; 5416 IndexExpr = RHSExp; 5417 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5418 } else if (RHSTy->isArrayType()) { 5419 // Same as previous, except for 123[f().a] case 5420 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5421 << RHSExp->getSourceRange(); 5422 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5423 CK_ArrayToPointerDecay).get(); 5424 RHSTy = RHSExp->getType(); 5425 5426 BaseExpr = RHSExp; 5427 IndexExpr = LHSExp; 5428 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5429 } else { 5430 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5431 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5432 } 5433 // C99 6.5.2.1p1 5434 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5435 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5436 << IndexExpr->getSourceRange()); 5437 5438 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5439 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5440 && !IndexExpr->isTypeDependent()) 5441 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5442 5443 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5444 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5445 // type. Note that Functions are not objects, and that (in C99 parlance) 5446 // incomplete types are not object types. 5447 if (ResultType->isFunctionType()) { 5448 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5449 << ResultType << BaseExpr->getSourceRange(); 5450 return ExprError(); 5451 } 5452 5453 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5454 // GNU extension: subscripting on pointer to void 5455 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5456 << BaseExpr->getSourceRange(); 5457 5458 // C forbids expressions of unqualified void type from being l-values. 5459 // See IsCForbiddenLValueType. 5460 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5461 } else if (!ResultType->isDependentType() && 5462 RequireCompleteSizedType( 5463 LLoc, ResultType, 5464 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5465 return ExprError(); 5466 5467 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5468 !ResultType.isCForbiddenLValueType()); 5469 5470 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5471 FunctionScopes.size() > 1) { 5472 if (auto *TT = 5473 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5474 for (auto I = FunctionScopes.rbegin(), 5475 E = std::prev(FunctionScopes.rend()); 5476 I != E; ++I) { 5477 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5478 if (CSI == nullptr) 5479 break; 5480 DeclContext *DC = nullptr; 5481 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5482 DC = LSI->CallOperator; 5483 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5484 DC = CRSI->TheCapturedDecl; 5485 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5486 DC = BSI->TheDecl; 5487 if (DC) { 5488 if (DC->containsDecl(TT->getDecl())) 5489 break; 5490 captureVariablyModifiedType( 5491 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5492 } 5493 } 5494 } 5495 } 5496 5497 return new (Context) 5498 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5499 } 5500 5501 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5502 ParmVarDecl *Param) { 5503 if (Param->hasUnparsedDefaultArg()) { 5504 Diag(CallLoc, 5505 diag::err_use_of_default_argument_to_function_declared_later) << 5506 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5507 Diag(UnparsedDefaultArgLocs[Param], 5508 diag::note_default_argument_declared_here); 5509 return true; 5510 } 5511 5512 if (Param->hasUninstantiatedDefaultArg()) { 5513 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5514 5515 EnterExpressionEvaluationContext EvalContext( 5516 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5517 5518 // Instantiate the expression. 5519 // 5520 // FIXME: Pass in a correct Pattern argument, otherwise 5521 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5522 // 5523 // template<typename T> 5524 // struct A { 5525 // static int FooImpl(); 5526 // 5527 // template<typename Tp> 5528 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5529 // // template argument list [[T], [Tp]], should be [[Tp]]. 5530 // friend A<Tp> Foo(int a); 5531 // }; 5532 // 5533 // template<typename T> 5534 // A<T> Foo(int a = A<T>::FooImpl()); 5535 MultiLevelTemplateArgumentList MutiLevelArgList 5536 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5537 5538 InstantiatingTemplate Inst(*this, CallLoc, Param, 5539 MutiLevelArgList.getInnermost()); 5540 if (Inst.isInvalid()) 5541 return true; 5542 if (Inst.isAlreadyInstantiating()) { 5543 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5544 Param->setInvalidDecl(); 5545 return true; 5546 } 5547 5548 ExprResult Result; 5549 { 5550 // C++ [dcl.fct.default]p5: 5551 // The names in the [default argument] expression are bound, and 5552 // the semantic constraints are checked, at the point where the 5553 // default argument expression appears. 5554 ContextRAII SavedContext(*this, FD); 5555 LocalInstantiationScope Local(*this); 5556 runWithSufficientStackSpace(CallLoc, [&] { 5557 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5558 /*DirectInit*/false); 5559 }); 5560 } 5561 if (Result.isInvalid()) 5562 return true; 5563 5564 // Check the expression as an initializer for the parameter. 5565 InitializedEntity Entity 5566 = InitializedEntity::InitializeParameter(Context, Param); 5567 InitializationKind Kind = InitializationKind::CreateCopy( 5568 Param->getLocation(), 5569 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5570 Expr *ResultE = Result.getAs<Expr>(); 5571 5572 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5573 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5574 if (Result.isInvalid()) 5575 return true; 5576 5577 Result = 5578 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5579 /*DiscardedValue*/ false); 5580 if (Result.isInvalid()) 5581 return true; 5582 5583 // Remember the instantiated default argument. 5584 Param->setDefaultArg(Result.getAs<Expr>()); 5585 if (ASTMutationListener *L = getASTMutationListener()) { 5586 L->DefaultArgumentInstantiated(Param); 5587 } 5588 } 5589 5590 // If the default argument expression is not set yet, we are building it now. 5591 if (!Param->hasInit()) { 5592 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5593 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5594 Param->setInvalidDecl(); 5595 return true; 5596 } 5597 5598 // If the default expression creates temporaries, we need to 5599 // push them to the current stack of expression temporaries so they'll 5600 // be properly destroyed. 5601 // FIXME: We should really be rebuilding the default argument with new 5602 // bound temporaries; see the comment in PR5810. 5603 // We don't need to do that with block decls, though, because 5604 // blocks in default argument expression can never capture anything. 5605 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5606 // Set the "needs cleanups" bit regardless of whether there are 5607 // any explicit objects. 5608 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5609 5610 // Append all the objects to the cleanup list. Right now, this 5611 // should always be a no-op, because blocks in default argument 5612 // expressions should never be able to capture anything. 5613 assert(!Init->getNumObjects() && 5614 "default argument expression has capturing blocks?"); 5615 } 5616 5617 // We already type-checked the argument, so we know it works. 5618 // Just mark all of the declarations in this potentially-evaluated expression 5619 // as being "referenced". 5620 EnterExpressionEvaluationContext EvalContext( 5621 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5622 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5623 /*SkipLocalVariables=*/true); 5624 return false; 5625 } 5626 5627 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5628 FunctionDecl *FD, ParmVarDecl *Param) { 5629 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5630 return ExprError(); 5631 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5632 } 5633 5634 Sema::VariadicCallType 5635 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5636 Expr *Fn) { 5637 if (Proto && Proto->isVariadic()) { 5638 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5639 return VariadicConstructor; 5640 else if (Fn && Fn->getType()->isBlockPointerType()) 5641 return VariadicBlock; 5642 else if (FDecl) { 5643 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5644 if (Method->isInstance()) 5645 return VariadicMethod; 5646 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5647 return VariadicMethod; 5648 return VariadicFunction; 5649 } 5650 return VariadicDoesNotApply; 5651 } 5652 5653 namespace { 5654 class FunctionCallCCC final : public FunctionCallFilterCCC { 5655 public: 5656 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5657 unsigned NumArgs, MemberExpr *ME) 5658 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5659 FunctionName(FuncName) {} 5660 5661 bool ValidateCandidate(const TypoCorrection &candidate) override { 5662 if (!candidate.getCorrectionSpecifier() || 5663 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5664 return false; 5665 } 5666 5667 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5668 } 5669 5670 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5671 return std::make_unique<FunctionCallCCC>(*this); 5672 } 5673 5674 private: 5675 const IdentifierInfo *const FunctionName; 5676 }; 5677 } 5678 5679 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5680 FunctionDecl *FDecl, 5681 ArrayRef<Expr *> Args) { 5682 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5683 DeclarationName FuncName = FDecl->getDeclName(); 5684 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5685 5686 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5687 if (TypoCorrection Corrected = S.CorrectTypo( 5688 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5689 S.getScopeForContext(S.CurContext), nullptr, CCC, 5690 Sema::CTK_ErrorRecovery)) { 5691 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5692 if (Corrected.isOverloaded()) { 5693 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5694 OverloadCandidateSet::iterator Best; 5695 for (NamedDecl *CD : Corrected) { 5696 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5697 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5698 OCS); 5699 } 5700 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5701 case OR_Success: 5702 ND = Best->FoundDecl; 5703 Corrected.setCorrectionDecl(ND); 5704 break; 5705 default: 5706 break; 5707 } 5708 } 5709 ND = ND->getUnderlyingDecl(); 5710 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5711 return Corrected; 5712 } 5713 } 5714 return TypoCorrection(); 5715 } 5716 5717 /// ConvertArgumentsForCall - Converts the arguments specified in 5718 /// Args/NumArgs to the parameter types of the function FDecl with 5719 /// function prototype Proto. Call is the call expression itself, and 5720 /// Fn is the function expression. For a C++ member function, this 5721 /// routine does not attempt to convert the object argument. Returns 5722 /// true if the call is ill-formed. 5723 bool 5724 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5725 FunctionDecl *FDecl, 5726 const FunctionProtoType *Proto, 5727 ArrayRef<Expr *> Args, 5728 SourceLocation RParenLoc, 5729 bool IsExecConfig) { 5730 // Bail out early if calling a builtin with custom typechecking. 5731 if (FDecl) 5732 if (unsigned ID = FDecl->getBuiltinID()) 5733 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5734 return false; 5735 5736 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5737 // assignment, to the types of the corresponding parameter, ... 5738 unsigned NumParams = Proto->getNumParams(); 5739 bool Invalid = false; 5740 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5741 unsigned FnKind = Fn->getType()->isBlockPointerType() 5742 ? 1 /* block */ 5743 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5744 : 0 /* function */); 5745 5746 // If too few arguments are available (and we don't have default 5747 // arguments for the remaining parameters), don't make the call. 5748 if (Args.size() < NumParams) { 5749 if (Args.size() < MinArgs) { 5750 TypoCorrection TC; 5751 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5752 unsigned diag_id = 5753 MinArgs == NumParams && !Proto->isVariadic() 5754 ? diag::err_typecheck_call_too_few_args_suggest 5755 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5756 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5757 << static_cast<unsigned>(Args.size()) 5758 << TC.getCorrectionRange()); 5759 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5760 Diag(RParenLoc, 5761 MinArgs == NumParams && !Proto->isVariadic() 5762 ? diag::err_typecheck_call_too_few_args_one 5763 : diag::err_typecheck_call_too_few_args_at_least_one) 5764 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5765 else 5766 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5767 ? diag::err_typecheck_call_too_few_args 5768 : diag::err_typecheck_call_too_few_args_at_least) 5769 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5770 << Fn->getSourceRange(); 5771 5772 // Emit the location of the prototype. 5773 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5774 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5775 5776 return true; 5777 } 5778 // We reserve space for the default arguments when we create 5779 // the call expression, before calling ConvertArgumentsForCall. 5780 assert((Call->getNumArgs() == NumParams) && 5781 "We should have reserved space for the default arguments before!"); 5782 } 5783 5784 // If too many are passed and not variadic, error on the extras and drop 5785 // them. 5786 if (Args.size() > NumParams) { 5787 if (!Proto->isVariadic()) { 5788 TypoCorrection TC; 5789 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5790 unsigned diag_id = 5791 MinArgs == NumParams && !Proto->isVariadic() 5792 ? diag::err_typecheck_call_too_many_args_suggest 5793 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5794 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5795 << static_cast<unsigned>(Args.size()) 5796 << TC.getCorrectionRange()); 5797 } else if (NumParams == 1 && FDecl && 5798 FDecl->getParamDecl(0)->getDeclName()) 5799 Diag(Args[NumParams]->getBeginLoc(), 5800 MinArgs == NumParams 5801 ? diag::err_typecheck_call_too_many_args_one 5802 : diag::err_typecheck_call_too_many_args_at_most_one) 5803 << FnKind << FDecl->getParamDecl(0) 5804 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5805 << SourceRange(Args[NumParams]->getBeginLoc(), 5806 Args.back()->getEndLoc()); 5807 else 5808 Diag(Args[NumParams]->getBeginLoc(), 5809 MinArgs == NumParams 5810 ? diag::err_typecheck_call_too_many_args 5811 : diag::err_typecheck_call_too_many_args_at_most) 5812 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5813 << Fn->getSourceRange() 5814 << SourceRange(Args[NumParams]->getBeginLoc(), 5815 Args.back()->getEndLoc()); 5816 5817 // Emit the location of the prototype. 5818 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5819 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5820 5821 // This deletes the extra arguments. 5822 Call->shrinkNumArgs(NumParams); 5823 return true; 5824 } 5825 } 5826 SmallVector<Expr *, 8> AllArgs; 5827 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5828 5829 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5830 AllArgs, CallType); 5831 if (Invalid) 5832 return true; 5833 unsigned TotalNumArgs = AllArgs.size(); 5834 for (unsigned i = 0; i < TotalNumArgs; ++i) 5835 Call->setArg(i, AllArgs[i]); 5836 5837 return false; 5838 } 5839 5840 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5841 const FunctionProtoType *Proto, 5842 unsigned FirstParam, ArrayRef<Expr *> Args, 5843 SmallVectorImpl<Expr *> &AllArgs, 5844 VariadicCallType CallType, bool AllowExplicit, 5845 bool IsListInitialization) { 5846 unsigned NumParams = Proto->getNumParams(); 5847 bool Invalid = false; 5848 size_t ArgIx = 0; 5849 // Continue to check argument types (even if we have too few/many args). 5850 for (unsigned i = FirstParam; i < NumParams; i++) { 5851 QualType ProtoArgType = Proto->getParamType(i); 5852 5853 Expr *Arg; 5854 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5855 if (ArgIx < Args.size()) { 5856 Arg = Args[ArgIx++]; 5857 5858 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5859 diag::err_call_incomplete_argument, Arg)) 5860 return true; 5861 5862 // Strip the unbridged-cast placeholder expression off, if applicable. 5863 bool CFAudited = false; 5864 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5865 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5866 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5867 Arg = stripARCUnbridgedCast(Arg); 5868 else if (getLangOpts().ObjCAutoRefCount && 5869 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5870 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5871 CFAudited = true; 5872 5873 if (Proto->getExtParameterInfo(i).isNoEscape()) 5874 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5875 BE->getBlockDecl()->setDoesNotEscape(); 5876 5877 InitializedEntity Entity = 5878 Param ? InitializedEntity::InitializeParameter(Context, Param, 5879 ProtoArgType) 5880 : InitializedEntity::InitializeParameter( 5881 Context, ProtoArgType, Proto->isParamConsumed(i)); 5882 5883 // Remember that parameter belongs to a CF audited API. 5884 if (CFAudited) 5885 Entity.setParameterCFAudited(); 5886 5887 ExprResult ArgE = PerformCopyInitialization( 5888 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5889 if (ArgE.isInvalid()) 5890 return true; 5891 5892 Arg = ArgE.getAs<Expr>(); 5893 } else { 5894 assert(Param && "can't use default arguments without a known callee"); 5895 5896 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5897 if (ArgExpr.isInvalid()) 5898 return true; 5899 5900 Arg = ArgExpr.getAs<Expr>(); 5901 } 5902 5903 // Check for array bounds violations for each argument to the call. This 5904 // check only triggers warnings when the argument isn't a more complex Expr 5905 // with its own checking, such as a BinaryOperator. 5906 CheckArrayAccess(Arg); 5907 5908 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5909 CheckStaticArrayArgument(CallLoc, Param, Arg); 5910 5911 AllArgs.push_back(Arg); 5912 } 5913 5914 // If this is a variadic call, handle args passed through "...". 5915 if (CallType != VariadicDoesNotApply) { 5916 // Assume that extern "C" functions with variadic arguments that 5917 // return __unknown_anytype aren't *really* variadic. 5918 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5919 FDecl->isExternC()) { 5920 for (Expr *A : Args.slice(ArgIx)) { 5921 QualType paramType; // ignored 5922 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5923 Invalid |= arg.isInvalid(); 5924 AllArgs.push_back(arg.get()); 5925 } 5926 5927 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5928 } else { 5929 for (Expr *A : Args.slice(ArgIx)) { 5930 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5931 Invalid |= Arg.isInvalid(); 5932 // Copy blocks to the heap. 5933 if (A->getType()->isBlockPointerType()) 5934 maybeExtendBlockObject(Arg); 5935 AllArgs.push_back(Arg.get()); 5936 } 5937 } 5938 5939 // Check for array bounds violations. 5940 for (Expr *A : Args.slice(ArgIx)) 5941 CheckArrayAccess(A); 5942 } 5943 return Invalid; 5944 } 5945 5946 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5947 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5948 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5949 TL = DTL.getOriginalLoc(); 5950 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5951 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5952 << ATL.getLocalSourceRange(); 5953 } 5954 5955 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5956 /// array parameter, check that it is non-null, and that if it is formed by 5957 /// array-to-pointer decay, the underlying array is sufficiently large. 5958 /// 5959 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5960 /// array type derivation, then for each call to the function, the value of the 5961 /// corresponding actual argument shall provide access to the first element of 5962 /// an array with at least as many elements as specified by the size expression. 5963 void 5964 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5965 ParmVarDecl *Param, 5966 const Expr *ArgExpr) { 5967 // Static array parameters are not supported in C++. 5968 if (!Param || getLangOpts().CPlusPlus) 5969 return; 5970 5971 QualType OrigTy = Param->getOriginalType(); 5972 5973 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5974 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5975 return; 5976 5977 if (ArgExpr->isNullPointerConstant(Context, 5978 Expr::NPC_NeverValueDependent)) { 5979 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5980 DiagnoseCalleeStaticArrayParam(*this, Param); 5981 return; 5982 } 5983 5984 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5985 if (!CAT) 5986 return; 5987 5988 const ConstantArrayType *ArgCAT = 5989 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5990 if (!ArgCAT) 5991 return; 5992 5993 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5994 ArgCAT->getElementType())) { 5995 if (ArgCAT->getSize().ult(CAT->getSize())) { 5996 Diag(CallLoc, diag::warn_static_array_too_small) 5997 << ArgExpr->getSourceRange() 5998 << (unsigned)ArgCAT->getSize().getZExtValue() 5999 << (unsigned)CAT->getSize().getZExtValue() << 0; 6000 DiagnoseCalleeStaticArrayParam(*this, Param); 6001 } 6002 return; 6003 } 6004 6005 Optional<CharUnits> ArgSize = 6006 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6007 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6008 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6009 Diag(CallLoc, diag::warn_static_array_too_small) 6010 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6011 << (unsigned)ParmSize->getQuantity() << 1; 6012 DiagnoseCalleeStaticArrayParam(*this, Param); 6013 } 6014 } 6015 6016 /// Given a function expression of unknown-any type, try to rebuild it 6017 /// to have a function type. 6018 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6019 6020 /// Is the given type a placeholder that we need to lower out 6021 /// immediately during argument processing? 6022 static bool isPlaceholderToRemoveAsArg(QualType type) { 6023 // Placeholders are never sugared. 6024 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6025 if (!placeholder) return false; 6026 6027 switch (placeholder->getKind()) { 6028 // Ignore all the non-placeholder types. 6029 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6030 case BuiltinType::Id: 6031 #include "clang/Basic/OpenCLImageTypes.def" 6032 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6033 case BuiltinType::Id: 6034 #include "clang/Basic/OpenCLExtensionTypes.def" 6035 // In practice we'll never use this, since all SVE types are sugared 6036 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6037 #define SVE_TYPE(Name, Id, SingletonId) \ 6038 case BuiltinType::Id: 6039 #include "clang/Basic/AArch64SVEACLETypes.def" 6040 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6041 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6042 #include "clang/AST/BuiltinTypes.def" 6043 return false; 6044 6045 // We cannot lower out overload sets; they might validly be resolved 6046 // by the call machinery. 6047 case BuiltinType::Overload: 6048 return false; 6049 6050 // Unbridged casts in ARC can be handled in some call positions and 6051 // should be left in place. 6052 case BuiltinType::ARCUnbridgedCast: 6053 return false; 6054 6055 // Pseudo-objects should be converted as soon as possible. 6056 case BuiltinType::PseudoObject: 6057 return true; 6058 6059 // The debugger mode could theoretically but currently does not try 6060 // to resolve unknown-typed arguments based on known parameter types. 6061 case BuiltinType::UnknownAny: 6062 return true; 6063 6064 // These are always invalid as call arguments and should be reported. 6065 case BuiltinType::BoundMember: 6066 case BuiltinType::BuiltinFn: 6067 case BuiltinType::IncompleteMatrixIdx: 6068 case BuiltinType::OMPArraySection: 6069 case BuiltinType::OMPArrayShaping: 6070 case BuiltinType::OMPIterator: 6071 return true; 6072 6073 } 6074 llvm_unreachable("bad builtin type kind"); 6075 } 6076 6077 /// Check an argument list for placeholders that we won't try to 6078 /// handle later. 6079 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6080 // Apply this processing to all the arguments at once instead of 6081 // dying at the first failure. 6082 bool hasInvalid = false; 6083 for (size_t i = 0, e = args.size(); i != e; i++) { 6084 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6085 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6086 if (result.isInvalid()) hasInvalid = true; 6087 else args[i] = result.get(); 6088 } else if (hasInvalid) { 6089 (void)S.CorrectDelayedTyposInExpr(args[i]); 6090 } 6091 } 6092 return hasInvalid; 6093 } 6094 6095 /// If a builtin function has a pointer argument with no explicit address 6096 /// space, then it should be able to accept a pointer to any address 6097 /// space as input. In order to do this, we need to replace the 6098 /// standard builtin declaration with one that uses the same address space 6099 /// as the call. 6100 /// 6101 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6102 /// it does not contain any pointer arguments without 6103 /// an address space qualifer. Otherwise the rewritten 6104 /// FunctionDecl is returned. 6105 /// TODO: Handle pointer return types. 6106 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6107 FunctionDecl *FDecl, 6108 MultiExprArg ArgExprs) { 6109 6110 QualType DeclType = FDecl->getType(); 6111 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6112 6113 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6114 ArgExprs.size() < FT->getNumParams()) 6115 return nullptr; 6116 6117 bool NeedsNewDecl = false; 6118 unsigned i = 0; 6119 SmallVector<QualType, 8> OverloadParams; 6120 6121 for (QualType ParamType : FT->param_types()) { 6122 6123 // Convert array arguments to pointer to simplify type lookup. 6124 ExprResult ArgRes = 6125 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6126 if (ArgRes.isInvalid()) 6127 return nullptr; 6128 Expr *Arg = ArgRes.get(); 6129 QualType ArgType = Arg->getType(); 6130 if (!ParamType->isPointerType() || 6131 ParamType.hasAddressSpace() || 6132 !ArgType->isPointerType() || 6133 !ArgType->getPointeeType().hasAddressSpace()) { 6134 OverloadParams.push_back(ParamType); 6135 continue; 6136 } 6137 6138 QualType PointeeType = ParamType->getPointeeType(); 6139 if (PointeeType.hasAddressSpace()) 6140 continue; 6141 6142 NeedsNewDecl = true; 6143 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6144 6145 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6146 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6147 } 6148 6149 if (!NeedsNewDecl) 6150 return nullptr; 6151 6152 FunctionProtoType::ExtProtoInfo EPI; 6153 EPI.Variadic = FT->isVariadic(); 6154 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6155 OverloadParams, EPI); 6156 DeclContext *Parent = FDecl->getParent(); 6157 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6158 FDecl->getLocation(), 6159 FDecl->getLocation(), 6160 FDecl->getIdentifier(), 6161 OverloadTy, 6162 /*TInfo=*/nullptr, 6163 SC_Extern, false, 6164 /*hasPrototype=*/true); 6165 SmallVector<ParmVarDecl*, 16> Params; 6166 FT = cast<FunctionProtoType>(OverloadTy); 6167 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6168 QualType ParamType = FT->getParamType(i); 6169 ParmVarDecl *Parm = 6170 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6171 SourceLocation(), nullptr, ParamType, 6172 /*TInfo=*/nullptr, SC_None, nullptr); 6173 Parm->setScopeInfo(0, i); 6174 Params.push_back(Parm); 6175 } 6176 OverloadDecl->setParams(Params); 6177 return OverloadDecl; 6178 } 6179 6180 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6181 FunctionDecl *Callee, 6182 MultiExprArg ArgExprs) { 6183 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6184 // similar attributes) really don't like it when functions are called with an 6185 // invalid number of args. 6186 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6187 /*PartialOverloading=*/false) && 6188 !Callee->isVariadic()) 6189 return; 6190 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6191 return; 6192 6193 if (const EnableIfAttr *Attr = 6194 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6195 S.Diag(Fn->getBeginLoc(), 6196 isa<CXXMethodDecl>(Callee) 6197 ? diag::err_ovl_no_viable_member_function_in_call 6198 : diag::err_ovl_no_viable_function_in_call) 6199 << Callee << Callee->getSourceRange(); 6200 S.Diag(Callee->getLocation(), 6201 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6202 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6203 return; 6204 } 6205 } 6206 6207 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6208 const UnresolvedMemberExpr *const UME, Sema &S) { 6209 6210 const auto GetFunctionLevelDCIfCXXClass = 6211 [](Sema &S) -> const CXXRecordDecl * { 6212 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6213 if (!DC || !DC->getParent()) 6214 return nullptr; 6215 6216 // If the call to some member function was made from within a member 6217 // function body 'M' return return 'M's parent. 6218 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6219 return MD->getParent()->getCanonicalDecl(); 6220 // else the call was made from within a default member initializer of a 6221 // class, so return the class. 6222 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6223 return RD->getCanonicalDecl(); 6224 return nullptr; 6225 }; 6226 // If our DeclContext is neither a member function nor a class (in the 6227 // case of a lambda in a default member initializer), we can't have an 6228 // enclosing 'this'. 6229 6230 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6231 if (!CurParentClass) 6232 return false; 6233 6234 // The naming class for implicit member functions call is the class in which 6235 // name lookup starts. 6236 const CXXRecordDecl *const NamingClass = 6237 UME->getNamingClass()->getCanonicalDecl(); 6238 assert(NamingClass && "Must have naming class even for implicit access"); 6239 6240 // If the unresolved member functions were found in a 'naming class' that is 6241 // related (either the same or derived from) to the class that contains the 6242 // member function that itself contained the implicit member access. 6243 6244 return CurParentClass == NamingClass || 6245 CurParentClass->isDerivedFrom(NamingClass); 6246 } 6247 6248 static void 6249 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6250 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6251 6252 if (!UME) 6253 return; 6254 6255 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6256 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6257 // already been captured, or if this is an implicit member function call (if 6258 // it isn't, an attempt to capture 'this' should already have been made). 6259 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6260 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6261 return; 6262 6263 // Check if the naming class in which the unresolved members were found is 6264 // related (same as or is a base of) to the enclosing class. 6265 6266 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6267 return; 6268 6269 6270 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6271 // If the enclosing function is not dependent, then this lambda is 6272 // capture ready, so if we can capture this, do so. 6273 if (!EnclosingFunctionCtx->isDependentContext()) { 6274 // If the current lambda and all enclosing lambdas can capture 'this' - 6275 // then go ahead and capture 'this' (since our unresolved overload set 6276 // contains at least one non-static member function). 6277 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6278 S.CheckCXXThisCapture(CallLoc); 6279 } else if (S.CurContext->isDependentContext()) { 6280 // ... since this is an implicit member reference, that might potentially 6281 // involve a 'this' capture, mark 'this' for potential capture in 6282 // enclosing lambdas. 6283 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6284 CurLSI->addPotentialThisCapture(CallLoc); 6285 } 6286 } 6287 6288 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6289 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6290 Expr *ExecConfig) { 6291 ExprResult Call = 6292 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6293 if (Call.isInvalid()) 6294 return Call; 6295 6296 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6297 // language modes. 6298 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6299 if (ULE->hasExplicitTemplateArgs() && 6300 ULE->decls_begin() == ULE->decls_end()) { 6301 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6302 ? diag::warn_cxx17_compat_adl_only_template_id 6303 : diag::ext_adl_only_template_id) 6304 << ULE->getName(); 6305 } 6306 } 6307 6308 if (LangOpts.OpenMP) 6309 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6310 ExecConfig); 6311 6312 return Call; 6313 } 6314 6315 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6316 /// This provides the location of the left/right parens and a list of comma 6317 /// locations. 6318 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6319 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6320 Expr *ExecConfig, bool IsExecConfig) { 6321 // Since this might be a postfix expression, get rid of ParenListExprs. 6322 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6323 if (Result.isInvalid()) return ExprError(); 6324 Fn = Result.get(); 6325 6326 if (checkArgsForPlaceholders(*this, ArgExprs)) 6327 return ExprError(); 6328 6329 if (getLangOpts().CPlusPlus) { 6330 // If this is a pseudo-destructor expression, build the call immediately. 6331 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6332 if (!ArgExprs.empty()) { 6333 // Pseudo-destructor calls should not have any arguments. 6334 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6335 << FixItHint::CreateRemoval( 6336 SourceRange(ArgExprs.front()->getBeginLoc(), 6337 ArgExprs.back()->getEndLoc())); 6338 } 6339 6340 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6341 VK_RValue, RParenLoc); 6342 } 6343 if (Fn->getType() == Context.PseudoObjectTy) { 6344 ExprResult result = CheckPlaceholderExpr(Fn); 6345 if (result.isInvalid()) return ExprError(); 6346 Fn = result.get(); 6347 } 6348 6349 // Determine whether this is a dependent call inside a C++ template, 6350 // in which case we won't do any semantic analysis now. 6351 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6352 if (ExecConfig) { 6353 return CUDAKernelCallExpr::Create( 6354 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6355 Context.DependentTy, VK_RValue, RParenLoc); 6356 } else { 6357 6358 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6359 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6360 Fn->getBeginLoc()); 6361 6362 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6363 VK_RValue, RParenLoc); 6364 } 6365 } 6366 6367 // Determine whether this is a call to an object (C++ [over.call.object]). 6368 if (Fn->getType()->isRecordType()) 6369 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6370 RParenLoc); 6371 6372 if (Fn->getType() == Context.UnknownAnyTy) { 6373 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6374 if (result.isInvalid()) return ExprError(); 6375 Fn = result.get(); 6376 } 6377 6378 if (Fn->getType() == Context.BoundMemberTy) { 6379 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6380 RParenLoc); 6381 } 6382 } 6383 6384 // Check for overloaded calls. This can happen even in C due to extensions. 6385 if (Fn->getType() == Context.OverloadTy) { 6386 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6387 6388 // We aren't supposed to apply this logic if there's an '&' involved. 6389 if (!find.HasFormOfMemberPointer) { 6390 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6391 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6392 VK_RValue, RParenLoc); 6393 OverloadExpr *ovl = find.Expression; 6394 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6395 return BuildOverloadedCallExpr( 6396 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6397 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6398 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6399 RParenLoc); 6400 } 6401 } 6402 6403 // If we're directly calling a function, get the appropriate declaration. 6404 if (Fn->getType() == Context.UnknownAnyTy) { 6405 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6406 if (result.isInvalid()) return ExprError(); 6407 Fn = result.get(); 6408 } 6409 6410 Expr *NakedFn = Fn->IgnoreParens(); 6411 6412 bool CallingNDeclIndirectly = false; 6413 NamedDecl *NDecl = nullptr; 6414 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6415 if (UnOp->getOpcode() == UO_AddrOf) { 6416 CallingNDeclIndirectly = true; 6417 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6418 } 6419 } 6420 6421 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6422 NDecl = DRE->getDecl(); 6423 6424 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6425 if (FDecl && FDecl->getBuiltinID()) { 6426 // Rewrite the function decl for this builtin by replacing parameters 6427 // with no explicit address space with the address space of the arguments 6428 // in ArgExprs. 6429 if ((FDecl = 6430 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6431 NDecl = FDecl; 6432 Fn = DeclRefExpr::Create( 6433 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6434 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6435 nullptr, DRE->isNonOdrUse()); 6436 } 6437 } 6438 } else if (isa<MemberExpr>(NakedFn)) 6439 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6440 6441 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6442 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6443 FD, /*Complain=*/true, Fn->getBeginLoc())) 6444 return ExprError(); 6445 6446 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6447 return ExprError(); 6448 6449 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6450 } 6451 6452 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6453 ExecConfig, IsExecConfig); 6454 } 6455 6456 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6457 /// 6458 /// __builtin_astype( value, dst type ) 6459 /// 6460 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6461 SourceLocation BuiltinLoc, 6462 SourceLocation RParenLoc) { 6463 ExprValueKind VK = VK_RValue; 6464 ExprObjectKind OK = OK_Ordinary; 6465 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6466 QualType SrcTy = E->getType(); 6467 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6468 return ExprError(Diag(BuiltinLoc, 6469 diag::err_invalid_astype_of_different_size) 6470 << DstTy 6471 << SrcTy 6472 << E->getSourceRange()); 6473 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6474 } 6475 6476 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6477 /// provided arguments. 6478 /// 6479 /// __builtin_convertvector( value, dst type ) 6480 /// 6481 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6482 SourceLocation BuiltinLoc, 6483 SourceLocation RParenLoc) { 6484 TypeSourceInfo *TInfo; 6485 GetTypeFromParser(ParsedDestTy, &TInfo); 6486 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6487 } 6488 6489 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6490 /// i.e. an expression not of \p OverloadTy. The expression should 6491 /// unary-convert to an expression of function-pointer or 6492 /// block-pointer type. 6493 /// 6494 /// \param NDecl the declaration being called, if available 6495 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6496 SourceLocation LParenLoc, 6497 ArrayRef<Expr *> Args, 6498 SourceLocation RParenLoc, Expr *Config, 6499 bool IsExecConfig, ADLCallKind UsesADL) { 6500 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6501 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6502 6503 // Functions with 'interrupt' attribute cannot be called directly. 6504 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6505 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6506 return ExprError(); 6507 } 6508 6509 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6510 // so there's some risk when calling out to non-interrupt handler functions 6511 // that the callee might not preserve them. This is easy to diagnose here, 6512 // but can be very challenging to debug. 6513 if (auto *Caller = getCurFunctionDecl()) 6514 if (Caller->hasAttr<ARMInterruptAttr>()) { 6515 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6516 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6517 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6518 } 6519 6520 // Promote the function operand. 6521 // We special-case function promotion here because we only allow promoting 6522 // builtin functions to function pointers in the callee of a call. 6523 ExprResult Result; 6524 QualType ResultTy; 6525 if (BuiltinID && 6526 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6527 // Extract the return type from the (builtin) function pointer type. 6528 // FIXME Several builtins still have setType in 6529 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6530 // Builtins.def to ensure they are correct before removing setType calls. 6531 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6532 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6533 ResultTy = FDecl->getCallResultType(); 6534 } else { 6535 Result = CallExprUnaryConversions(Fn); 6536 ResultTy = Context.BoolTy; 6537 } 6538 if (Result.isInvalid()) 6539 return ExprError(); 6540 Fn = Result.get(); 6541 6542 // Check for a valid function type, but only if it is not a builtin which 6543 // requires custom type checking. These will be handled by 6544 // CheckBuiltinFunctionCall below just after creation of the call expression. 6545 const FunctionType *FuncT = nullptr; 6546 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6547 retry: 6548 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6549 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6550 // have type pointer to function". 6551 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6552 if (!FuncT) 6553 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6554 << Fn->getType() << Fn->getSourceRange()); 6555 } else if (const BlockPointerType *BPT = 6556 Fn->getType()->getAs<BlockPointerType>()) { 6557 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6558 } else { 6559 // Handle calls to expressions of unknown-any type. 6560 if (Fn->getType() == Context.UnknownAnyTy) { 6561 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6562 if (rewrite.isInvalid()) 6563 return ExprError(); 6564 Fn = rewrite.get(); 6565 goto retry; 6566 } 6567 6568 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6569 << Fn->getType() << Fn->getSourceRange()); 6570 } 6571 } 6572 6573 // Get the number of parameters in the function prototype, if any. 6574 // We will allocate space for max(Args.size(), NumParams) arguments 6575 // in the call expression. 6576 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6577 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6578 6579 CallExpr *TheCall; 6580 if (Config) { 6581 assert(UsesADL == ADLCallKind::NotADL && 6582 "CUDAKernelCallExpr should not use ADL"); 6583 TheCall = 6584 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6585 ResultTy, VK_RValue, RParenLoc, NumParams); 6586 } else { 6587 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6588 RParenLoc, NumParams, UsesADL); 6589 } 6590 6591 if (!getLangOpts().CPlusPlus) { 6592 // Forget about the nulled arguments since typo correction 6593 // do not handle them well. 6594 TheCall->shrinkNumArgs(Args.size()); 6595 // C cannot always handle TypoExpr nodes in builtin calls and direct 6596 // function calls as their argument checking don't necessarily handle 6597 // dependent types properly, so make sure any TypoExprs have been 6598 // dealt with. 6599 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6600 if (!Result.isUsable()) return ExprError(); 6601 CallExpr *TheOldCall = TheCall; 6602 TheCall = dyn_cast<CallExpr>(Result.get()); 6603 bool CorrectedTypos = TheCall != TheOldCall; 6604 if (!TheCall) return Result; 6605 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6606 6607 // A new call expression node was created if some typos were corrected. 6608 // However it may not have been constructed with enough storage. In this 6609 // case, rebuild the node with enough storage. The waste of space is 6610 // immaterial since this only happens when some typos were corrected. 6611 if (CorrectedTypos && Args.size() < NumParams) { 6612 if (Config) 6613 TheCall = CUDAKernelCallExpr::Create( 6614 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6615 RParenLoc, NumParams); 6616 else 6617 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6618 RParenLoc, NumParams, UsesADL); 6619 } 6620 // We can now handle the nulled arguments for the default arguments. 6621 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6622 } 6623 6624 // Bail out early if calling a builtin with custom type checking. 6625 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6626 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6627 6628 if (getLangOpts().CUDA) { 6629 if (Config) { 6630 // CUDA: Kernel calls must be to global functions 6631 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6632 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6633 << FDecl << Fn->getSourceRange()); 6634 6635 // CUDA: Kernel function must have 'void' return type 6636 if (!FuncT->getReturnType()->isVoidType() && 6637 !FuncT->getReturnType()->getAs<AutoType>() && 6638 !FuncT->getReturnType()->isInstantiationDependentType()) 6639 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6640 << Fn->getType() << Fn->getSourceRange()); 6641 } else { 6642 // CUDA: Calls to global functions must be configured 6643 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6644 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6645 << FDecl << Fn->getSourceRange()); 6646 } 6647 } 6648 6649 // Check for a valid return type 6650 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6651 FDecl)) 6652 return ExprError(); 6653 6654 // We know the result type of the call, set it. 6655 TheCall->setType(FuncT->getCallResultType(Context)); 6656 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6657 6658 if (Proto) { 6659 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6660 IsExecConfig)) 6661 return ExprError(); 6662 } else { 6663 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6664 6665 if (FDecl) { 6666 // Check if we have too few/too many template arguments, based 6667 // on our knowledge of the function definition. 6668 const FunctionDecl *Def = nullptr; 6669 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6670 Proto = Def->getType()->getAs<FunctionProtoType>(); 6671 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6672 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6673 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6674 } 6675 6676 // If the function we're calling isn't a function prototype, but we have 6677 // a function prototype from a prior declaratiom, use that prototype. 6678 if (!FDecl->hasPrototype()) 6679 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6680 } 6681 6682 // Promote the arguments (C99 6.5.2.2p6). 6683 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6684 Expr *Arg = Args[i]; 6685 6686 if (Proto && i < Proto->getNumParams()) { 6687 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6688 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6689 ExprResult ArgE = 6690 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6691 if (ArgE.isInvalid()) 6692 return true; 6693 6694 Arg = ArgE.getAs<Expr>(); 6695 6696 } else { 6697 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6698 6699 if (ArgE.isInvalid()) 6700 return true; 6701 6702 Arg = ArgE.getAs<Expr>(); 6703 } 6704 6705 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6706 diag::err_call_incomplete_argument, Arg)) 6707 return ExprError(); 6708 6709 TheCall->setArg(i, Arg); 6710 } 6711 } 6712 6713 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6714 if (!Method->isStatic()) 6715 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6716 << Fn->getSourceRange()); 6717 6718 // Check for sentinels 6719 if (NDecl) 6720 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6721 6722 // Warn for unions passing across security boundary (CMSE). 6723 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6724 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6725 if (const auto *RT = 6726 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6727 if (RT->getDecl()->isOrContainsUnion()) 6728 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6729 << 0 << i; 6730 } 6731 } 6732 } 6733 6734 // Do special checking on direct calls to functions. 6735 if (FDecl) { 6736 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6737 return ExprError(); 6738 6739 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6740 6741 if (BuiltinID) 6742 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6743 } else if (NDecl) { 6744 if (CheckPointerCall(NDecl, TheCall, Proto)) 6745 return ExprError(); 6746 } else { 6747 if (CheckOtherCall(TheCall, Proto)) 6748 return ExprError(); 6749 } 6750 6751 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6752 } 6753 6754 ExprResult 6755 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6756 SourceLocation RParenLoc, Expr *InitExpr) { 6757 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6758 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6759 6760 TypeSourceInfo *TInfo; 6761 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6762 if (!TInfo) 6763 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6764 6765 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6766 } 6767 6768 ExprResult 6769 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6770 SourceLocation RParenLoc, Expr *LiteralExpr) { 6771 QualType literalType = TInfo->getType(); 6772 6773 if (literalType->isArrayType()) { 6774 if (RequireCompleteSizedType( 6775 LParenLoc, Context.getBaseElementType(literalType), 6776 diag::err_array_incomplete_or_sizeless_type, 6777 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6778 return ExprError(); 6779 if (literalType->isVariableArrayType()) 6780 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6781 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6782 } else if (!literalType->isDependentType() && 6783 RequireCompleteType(LParenLoc, literalType, 6784 diag::err_typecheck_decl_incomplete_type, 6785 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6786 return ExprError(); 6787 6788 InitializedEntity Entity 6789 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6790 InitializationKind Kind 6791 = InitializationKind::CreateCStyleCast(LParenLoc, 6792 SourceRange(LParenLoc, RParenLoc), 6793 /*InitList=*/true); 6794 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6795 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6796 &literalType); 6797 if (Result.isInvalid()) 6798 return ExprError(); 6799 LiteralExpr = Result.get(); 6800 6801 bool isFileScope = !CurContext->isFunctionOrMethod(); 6802 6803 // In C, compound literals are l-values for some reason. 6804 // For GCC compatibility, in C++, file-scope array compound literals with 6805 // constant initializers are also l-values, and compound literals are 6806 // otherwise prvalues. 6807 // 6808 // (GCC also treats C++ list-initialized file-scope array prvalues with 6809 // constant initializers as l-values, but that's non-conforming, so we don't 6810 // follow it there.) 6811 // 6812 // FIXME: It would be better to handle the lvalue cases as materializing and 6813 // lifetime-extending a temporary object, but our materialized temporaries 6814 // representation only supports lifetime extension from a variable, not "out 6815 // of thin air". 6816 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6817 // is bound to the result of applying array-to-pointer decay to the compound 6818 // literal. 6819 // FIXME: GCC supports compound literals of reference type, which should 6820 // obviously have a value kind derived from the kind of reference involved. 6821 ExprValueKind VK = 6822 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6823 ? VK_RValue 6824 : VK_LValue; 6825 6826 if (isFileScope) 6827 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6828 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6829 Expr *Init = ILE->getInit(i); 6830 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6831 } 6832 6833 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6834 VK, LiteralExpr, isFileScope); 6835 if (isFileScope) { 6836 if (!LiteralExpr->isTypeDependent() && 6837 !LiteralExpr->isValueDependent() && 6838 !literalType->isDependentType()) // C99 6.5.2.5p3 6839 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6840 return ExprError(); 6841 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6842 literalType.getAddressSpace() != LangAS::Default) { 6843 // Embedded-C extensions to C99 6.5.2.5: 6844 // "If the compound literal occurs inside the body of a function, the 6845 // type name shall not be qualified by an address-space qualifier." 6846 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6847 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6848 return ExprError(); 6849 } 6850 6851 if (!isFileScope && !getLangOpts().CPlusPlus) { 6852 // Compound literals that have automatic storage duration are destroyed at 6853 // the end of the scope in C; in C++, they're just temporaries. 6854 6855 // Emit diagnostics if it is or contains a C union type that is non-trivial 6856 // to destruct. 6857 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6858 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6859 NTCUC_CompoundLiteral, NTCUK_Destruct); 6860 6861 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6862 if (literalType.isDestructedType()) { 6863 Cleanup.setExprNeedsCleanups(true); 6864 ExprCleanupObjects.push_back(E); 6865 getCurFunction()->setHasBranchProtectedScope(); 6866 } 6867 } 6868 6869 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6870 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6871 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6872 E->getInitializer()->getExprLoc()); 6873 6874 return MaybeBindToTemporary(E); 6875 } 6876 6877 ExprResult 6878 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6879 SourceLocation RBraceLoc) { 6880 // Only produce each kind of designated initialization diagnostic once. 6881 SourceLocation FirstDesignator; 6882 bool DiagnosedArrayDesignator = false; 6883 bool DiagnosedNestedDesignator = false; 6884 bool DiagnosedMixedDesignator = false; 6885 6886 // Check that any designated initializers are syntactically valid in the 6887 // current language mode. 6888 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6889 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6890 if (FirstDesignator.isInvalid()) 6891 FirstDesignator = DIE->getBeginLoc(); 6892 6893 if (!getLangOpts().CPlusPlus) 6894 break; 6895 6896 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6897 DiagnosedNestedDesignator = true; 6898 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6899 << DIE->getDesignatorsSourceRange(); 6900 } 6901 6902 for (auto &Desig : DIE->designators()) { 6903 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6904 DiagnosedArrayDesignator = true; 6905 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6906 << Desig.getSourceRange(); 6907 } 6908 } 6909 6910 if (!DiagnosedMixedDesignator && 6911 !isa<DesignatedInitExpr>(InitArgList[0])) { 6912 DiagnosedMixedDesignator = true; 6913 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6914 << DIE->getSourceRange(); 6915 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6916 << InitArgList[0]->getSourceRange(); 6917 } 6918 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6919 isa<DesignatedInitExpr>(InitArgList[0])) { 6920 DiagnosedMixedDesignator = true; 6921 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6922 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6923 << DIE->getSourceRange(); 6924 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6925 << InitArgList[I]->getSourceRange(); 6926 } 6927 } 6928 6929 if (FirstDesignator.isValid()) { 6930 // Only diagnose designated initiaization as a C++20 extension if we didn't 6931 // already diagnose use of (non-C++20) C99 designator syntax. 6932 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6933 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6934 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6935 ? diag::warn_cxx17_compat_designated_init 6936 : diag::ext_cxx_designated_init); 6937 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6938 Diag(FirstDesignator, diag::ext_designated_init); 6939 } 6940 } 6941 6942 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6943 } 6944 6945 ExprResult 6946 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6947 SourceLocation RBraceLoc) { 6948 // Semantic analysis for initializers is done by ActOnDeclarator() and 6949 // CheckInitializer() - it requires knowledge of the object being initialized. 6950 6951 // Immediately handle non-overload placeholders. Overloads can be 6952 // resolved contextually, but everything else here can't. 6953 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6954 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6955 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6956 6957 // Ignore failures; dropping the entire initializer list because 6958 // of one failure would be terrible for indexing/etc. 6959 if (result.isInvalid()) continue; 6960 6961 InitArgList[I] = result.get(); 6962 } 6963 } 6964 6965 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6966 RBraceLoc); 6967 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6968 return E; 6969 } 6970 6971 /// Do an explicit extend of the given block pointer if we're in ARC. 6972 void Sema::maybeExtendBlockObject(ExprResult &E) { 6973 assert(E.get()->getType()->isBlockPointerType()); 6974 assert(E.get()->isRValue()); 6975 6976 // Only do this in an r-value context. 6977 if (!getLangOpts().ObjCAutoRefCount) return; 6978 6979 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6980 CK_ARCExtendBlockObject, E.get(), 6981 /*base path*/ nullptr, VK_RValue); 6982 Cleanup.setExprNeedsCleanups(true); 6983 } 6984 6985 /// Prepare a conversion of the given expression to an ObjC object 6986 /// pointer type. 6987 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6988 QualType type = E.get()->getType(); 6989 if (type->isObjCObjectPointerType()) { 6990 return CK_BitCast; 6991 } else if (type->isBlockPointerType()) { 6992 maybeExtendBlockObject(E); 6993 return CK_BlockPointerToObjCPointerCast; 6994 } else { 6995 assert(type->isPointerType()); 6996 return CK_CPointerToObjCPointerCast; 6997 } 6998 } 6999 7000 /// Prepares for a scalar cast, performing all the necessary stages 7001 /// except the final cast and returning the kind required. 7002 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7003 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7004 // Also, callers should have filtered out the invalid cases with 7005 // pointers. Everything else should be possible. 7006 7007 QualType SrcTy = Src.get()->getType(); 7008 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7009 return CK_NoOp; 7010 7011 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7012 case Type::STK_MemberPointer: 7013 llvm_unreachable("member pointer type in C"); 7014 7015 case Type::STK_CPointer: 7016 case Type::STK_BlockPointer: 7017 case Type::STK_ObjCObjectPointer: 7018 switch (DestTy->getScalarTypeKind()) { 7019 case Type::STK_CPointer: { 7020 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7021 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7022 if (SrcAS != DestAS) 7023 return CK_AddressSpaceConversion; 7024 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7025 return CK_NoOp; 7026 return CK_BitCast; 7027 } 7028 case Type::STK_BlockPointer: 7029 return (SrcKind == Type::STK_BlockPointer 7030 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7031 case Type::STK_ObjCObjectPointer: 7032 if (SrcKind == Type::STK_ObjCObjectPointer) 7033 return CK_BitCast; 7034 if (SrcKind == Type::STK_CPointer) 7035 return CK_CPointerToObjCPointerCast; 7036 maybeExtendBlockObject(Src); 7037 return CK_BlockPointerToObjCPointerCast; 7038 case Type::STK_Bool: 7039 return CK_PointerToBoolean; 7040 case Type::STK_Integral: 7041 return CK_PointerToIntegral; 7042 case Type::STK_Floating: 7043 case Type::STK_FloatingComplex: 7044 case Type::STK_IntegralComplex: 7045 case Type::STK_MemberPointer: 7046 case Type::STK_FixedPoint: 7047 llvm_unreachable("illegal cast from pointer"); 7048 } 7049 llvm_unreachable("Should have returned before this"); 7050 7051 case Type::STK_FixedPoint: 7052 switch (DestTy->getScalarTypeKind()) { 7053 case Type::STK_FixedPoint: 7054 return CK_FixedPointCast; 7055 case Type::STK_Bool: 7056 return CK_FixedPointToBoolean; 7057 case Type::STK_Integral: 7058 return CK_FixedPointToIntegral; 7059 case Type::STK_Floating: 7060 case Type::STK_IntegralComplex: 7061 case Type::STK_FloatingComplex: 7062 Diag(Src.get()->getExprLoc(), 7063 diag::err_unimplemented_conversion_with_fixed_point_type) 7064 << DestTy; 7065 return CK_IntegralCast; 7066 case Type::STK_CPointer: 7067 case Type::STK_ObjCObjectPointer: 7068 case Type::STK_BlockPointer: 7069 case Type::STK_MemberPointer: 7070 llvm_unreachable("illegal cast to pointer type"); 7071 } 7072 llvm_unreachable("Should have returned before this"); 7073 7074 case Type::STK_Bool: // casting from bool is like casting from an integer 7075 case Type::STK_Integral: 7076 switch (DestTy->getScalarTypeKind()) { 7077 case Type::STK_CPointer: 7078 case Type::STK_ObjCObjectPointer: 7079 case Type::STK_BlockPointer: 7080 if (Src.get()->isNullPointerConstant(Context, 7081 Expr::NPC_ValueDependentIsNull)) 7082 return CK_NullToPointer; 7083 return CK_IntegralToPointer; 7084 case Type::STK_Bool: 7085 return CK_IntegralToBoolean; 7086 case Type::STK_Integral: 7087 return CK_IntegralCast; 7088 case Type::STK_Floating: 7089 return CK_IntegralToFloating; 7090 case Type::STK_IntegralComplex: 7091 Src = ImpCastExprToType(Src.get(), 7092 DestTy->castAs<ComplexType>()->getElementType(), 7093 CK_IntegralCast); 7094 return CK_IntegralRealToComplex; 7095 case Type::STK_FloatingComplex: 7096 Src = ImpCastExprToType(Src.get(), 7097 DestTy->castAs<ComplexType>()->getElementType(), 7098 CK_IntegralToFloating); 7099 return CK_FloatingRealToComplex; 7100 case Type::STK_MemberPointer: 7101 llvm_unreachable("member pointer type in C"); 7102 case Type::STK_FixedPoint: 7103 return CK_IntegralToFixedPoint; 7104 } 7105 llvm_unreachable("Should have returned before this"); 7106 7107 case Type::STK_Floating: 7108 switch (DestTy->getScalarTypeKind()) { 7109 case Type::STK_Floating: 7110 return CK_FloatingCast; 7111 case Type::STK_Bool: 7112 return CK_FloatingToBoolean; 7113 case Type::STK_Integral: 7114 return CK_FloatingToIntegral; 7115 case Type::STK_FloatingComplex: 7116 Src = ImpCastExprToType(Src.get(), 7117 DestTy->castAs<ComplexType>()->getElementType(), 7118 CK_FloatingCast); 7119 return CK_FloatingRealToComplex; 7120 case Type::STK_IntegralComplex: 7121 Src = ImpCastExprToType(Src.get(), 7122 DestTy->castAs<ComplexType>()->getElementType(), 7123 CK_FloatingToIntegral); 7124 return CK_IntegralRealToComplex; 7125 case Type::STK_CPointer: 7126 case Type::STK_ObjCObjectPointer: 7127 case Type::STK_BlockPointer: 7128 llvm_unreachable("valid float->pointer cast?"); 7129 case Type::STK_MemberPointer: 7130 llvm_unreachable("member pointer type in C"); 7131 case Type::STK_FixedPoint: 7132 Diag(Src.get()->getExprLoc(), 7133 diag::err_unimplemented_conversion_with_fixed_point_type) 7134 << SrcTy; 7135 return CK_IntegralCast; 7136 } 7137 llvm_unreachable("Should have returned before this"); 7138 7139 case Type::STK_FloatingComplex: 7140 switch (DestTy->getScalarTypeKind()) { 7141 case Type::STK_FloatingComplex: 7142 return CK_FloatingComplexCast; 7143 case Type::STK_IntegralComplex: 7144 return CK_FloatingComplexToIntegralComplex; 7145 case Type::STK_Floating: { 7146 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7147 if (Context.hasSameType(ET, DestTy)) 7148 return CK_FloatingComplexToReal; 7149 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7150 return CK_FloatingCast; 7151 } 7152 case Type::STK_Bool: 7153 return CK_FloatingComplexToBoolean; 7154 case Type::STK_Integral: 7155 Src = ImpCastExprToType(Src.get(), 7156 SrcTy->castAs<ComplexType>()->getElementType(), 7157 CK_FloatingComplexToReal); 7158 return CK_FloatingToIntegral; 7159 case Type::STK_CPointer: 7160 case Type::STK_ObjCObjectPointer: 7161 case Type::STK_BlockPointer: 7162 llvm_unreachable("valid complex float->pointer cast?"); 7163 case Type::STK_MemberPointer: 7164 llvm_unreachable("member pointer type in C"); 7165 case Type::STK_FixedPoint: 7166 Diag(Src.get()->getExprLoc(), 7167 diag::err_unimplemented_conversion_with_fixed_point_type) 7168 << SrcTy; 7169 return CK_IntegralCast; 7170 } 7171 llvm_unreachable("Should have returned before this"); 7172 7173 case Type::STK_IntegralComplex: 7174 switch (DestTy->getScalarTypeKind()) { 7175 case Type::STK_FloatingComplex: 7176 return CK_IntegralComplexToFloatingComplex; 7177 case Type::STK_IntegralComplex: 7178 return CK_IntegralComplexCast; 7179 case Type::STK_Integral: { 7180 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7181 if (Context.hasSameType(ET, DestTy)) 7182 return CK_IntegralComplexToReal; 7183 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7184 return CK_IntegralCast; 7185 } 7186 case Type::STK_Bool: 7187 return CK_IntegralComplexToBoolean; 7188 case Type::STK_Floating: 7189 Src = ImpCastExprToType(Src.get(), 7190 SrcTy->castAs<ComplexType>()->getElementType(), 7191 CK_IntegralComplexToReal); 7192 return CK_IntegralToFloating; 7193 case Type::STK_CPointer: 7194 case Type::STK_ObjCObjectPointer: 7195 case Type::STK_BlockPointer: 7196 llvm_unreachable("valid complex int->pointer cast?"); 7197 case Type::STK_MemberPointer: 7198 llvm_unreachable("member pointer type in C"); 7199 case Type::STK_FixedPoint: 7200 Diag(Src.get()->getExprLoc(), 7201 diag::err_unimplemented_conversion_with_fixed_point_type) 7202 << SrcTy; 7203 return CK_IntegralCast; 7204 } 7205 llvm_unreachable("Should have returned before this"); 7206 } 7207 7208 llvm_unreachable("Unhandled scalar cast"); 7209 } 7210 7211 static bool breakDownVectorType(QualType type, uint64_t &len, 7212 QualType &eltType) { 7213 // Vectors are simple. 7214 if (const VectorType *vecType = type->getAs<VectorType>()) { 7215 len = vecType->getNumElements(); 7216 eltType = vecType->getElementType(); 7217 assert(eltType->isScalarType()); 7218 return true; 7219 } 7220 7221 // We allow lax conversion to and from non-vector types, but only if 7222 // they're real types (i.e. non-complex, non-pointer scalar types). 7223 if (!type->isRealType()) return false; 7224 7225 len = 1; 7226 eltType = type; 7227 return true; 7228 } 7229 7230 /// Are the two types lax-compatible vector types? That is, given 7231 /// that one of them is a vector, do they have equal storage sizes, 7232 /// where the storage size is the number of elements times the element 7233 /// size? 7234 /// 7235 /// This will also return false if either of the types is neither a 7236 /// vector nor a real type. 7237 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7238 assert(destTy->isVectorType() || srcTy->isVectorType()); 7239 7240 // Disallow lax conversions between scalars and ExtVectors (these 7241 // conversions are allowed for other vector types because common headers 7242 // depend on them). Most scalar OP ExtVector cases are handled by the 7243 // splat path anyway, which does what we want (convert, not bitcast). 7244 // What this rules out for ExtVectors is crazy things like char4*float. 7245 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7246 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7247 7248 uint64_t srcLen, destLen; 7249 QualType srcEltTy, destEltTy; 7250 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7251 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7252 7253 // ASTContext::getTypeSize will return the size rounded up to a 7254 // power of 2, so instead of using that, we need to use the raw 7255 // element size multiplied by the element count. 7256 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7257 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7258 7259 return (srcLen * srcEltSize == destLen * destEltSize); 7260 } 7261 7262 /// Is this a legal conversion between two types, one of which is 7263 /// known to be a vector type? 7264 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7265 assert(destTy->isVectorType() || srcTy->isVectorType()); 7266 7267 switch (Context.getLangOpts().getLaxVectorConversions()) { 7268 case LangOptions::LaxVectorConversionKind::None: 7269 return false; 7270 7271 case LangOptions::LaxVectorConversionKind::Integer: 7272 if (!srcTy->isIntegralOrEnumerationType()) { 7273 auto *Vec = srcTy->getAs<VectorType>(); 7274 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7275 return false; 7276 } 7277 if (!destTy->isIntegralOrEnumerationType()) { 7278 auto *Vec = destTy->getAs<VectorType>(); 7279 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7280 return false; 7281 } 7282 // OK, integer (vector) -> integer (vector) bitcast. 7283 break; 7284 7285 case LangOptions::LaxVectorConversionKind::All: 7286 break; 7287 } 7288 7289 return areLaxCompatibleVectorTypes(srcTy, destTy); 7290 } 7291 7292 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7293 CastKind &Kind) { 7294 assert(VectorTy->isVectorType() && "Not a vector type!"); 7295 7296 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7297 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7298 return Diag(R.getBegin(), 7299 Ty->isVectorType() ? 7300 diag::err_invalid_conversion_between_vectors : 7301 diag::err_invalid_conversion_between_vector_and_integer) 7302 << VectorTy << Ty << R; 7303 } else 7304 return Diag(R.getBegin(), 7305 diag::err_invalid_conversion_between_vector_and_scalar) 7306 << VectorTy << Ty << R; 7307 7308 Kind = CK_BitCast; 7309 return false; 7310 } 7311 7312 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7313 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7314 7315 if (DestElemTy == SplattedExpr->getType()) 7316 return SplattedExpr; 7317 7318 assert(DestElemTy->isFloatingType() || 7319 DestElemTy->isIntegralOrEnumerationType()); 7320 7321 CastKind CK; 7322 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7323 // OpenCL requires that we convert `true` boolean expressions to -1, but 7324 // only when splatting vectors. 7325 if (DestElemTy->isFloatingType()) { 7326 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7327 // in two steps: boolean to signed integral, then to floating. 7328 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7329 CK_BooleanToSignedIntegral); 7330 SplattedExpr = CastExprRes.get(); 7331 CK = CK_IntegralToFloating; 7332 } else { 7333 CK = CK_BooleanToSignedIntegral; 7334 } 7335 } else { 7336 ExprResult CastExprRes = SplattedExpr; 7337 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7338 if (CastExprRes.isInvalid()) 7339 return ExprError(); 7340 SplattedExpr = CastExprRes.get(); 7341 } 7342 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7343 } 7344 7345 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7346 Expr *CastExpr, CastKind &Kind) { 7347 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7348 7349 QualType SrcTy = CastExpr->getType(); 7350 7351 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7352 // an ExtVectorType. 7353 // In OpenCL, casts between vectors of different types are not allowed. 7354 // (See OpenCL 6.2). 7355 if (SrcTy->isVectorType()) { 7356 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7357 (getLangOpts().OpenCL && 7358 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7359 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7360 << DestTy << SrcTy << R; 7361 return ExprError(); 7362 } 7363 Kind = CK_BitCast; 7364 return CastExpr; 7365 } 7366 7367 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7368 // conversion will take place first from scalar to elt type, and then 7369 // splat from elt type to vector. 7370 if (SrcTy->isPointerType()) 7371 return Diag(R.getBegin(), 7372 diag::err_invalid_conversion_between_vector_and_scalar) 7373 << DestTy << SrcTy << R; 7374 7375 Kind = CK_VectorSplat; 7376 return prepareVectorSplat(DestTy, CastExpr); 7377 } 7378 7379 ExprResult 7380 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7381 Declarator &D, ParsedType &Ty, 7382 SourceLocation RParenLoc, Expr *CastExpr) { 7383 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7384 "ActOnCastExpr(): missing type or expr"); 7385 7386 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7387 if (D.isInvalidType()) 7388 return ExprError(); 7389 7390 if (getLangOpts().CPlusPlus) { 7391 // Check that there are no default arguments (C++ only). 7392 CheckExtraCXXDefaultArguments(D); 7393 } else { 7394 // Make sure any TypoExprs have been dealt with. 7395 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7396 if (!Res.isUsable()) 7397 return ExprError(); 7398 CastExpr = Res.get(); 7399 } 7400 7401 checkUnusedDeclAttributes(D); 7402 7403 QualType castType = castTInfo->getType(); 7404 Ty = CreateParsedType(castType, castTInfo); 7405 7406 bool isVectorLiteral = false; 7407 7408 // Check for an altivec or OpenCL literal, 7409 // i.e. all the elements are integer constants. 7410 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7411 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7412 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7413 && castType->isVectorType() && (PE || PLE)) { 7414 if (PLE && PLE->getNumExprs() == 0) { 7415 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7416 return ExprError(); 7417 } 7418 if (PE || PLE->getNumExprs() == 1) { 7419 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7420 if (!E->getType()->isVectorType()) 7421 isVectorLiteral = true; 7422 } 7423 else 7424 isVectorLiteral = true; 7425 } 7426 7427 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7428 // then handle it as such. 7429 if (isVectorLiteral) 7430 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7431 7432 // If the Expr being casted is a ParenListExpr, handle it specially. 7433 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7434 // sequence of BinOp comma operators. 7435 if (isa<ParenListExpr>(CastExpr)) { 7436 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7437 if (Result.isInvalid()) return ExprError(); 7438 CastExpr = Result.get(); 7439 } 7440 7441 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7442 !getSourceManager().isInSystemMacro(LParenLoc)) 7443 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7444 7445 CheckTollFreeBridgeCast(castType, CastExpr); 7446 7447 CheckObjCBridgeRelatedCast(castType, CastExpr); 7448 7449 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7450 7451 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7452 } 7453 7454 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7455 SourceLocation RParenLoc, Expr *E, 7456 TypeSourceInfo *TInfo) { 7457 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7458 "Expected paren or paren list expression"); 7459 7460 Expr **exprs; 7461 unsigned numExprs; 7462 Expr *subExpr; 7463 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7464 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7465 LiteralLParenLoc = PE->getLParenLoc(); 7466 LiteralRParenLoc = PE->getRParenLoc(); 7467 exprs = PE->getExprs(); 7468 numExprs = PE->getNumExprs(); 7469 } else { // isa<ParenExpr> by assertion at function entrance 7470 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7471 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7472 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7473 exprs = &subExpr; 7474 numExprs = 1; 7475 } 7476 7477 QualType Ty = TInfo->getType(); 7478 assert(Ty->isVectorType() && "Expected vector type"); 7479 7480 SmallVector<Expr *, 8> initExprs; 7481 const VectorType *VTy = Ty->castAs<VectorType>(); 7482 unsigned numElems = VTy->getNumElements(); 7483 7484 // '(...)' form of vector initialization in AltiVec: the number of 7485 // initializers must be one or must match the size of the vector. 7486 // If a single value is specified in the initializer then it will be 7487 // replicated to all the components of the vector 7488 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7489 // The number of initializers must be one or must match the size of the 7490 // vector. If a single value is specified in the initializer then it will 7491 // be replicated to all the components of the vector 7492 if (numExprs == 1) { 7493 QualType ElemTy = VTy->getElementType(); 7494 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7495 if (Literal.isInvalid()) 7496 return ExprError(); 7497 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7498 PrepareScalarCast(Literal, ElemTy)); 7499 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7500 } 7501 else if (numExprs < numElems) { 7502 Diag(E->getExprLoc(), 7503 diag::err_incorrect_number_of_vector_initializers); 7504 return ExprError(); 7505 } 7506 else 7507 initExprs.append(exprs, exprs + numExprs); 7508 } 7509 else { 7510 // For OpenCL, when the number of initializers is a single value, 7511 // it will be replicated to all components of the vector. 7512 if (getLangOpts().OpenCL && 7513 VTy->getVectorKind() == VectorType::GenericVector && 7514 numExprs == 1) { 7515 QualType ElemTy = VTy->getElementType(); 7516 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7517 if (Literal.isInvalid()) 7518 return ExprError(); 7519 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7520 PrepareScalarCast(Literal, ElemTy)); 7521 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7522 } 7523 7524 initExprs.append(exprs, exprs + numExprs); 7525 } 7526 // FIXME: This means that pretty-printing the final AST will produce curly 7527 // braces instead of the original commas. 7528 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7529 initExprs, LiteralRParenLoc); 7530 initE->setType(Ty); 7531 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7532 } 7533 7534 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7535 /// the ParenListExpr into a sequence of comma binary operators. 7536 ExprResult 7537 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7538 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7539 if (!E) 7540 return OrigExpr; 7541 7542 ExprResult Result(E->getExpr(0)); 7543 7544 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7545 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7546 E->getExpr(i)); 7547 7548 if (Result.isInvalid()) return ExprError(); 7549 7550 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7551 } 7552 7553 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7554 SourceLocation R, 7555 MultiExprArg Val) { 7556 return ParenListExpr::Create(Context, L, Val, R); 7557 } 7558 7559 /// Emit a specialized diagnostic when one expression is a null pointer 7560 /// constant and the other is not a pointer. Returns true if a diagnostic is 7561 /// emitted. 7562 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7563 SourceLocation QuestionLoc) { 7564 Expr *NullExpr = LHSExpr; 7565 Expr *NonPointerExpr = RHSExpr; 7566 Expr::NullPointerConstantKind NullKind = 7567 NullExpr->isNullPointerConstant(Context, 7568 Expr::NPC_ValueDependentIsNotNull); 7569 7570 if (NullKind == Expr::NPCK_NotNull) { 7571 NullExpr = RHSExpr; 7572 NonPointerExpr = LHSExpr; 7573 NullKind = 7574 NullExpr->isNullPointerConstant(Context, 7575 Expr::NPC_ValueDependentIsNotNull); 7576 } 7577 7578 if (NullKind == Expr::NPCK_NotNull) 7579 return false; 7580 7581 if (NullKind == Expr::NPCK_ZeroExpression) 7582 return false; 7583 7584 if (NullKind == Expr::NPCK_ZeroLiteral) { 7585 // In this case, check to make sure that we got here from a "NULL" 7586 // string in the source code. 7587 NullExpr = NullExpr->IgnoreParenImpCasts(); 7588 SourceLocation loc = NullExpr->getExprLoc(); 7589 if (!findMacroSpelling(loc, "NULL")) 7590 return false; 7591 } 7592 7593 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7594 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7595 << NonPointerExpr->getType() << DiagType 7596 << NonPointerExpr->getSourceRange(); 7597 return true; 7598 } 7599 7600 /// Return false if the condition expression is valid, true otherwise. 7601 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7602 QualType CondTy = Cond->getType(); 7603 7604 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7605 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7606 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7607 << CondTy << Cond->getSourceRange(); 7608 return true; 7609 } 7610 7611 // C99 6.5.15p2 7612 if (CondTy->isScalarType()) return false; 7613 7614 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7615 << CondTy << Cond->getSourceRange(); 7616 return true; 7617 } 7618 7619 /// Handle when one or both operands are void type. 7620 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7621 ExprResult &RHS) { 7622 Expr *LHSExpr = LHS.get(); 7623 Expr *RHSExpr = RHS.get(); 7624 7625 if (!LHSExpr->getType()->isVoidType()) 7626 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7627 << RHSExpr->getSourceRange(); 7628 if (!RHSExpr->getType()->isVoidType()) 7629 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7630 << LHSExpr->getSourceRange(); 7631 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7632 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7633 return S.Context.VoidTy; 7634 } 7635 7636 /// Return false if the NullExpr can be promoted to PointerTy, 7637 /// true otherwise. 7638 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7639 QualType PointerTy) { 7640 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7641 !NullExpr.get()->isNullPointerConstant(S.Context, 7642 Expr::NPC_ValueDependentIsNull)) 7643 return true; 7644 7645 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7646 return false; 7647 } 7648 7649 /// Checks compatibility between two pointers and return the resulting 7650 /// type. 7651 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7652 ExprResult &RHS, 7653 SourceLocation Loc) { 7654 QualType LHSTy = LHS.get()->getType(); 7655 QualType RHSTy = RHS.get()->getType(); 7656 7657 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7658 // Two identical pointers types are always compatible. 7659 return LHSTy; 7660 } 7661 7662 QualType lhptee, rhptee; 7663 7664 // Get the pointee types. 7665 bool IsBlockPointer = false; 7666 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7667 lhptee = LHSBTy->getPointeeType(); 7668 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7669 IsBlockPointer = true; 7670 } else { 7671 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7672 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7673 } 7674 7675 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7676 // differently qualified versions of compatible types, the result type is 7677 // a pointer to an appropriately qualified version of the composite 7678 // type. 7679 7680 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7681 // clause doesn't make sense for our extensions. E.g. address space 2 should 7682 // be incompatible with address space 3: they may live on different devices or 7683 // anything. 7684 Qualifiers lhQual = lhptee.getQualifiers(); 7685 Qualifiers rhQual = rhptee.getQualifiers(); 7686 7687 LangAS ResultAddrSpace = LangAS::Default; 7688 LangAS LAddrSpace = lhQual.getAddressSpace(); 7689 LangAS RAddrSpace = rhQual.getAddressSpace(); 7690 7691 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7692 // spaces is disallowed. 7693 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7694 ResultAddrSpace = LAddrSpace; 7695 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7696 ResultAddrSpace = RAddrSpace; 7697 else { 7698 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7699 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7700 << RHS.get()->getSourceRange(); 7701 return QualType(); 7702 } 7703 7704 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7705 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7706 lhQual.removeCVRQualifiers(); 7707 rhQual.removeCVRQualifiers(); 7708 7709 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7710 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7711 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7712 // qual types are compatible iff 7713 // * corresponded types are compatible 7714 // * CVR qualifiers are equal 7715 // * address spaces are equal 7716 // Thus for conditional operator we merge CVR and address space unqualified 7717 // pointees and if there is a composite type we return a pointer to it with 7718 // merged qualifiers. 7719 LHSCastKind = 7720 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7721 RHSCastKind = 7722 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7723 lhQual.removeAddressSpace(); 7724 rhQual.removeAddressSpace(); 7725 7726 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7727 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7728 7729 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7730 7731 if (CompositeTy.isNull()) { 7732 // In this situation, we assume void* type. No especially good 7733 // reason, but this is what gcc does, and we do have to pick 7734 // to get a consistent AST. 7735 QualType incompatTy; 7736 incompatTy = S.Context.getPointerType( 7737 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7738 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7739 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7740 7741 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7742 // for casts between types with incompatible address space qualifiers. 7743 // For the following code the compiler produces casts between global and 7744 // local address spaces of the corresponded innermost pointees: 7745 // local int *global *a; 7746 // global int *global *b; 7747 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7748 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7749 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7750 << RHS.get()->getSourceRange(); 7751 7752 return incompatTy; 7753 } 7754 7755 // The pointer types are compatible. 7756 // In case of OpenCL ResultTy should have the address space qualifier 7757 // which is a superset of address spaces of both the 2nd and the 3rd 7758 // operands of the conditional operator. 7759 QualType ResultTy = [&, ResultAddrSpace]() { 7760 if (S.getLangOpts().OpenCL) { 7761 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7762 CompositeQuals.setAddressSpace(ResultAddrSpace); 7763 return S.Context 7764 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7765 .withCVRQualifiers(MergedCVRQual); 7766 } 7767 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7768 }(); 7769 if (IsBlockPointer) 7770 ResultTy = S.Context.getBlockPointerType(ResultTy); 7771 else 7772 ResultTy = S.Context.getPointerType(ResultTy); 7773 7774 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7775 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7776 return ResultTy; 7777 } 7778 7779 /// Return the resulting type when the operands are both block pointers. 7780 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7781 ExprResult &LHS, 7782 ExprResult &RHS, 7783 SourceLocation Loc) { 7784 QualType LHSTy = LHS.get()->getType(); 7785 QualType RHSTy = RHS.get()->getType(); 7786 7787 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7788 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7789 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7790 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7791 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7792 return destType; 7793 } 7794 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7795 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7796 << RHS.get()->getSourceRange(); 7797 return QualType(); 7798 } 7799 7800 // We have 2 block pointer types. 7801 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7802 } 7803 7804 /// Return the resulting type when the operands are both pointers. 7805 static QualType 7806 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7807 ExprResult &RHS, 7808 SourceLocation Loc) { 7809 // get the pointer types 7810 QualType LHSTy = LHS.get()->getType(); 7811 QualType RHSTy = RHS.get()->getType(); 7812 7813 // get the "pointed to" types 7814 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7815 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7816 7817 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7818 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7819 // Figure out necessary qualifiers (C99 6.5.15p6) 7820 QualType destPointee 7821 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7822 QualType destType = S.Context.getPointerType(destPointee); 7823 // Add qualifiers if necessary. 7824 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7825 // Promote to void*. 7826 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7827 return destType; 7828 } 7829 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7830 QualType destPointee 7831 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7832 QualType destType = S.Context.getPointerType(destPointee); 7833 // Add qualifiers if necessary. 7834 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7835 // Promote to void*. 7836 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7837 return destType; 7838 } 7839 7840 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7841 } 7842 7843 /// Return false if the first expression is not an integer and the second 7844 /// expression is not a pointer, true otherwise. 7845 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7846 Expr* PointerExpr, SourceLocation Loc, 7847 bool IsIntFirstExpr) { 7848 if (!PointerExpr->getType()->isPointerType() || 7849 !Int.get()->getType()->isIntegerType()) 7850 return false; 7851 7852 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7853 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7854 7855 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7856 << Expr1->getType() << Expr2->getType() 7857 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7858 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7859 CK_IntegralToPointer); 7860 return true; 7861 } 7862 7863 /// Simple conversion between integer and floating point types. 7864 /// 7865 /// Used when handling the OpenCL conditional operator where the 7866 /// condition is a vector while the other operands are scalar. 7867 /// 7868 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7869 /// types are either integer or floating type. Between the two 7870 /// operands, the type with the higher rank is defined as the "result 7871 /// type". The other operand needs to be promoted to the same type. No 7872 /// other type promotion is allowed. We cannot use 7873 /// UsualArithmeticConversions() for this purpose, since it always 7874 /// promotes promotable types. 7875 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7876 ExprResult &RHS, 7877 SourceLocation QuestionLoc) { 7878 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7879 if (LHS.isInvalid()) 7880 return QualType(); 7881 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7882 if (RHS.isInvalid()) 7883 return QualType(); 7884 7885 // For conversion purposes, we ignore any qualifiers. 7886 // For example, "const float" and "float" are equivalent. 7887 QualType LHSType = 7888 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7889 QualType RHSType = 7890 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7891 7892 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7893 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7894 << LHSType << LHS.get()->getSourceRange(); 7895 return QualType(); 7896 } 7897 7898 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7899 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7900 << RHSType << RHS.get()->getSourceRange(); 7901 return QualType(); 7902 } 7903 7904 // If both types are identical, no conversion is needed. 7905 if (LHSType == RHSType) 7906 return LHSType; 7907 7908 // Now handle "real" floating types (i.e. float, double, long double). 7909 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7910 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7911 /*IsCompAssign = */ false); 7912 7913 // Finally, we have two differing integer types. 7914 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7915 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7916 } 7917 7918 /// Convert scalar operands to a vector that matches the 7919 /// condition in length. 7920 /// 7921 /// Used when handling the OpenCL conditional operator where the 7922 /// condition is a vector while the other operands are scalar. 7923 /// 7924 /// We first compute the "result type" for the scalar operands 7925 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7926 /// into a vector of that type where the length matches the condition 7927 /// vector type. s6.11.6 requires that the element types of the result 7928 /// and the condition must have the same number of bits. 7929 static QualType 7930 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7931 QualType CondTy, SourceLocation QuestionLoc) { 7932 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7933 if (ResTy.isNull()) return QualType(); 7934 7935 const VectorType *CV = CondTy->getAs<VectorType>(); 7936 assert(CV); 7937 7938 // Determine the vector result type 7939 unsigned NumElements = CV->getNumElements(); 7940 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7941 7942 // Ensure that all types have the same number of bits 7943 if (S.Context.getTypeSize(CV->getElementType()) 7944 != S.Context.getTypeSize(ResTy)) { 7945 // Since VectorTy is created internally, it does not pretty print 7946 // with an OpenCL name. Instead, we just print a description. 7947 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7948 SmallString<64> Str; 7949 llvm::raw_svector_ostream OS(Str); 7950 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7951 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7952 << CondTy << OS.str(); 7953 return QualType(); 7954 } 7955 7956 // Convert operands to the vector result type 7957 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7958 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7959 7960 return VectorTy; 7961 } 7962 7963 /// Return false if this is a valid OpenCL condition vector 7964 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7965 SourceLocation QuestionLoc) { 7966 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7967 // integral type. 7968 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7969 assert(CondTy); 7970 QualType EleTy = CondTy->getElementType(); 7971 if (EleTy->isIntegerType()) return false; 7972 7973 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7974 << Cond->getType() << Cond->getSourceRange(); 7975 return true; 7976 } 7977 7978 /// Return false if the vector condition type and the vector 7979 /// result type are compatible. 7980 /// 7981 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7982 /// number of elements, and their element types have the same number 7983 /// of bits. 7984 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7985 SourceLocation QuestionLoc) { 7986 const VectorType *CV = CondTy->getAs<VectorType>(); 7987 const VectorType *RV = VecResTy->getAs<VectorType>(); 7988 assert(CV && RV); 7989 7990 if (CV->getNumElements() != RV->getNumElements()) { 7991 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7992 << CondTy << VecResTy; 7993 return true; 7994 } 7995 7996 QualType CVE = CV->getElementType(); 7997 QualType RVE = RV->getElementType(); 7998 7999 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8000 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8001 << CondTy << VecResTy; 8002 return true; 8003 } 8004 8005 return false; 8006 } 8007 8008 /// Return the resulting type for the conditional operator in 8009 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8010 /// s6.3.i) when the condition is a vector type. 8011 static QualType 8012 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8013 ExprResult &LHS, ExprResult &RHS, 8014 SourceLocation QuestionLoc) { 8015 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8016 if (Cond.isInvalid()) 8017 return QualType(); 8018 QualType CondTy = Cond.get()->getType(); 8019 8020 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8021 return QualType(); 8022 8023 // If either operand is a vector then find the vector type of the 8024 // result as specified in OpenCL v1.1 s6.3.i. 8025 if (LHS.get()->getType()->isVectorType() || 8026 RHS.get()->getType()->isVectorType()) { 8027 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8028 /*isCompAssign*/false, 8029 /*AllowBothBool*/true, 8030 /*AllowBoolConversions*/false); 8031 if (VecResTy.isNull()) return QualType(); 8032 // The result type must match the condition type as specified in 8033 // OpenCL v1.1 s6.11.6. 8034 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8035 return QualType(); 8036 return VecResTy; 8037 } 8038 8039 // Both operands are scalar. 8040 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8041 } 8042 8043 /// Return true if the Expr is block type 8044 static bool checkBlockType(Sema &S, const Expr *E) { 8045 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8046 QualType Ty = CE->getCallee()->getType(); 8047 if (Ty->isBlockPointerType()) { 8048 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8049 return true; 8050 } 8051 } 8052 return false; 8053 } 8054 8055 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8056 /// In that case, LHS = cond. 8057 /// C99 6.5.15 8058 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8059 ExprResult &RHS, ExprValueKind &VK, 8060 ExprObjectKind &OK, 8061 SourceLocation QuestionLoc) { 8062 8063 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8064 if (!LHSResult.isUsable()) return QualType(); 8065 LHS = LHSResult; 8066 8067 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8068 if (!RHSResult.isUsable()) return QualType(); 8069 RHS = RHSResult; 8070 8071 // C++ is sufficiently different to merit its own checker. 8072 if (getLangOpts().CPlusPlus) 8073 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8074 8075 VK = VK_RValue; 8076 OK = OK_Ordinary; 8077 8078 // The OpenCL operator with a vector condition is sufficiently 8079 // different to merit its own checker. 8080 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 8081 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8082 8083 // First, check the condition. 8084 Cond = UsualUnaryConversions(Cond.get()); 8085 if (Cond.isInvalid()) 8086 return QualType(); 8087 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8088 return QualType(); 8089 8090 // Now check the two expressions. 8091 if (LHS.get()->getType()->isVectorType() || 8092 RHS.get()->getType()->isVectorType()) 8093 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8094 /*AllowBothBool*/true, 8095 /*AllowBoolConversions*/false); 8096 8097 QualType ResTy = 8098 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8099 if (LHS.isInvalid() || RHS.isInvalid()) 8100 return QualType(); 8101 8102 QualType LHSTy = LHS.get()->getType(); 8103 QualType RHSTy = RHS.get()->getType(); 8104 8105 // Diagnose attempts to convert between __float128 and long double where 8106 // such conversions currently can't be handled. 8107 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8108 Diag(QuestionLoc, 8109 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8111 return QualType(); 8112 } 8113 8114 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8115 // selection operator (?:). 8116 if (getLangOpts().OpenCL && 8117 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8118 return QualType(); 8119 } 8120 8121 // If both operands have arithmetic type, do the usual arithmetic conversions 8122 // to find a common type: C99 6.5.15p3,5. 8123 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8124 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8125 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8126 8127 return ResTy; 8128 } 8129 8130 // If both operands are the same structure or union type, the result is that 8131 // type. 8132 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8133 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8134 if (LHSRT->getDecl() == RHSRT->getDecl()) 8135 // "If both the operands have structure or union type, the result has 8136 // that type." This implies that CV qualifiers are dropped. 8137 return LHSTy.getUnqualifiedType(); 8138 // FIXME: Type of conditional expression must be complete in C mode. 8139 } 8140 8141 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8142 // The following || allows only one side to be void (a GCC-ism). 8143 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8144 return checkConditionalVoidType(*this, LHS, RHS); 8145 } 8146 8147 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8148 // the type of the other operand." 8149 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8150 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8151 8152 // All objective-c pointer type analysis is done here. 8153 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8154 QuestionLoc); 8155 if (LHS.isInvalid() || RHS.isInvalid()) 8156 return QualType(); 8157 if (!compositeType.isNull()) 8158 return compositeType; 8159 8160 8161 // Handle block pointer types. 8162 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8163 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8164 QuestionLoc); 8165 8166 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8167 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8168 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8169 QuestionLoc); 8170 8171 // GCC compatibility: soften pointer/integer mismatch. Note that 8172 // null pointers have been filtered out by this point. 8173 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8174 /*IsIntFirstExpr=*/true)) 8175 return RHSTy; 8176 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8177 /*IsIntFirstExpr=*/false)) 8178 return LHSTy; 8179 8180 // Allow ?: operations in which both operands have the same 8181 // built-in sizeless type. 8182 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8183 return LHSTy; 8184 8185 // Emit a better diagnostic if one of the expressions is a null pointer 8186 // constant and the other is not a pointer type. In this case, the user most 8187 // likely forgot to take the address of the other expression. 8188 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8189 return QualType(); 8190 8191 // Otherwise, the operands are not compatible. 8192 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8193 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8194 << RHS.get()->getSourceRange(); 8195 return QualType(); 8196 } 8197 8198 /// FindCompositeObjCPointerType - Helper method to find composite type of 8199 /// two objective-c pointer types of the two input expressions. 8200 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8201 SourceLocation QuestionLoc) { 8202 QualType LHSTy = LHS.get()->getType(); 8203 QualType RHSTy = RHS.get()->getType(); 8204 8205 // Handle things like Class and struct objc_class*. Here we case the result 8206 // to the pseudo-builtin, because that will be implicitly cast back to the 8207 // redefinition type if an attempt is made to access its fields. 8208 if (LHSTy->isObjCClassType() && 8209 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8210 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8211 return LHSTy; 8212 } 8213 if (RHSTy->isObjCClassType() && 8214 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8215 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8216 return RHSTy; 8217 } 8218 // And the same for struct objc_object* / id 8219 if (LHSTy->isObjCIdType() && 8220 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8221 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8222 return LHSTy; 8223 } 8224 if (RHSTy->isObjCIdType() && 8225 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8226 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8227 return RHSTy; 8228 } 8229 // And the same for struct objc_selector* / SEL 8230 if (Context.isObjCSelType(LHSTy) && 8231 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8232 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8233 return LHSTy; 8234 } 8235 if (Context.isObjCSelType(RHSTy) && 8236 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8237 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8238 return RHSTy; 8239 } 8240 // Check constraints for Objective-C object pointers types. 8241 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8242 8243 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8244 // Two identical object pointer types are always compatible. 8245 return LHSTy; 8246 } 8247 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8248 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8249 QualType compositeType = LHSTy; 8250 8251 // If both operands are interfaces and either operand can be 8252 // assigned to the other, use that type as the composite 8253 // type. This allows 8254 // xxx ? (A*) a : (B*) b 8255 // where B is a subclass of A. 8256 // 8257 // Additionally, as for assignment, if either type is 'id' 8258 // allow silent coercion. Finally, if the types are 8259 // incompatible then make sure to use 'id' as the composite 8260 // type so the result is acceptable for sending messages to. 8261 8262 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8263 // It could return the composite type. 8264 if (!(compositeType = 8265 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8266 // Nothing more to do. 8267 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8268 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8269 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8270 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8271 } else if ((LHSOPT->isObjCQualifiedIdType() || 8272 RHSOPT->isObjCQualifiedIdType()) && 8273 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8274 true)) { 8275 // Need to handle "id<xx>" explicitly. 8276 // GCC allows qualified id and any Objective-C type to devolve to 8277 // id. Currently localizing to here until clear this should be 8278 // part of ObjCQualifiedIdTypesAreCompatible. 8279 compositeType = Context.getObjCIdType(); 8280 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8281 compositeType = Context.getObjCIdType(); 8282 } else { 8283 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8284 << LHSTy << RHSTy 8285 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8286 QualType incompatTy = Context.getObjCIdType(); 8287 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8288 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8289 return incompatTy; 8290 } 8291 // The object pointer types are compatible. 8292 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8293 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8294 return compositeType; 8295 } 8296 // Check Objective-C object pointer types and 'void *' 8297 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8298 if (getLangOpts().ObjCAutoRefCount) { 8299 // ARC forbids the implicit conversion of object pointers to 'void *', 8300 // so these types are not compatible. 8301 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8302 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8303 LHS = RHS = true; 8304 return QualType(); 8305 } 8306 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8307 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8308 QualType destPointee 8309 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8310 QualType destType = Context.getPointerType(destPointee); 8311 // Add qualifiers if necessary. 8312 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8313 // Promote to void*. 8314 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8315 return destType; 8316 } 8317 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8318 if (getLangOpts().ObjCAutoRefCount) { 8319 // ARC forbids the implicit conversion of object pointers to 'void *', 8320 // so these types are not compatible. 8321 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8322 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8323 LHS = RHS = true; 8324 return QualType(); 8325 } 8326 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8327 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8328 QualType destPointee 8329 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8330 QualType destType = Context.getPointerType(destPointee); 8331 // Add qualifiers if necessary. 8332 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8333 // Promote to void*. 8334 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8335 return destType; 8336 } 8337 return QualType(); 8338 } 8339 8340 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8341 /// ParenRange in parentheses. 8342 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8343 const PartialDiagnostic &Note, 8344 SourceRange ParenRange) { 8345 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8346 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8347 EndLoc.isValid()) { 8348 Self.Diag(Loc, Note) 8349 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8350 << FixItHint::CreateInsertion(EndLoc, ")"); 8351 } else { 8352 // We can't display the parentheses, so just show the bare note. 8353 Self.Diag(Loc, Note) << ParenRange; 8354 } 8355 } 8356 8357 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8358 return BinaryOperator::isAdditiveOp(Opc) || 8359 BinaryOperator::isMultiplicativeOp(Opc) || 8360 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8361 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8362 // not any of the logical operators. Bitwise-xor is commonly used as a 8363 // logical-xor because there is no logical-xor operator. The logical 8364 // operators, including uses of xor, have a high false positive rate for 8365 // precedence warnings. 8366 } 8367 8368 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8369 /// expression, either using a built-in or overloaded operator, 8370 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8371 /// expression. 8372 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8373 Expr **RHSExprs) { 8374 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8375 E = E->IgnoreImpCasts(); 8376 E = E->IgnoreConversionOperator(); 8377 E = E->IgnoreImpCasts(); 8378 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8379 E = MTE->getSubExpr(); 8380 E = E->IgnoreImpCasts(); 8381 } 8382 8383 // Built-in binary operator. 8384 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8385 if (IsArithmeticOp(OP->getOpcode())) { 8386 *Opcode = OP->getOpcode(); 8387 *RHSExprs = OP->getRHS(); 8388 return true; 8389 } 8390 } 8391 8392 // Overloaded operator. 8393 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8394 if (Call->getNumArgs() != 2) 8395 return false; 8396 8397 // Make sure this is really a binary operator that is safe to pass into 8398 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8399 OverloadedOperatorKind OO = Call->getOperator(); 8400 if (OO < OO_Plus || OO > OO_Arrow || 8401 OO == OO_PlusPlus || OO == OO_MinusMinus) 8402 return false; 8403 8404 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8405 if (IsArithmeticOp(OpKind)) { 8406 *Opcode = OpKind; 8407 *RHSExprs = Call->getArg(1); 8408 return true; 8409 } 8410 } 8411 8412 return false; 8413 } 8414 8415 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8416 /// or is a logical expression such as (x==y) which has int type, but is 8417 /// commonly interpreted as boolean. 8418 static bool ExprLooksBoolean(Expr *E) { 8419 E = E->IgnoreParenImpCasts(); 8420 8421 if (E->getType()->isBooleanType()) 8422 return true; 8423 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8424 return OP->isComparisonOp() || OP->isLogicalOp(); 8425 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8426 return OP->getOpcode() == UO_LNot; 8427 if (E->getType()->isPointerType()) 8428 return true; 8429 // FIXME: What about overloaded operator calls returning "unspecified boolean 8430 // type"s (commonly pointer-to-members)? 8431 8432 return false; 8433 } 8434 8435 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8436 /// and binary operator are mixed in a way that suggests the programmer assumed 8437 /// the conditional operator has higher precedence, for example: 8438 /// "int x = a + someBinaryCondition ? 1 : 2". 8439 static void DiagnoseConditionalPrecedence(Sema &Self, 8440 SourceLocation OpLoc, 8441 Expr *Condition, 8442 Expr *LHSExpr, 8443 Expr *RHSExpr) { 8444 BinaryOperatorKind CondOpcode; 8445 Expr *CondRHS; 8446 8447 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8448 return; 8449 if (!ExprLooksBoolean(CondRHS)) 8450 return; 8451 8452 // The condition is an arithmetic binary expression, with a right- 8453 // hand side that looks boolean, so warn. 8454 8455 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8456 ? diag::warn_precedence_bitwise_conditional 8457 : diag::warn_precedence_conditional; 8458 8459 Self.Diag(OpLoc, DiagID) 8460 << Condition->getSourceRange() 8461 << BinaryOperator::getOpcodeStr(CondOpcode); 8462 8463 SuggestParentheses( 8464 Self, OpLoc, 8465 Self.PDiag(diag::note_precedence_silence) 8466 << BinaryOperator::getOpcodeStr(CondOpcode), 8467 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8468 8469 SuggestParentheses(Self, OpLoc, 8470 Self.PDiag(diag::note_precedence_conditional_first), 8471 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8472 } 8473 8474 /// Compute the nullability of a conditional expression. 8475 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8476 QualType LHSTy, QualType RHSTy, 8477 ASTContext &Ctx) { 8478 if (!ResTy->isAnyPointerType()) 8479 return ResTy; 8480 8481 auto GetNullability = [&Ctx](QualType Ty) { 8482 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8483 if (Kind) 8484 return *Kind; 8485 return NullabilityKind::Unspecified; 8486 }; 8487 8488 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8489 NullabilityKind MergedKind; 8490 8491 // Compute nullability of a binary conditional expression. 8492 if (IsBin) { 8493 if (LHSKind == NullabilityKind::NonNull) 8494 MergedKind = NullabilityKind::NonNull; 8495 else 8496 MergedKind = RHSKind; 8497 // Compute nullability of a normal conditional expression. 8498 } else { 8499 if (LHSKind == NullabilityKind::Nullable || 8500 RHSKind == NullabilityKind::Nullable) 8501 MergedKind = NullabilityKind::Nullable; 8502 else if (LHSKind == NullabilityKind::NonNull) 8503 MergedKind = RHSKind; 8504 else if (RHSKind == NullabilityKind::NonNull) 8505 MergedKind = LHSKind; 8506 else 8507 MergedKind = NullabilityKind::Unspecified; 8508 } 8509 8510 // Return if ResTy already has the correct nullability. 8511 if (GetNullability(ResTy) == MergedKind) 8512 return ResTy; 8513 8514 // Strip all nullability from ResTy. 8515 while (ResTy->getNullability(Ctx)) 8516 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8517 8518 // Create a new AttributedType with the new nullability kind. 8519 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8520 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8521 } 8522 8523 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8524 /// in the case of a the GNU conditional expr extension. 8525 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8526 SourceLocation ColonLoc, 8527 Expr *CondExpr, Expr *LHSExpr, 8528 Expr *RHSExpr) { 8529 if (!getLangOpts().CPlusPlus) { 8530 // C cannot handle TypoExpr nodes in the condition because it 8531 // doesn't handle dependent types properly, so make sure any TypoExprs have 8532 // been dealt with before checking the operands. 8533 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8534 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8535 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8536 8537 if (!CondResult.isUsable()) 8538 return ExprError(); 8539 8540 if (LHSExpr) { 8541 if (!LHSResult.isUsable()) 8542 return ExprError(); 8543 } 8544 8545 if (!RHSResult.isUsable()) 8546 return ExprError(); 8547 8548 CondExpr = CondResult.get(); 8549 LHSExpr = LHSResult.get(); 8550 RHSExpr = RHSResult.get(); 8551 } 8552 8553 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8554 // was the condition. 8555 OpaqueValueExpr *opaqueValue = nullptr; 8556 Expr *commonExpr = nullptr; 8557 if (!LHSExpr) { 8558 commonExpr = CondExpr; 8559 // Lower out placeholder types first. This is important so that we don't 8560 // try to capture a placeholder. This happens in few cases in C++; such 8561 // as Objective-C++'s dictionary subscripting syntax. 8562 if (commonExpr->hasPlaceholderType()) { 8563 ExprResult result = CheckPlaceholderExpr(commonExpr); 8564 if (!result.isUsable()) return ExprError(); 8565 commonExpr = result.get(); 8566 } 8567 // We usually want to apply unary conversions *before* saving, except 8568 // in the special case of a C++ l-value conditional. 8569 if (!(getLangOpts().CPlusPlus 8570 && !commonExpr->isTypeDependent() 8571 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8572 && commonExpr->isGLValue() 8573 && commonExpr->isOrdinaryOrBitFieldObject() 8574 && RHSExpr->isOrdinaryOrBitFieldObject() 8575 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8576 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8577 if (commonRes.isInvalid()) 8578 return ExprError(); 8579 commonExpr = commonRes.get(); 8580 } 8581 8582 // If the common expression is a class or array prvalue, materialize it 8583 // so that we can safely refer to it multiple times. 8584 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8585 commonExpr->getType()->isArrayType())) { 8586 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8587 if (MatExpr.isInvalid()) 8588 return ExprError(); 8589 commonExpr = MatExpr.get(); 8590 } 8591 8592 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8593 commonExpr->getType(), 8594 commonExpr->getValueKind(), 8595 commonExpr->getObjectKind(), 8596 commonExpr); 8597 LHSExpr = CondExpr = opaqueValue; 8598 } 8599 8600 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8601 ExprValueKind VK = VK_RValue; 8602 ExprObjectKind OK = OK_Ordinary; 8603 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8604 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8605 VK, OK, QuestionLoc); 8606 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8607 RHS.isInvalid()) 8608 return ExprError(); 8609 8610 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8611 RHS.get()); 8612 8613 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8614 8615 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8616 Context); 8617 8618 if (!commonExpr) 8619 return new (Context) 8620 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8621 RHS.get(), result, VK, OK); 8622 8623 return new (Context) BinaryConditionalOperator( 8624 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8625 ColonLoc, result, VK, OK); 8626 } 8627 8628 // Check if we have a conversion between incompatible cmse function pointer 8629 // types, that is, a conversion between a function pointer with the 8630 // cmse_nonsecure_call attribute and one without. 8631 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8632 QualType ToType) { 8633 if (const auto *ToFn = 8634 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8635 if (const auto *FromFn = 8636 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8637 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8638 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8639 8640 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8641 } 8642 } 8643 return false; 8644 } 8645 8646 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8647 // being closely modeled after the C99 spec:-). The odd characteristic of this 8648 // routine is it effectively iqnores the qualifiers on the top level pointee. 8649 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8650 // FIXME: add a couple examples in this comment. 8651 static Sema::AssignConvertType 8652 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8653 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8654 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8655 8656 // get the "pointed to" type (ignoring qualifiers at the top level) 8657 const Type *lhptee, *rhptee; 8658 Qualifiers lhq, rhq; 8659 std::tie(lhptee, lhq) = 8660 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8661 std::tie(rhptee, rhq) = 8662 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8663 8664 Sema::AssignConvertType ConvTy = Sema::Compatible; 8665 8666 // C99 6.5.16.1p1: This following citation is common to constraints 8667 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8668 // qualifiers of the type *pointed to* by the right; 8669 8670 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8671 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8672 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8673 // Ignore lifetime for further calculation. 8674 lhq.removeObjCLifetime(); 8675 rhq.removeObjCLifetime(); 8676 } 8677 8678 if (!lhq.compatiblyIncludes(rhq)) { 8679 // Treat address-space mismatches as fatal. 8680 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8681 return Sema::IncompatiblePointerDiscardsQualifiers; 8682 8683 // It's okay to add or remove GC or lifetime qualifiers when converting to 8684 // and from void*. 8685 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8686 .compatiblyIncludes( 8687 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8688 && (lhptee->isVoidType() || rhptee->isVoidType())) 8689 ; // keep old 8690 8691 // Treat lifetime mismatches as fatal. 8692 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8693 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8694 8695 // For GCC/MS compatibility, other qualifier mismatches are treated 8696 // as still compatible in C. 8697 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8698 } 8699 8700 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8701 // incomplete type and the other is a pointer to a qualified or unqualified 8702 // version of void... 8703 if (lhptee->isVoidType()) { 8704 if (rhptee->isIncompleteOrObjectType()) 8705 return ConvTy; 8706 8707 // As an extension, we allow cast to/from void* to function pointer. 8708 assert(rhptee->isFunctionType()); 8709 return Sema::FunctionVoidPointer; 8710 } 8711 8712 if (rhptee->isVoidType()) { 8713 if (lhptee->isIncompleteOrObjectType()) 8714 return ConvTy; 8715 8716 // As an extension, we allow cast to/from void* to function pointer. 8717 assert(lhptee->isFunctionType()); 8718 return Sema::FunctionVoidPointer; 8719 } 8720 8721 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8722 // unqualified versions of compatible types, ... 8723 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8724 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8725 // Check if the pointee types are compatible ignoring the sign. 8726 // We explicitly check for char so that we catch "char" vs 8727 // "unsigned char" on systems where "char" is unsigned. 8728 if (lhptee->isCharType()) 8729 ltrans = S.Context.UnsignedCharTy; 8730 else if (lhptee->hasSignedIntegerRepresentation()) 8731 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8732 8733 if (rhptee->isCharType()) 8734 rtrans = S.Context.UnsignedCharTy; 8735 else if (rhptee->hasSignedIntegerRepresentation()) 8736 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8737 8738 if (ltrans == rtrans) { 8739 // Types are compatible ignoring the sign. Qualifier incompatibility 8740 // takes priority over sign incompatibility because the sign 8741 // warning can be disabled. 8742 if (ConvTy != Sema::Compatible) 8743 return ConvTy; 8744 8745 return Sema::IncompatiblePointerSign; 8746 } 8747 8748 // If we are a multi-level pointer, it's possible that our issue is simply 8749 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8750 // the eventual target type is the same and the pointers have the same 8751 // level of indirection, this must be the issue. 8752 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8753 do { 8754 std::tie(lhptee, lhq) = 8755 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8756 std::tie(rhptee, rhq) = 8757 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8758 8759 // Inconsistent address spaces at this point is invalid, even if the 8760 // address spaces would be compatible. 8761 // FIXME: This doesn't catch address space mismatches for pointers of 8762 // different nesting levels, like: 8763 // __local int *** a; 8764 // int ** b = a; 8765 // It's not clear how to actually determine when such pointers are 8766 // invalidly incompatible. 8767 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8768 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8769 8770 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8771 8772 if (lhptee == rhptee) 8773 return Sema::IncompatibleNestedPointerQualifiers; 8774 } 8775 8776 // General pointer incompatibility takes priority over qualifiers. 8777 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8778 return Sema::IncompatibleFunctionPointer; 8779 return Sema::IncompatiblePointer; 8780 } 8781 if (!S.getLangOpts().CPlusPlus && 8782 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8783 return Sema::IncompatibleFunctionPointer; 8784 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8785 return Sema::IncompatibleFunctionPointer; 8786 return ConvTy; 8787 } 8788 8789 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8790 /// block pointer types are compatible or whether a block and normal pointer 8791 /// are compatible. It is more restrict than comparing two function pointer 8792 // types. 8793 static Sema::AssignConvertType 8794 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8795 QualType RHSType) { 8796 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8797 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8798 8799 QualType lhptee, rhptee; 8800 8801 // get the "pointed to" type (ignoring qualifiers at the top level) 8802 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8803 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8804 8805 // In C++, the types have to match exactly. 8806 if (S.getLangOpts().CPlusPlus) 8807 return Sema::IncompatibleBlockPointer; 8808 8809 Sema::AssignConvertType ConvTy = Sema::Compatible; 8810 8811 // For blocks we enforce that qualifiers are identical. 8812 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8813 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8814 if (S.getLangOpts().OpenCL) { 8815 LQuals.removeAddressSpace(); 8816 RQuals.removeAddressSpace(); 8817 } 8818 if (LQuals != RQuals) 8819 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8820 8821 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8822 // assignment. 8823 // The current behavior is similar to C++ lambdas. A block might be 8824 // assigned to a variable iff its return type and parameters are compatible 8825 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8826 // an assignment. Presumably it should behave in way that a function pointer 8827 // assignment does in C, so for each parameter and return type: 8828 // * CVR and address space of LHS should be a superset of CVR and address 8829 // space of RHS. 8830 // * unqualified types should be compatible. 8831 if (S.getLangOpts().OpenCL) { 8832 if (!S.Context.typesAreBlockPointerCompatible( 8833 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8834 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8835 return Sema::IncompatibleBlockPointer; 8836 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8837 return Sema::IncompatibleBlockPointer; 8838 8839 return ConvTy; 8840 } 8841 8842 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8843 /// for assignment compatibility. 8844 static Sema::AssignConvertType 8845 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8846 QualType RHSType) { 8847 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8848 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8849 8850 if (LHSType->isObjCBuiltinType()) { 8851 // Class is not compatible with ObjC object pointers. 8852 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8853 !RHSType->isObjCQualifiedClassType()) 8854 return Sema::IncompatiblePointer; 8855 return Sema::Compatible; 8856 } 8857 if (RHSType->isObjCBuiltinType()) { 8858 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8859 !LHSType->isObjCQualifiedClassType()) 8860 return Sema::IncompatiblePointer; 8861 return Sema::Compatible; 8862 } 8863 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8864 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8865 8866 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8867 // make an exception for id<P> 8868 !LHSType->isObjCQualifiedIdType()) 8869 return Sema::CompatiblePointerDiscardsQualifiers; 8870 8871 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8872 return Sema::Compatible; 8873 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8874 return Sema::IncompatibleObjCQualifiedId; 8875 return Sema::IncompatiblePointer; 8876 } 8877 8878 Sema::AssignConvertType 8879 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8880 QualType LHSType, QualType RHSType) { 8881 // Fake up an opaque expression. We don't actually care about what 8882 // cast operations are required, so if CheckAssignmentConstraints 8883 // adds casts to this they'll be wasted, but fortunately that doesn't 8884 // usually happen on valid code. 8885 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8886 ExprResult RHSPtr = &RHSExpr; 8887 CastKind K; 8888 8889 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8890 } 8891 8892 /// This helper function returns true if QT is a vector type that has element 8893 /// type ElementType. 8894 static bool isVector(QualType QT, QualType ElementType) { 8895 if (const VectorType *VT = QT->getAs<VectorType>()) 8896 return VT->getElementType().getCanonicalType() == ElementType; 8897 return false; 8898 } 8899 8900 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8901 /// has code to accommodate several GCC extensions when type checking 8902 /// pointers. Here are some objectionable examples that GCC considers warnings: 8903 /// 8904 /// int a, *pint; 8905 /// short *pshort; 8906 /// struct foo *pfoo; 8907 /// 8908 /// pint = pshort; // warning: assignment from incompatible pointer type 8909 /// a = pint; // warning: assignment makes integer from pointer without a cast 8910 /// pint = a; // warning: assignment makes pointer from integer without a cast 8911 /// pint = pfoo; // warning: assignment from incompatible pointer type 8912 /// 8913 /// As a result, the code for dealing with pointers is more complex than the 8914 /// C99 spec dictates. 8915 /// 8916 /// Sets 'Kind' for any result kind except Incompatible. 8917 Sema::AssignConvertType 8918 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8919 CastKind &Kind, bool ConvertRHS) { 8920 QualType RHSType = RHS.get()->getType(); 8921 QualType OrigLHSType = LHSType; 8922 8923 // Get canonical types. We're not formatting these types, just comparing 8924 // them. 8925 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8926 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8927 8928 // Common case: no conversion required. 8929 if (LHSType == RHSType) { 8930 Kind = CK_NoOp; 8931 return Compatible; 8932 } 8933 8934 // If we have an atomic type, try a non-atomic assignment, then just add an 8935 // atomic qualification step. 8936 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8937 Sema::AssignConvertType result = 8938 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8939 if (result != Compatible) 8940 return result; 8941 if (Kind != CK_NoOp && ConvertRHS) 8942 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8943 Kind = CK_NonAtomicToAtomic; 8944 return Compatible; 8945 } 8946 8947 // If the left-hand side is a reference type, then we are in a 8948 // (rare!) case where we've allowed the use of references in C, 8949 // e.g., as a parameter type in a built-in function. In this case, 8950 // just make sure that the type referenced is compatible with the 8951 // right-hand side type. The caller is responsible for adjusting 8952 // LHSType so that the resulting expression does not have reference 8953 // type. 8954 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8955 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8956 Kind = CK_LValueBitCast; 8957 return Compatible; 8958 } 8959 return Incompatible; 8960 } 8961 8962 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8963 // to the same ExtVector type. 8964 if (LHSType->isExtVectorType()) { 8965 if (RHSType->isExtVectorType()) 8966 return Incompatible; 8967 if (RHSType->isArithmeticType()) { 8968 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8969 if (ConvertRHS) 8970 RHS = prepareVectorSplat(LHSType, RHS.get()); 8971 Kind = CK_VectorSplat; 8972 return Compatible; 8973 } 8974 } 8975 8976 // Conversions to or from vector type. 8977 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8978 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8979 // Allow assignments of an AltiVec vector type to an equivalent GCC 8980 // vector type and vice versa 8981 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8982 Kind = CK_BitCast; 8983 return Compatible; 8984 } 8985 8986 // If we are allowing lax vector conversions, and LHS and RHS are both 8987 // vectors, the total size only needs to be the same. This is a bitcast; 8988 // no bits are changed but the result type is different. 8989 if (isLaxVectorConversion(RHSType, LHSType)) { 8990 Kind = CK_BitCast; 8991 return IncompatibleVectors; 8992 } 8993 } 8994 8995 // When the RHS comes from another lax conversion (e.g. binops between 8996 // scalars and vectors) the result is canonicalized as a vector. When the 8997 // LHS is also a vector, the lax is allowed by the condition above. Handle 8998 // the case where LHS is a scalar. 8999 if (LHSType->isScalarType()) { 9000 const VectorType *VecType = RHSType->getAs<VectorType>(); 9001 if (VecType && VecType->getNumElements() == 1 && 9002 isLaxVectorConversion(RHSType, LHSType)) { 9003 ExprResult *VecExpr = &RHS; 9004 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9005 Kind = CK_BitCast; 9006 return Compatible; 9007 } 9008 } 9009 9010 return Incompatible; 9011 } 9012 9013 // Diagnose attempts to convert between __float128 and long double where 9014 // such conversions currently can't be handled. 9015 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9016 return Incompatible; 9017 9018 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9019 // discards the imaginary part. 9020 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9021 !LHSType->getAs<ComplexType>()) 9022 return Incompatible; 9023 9024 // Arithmetic conversions. 9025 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9026 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9027 if (ConvertRHS) 9028 Kind = PrepareScalarCast(RHS, LHSType); 9029 return Compatible; 9030 } 9031 9032 // Conversions to normal pointers. 9033 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9034 // U* -> T* 9035 if (isa<PointerType>(RHSType)) { 9036 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9037 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9038 if (AddrSpaceL != AddrSpaceR) 9039 Kind = CK_AddressSpaceConversion; 9040 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9041 Kind = CK_NoOp; 9042 else 9043 Kind = CK_BitCast; 9044 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9045 } 9046 9047 // int -> T* 9048 if (RHSType->isIntegerType()) { 9049 Kind = CK_IntegralToPointer; // FIXME: null? 9050 return IntToPointer; 9051 } 9052 9053 // C pointers are not compatible with ObjC object pointers, 9054 // with two exceptions: 9055 if (isa<ObjCObjectPointerType>(RHSType)) { 9056 // - conversions to void* 9057 if (LHSPointer->getPointeeType()->isVoidType()) { 9058 Kind = CK_BitCast; 9059 return Compatible; 9060 } 9061 9062 // - conversions from 'Class' to the redefinition type 9063 if (RHSType->isObjCClassType() && 9064 Context.hasSameType(LHSType, 9065 Context.getObjCClassRedefinitionType())) { 9066 Kind = CK_BitCast; 9067 return Compatible; 9068 } 9069 9070 Kind = CK_BitCast; 9071 return IncompatiblePointer; 9072 } 9073 9074 // U^ -> void* 9075 if (RHSType->getAs<BlockPointerType>()) { 9076 if (LHSPointer->getPointeeType()->isVoidType()) { 9077 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9078 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9079 ->getPointeeType() 9080 .getAddressSpace(); 9081 Kind = 9082 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9083 return Compatible; 9084 } 9085 } 9086 9087 return Incompatible; 9088 } 9089 9090 // Conversions to block pointers. 9091 if (isa<BlockPointerType>(LHSType)) { 9092 // U^ -> T^ 9093 if (RHSType->isBlockPointerType()) { 9094 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9095 ->getPointeeType() 9096 .getAddressSpace(); 9097 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9098 ->getPointeeType() 9099 .getAddressSpace(); 9100 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9101 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9102 } 9103 9104 // int or null -> T^ 9105 if (RHSType->isIntegerType()) { 9106 Kind = CK_IntegralToPointer; // FIXME: null 9107 return IntToBlockPointer; 9108 } 9109 9110 // id -> T^ 9111 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9112 Kind = CK_AnyPointerToBlockPointerCast; 9113 return Compatible; 9114 } 9115 9116 // void* -> T^ 9117 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9118 if (RHSPT->getPointeeType()->isVoidType()) { 9119 Kind = CK_AnyPointerToBlockPointerCast; 9120 return Compatible; 9121 } 9122 9123 return Incompatible; 9124 } 9125 9126 // Conversions to Objective-C pointers. 9127 if (isa<ObjCObjectPointerType>(LHSType)) { 9128 // A* -> B* 9129 if (RHSType->isObjCObjectPointerType()) { 9130 Kind = CK_BitCast; 9131 Sema::AssignConvertType result = 9132 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9133 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9134 result == Compatible && 9135 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9136 result = IncompatibleObjCWeakRef; 9137 return result; 9138 } 9139 9140 // int or null -> A* 9141 if (RHSType->isIntegerType()) { 9142 Kind = CK_IntegralToPointer; // FIXME: null 9143 return IntToPointer; 9144 } 9145 9146 // In general, C pointers are not compatible with ObjC object pointers, 9147 // with two exceptions: 9148 if (isa<PointerType>(RHSType)) { 9149 Kind = CK_CPointerToObjCPointerCast; 9150 9151 // - conversions from 'void*' 9152 if (RHSType->isVoidPointerType()) { 9153 return Compatible; 9154 } 9155 9156 // - conversions to 'Class' from its redefinition type 9157 if (LHSType->isObjCClassType() && 9158 Context.hasSameType(RHSType, 9159 Context.getObjCClassRedefinitionType())) { 9160 return Compatible; 9161 } 9162 9163 return IncompatiblePointer; 9164 } 9165 9166 // Only under strict condition T^ is compatible with an Objective-C pointer. 9167 if (RHSType->isBlockPointerType() && 9168 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9169 if (ConvertRHS) 9170 maybeExtendBlockObject(RHS); 9171 Kind = CK_BlockPointerToObjCPointerCast; 9172 return Compatible; 9173 } 9174 9175 return Incompatible; 9176 } 9177 9178 // Conversions from pointers that are not covered by the above. 9179 if (isa<PointerType>(RHSType)) { 9180 // T* -> _Bool 9181 if (LHSType == Context.BoolTy) { 9182 Kind = CK_PointerToBoolean; 9183 return Compatible; 9184 } 9185 9186 // T* -> int 9187 if (LHSType->isIntegerType()) { 9188 Kind = CK_PointerToIntegral; 9189 return PointerToInt; 9190 } 9191 9192 return Incompatible; 9193 } 9194 9195 // Conversions from Objective-C pointers that are not covered by the above. 9196 if (isa<ObjCObjectPointerType>(RHSType)) { 9197 // T* -> _Bool 9198 if (LHSType == Context.BoolTy) { 9199 Kind = CK_PointerToBoolean; 9200 return Compatible; 9201 } 9202 9203 // T* -> int 9204 if (LHSType->isIntegerType()) { 9205 Kind = CK_PointerToIntegral; 9206 return PointerToInt; 9207 } 9208 9209 return Incompatible; 9210 } 9211 9212 // struct A -> struct B 9213 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9214 if (Context.typesAreCompatible(LHSType, RHSType)) { 9215 Kind = CK_NoOp; 9216 return Compatible; 9217 } 9218 } 9219 9220 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9221 Kind = CK_IntToOCLSampler; 9222 return Compatible; 9223 } 9224 9225 return Incompatible; 9226 } 9227 9228 /// Constructs a transparent union from an expression that is 9229 /// used to initialize the transparent union. 9230 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9231 ExprResult &EResult, QualType UnionType, 9232 FieldDecl *Field) { 9233 // Build an initializer list that designates the appropriate member 9234 // of the transparent union. 9235 Expr *E = EResult.get(); 9236 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9237 E, SourceLocation()); 9238 Initializer->setType(UnionType); 9239 Initializer->setInitializedFieldInUnion(Field); 9240 9241 // Build a compound literal constructing a value of the transparent 9242 // union type from this initializer list. 9243 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9244 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9245 VK_RValue, Initializer, false); 9246 } 9247 9248 Sema::AssignConvertType 9249 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9250 ExprResult &RHS) { 9251 QualType RHSType = RHS.get()->getType(); 9252 9253 // If the ArgType is a Union type, we want to handle a potential 9254 // transparent_union GCC extension. 9255 const RecordType *UT = ArgType->getAsUnionType(); 9256 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9257 return Incompatible; 9258 9259 // The field to initialize within the transparent union. 9260 RecordDecl *UD = UT->getDecl(); 9261 FieldDecl *InitField = nullptr; 9262 // It's compatible if the expression matches any of the fields. 9263 for (auto *it : UD->fields()) { 9264 if (it->getType()->isPointerType()) { 9265 // If the transparent union contains a pointer type, we allow: 9266 // 1) void pointer 9267 // 2) null pointer constant 9268 if (RHSType->isPointerType()) 9269 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9270 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9271 InitField = it; 9272 break; 9273 } 9274 9275 if (RHS.get()->isNullPointerConstant(Context, 9276 Expr::NPC_ValueDependentIsNull)) { 9277 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9278 CK_NullToPointer); 9279 InitField = it; 9280 break; 9281 } 9282 } 9283 9284 CastKind Kind; 9285 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9286 == Compatible) { 9287 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9288 InitField = it; 9289 break; 9290 } 9291 } 9292 9293 if (!InitField) 9294 return Incompatible; 9295 9296 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9297 return Compatible; 9298 } 9299 9300 Sema::AssignConvertType 9301 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9302 bool Diagnose, 9303 bool DiagnoseCFAudited, 9304 bool ConvertRHS) { 9305 // We need to be able to tell the caller whether we diagnosed a problem, if 9306 // they ask us to issue diagnostics. 9307 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9308 9309 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9310 // we can't avoid *all* modifications at the moment, so we need some somewhere 9311 // to put the updated value. 9312 ExprResult LocalRHS = CallerRHS; 9313 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9314 9315 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9316 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9317 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9318 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9319 Diag(RHS.get()->getExprLoc(), 9320 diag::warn_noderef_to_dereferenceable_pointer) 9321 << RHS.get()->getSourceRange(); 9322 } 9323 } 9324 } 9325 9326 if (getLangOpts().CPlusPlus) { 9327 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9328 // C++ 5.17p3: If the left operand is not of class type, the 9329 // expression is implicitly converted (C++ 4) to the 9330 // cv-unqualified type of the left operand. 9331 QualType RHSType = RHS.get()->getType(); 9332 if (Diagnose) { 9333 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9334 AA_Assigning); 9335 } else { 9336 ImplicitConversionSequence ICS = 9337 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9338 /*SuppressUserConversions=*/false, 9339 AllowedExplicit::None, 9340 /*InOverloadResolution=*/false, 9341 /*CStyle=*/false, 9342 /*AllowObjCWritebackConversion=*/false); 9343 if (ICS.isFailure()) 9344 return Incompatible; 9345 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9346 ICS, AA_Assigning); 9347 } 9348 if (RHS.isInvalid()) 9349 return Incompatible; 9350 Sema::AssignConvertType result = Compatible; 9351 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9352 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9353 result = IncompatibleObjCWeakRef; 9354 return result; 9355 } 9356 9357 // FIXME: Currently, we fall through and treat C++ classes like C 9358 // structures. 9359 // FIXME: We also fall through for atomics; not sure what should 9360 // happen there, though. 9361 } else if (RHS.get()->getType() == Context.OverloadTy) { 9362 // As a set of extensions to C, we support overloading on functions. These 9363 // functions need to be resolved here. 9364 DeclAccessPair DAP; 9365 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9366 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9367 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9368 else 9369 return Incompatible; 9370 } 9371 9372 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9373 // a null pointer constant. 9374 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9375 LHSType->isBlockPointerType()) && 9376 RHS.get()->isNullPointerConstant(Context, 9377 Expr::NPC_ValueDependentIsNull)) { 9378 if (Diagnose || ConvertRHS) { 9379 CastKind Kind; 9380 CXXCastPath Path; 9381 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9382 /*IgnoreBaseAccess=*/false, Diagnose); 9383 if (ConvertRHS) 9384 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9385 } 9386 return Compatible; 9387 } 9388 9389 // OpenCL queue_t type assignment. 9390 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9391 Context, Expr::NPC_ValueDependentIsNull)) { 9392 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9393 return Compatible; 9394 } 9395 9396 // This check seems unnatural, however it is necessary to ensure the proper 9397 // conversion of functions/arrays. If the conversion were done for all 9398 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9399 // expressions that suppress this implicit conversion (&, sizeof). 9400 // 9401 // Suppress this for references: C++ 8.5.3p5. 9402 if (!LHSType->isReferenceType()) { 9403 // FIXME: We potentially allocate here even if ConvertRHS is false. 9404 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9405 if (RHS.isInvalid()) 9406 return Incompatible; 9407 } 9408 CastKind Kind; 9409 Sema::AssignConvertType result = 9410 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9411 9412 // C99 6.5.16.1p2: The value of the right operand is converted to the 9413 // type of the assignment expression. 9414 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9415 // so that we can use references in built-in functions even in C. 9416 // The getNonReferenceType() call makes sure that the resulting expression 9417 // does not have reference type. 9418 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9419 QualType Ty = LHSType.getNonLValueExprType(Context); 9420 Expr *E = RHS.get(); 9421 9422 // Check for various Objective-C errors. If we are not reporting 9423 // diagnostics and just checking for errors, e.g., during overload 9424 // resolution, return Incompatible to indicate the failure. 9425 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9426 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9427 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9428 if (!Diagnose) 9429 return Incompatible; 9430 } 9431 if (getLangOpts().ObjC && 9432 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9433 E->getType(), E, Diagnose) || 9434 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9435 if (!Diagnose) 9436 return Incompatible; 9437 // Replace the expression with a corrected version and continue so we 9438 // can find further errors. 9439 RHS = E; 9440 return Compatible; 9441 } 9442 9443 if (ConvertRHS) 9444 RHS = ImpCastExprToType(E, Ty, Kind); 9445 } 9446 9447 return result; 9448 } 9449 9450 namespace { 9451 /// The original operand to an operator, prior to the application of the usual 9452 /// arithmetic conversions and converting the arguments of a builtin operator 9453 /// candidate. 9454 struct OriginalOperand { 9455 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9456 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9457 Op = MTE->getSubExpr(); 9458 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9459 Op = BTE->getSubExpr(); 9460 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9461 Orig = ICE->getSubExprAsWritten(); 9462 Conversion = ICE->getConversionFunction(); 9463 } 9464 } 9465 9466 QualType getType() const { return Orig->getType(); } 9467 9468 Expr *Orig; 9469 NamedDecl *Conversion; 9470 }; 9471 } 9472 9473 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9474 ExprResult &RHS) { 9475 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9476 9477 Diag(Loc, diag::err_typecheck_invalid_operands) 9478 << OrigLHS.getType() << OrigRHS.getType() 9479 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9480 9481 // If a user-defined conversion was applied to either of the operands prior 9482 // to applying the built-in operator rules, tell the user about it. 9483 if (OrigLHS.Conversion) { 9484 Diag(OrigLHS.Conversion->getLocation(), 9485 diag::note_typecheck_invalid_operands_converted) 9486 << 0 << LHS.get()->getType(); 9487 } 9488 if (OrigRHS.Conversion) { 9489 Diag(OrigRHS.Conversion->getLocation(), 9490 diag::note_typecheck_invalid_operands_converted) 9491 << 1 << RHS.get()->getType(); 9492 } 9493 9494 return QualType(); 9495 } 9496 9497 // Diagnose cases where a scalar was implicitly converted to a vector and 9498 // diagnose the underlying types. Otherwise, diagnose the error 9499 // as invalid vector logical operands for non-C++ cases. 9500 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9501 ExprResult &RHS) { 9502 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9503 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9504 9505 bool LHSNatVec = LHSType->isVectorType(); 9506 bool RHSNatVec = RHSType->isVectorType(); 9507 9508 if (!(LHSNatVec && RHSNatVec)) { 9509 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9510 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9511 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9512 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9513 << Vector->getSourceRange(); 9514 return QualType(); 9515 } 9516 9517 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9518 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9519 << RHS.get()->getSourceRange(); 9520 9521 return QualType(); 9522 } 9523 9524 /// Try to convert a value of non-vector type to a vector type by converting 9525 /// the type to the element type of the vector and then performing a splat. 9526 /// If the language is OpenCL, we only use conversions that promote scalar 9527 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9528 /// for float->int. 9529 /// 9530 /// OpenCL V2.0 6.2.6.p2: 9531 /// An error shall occur if any scalar operand type has greater rank 9532 /// than the type of the vector element. 9533 /// 9534 /// \param scalar - if non-null, actually perform the conversions 9535 /// \return true if the operation fails (but without diagnosing the failure) 9536 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9537 QualType scalarTy, 9538 QualType vectorEltTy, 9539 QualType vectorTy, 9540 unsigned &DiagID) { 9541 // The conversion to apply to the scalar before splatting it, 9542 // if necessary. 9543 CastKind scalarCast = CK_NoOp; 9544 9545 if (vectorEltTy->isIntegralType(S.Context)) { 9546 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9547 (scalarTy->isIntegerType() && 9548 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9549 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9550 return true; 9551 } 9552 if (!scalarTy->isIntegralType(S.Context)) 9553 return true; 9554 scalarCast = CK_IntegralCast; 9555 } else if (vectorEltTy->isRealFloatingType()) { 9556 if (scalarTy->isRealFloatingType()) { 9557 if (S.getLangOpts().OpenCL && 9558 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9559 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9560 return true; 9561 } 9562 scalarCast = CK_FloatingCast; 9563 } 9564 else if (scalarTy->isIntegralType(S.Context)) 9565 scalarCast = CK_IntegralToFloating; 9566 else 9567 return true; 9568 } else { 9569 return true; 9570 } 9571 9572 // Adjust scalar if desired. 9573 if (scalar) { 9574 if (scalarCast != CK_NoOp) 9575 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9576 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9577 } 9578 return false; 9579 } 9580 9581 /// Convert vector E to a vector with the same number of elements but different 9582 /// element type. 9583 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9584 const auto *VecTy = E->getType()->getAs<VectorType>(); 9585 assert(VecTy && "Expression E must be a vector"); 9586 QualType NewVecTy = S.Context.getVectorType(ElementType, 9587 VecTy->getNumElements(), 9588 VecTy->getVectorKind()); 9589 9590 // Look through the implicit cast. Return the subexpression if its type is 9591 // NewVecTy. 9592 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9593 if (ICE->getSubExpr()->getType() == NewVecTy) 9594 return ICE->getSubExpr(); 9595 9596 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9597 return S.ImpCastExprToType(E, NewVecTy, Cast); 9598 } 9599 9600 /// Test if a (constant) integer Int can be casted to another integer type 9601 /// IntTy without losing precision. 9602 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9603 QualType OtherIntTy) { 9604 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9605 9606 // Reject cases where the value of the Int is unknown as that would 9607 // possibly cause truncation, but accept cases where the scalar can be 9608 // demoted without loss of precision. 9609 Expr::EvalResult EVResult; 9610 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9611 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9612 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9613 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9614 9615 if (CstInt) { 9616 // If the scalar is constant and is of a higher order and has more active 9617 // bits that the vector element type, reject it. 9618 llvm::APSInt Result = EVResult.Val.getInt(); 9619 unsigned NumBits = IntSigned 9620 ? (Result.isNegative() ? Result.getMinSignedBits() 9621 : Result.getActiveBits()) 9622 : Result.getActiveBits(); 9623 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9624 return true; 9625 9626 // If the signedness of the scalar type and the vector element type 9627 // differs and the number of bits is greater than that of the vector 9628 // element reject it. 9629 return (IntSigned != OtherIntSigned && 9630 NumBits > S.Context.getIntWidth(OtherIntTy)); 9631 } 9632 9633 // Reject cases where the value of the scalar is not constant and it's 9634 // order is greater than that of the vector element type. 9635 return (Order < 0); 9636 } 9637 9638 /// Test if a (constant) integer Int can be casted to floating point type 9639 /// FloatTy without losing precision. 9640 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9641 QualType FloatTy) { 9642 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9643 9644 // Determine if the integer constant can be expressed as a floating point 9645 // number of the appropriate type. 9646 Expr::EvalResult EVResult; 9647 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9648 9649 uint64_t Bits = 0; 9650 if (CstInt) { 9651 // Reject constants that would be truncated if they were converted to 9652 // the floating point type. Test by simple to/from conversion. 9653 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9654 // could be avoided if there was a convertFromAPInt method 9655 // which could signal back if implicit truncation occurred. 9656 llvm::APSInt Result = EVResult.Val.getInt(); 9657 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9658 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9659 llvm::APFloat::rmTowardZero); 9660 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9661 !IntTy->hasSignedIntegerRepresentation()); 9662 bool Ignored = false; 9663 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9664 &Ignored); 9665 if (Result != ConvertBack) 9666 return true; 9667 } else { 9668 // Reject types that cannot be fully encoded into the mantissa of 9669 // the float. 9670 Bits = S.Context.getTypeSize(IntTy); 9671 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9672 S.Context.getFloatTypeSemantics(FloatTy)); 9673 if (Bits > FloatPrec) 9674 return true; 9675 } 9676 9677 return false; 9678 } 9679 9680 /// Attempt to convert and splat Scalar into a vector whose types matches 9681 /// Vector following GCC conversion rules. The rule is that implicit 9682 /// conversion can occur when Scalar can be casted to match Vector's element 9683 /// type without causing truncation of Scalar. 9684 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9685 ExprResult *Vector) { 9686 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9687 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9688 const VectorType *VT = VectorTy->getAs<VectorType>(); 9689 9690 assert(!isa<ExtVectorType>(VT) && 9691 "ExtVectorTypes should not be handled here!"); 9692 9693 QualType VectorEltTy = VT->getElementType(); 9694 9695 // Reject cases where the vector element type or the scalar element type are 9696 // not integral or floating point types. 9697 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9698 return true; 9699 9700 // The conversion to apply to the scalar before splatting it, 9701 // if necessary. 9702 CastKind ScalarCast = CK_NoOp; 9703 9704 // Accept cases where the vector elements are integers and the scalar is 9705 // an integer. 9706 // FIXME: Notionally if the scalar was a floating point value with a precise 9707 // integral representation, we could cast it to an appropriate integer 9708 // type and then perform the rest of the checks here. GCC will perform 9709 // this conversion in some cases as determined by the input language. 9710 // We should accept it on a language independent basis. 9711 if (VectorEltTy->isIntegralType(S.Context) && 9712 ScalarTy->isIntegralType(S.Context) && 9713 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9714 9715 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9716 return true; 9717 9718 ScalarCast = CK_IntegralCast; 9719 } else if (VectorEltTy->isIntegralType(S.Context) && 9720 ScalarTy->isRealFloatingType()) { 9721 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9722 ScalarCast = CK_FloatingToIntegral; 9723 else 9724 return true; 9725 } else if (VectorEltTy->isRealFloatingType()) { 9726 if (ScalarTy->isRealFloatingType()) { 9727 9728 // Reject cases where the scalar type is not a constant and has a higher 9729 // Order than the vector element type. 9730 llvm::APFloat Result(0.0); 9731 9732 // Determine whether this is a constant scalar. In the event that the 9733 // value is dependent (and thus cannot be evaluated by the constant 9734 // evaluator), skip the evaluation. This will then diagnose once the 9735 // expression is instantiated. 9736 bool CstScalar = Scalar->get()->isValueDependent() || 9737 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9738 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9739 if (!CstScalar && Order < 0) 9740 return true; 9741 9742 // If the scalar cannot be safely casted to the vector element type, 9743 // reject it. 9744 if (CstScalar) { 9745 bool Truncated = false; 9746 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9747 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9748 if (Truncated) 9749 return true; 9750 } 9751 9752 ScalarCast = CK_FloatingCast; 9753 } else if (ScalarTy->isIntegralType(S.Context)) { 9754 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9755 return true; 9756 9757 ScalarCast = CK_IntegralToFloating; 9758 } else 9759 return true; 9760 } else if (ScalarTy->isEnumeralType()) 9761 return true; 9762 9763 // Adjust scalar if desired. 9764 if (Scalar) { 9765 if (ScalarCast != CK_NoOp) 9766 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9767 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9768 } 9769 return false; 9770 } 9771 9772 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9773 SourceLocation Loc, bool IsCompAssign, 9774 bool AllowBothBool, 9775 bool AllowBoolConversions) { 9776 if (!IsCompAssign) { 9777 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9778 if (LHS.isInvalid()) 9779 return QualType(); 9780 } 9781 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9782 if (RHS.isInvalid()) 9783 return QualType(); 9784 9785 // For conversion purposes, we ignore any qualifiers. 9786 // For example, "const float" and "float" are equivalent. 9787 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9788 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9789 9790 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9791 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9792 assert(LHSVecType || RHSVecType); 9793 9794 // AltiVec-style "vector bool op vector bool" combinations are allowed 9795 // for some operators but not others. 9796 if (!AllowBothBool && 9797 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9798 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9799 return InvalidOperands(Loc, LHS, RHS); 9800 9801 // If the vector types are identical, return. 9802 if (Context.hasSameType(LHSType, RHSType)) 9803 return LHSType; 9804 9805 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9806 if (LHSVecType && RHSVecType && 9807 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9808 if (isa<ExtVectorType>(LHSVecType)) { 9809 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9810 return LHSType; 9811 } 9812 9813 if (!IsCompAssign) 9814 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9815 return RHSType; 9816 } 9817 9818 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9819 // can be mixed, with the result being the non-bool type. The non-bool 9820 // operand must have integer element type. 9821 if (AllowBoolConversions && LHSVecType && RHSVecType && 9822 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9823 (Context.getTypeSize(LHSVecType->getElementType()) == 9824 Context.getTypeSize(RHSVecType->getElementType()))) { 9825 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9826 LHSVecType->getElementType()->isIntegerType() && 9827 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9828 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9829 return LHSType; 9830 } 9831 if (!IsCompAssign && 9832 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9833 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9834 RHSVecType->getElementType()->isIntegerType()) { 9835 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9836 return RHSType; 9837 } 9838 } 9839 9840 // If there's a vector type and a scalar, try to convert the scalar to 9841 // the vector element type and splat. 9842 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9843 if (!RHSVecType) { 9844 if (isa<ExtVectorType>(LHSVecType)) { 9845 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9846 LHSVecType->getElementType(), LHSType, 9847 DiagID)) 9848 return LHSType; 9849 } else { 9850 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9851 return LHSType; 9852 } 9853 } 9854 if (!LHSVecType) { 9855 if (isa<ExtVectorType>(RHSVecType)) { 9856 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9857 LHSType, RHSVecType->getElementType(), 9858 RHSType, DiagID)) 9859 return RHSType; 9860 } else { 9861 if (LHS.get()->getValueKind() == VK_LValue || 9862 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9863 return RHSType; 9864 } 9865 } 9866 9867 // FIXME: The code below also handles conversion between vectors and 9868 // non-scalars, we should break this down into fine grained specific checks 9869 // and emit proper diagnostics. 9870 QualType VecType = LHSVecType ? LHSType : RHSType; 9871 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9872 QualType OtherType = LHSVecType ? RHSType : LHSType; 9873 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9874 if (isLaxVectorConversion(OtherType, VecType)) { 9875 // If we're allowing lax vector conversions, only the total (data) size 9876 // needs to be the same. For non compound assignment, if one of the types is 9877 // scalar, the result is always the vector type. 9878 if (!IsCompAssign) { 9879 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9880 return VecType; 9881 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9882 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9883 // type. Note that this is already done by non-compound assignments in 9884 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9885 // <1 x T> -> T. The result is also a vector type. 9886 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9887 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9888 ExprResult *RHSExpr = &RHS; 9889 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9890 return VecType; 9891 } 9892 } 9893 9894 // Okay, the expression is invalid. 9895 9896 // If there's a non-vector, non-real operand, diagnose that. 9897 if ((!RHSVecType && !RHSType->isRealType()) || 9898 (!LHSVecType && !LHSType->isRealType())) { 9899 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9900 << LHSType << RHSType 9901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9902 return QualType(); 9903 } 9904 9905 // OpenCL V1.1 6.2.6.p1: 9906 // If the operands are of more than one vector type, then an error shall 9907 // occur. Implicit conversions between vector types are not permitted, per 9908 // section 6.2.1. 9909 if (getLangOpts().OpenCL && 9910 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9911 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9912 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9913 << RHSType; 9914 return QualType(); 9915 } 9916 9917 9918 // If there is a vector type that is not a ExtVector and a scalar, we reach 9919 // this point if scalar could not be converted to the vector's element type 9920 // without truncation. 9921 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9922 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9923 QualType Scalar = LHSVecType ? RHSType : LHSType; 9924 QualType Vector = LHSVecType ? LHSType : RHSType; 9925 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9926 Diag(Loc, 9927 diag::err_typecheck_vector_not_convertable_implict_truncation) 9928 << ScalarOrVector << Scalar << Vector; 9929 9930 return QualType(); 9931 } 9932 9933 // Otherwise, use the generic diagnostic. 9934 Diag(Loc, DiagID) 9935 << LHSType << RHSType 9936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9937 return QualType(); 9938 } 9939 9940 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9941 // expression. These are mainly cases where the null pointer is used as an 9942 // integer instead of a pointer. 9943 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9944 SourceLocation Loc, bool IsCompare) { 9945 // The canonical way to check for a GNU null is with isNullPointerConstant, 9946 // but we use a bit of a hack here for speed; this is a relatively 9947 // hot path, and isNullPointerConstant is slow. 9948 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9949 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9950 9951 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9952 9953 // Avoid analyzing cases where the result will either be invalid (and 9954 // diagnosed as such) or entirely valid and not something to warn about. 9955 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9956 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9957 return; 9958 9959 // Comparison operations would not make sense with a null pointer no matter 9960 // what the other expression is. 9961 if (!IsCompare) { 9962 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9963 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9964 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9965 return; 9966 } 9967 9968 // The rest of the operations only make sense with a null pointer 9969 // if the other expression is a pointer. 9970 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9971 NonNullType->canDecayToPointerType()) 9972 return; 9973 9974 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9975 << LHSNull /* LHS is NULL */ << NonNullType 9976 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9977 } 9978 9979 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9980 SourceLocation Loc) { 9981 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9982 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9983 if (!LUE || !RUE) 9984 return; 9985 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9986 RUE->getKind() != UETT_SizeOf) 9987 return; 9988 9989 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9990 QualType LHSTy = LHSArg->getType(); 9991 QualType RHSTy; 9992 9993 if (RUE->isArgumentType()) 9994 RHSTy = RUE->getArgumentType(); 9995 else 9996 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9997 9998 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9999 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10000 return; 10001 10002 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10003 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10004 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10005 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10006 << LHSArgDecl; 10007 } 10008 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10009 QualType ArrayElemTy = ArrayTy->getElementType(); 10010 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10011 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10012 ArrayElemTy->isCharType() || 10013 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10014 return; 10015 S.Diag(Loc, diag::warn_division_sizeof_array) 10016 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10017 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10018 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10019 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10020 << LHSArgDecl; 10021 } 10022 10023 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10024 } 10025 } 10026 10027 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10028 ExprResult &RHS, 10029 SourceLocation Loc, bool IsDiv) { 10030 // Check for division/remainder by zero. 10031 Expr::EvalResult RHSValue; 10032 if (!RHS.get()->isValueDependent() && 10033 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10034 RHSValue.Val.getInt() == 0) 10035 S.DiagRuntimeBehavior(Loc, RHS.get(), 10036 S.PDiag(diag::warn_remainder_division_by_zero) 10037 << IsDiv << RHS.get()->getSourceRange()); 10038 } 10039 10040 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10041 SourceLocation Loc, 10042 bool IsCompAssign, bool IsDiv) { 10043 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10044 10045 if (LHS.get()->getType()->isVectorType() || 10046 RHS.get()->getType()->isVectorType()) 10047 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10048 /*AllowBothBool*/getLangOpts().AltiVec, 10049 /*AllowBoolConversions*/false); 10050 10051 QualType compType = UsualArithmeticConversions( 10052 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10053 if (LHS.isInvalid() || RHS.isInvalid()) 10054 return QualType(); 10055 10056 10057 if (compType.isNull() || !compType->isArithmeticType()) 10058 return InvalidOperands(Loc, LHS, RHS); 10059 if (IsDiv) { 10060 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10061 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10062 } 10063 return compType; 10064 } 10065 10066 QualType Sema::CheckRemainderOperands( 10067 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10068 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10069 10070 if (LHS.get()->getType()->isVectorType() || 10071 RHS.get()->getType()->isVectorType()) { 10072 if (LHS.get()->getType()->hasIntegerRepresentation() && 10073 RHS.get()->getType()->hasIntegerRepresentation()) 10074 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10075 /*AllowBothBool*/getLangOpts().AltiVec, 10076 /*AllowBoolConversions*/false); 10077 return InvalidOperands(Loc, LHS, RHS); 10078 } 10079 10080 QualType compType = UsualArithmeticConversions( 10081 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10082 if (LHS.isInvalid() || RHS.isInvalid()) 10083 return QualType(); 10084 10085 if (compType.isNull() || !compType->isIntegerType()) 10086 return InvalidOperands(Loc, LHS, RHS); 10087 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10088 return compType; 10089 } 10090 10091 /// Diagnose invalid arithmetic on two void pointers. 10092 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10093 Expr *LHSExpr, Expr *RHSExpr) { 10094 S.Diag(Loc, S.getLangOpts().CPlusPlus 10095 ? diag::err_typecheck_pointer_arith_void_type 10096 : diag::ext_gnu_void_ptr) 10097 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10098 << RHSExpr->getSourceRange(); 10099 } 10100 10101 /// Diagnose invalid arithmetic on a void pointer. 10102 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10103 Expr *Pointer) { 10104 S.Diag(Loc, S.getLangOpts().CPlusPlus 10105 ? diag::err_typecheck_pointer_arith_void_type 10106 : diag::ext_gnu_void_ptr) 10107 << 0 /* one pointer */ << Pointer->getSourceRange(); 10108 } 10109 10110 /// Diagnose invalid arithmetic on a null pointer. 10111 /// 10112 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10113 /// idiom, which we recognize as a GNU extension. 10114 /// 10115 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10116 Expr *Pointer, bool IsGNUIdiom) { 10117 if (IsGNUIdiom) 10118 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10119 << Pointer->getSourceRange(); 10120 else 10121 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10122 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10123 } 10124 10125 /// Diagnose invalid arithmetic on two function pointers. 10126 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10127 Expr *LHS, Expr *RHS) { 10128 assert(LHS->getType()->isAnyPointerType()); 10129 assert(RHS->getType()->isAnyPointerType()); 10130 S.Diag(Loc, S.getLangOpts().CPlusPlus 10131 ? diag::err_typecheck_pointer_arith_function_type 10132 : diag::ext_gnu_ptr_func_arith) 10133 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10134 // We only show the second type if it differs from the first. 10135 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10136 RHS->getType()) 10137 << RHS->getType()->getPointeeType() 10138 << LHS->getSourceRange() << RHS->getSourceRange(); 10139 } 10140 10141 /// Diagnose invalid arithmetic on a function pointer. 10142 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10143 Expr *Pointer) { 10144 assert(Pointer->getType()->isAnyPointerType()); 10145 S.Diag(Loc, S.getLangOpts().CPlusPlus 10146 ? diag::err_typecheck_pointer_arith_function_type 10147 : diag::ext_gnu_ptr_func_arith) 10148 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10149 << 0 /* one pointer, so only one type */ 10150 << Pointer->getSourceRange(); 10151 } 10152 10153 /// Emit error if Operand is incomplete pointer type 10154 /// 10155 /// \returns True if pointer has incomplete type 10156 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10157 Expr *Operand) { 10158 QualType ResType = Operand->getType(); 10159 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10160 ResType = ResAtomicType->getValueType(); 10161 10162 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10163 QualType PointeeTy = ResType->getPointeeType(); 10164 return S.RequireCompleteSizedType( 10165 Loc, PointeeTy, 10166 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10167 Operand->getSourceRange()); 10168 } 10169 10170 /// Check the validity of an arithmetic pointer operand. 10171 /// 10172 /// If the operand has pointer type, this code will check for pointer types 10173 /// which are invalid in arithmetic operations. These will be diagnosed 10174 /// appropriately, including whether or not the use is supported as an 10175 /// extension. 10176 /// 10177 /// \returns True when the operand is valid to use (even if as an extension). 10178 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10179 Expr *Operand) { 10180 QualType ResType = Operand->getType(); 10181 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10182 ResType = ResAtomicType->getValueType(); 10183 10184 if (!ResType->isAnyPointerType()) return true; 10185 10186 QualType PointeeTy = ResType->getPointeeType(); 10187 if (PointeeTy->isVoidType()) { 10188 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10189 return !S.getLangOpts().CPlusPlus; 10190 } 10191 if (PointeeTy->isFunctionType()) { 10192 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10193 return !S.getLangOpts().CPlusPlus; 10194 } 10195 10196 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10197 10198 return true; 10199 } 10200 10201 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10202 /// operands. 10203 /// 10204 /// This routine will diagnose any invalid arithmetic on pointer operands much 10205 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10206 /// for emitting a single diagnostic even for operations where both LHS and RHS 10207 /// are (potentially problematic) pointers. 10208 /// 10209 /// \returns True when the operand is valid to use (even if as an extension). 10210 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10211 Expr *LHSExpr, Expr *RHSExpr) { 10212 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10213 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10214 if (!isLHSPointer && !isRHSPointer) return true; 10215 10216 QualType LHSPointeeTy, RHSPointeeTy; 10217 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10218 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10219 10220 // if both are pointers check if operation is valid wrt address spaces 10221 if (isLHSPointer && isRHSPointer) { 10222 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10223 S.Diag(Loc, 10224 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10225 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10226 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10227 return false; 10228 } 10229 } 10230 10231 // Check for arithmetic on pointers to incomplete types. 10232 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10233 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10234 if (isLHSVoidPtr || isRHSVoidPtr) { 10235 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10236 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10237 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10238 10239 return !S.getLangOpts().CPlusPlus; 10240 } 10241 10242 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10243 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10244 if (isLHSFuncPtr || isRHSFuncPtr) { 10245 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10246 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10247 RHSExpr); 10248 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10249 10250 return !S.getLangOpts().CPlusPlus; 10251 } 10252 10253 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10254 return false; 10255 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10256 return false; 10257 10258 return true; 10259 } 10260 10261 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10262 /// literal. 10263 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10264 Expr *LHSExpr, Expr *RHSExpr) { 10265 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10266 Expr* IndexExpr = RHSExpr; 10267 if (!StrExpr) { 10268 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10269 IndexExpr = LHSExpr; 10270 } 10271 10272 bool IsStringPlusInt = StrExpr && 10273 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10274 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10275 return; 10276 10277 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10278 Self.Diag(OpLoc, diag::warn_string_plus_int) 10279 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10280 10281 // Only print a fixit for "str" + int, not for int + "str". 10282 if (IndexExpr == RHSExpr) { 10283 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10284 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10285 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10286 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10287 << FixItHint::CreateInsertion(EndLoc, "]"); 10288 } else 10289 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10290 } 10291 10292 /// Emit a warning when adding a char literal to a string. 10293 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10294 Expr *LHSExpr, Expr *RHSExpr) { 10295 const Expr *StringRefExpr = LHSExpr; 10296 const CharacterLiteral *CharExpr = 10297 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10298 10299 if (!CharExpr) { 10300 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10301 StringRefExpr = RHSExpr; 10302 } 10303 10304 if (!CharExpr || !StringRefExpr) 10305 return; 10306 10307 const QualType StringType = StringRefExpr->getType(); 10308 10309 // Return if not a PointerType. 10310 if (!StringType->isAnyPointerType()) 10311 return; 10312 10313 // Return if not a CharacterType. 10314 if (!StringType->getPointeeType()->isAnyCharacterType()) 10315 return; 10316 10317 ASTContext &Ctx = Self.getASTContext(); 10318 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10319 10320 const QualType CharType = CharExpr->getType(); 10321 if (!CharType->isAnyCharacterType() && 10322 CharType->isIntegerType() && 10323 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10324 Self.Diag(OpLoc, diag::warn_string_plus_char) 10325 << DiagRange << Ctx.CharTy; 10326 } else { 10327 Self.Diag(OpLoc, diag::warn_string_plus_char) 10328 << DiagRange << CharExpr->getType(); 10329 } 10330 10331 // Only print a fixit for str + char, not for char + str. 10332 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10333 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10334 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10335 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10336 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10337 << FixItHint::CreateInsertion(EndLoc, "]"); 10338 } else { 10339 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10340 } 10341 } 10342 10343 /// Emit error when two pointers are incompatible. 10344 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10345 Expr *LHSExpr, Expr *RHSExpr) { 10346 assert(LHSExpr->getType()->isAnyPointerType()); 10347 assert(RHSExpr->getType()->isAnyPointerType()); 10348 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10349 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10350 << RHSExpr->getSourceRange(); 10351 } 10352 10353 // C99 6.5.6 10354 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10355 SourceLocation Loc, BinaryOperatorKind Opc, 10356 QualType* CompLHSTy) { 10357 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10358 10359 if (LHS.get()->getType()->isVectorType() || 10360 RHS.get()->getType()->isVectorType()) { 10361 QualType compType = CheckVectorOperands( 10362 LHS, RHS, Loc, CompLHSTy, 10363 /*AllowBothBool*/getLangOpts().AltiVec, 10364 /*AllowBoolConversions*/getLangOpts().ZVector); 10365 if (CompLHSTy) *CompLHSTy = compType; 10366 return compType; 10367 } 10368 10369 if (LHS.get()->getType()->isConstantMatrixType() || 10370 RHS.get()->getType()->isConstantMatrixType()) { 10371 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10372 } 10373 10374 QualType compType = UsualArithmeticConversions( 10375 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10376 if (LHS.isInvalid() || RHS.isInvalid()) 10377 return QualType(); 10378 10379 // Diagnose "string literal" '+' int and string '+' "char literal". 10380 if (Opc == BO_Add) { 10381 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10382 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10383 } 10384 10385 // handle the common case first (both operands are arithmetic). 10386 if (!compType.isNull() && compType->isArithmeticType()) { 10387 if (CompLHSTy) *CompLHSTy = compType; 10388 return compType; 10389 } 10390 10391 // Type-checking. Ultimately the pointer's going to be in PExp; 10392 // note that we bias towards the LHS being the pointer. 10393 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10394 10395 bool isObjCPointer; 10396 if (PExp->getType()->isPointerType()) { 10397 isObjCPointer = false; 10398 } else if (PExp->getType()->isObjCObjectPointerType()) { 10399 isObjCPointer = true; 10400 } else { 10401 std::swap(PExp, IExp); 10402 if (PExp->getType()->isPointerType()) { 10403 isObjCPointer = false; 10404 } else if (PExp->getType()->isObjCObjectPointerType()) { 10405 isObjCPointer = true; 10406 } else { 10407 return InvalidOperands(Loc, LHS, RHS); 10408 } 10409 } 10410 assert(PExp->getType()->isAnyPointerType()); 10411 10412 if (!IExp->getType()->isIntegerType()) 10413 return InvalidOperands(Loc, LHS, RHS); 10414 10415 // Adding to a null pointer results in undefined behavior. 10416 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10417 Context, Expr::NPC_ValueDependentIsNotNull)) { 10418 // In C++ adding zero to a null pointer is defined. 10419 Expr::EvalResult KnownVal; 10420 if (!getLangOpts().CPlusPlus || 10421 (!IExp->isValueDependent() && 10422 (!IExp->EvaluateAsInt(KnownVal, Context) || 10423 KnownVal.Val.getInt() != 0))) { 10424 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10425 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10426 Context, BO_Add, PExp, IExp); 10427 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10428 } 10429 } 10430 10431 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10432 return QualType(); 10433 10434 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10435 return QualType(); 10436 10437 // Check array bounds for pointer arithemtic 10438 CheckArrayAccess(PExp, IExp); 10439 10440 if (CompLHSTy) { 10441 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10442 if (LHSTy.isNull()) { 10443 LHSTy = LHS.get()->getType(); 10444 if (LHSTy->isPromotableIntegerType()) 10445 LHSTy = Context.getPromotedIntegerType(LHSTy); 10446 } 10447 *CompLHSTy = LHSTy; 10448 } 10449 10450 return PExp->getType(); 10451 } 10452 10453 // C99 6.5.6 10454 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10455 SourceLocation Loc, 10456 QualType* CompLHSTy) { 10457 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10458 10459 if (LHS.get()->getType()->isVectorType() || 10460 RHS.get()->getType()->isVectorType()) { 10461 QualType compType = CheckVectorOperands( 10462 LHS, RHS, Loc, CompLHSTy, 10463 /*AllowBothBool*/getLangOpts().AltiVec, 10464 /*AllowBoolConversions*/getLangOpts().ZVector); 10465 if (CompLHSTy) *CompLHSTy = compType; 10466 return compType; 10467 } 10468 10469 if (LHS.get()->getType()->isConstantMatrixType() || 10470 RHS.get()->getType()->isConstantMatrixType()) { 10471 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10472 } 10473 10474 QualType compType = UsualArithmeticConversions( 10475 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10476 if (LHS.isInvalid() || RHS.isInvalid()) 10477 return QualType(); 10478 10479 // Enforce type constraints: C99 6.5.6p3. 10480 10481 // Handle the common case first (both operands are arithmetic). 10482 if (!compType.isNull() && compType->isArithmeticType()) { 10483 if (CompLHSTy) *CompLHSTy = compType; 10484 return compType; 10485 } 10486 10487 // Either ptr - int or ptr - ptr. 10488 if (LHS.get()->getType()->isAnyPointerType()) { 10489 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10490 10491 // Diagnose bad cases where we step over interface counts. 10492 if (LHS.get()->getType()->isObjCObjectPointerType() && 10493 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10494 return QualType(); 10495 10496 // The result type of a pointer-int computation is the pointer type. 10497 if (RHS.get()->getType()->isIntegerType()) { 10498 // Subtracting from a null pointer should produce a warning. 10499 // The last argument to the diagnose call says this doesn't match the 10500 // GNU int-to-pointer idiom. 10501 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10502 Expr::NPC_ValueDependentIsNotNull)) { 10503 // In C++ adding zero to a null pointer is defined. 10504 Expr::EvalResult KnownVal; 10505 if (!getLangOpts().CPlusPlus || 10506 (!RHS.get()->isValueDependent() && 10507 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10508 KnownVal.Val.getInt() != 0))) { 10509 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10510 } 10511 } 10512 10513 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10514 return QualType(); 10515 10516 // Check array bounds for pointer arithemtic 10517 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10518 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10519 10520 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10521 return LHS.get()->getType(); 10522 } 10523 10524 // Handle pointer-pointer subtractions. 10525 if (const PointerType *RHSPTy 10526 = RHS.get()->getType()->getAs<PointerType>()) { 10527 QualType rpointee = RHSPTy->getPointeeType(); 10528 10529 if (getLangOpts().CPlusPlus) { 10530 // Pointee types must be the same: C++ [expr.add] 10531 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10532 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10533 } 10534 } else { 10535 // Pointee types must be compatible C99 6.5.6p3 10536 if (!Context.typesAreCompatible( 10537 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10538 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10539 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10540 return QualType(); 10541 } 10542 } 10543 10544 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10545 LHS.get(), RHS.get())) 10546 return QualType(); 10547 10548 // FIXME: Add warnings for nullptr - ptr. 10549 10550 // The pointee type may have zero size. As an extension, a structure or 10551 // union may have zero size or an array may have zero length. In this 10552 // case subtraction does not make sense. 10553 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10554 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10555 if (ElementSize.isZero()) { 10556 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10557 << rpointee.getUnqualifiedType() 10558 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10559 } 10560 } 10561 10562 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10563 return Context.getPointerDiffType(); 10564 } 10565 } 10566 10567 return InvalidOperands(Loc, LHS, RHS); 10568 } 10569 10570 static bool isScopedEnumerationType(QualType T) { 10571 if (const EnumType *ET = T->getAs<EnumType>()) 10572 return ET->getDecl()->isScoped(); 10573 return false; 10574 } 10575 10576 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10577 SourceLocation Loc, BinaryOperatorKind Opc, 10578 QualType LHSType) { 10579 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10580 // so skip remaining warnings as we don't want to modify values within Sema. 10581 if (S.getLangOpts().OpenCL) 10582 return; 10583 10584 // Check right/shifter operand 10585 Expr::EvalResult RHSResult; 10586 if (RHS.get()->isValueDependent() || 10587 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10588 return; 10589 llvm::APSInt Right = RHSResult.Val.getInt(); 10590 10591 if (Right.isNegative()) { 10592 S.DiagRuntimeBehavior(Loc, RHS.get(), 10593 S.PDiag(diag::warn_shift_negative) 10594 << RHS.get()->getSourceRange()); 10595 return; 10596 } 10597 10598 QualType LHSExprType = LHS.get()->getType(); 10599 uint64_t LeftSize = LHSExprType->isExtIntType() 10600 ? S.Context.getIntWidth(LHSExprType) 10601 : S.Context.getTypeSize(LHSExprType); 10602 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10603 if (Right.uge(LeftBits)) { 10604 S.DiagRuntimeBehavior(Loc, RHS.get(), 10605 S.PDiag(diag::warn_shift_gt_typewidth) 10606 << RHS.get()->getSourceRange()); 10607 return; 10608 } 10609 10610 if (Opc != BO_Shl) 10611 return; 10612 10613 // When left shifting an ICE which is signed, we can check for overflow which 10614 // according to C++ standards prior to C++2a has undefined behavior 10615 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10616 // more than the maximum value representable in the result type, so never 10617 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10618 // expression is still probably a bug.) 10619 Expr::EvalResult LHSResult; 10620 if (LHS.get()->isValueDependent() || 10621 LHSType->hasUnsignedIntegerRepresentation() || 10622 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10623 return; 10624 llvm::APSInt Left = LHSResult.Val.getInt(); 10625 10626 // If LHS does not have a signed type and non-negative value 10627 // then, the behavior is undefined before C++2a. Warn about it. 10628 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10629 !S.getLangOpts().CPlusPlus20) { 10630 S.DiagRuntimeBehavior(Loc, LHS.get(), 10631 S.PDiag(diag::warn_shift_lhs_negative) 10632 << LHS.get()->getSourceRange()); 10633 return; 10634 } 10635 10636 llvm::APInt ResultBits = 10637 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10638 if (LeftBits.uge(ResultBits)) 10639 return; 10640 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10641 Result = Result.shl(Right); 10642 10643 // Print the bit representation of the signed integer as an unsigned 10644 // hexadecimal number. 10645 SmallString<40> HexResult; 10646 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10647 10648 // If we are only missing a sign bit, this is less likely to result in actual 10649 // bugs -- if the result is cast back to an unsigned type, it will have the 10650 // expected value. Thus we place this behind a different warning that can be 10651 // turned off separately if needed. 10652 if (LeftBits == ResultBits - 1) { 10653 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10654 << HexResult << LHSType 10655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10656 return; 10657 } 10658 10659 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10660 << HexResult.str() << Result.getMinSignedBits() << LHSType 10661 << Left.getBitWidth() << LHS.get()->getSourceRange() 10662 << RHS.get()->getSourceRange(); 10663 } 10664 10665 /// Return the resulting type when a vector is shifted 10666 /// by a scalar or vector shift amount. 10667 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10668 SourceLocation Loc, bool IsCompAssign) { 10669 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10670 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10671 !LHS.get()->getType()->isVectorType()) { 10672 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10673 << RHS.get()->getType() << LHS.get()->getType() 10674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10675 return QualType(); 10676 } 10677 10678 if (!IsCompAssign) { 10679 LHS = S.UsualUnaryConversions(LHS.get()); 10680 if (LHS.isInvalid()) return QualType(); 10681 } 10682 10683 RHS = S.UsualUnaryConversions(RHS.get()); 10684 if (RHS.isInvalid()) return QualType(); 10685 10686 QualType LHSType = LHS.get()->getType(); 10687 // Note that LHS might be a scalar because the routine calls not only in 10688 // OpenCL case. 10689 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10690 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10691 10692 // Note that RHS might not be a vector. 10693 QualType RHSType = RHS.get()->getType(); 10694 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10695 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10696 10697 // The operands need to be integers. 10698 if (!LHSEleType->isIntegerType()) { 10699 S.Diag(Loc, diag::err_typecheck_expect_int) 10700 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10701 return QualType(); 10702 } 10703 10704 if (!RHSEleType->isIntegerType()) { 10705 S.Diag(Loc, diag::err_typecheck_expect_int) 10706 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10707 return QualType(); 10708 } 10709 10710 if (!LHSVecTy) { 10711 assert(RHSVecTy); 10712 if (IsCompAssign) 10713 return RHSType; 10714 if (LHSEleType != RHSEleType) { 10715 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10716 LHSEleType = RHSEleType; 10717 } 10718 QualType VecTy = 10719 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10720 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10721 LHSType = VecTy; 10722 } else if (RHSVecTy) { 10723 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10724 // are applied component-wise. So if RHS is a vector, then ensure 10725 // that the number of elements is the same as LHS... 10726 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10727 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10728 << LHS.get()->getType() << RHS.get()->getType() 10729 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10730 return QualType(); 10731 } 10732 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10733 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10734 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10735 if (LHSBT != RHSBT && 10736 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10737 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10738 << LHS.get()->getType() << RHS.get()->getType() 10739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10740 } 10741 } 10742 } else { 10743 // ...else expand RHS to match the number of elements in LHS. 10744 QualType VecTy = 10745 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10746 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10747 } 10748 10749 return LHSType; 10750 } 10751 10752 // C99 6.5.7 10753 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10754 SourceLocation Loc, BinaryOperatorKind Opc, 10755 bool IsCompAssign) { 10756 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10757 10758 // Vector shifts promote their scalar inputs to vector type. 10759 if (LHS.get()->getType()->isVectorType() || 10760 RHS.get()->getType()->isVectorType()) { 10761 if (LangOpts.ZVector) { 10762 // The shift operators for the z vector extensions work basically 10763 // like general shifts, except that neither the LHS nor the RHS is 10764 // allowed to be a "vector bool". 10765 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10766 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10767 return InvalidOperands(Loc, LHS, RHS); 10768 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10769 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10770 return InvalidOperands(Loc, LHS, RHS); 10771 } 10772 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10773 } 10774 10775 // Shifts don't perform usual arithmetic conversions, they just do integer 10776 // promotions on each operand. C99 6.5.7p3 10777 10778 // For the LHS, do usual unary conversions, but then reset them away 10779 // if this is a compound assignment. 10780 ExprResult OldLHS = LHS; 10781 LHS = UsualUnaryConversions(LHS.get()); 10782 if (LHS.isInvalid()) 10783 return QualType(); 10784 QualType LHSType = LHS.get()->getType(); 10785 if (IsCompAssign) LHS = OldLHS; 10786 10787 // The RHS is simpler. 10788 RHS = UsualUnaryConversions(RHS.get()); 10789 if (RHS.isInvalid()) 10790 return QualType(); 10791 QualType RHSType = RHS.get()->getType(); 10792 10793 // C99 6.5.7p2: Each of the operands shall have integer type. 10794 if (!LHSType->hasIntegerRepresentation() || 10795 !RHSType->hasIntegerRepresentation()) 10796 return InvalidOperands(Loc, LHS, RHS); 10797 10798 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10799 // hasIntegerRepresentation() above instead of this. 10800 if (isScopedEnumerationType(LHSType) || 10801 isScopedEnumerationType(RHSType)) { 10802 return InvalidOperands(Loc, LHS, RHS); 10803 } 10804 // Sanity-check shift operands 10805 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10806 10807 // "The type of the result is that of the promoted left operand." 10808 return LHSType; 10809 } 10810 10811 /// Diagnose bad pointer comparisons. 10812 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10813 ExprResult &LHS, ExprResult &RHS, 10814 bool IsError) { 10815 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10816 : diag::ext_typecheck_comparison_of_distinct_pointers) 10817 << LHS.get()->getType() << RHS.get()->getType() 10818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10819 } 10820 10821 /// Returns false if the pointers are converted to a composite type, 10822 /// true otherwise. 10823 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10824 ExprResult &LHS, ExprResult &RHS) { 10825 // C++ [expr.rel]p2: 10826 // [...] Pointer conversions (4.10) and qualification 10827 // conversions (4.4) are performed on pointer operands (or on 10828 // a pointer operand and a null pointer constant) to bring 10829 // them to their composite pointer type. [...] 10830 // 10831 // C++ [expr.eq]p1 uses the same notion for (in)equality 10832 // comparisons of pointers. 10833 10834 QualType LHSType = LHS.get()->getType(); 10835 QualType RHSType = RHS.get()->getType(); 10836 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10837 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10838 10839 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10840 if (T.isNull()) { 10841 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10842 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10843 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10844 else 10845 S.InvalidOperands(Loc, LHS, RHS); 10846 return true; 10847 } 10848 10849 return false; 10850 } 10851 10852 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10853 ExprResult &LHS, 10854 ExprResult &RHS, 10855 bool IsError) { 10856 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10857 : diag::ext_typecheck_comparison_of_fptr_to_void) 10858 << LHS.get()->getType() << RHS.get()->getType() 10859 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10860 } 10861 10862 static bool isObjCObjectLiteral(ExprResult &E) { 10863 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10864 case Stmt::ObjCArrayLiteralClass: 10865 case Stmt::ObjCDictionaryLiteralClass: 10866 case Stmt::ObjCStringLiteralClass: 10867 case Stmt::ObjCBoxedExprClass: 10868 return true; 10869 default: 10870 // Note that ObjCBoolLiteral is NOT an object literal! 10871 return false; 10872 } 10873 } 10874 10875 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10876 const ObjCObjectPointerType *Type = 10877 LHS->getType()->getAs<ObjCObjectPointerType>(); 10878 10879 // If this is not actually an Objective-C object, bail out. 10880 if (!Type) 10881 return false; 10882 10883 // Get the LHS object's interface type. 10884 QualType InterfaceType = Type->getPointeeType(); 10885 10886 // If the RHS isn't an Objective-C object, bail out. 10887 if (!RHS->getType()->isObjCObjectPointerType()) 10888 return false; 10889 10890 // Try to find the -isEqual: method. 10891 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10892 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10893 InterfaceType, 10894 /*IsInstance=*/true); 10895 if (!Method) { 10896 if (Type->isObjCIdType()) { 10897 // For 'id', just check the global pool. 10898 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10899 /*receiverId=*/true); 10900 } else { 10901 // Check protocols. 10902 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10903 /*IsInstance=*/true); 10904 } 10905 } 10906 10907 if (!Method) 10908 return false; 10909 10910 QualType T = Method->parameters()[0]->getType(); 10911 if (!T->isObjCObjectPointerType()) 10912 return false; 10913 10914 QualType R = Method->getReturnType(); 10915 if (!R->isScalarType()) 10916 return false; 10917 10918 return true; 10919 } 10920 10921 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10922 FromE = FromE->IgnoreParenImpCasts(); 10923 switch (FromE->getStmtClass()) { 10924 default: 10925 break; 10926 case Stmt::ObjCStringLiteralClass: 10927 // "string literal" 10928 return LK_String; 10929 case Stmt::ObjCArrayLiteralClass: 10930 // "array literal" 10931 return LK_Array; 10932 case Stmt::ObjCDictionaryLiteralClass: 10933 // "dictionary literal" 10934 return LK_Dictionary; 10935 case Stmt::BlockExprClass: 10936 return LK_Block; 10937 case Stmt::ObjCBoxedExprClass: { 10938 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10939 switch (Inner->getStmtClass()) { 10940 case Stmt::IntegerLiteralClass: 10941 case Stmt::FloatingLiteralClass: 10942 case Stmt::CharacterLiteralClass: 10943 case Stmt::ObjCBoolLiteralExprClass: 10944 case Stmt::CXXBoolLiteralExprClass: 10945 // "numeric literal" 10946 return LK_Numeric; 10947 case Stmt::ImplicitCastExprClass: { 10948 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10949 // Boolean literals can be represented by implicit casts. 10950 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10951 return LK_Numeric; 10952 break; 10953 } 10954 default: 10955 break; 10956 } 10957 return LK_Boxed; 10958 } 10959 } 10960 return LK_None; 10961 } 10962 10963 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10964 ExprResult &LHS, ExprResult &RHS, 10965 BinaryOperator::Opcode Opc){ 10966 Expr *Literal; 10967 Expr *Other; 10968 if (isObjCObjectLiteral(LHS)) { 10969 Literal = LHS.get(); 10970 Other = RHS.get(); 10971 } else { 10972 Literal = RHS.get(); 10973 Other = LHS.get(); 10974 } 10975 10976 // Don't warn on comparisons against nil. 10977 Other = Other->IgnoreParenCasts(); 10978 if (Other->isNullPointerConstant(S.getASTContext(), 10979 Expr::NPC_ValueDependentIsNotNull)) 10980 return; 10981 10982 // This should be kept in sync with warn_objc_literal_comparison. 10983 // LK_String should always be after the other literals, since it has its own 10984 // warning flag. 10985 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10986 assert(LiteralKind != Sema::LK_Block); 10987 if (LiteralKind == Sema::LK_None) { 10988 llvm_unreachable("Unknown Objective-C object literal kind"); 10989 } 10990 10991 if (LiteralKind == Sema::LK_String) 10992 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10993 << Literal->getSourceRange(); 10994 else 10995 S.Diag(Loc, diag::warn_objc_literal_comparison) 10996 << LiteralKind << Literal->getSourceRange(); 10997 10998 if (BinaryOperator::isEqualityOp(Opc) && 10999 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11000 SourceLocation Start = LHS.get()->getBeginLoc(); 11001 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11002 CharSourceRange OpRange = 11003 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11004 11005 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11006 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11007 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11008 << FixItHint::CreateInsertion(End, "]"); 11009 } 11010 } 11011 11012 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11013 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11014 ExprResult &RHS, SourceLocation Loc, 11015 BinaryOperatorKind Opc) { 11016 // Check that left hand side is !something. 11017 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11018 if (!UO || UO->getOpcode() != UO_LNot) return; 11019 11020 // Only check if the right hand side is non-bool arithmetic type. 11021 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11022 11023 // Make sure that the something in !something is not bool. 11024 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11025 if (SubExpr->isKnownToHaveBooleanValue()) return; 11026 11027 // Emit warning. 11028 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11029 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11030 << Loc << IsBitwiseOp; 11031 11032 // First note suggest !(x < y) 11033 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11034 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11035 FirstClose = S.getLocForEndOfToken(FirstClose); 11036 if (FirstClose.isInvalid()) 11037 FirstOpen = SourceLocation(); 11038 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11039 << IsBitwiseOp 11040 << FixItHint::CreateInsertion(FirstOpen, "(") 11041 << FixItHint::CreateInsertion(FirstClose, ")"); 11042 11043 // Second note suggests (!x) < y 11044 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11045 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11046 SecondClose = S.getLocForEndOfToken(SecondClose); 11047 if (SecondClose.isInvalid()) 11048 SecondOpen = SourceLocation(); 11049 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11050 << FixItHint::CreateInsertion(SecondOpen, "(") 11051 << FixItHint::CreateInsertion(SecondClose, ")"); 11052 } 11053 11054 // Returns true if E refers to a non-weak array. 11055 static bool checkForArray(const Expr *E) { 11056 const ValueDecl *D = nullptr; 11057 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11058 D = DR->getDecl(); 11059 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11060 if (Mem->isImplicitAccess()) 11061 D = Mem->getMemberDecl(); 11062 } 11063 if (!D) 11064 return false; 11065 return D->getType()->isArrayType() && !D->isWeak(); 11066 } 11067 11068 /// Diagnose some forms of syntactically-obvious tautological comparison. 11069 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11070 Expr *LHS, Expr *RHS, 11071 BinaryOperatorKind Opc) { 11072 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11073 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11074 11075 QualType LHSType = LHS->getType(); 11076 QualType RHSType = RHS->getType(); 11077 if (LHSType->hasFloatingRepresentation() || 11078 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11079 S.inTemplateInstantiation()) 11080 return; 11081 11082 // Comparisons between two array types are ill-formed for operator<=>, so 11083 // we shouldn't emit any additional warnings about it. 11084 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11085 return; 11086 11087 // For non-floating point types, check for self-comparisons of the form 11088 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11089 // often indicate logic errors in the program. 11090 // 11091 // NOTE: Don't warn about comparison expressions resulting from macro 11092 // expansion. Also don't warn about comparisons which are only self 11093 // comparisons within a template instantiation. The warnings should catch 11094 // obvious cases in the definition of the template anyways. The idea is to 11095 // warn when the typed comparison operator will always evaluate to the same 11096 // result. 11097 11098 // Used for indexing into %select in warn_comparison_always 11099 enum { 11100 AlwaysConstant, 11101 AlwaysTrue, 11102 AlwaysFalse, 11103 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11104 }; 11105 11106 // C++2a [depr.array.comp]: 11107 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11108 // operands of array type are deprecated. 11109 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11110 RHSStripped->getType()->isArrayType()) { 11111 S.Diag(Loc, diag::warn_depr_array_comparison) 11112 << LHS->getSourceRange() << RHS->getSourceRange() 11113 << LHSStripped->getType() << RHSStripped->getType(); 11114 // Carry on to produce the tautological comparison warning, if this 11115 // expression is potentially-evaluated, we can resolve the array to a 11116 // non-weak declaration, and so on. 11117 } 11118 11119 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11120 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11121 unsigned Result; 11122 switch (Opc) { 11123 case BO_EQ: 11124 case BO_LE: 11125 case BO_GE: 11126 Result = AlwaysTrue; 11127 break; 11128 case BO_NE: 11129 case BO_LT: 11130 case BO_GT: 11131 Result = AlwaysFalse; 11132 break; 11133 case BO_Cmp: 11134 Result = AlwaysEqual; 11135 break; 11136 default: 11137 Result = AlwaysConstant; 11138 break; 11139 } 11140 S.DiagRuntimeBehavior(Loc, nullptr, 11141 S.PDiag(diag::warn_comparison_always) 11142 << 0 /*self-comparison*/ 11143 << Result); 11144 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11145 // What is it always going to evaluate to? 11146 unsigned Result; 11147 switch (Opc) { 11148 case BO_EQ: // e.g. array1 == array2 11149 Result = AlwaysFalse; 11150 break; 11151 case BO_NE: // e.g. array1 != array2 11152 Result = AlwaysTrue; 11153 break; 11154 default: // e.g. array1 <= array2 11155 // The best we can say is 'a constant' 11156 Result = AlwaysConstant; 11157 break; 11158 } 11159 S.DiagRuntimeBehavior(Loc, nullptr, 11160 S.PDiag(diag::warn_comparison_always) 11161 << 1 /*array comparison*/ 11162 << Result); 11163 } 11164 } 11165 11166 if (isa<CastExpr>(LHSStripped)) 11167 LHSStripped = LHSStripped->IgnoreParenCasts(); 11168 if (isa<CastExpr>(RHSStripped)) 11169 RHSStripped = RHSStripped->IgnoreParenCasts(); 11170 11171 // Warn about comparisons against a string constant (unless the other 11172 // operand is null); the user probably wants string comparison function. 11173 Expr *LiteralString = nullptr; 11174 Expr *LiteralStringStripped = nullptr; 11175 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11176 !RHSStripped->isNullPointerConstant(S.Context, 11177 Expr::NPC_ValueDependentIsNull)) { 11178 LiteralString = LHS; 11179 LiteralStringStripped = LHSStripped; 11180 } else if ((isa<StringLiteral>(RHSStripped) || 11181 isa<ObjCEncodeExpr>(RHSStripped)) && 11182 !LHSStripped->isNullPointerConstant(S.Context, 11183 Expr::NPC_ValueDependentIsNull)) { 11184 LiteralString = RHS; 11185 LiteralStringStripped = RHSStripped; 11186 } 11187 11188 if (LiteralString) { 11189 S.DiagRuntimeBehavior(Loc, nullptr, 11190 S.PDiag(diag::warn_stringcompare) 11191 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11192 << LiteralString->getSourceRange()); 11193 } 11194 } 11195 11196 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11197 switch (CK) { 11198 default: { 11199 #ifndef NDEBUG 11200 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11201 << "\n"; 11202 #endif 11203 llvm_unreachable("unhandled cast kind"); 11204 } 11205 case CK_UserDefinedConversion: 11206 return ICK_Identity; 11207 case CK_LValueToRValue: 11208 return ICK_Lvalue_To_Rvalue; 11209 case CK_ArrayToPointerDecay: 11210 return ICK_Array_To_Pointer; 11211 case CK_FunctionToPointerDecay: 11212 return ICK_Function_To_Pointer; 11213 case CK_IntegralCast: 11214 return ICK_Integral_Conversion; 11215 case CK_FloatingCast: 11216 return ICK_Floating_Conversion; 11217 case CK_IntegralToFloating: 11218 case CK_FloatingToIntegral: 11219 return ICK_Floating_Integral; 11220 case CK_IntegralComplexCast: 11221 case CK_FloatingComplexCast: 11222 case CK_FloatingComplexToIntegralComplex: 11223 case CK_IntegralComplexToFloatingComplex: 11224 return ICK_Complex_Conversion; 11225 case CK_FloatingComplexToReal: 11226 case CK_FloatingRealToComplex: 11227 case CK_IntegralComplexToReal: 11228 case CK_IntegralRealToComplex: 11229 return ICK_Complex_Real; 11230 } 11231 } 11232 11233 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11234 QualType FromType, 11235 SourceLocation Loc) { 11236 // Check for a narrowing implicit conversion. 11237 StandardConversionSequence SCS; 11238 SCS.setAsIdentityConversion(); 11239 SCS.setToType(0, FromType); 11240 SCS.setToType(1, ToType); 11241 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11242 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11243 11244 APValue PreNarrowingValue; 11245 QualType PreNarrowingType; 11246 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11247 PreNarrowingType, 11248 /*IgnoreFloatToIntegralConversion*/ true)) { 11249 case NK_Dependent_Narrowing: 11250 // Implicit conversion to a narrower type, but the expression is 11251 // value-dependent so we can't tell whether it's actually narrowing. 11252 case NK_Not_Narrowing: 11253 return false; 11254 11255 case NK_Constant_Narrowing: 11256 // Implicit conversion to a narrower type, and the value is not a constant 11257 // expression. 11258 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11259 << /*Constant*/ 1 11260 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11261 return true; 11262 11263 case NK_Variable_Narrowing: 11264 // Implicit conversion to a narrower type, and the value is not a constant 11265 // expression. 11266 case NK_Type_Narrowing: 11267 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11268 << /*Constant*/ 0 << FromType << ToType; 11269 // TODO: It's not a constant expression, but what if the user intended it 11270 // to be? Can we produce notes to help them figure out why it isn't? 11271 return true; 11272 } 11273 llvm_unreachable("unhandled case in switch"); 11274 } 11275 11276 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11277 ExprResult &LHS, 11278 ExprResult &RHS, 11279 SourceLocation Loc) { 11280 QualType LHSType = LHS.get()->getType(); 11281 QualType RHSType = RHS.get()->getType(); 11282 // Dig out the original argument type and expression before implicit casts 11283 // were applied. These are the types/expressions we need to check the 11284 // [expr.spaceship] requirements against. 11285 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11286 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11287 QualType LHSStrippedType = LHSStripped.get()->getType(); 11288 QualType RHSStrippedType = RHSStripped.get()->getType(); 11289 11290 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11291 // other is not, the program is ill-formed. 11292 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11293 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11294 return QualType(); 11295 } 11296 11297 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11298 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11299 RHSStrippedType->isEnumeralType(); 11300 if (NumEnumArgs == 1) { 11301 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11302 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11303 if (OtherTy->hasFloatingRepresentation()) { 11304 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11305 return QualType(); 11306 } 11307 } 11308 if (NumEnumArgs == 2) { 11309 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11310 // type E, the operator yields the result of converting the operands 11311 // to the underlying type of E and applying <=> to the converted operands. 11312 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11313 S.InvalidOperands(Loc, LHS, RHS); 11314 return QualType(); 11315 } 11316 QualType IntType = 11317 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11318 assert(IntType->isArithmeticType()); 11319 11320 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11321 // promote the boolean type, and all other promotable integer types, to 11322 // avoid this. 11323 if (IntType->isPromotableIntegerType()) 11324 IntType = S.Context.getPromotedIntegerType(IntType); 11325 11326 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11327 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11328 LHSType = RHSType = IntType; 11329 } 11330 11331 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11332 // usual arithmetic conversions are applied to the operands. 11333 QualType Type = 11334 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11335 if (LHS.isInvalid() || RHS.isInvalid()) 11336 return QualType(); 11337 if (Type.isNull()) 11338 return S.InvalidOperands(Loc, LHS, RHS); 11339 11340 Optional<ComparisonCategoryType> CCT = 11341 getComparisonCategoryForBuiltinCmp(Type); 11342 if (!CCT) 11343 return S.InvalidOperands(Loc, LHS, RHS); 11344 11345 bool HasNarrowing = checkThreeWayNarrowingConversion( 11346 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11347 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11348 RHS.get()->getBeginLoc()); 11349 if (HasNarrowing) 11350 return QualType(); 11351 11352 assert(!Type.isNull() && "composite type for <=> has not been set"); 11353 11354 return S.CheckComparisonCategoryType( 11355 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11356 } 11357 11358 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11359 ExprResult &RHS, 11360 SourceLocation Loc, 11361 BinaryOperatorKind Opc) { 11362 if (Opc == BO_Cmp) 11363 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11364 11365 // C99 6.5.8p3 / C99 6.5.9p4 11366 QualType Type = 11367 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11368 if (LHS.isInvalid() || RHS.isInvalid()) 11369 return QualType(); 11370 if (Type.isNull()) 11371 return S.InvalidOperands(Loc, LHS, RHS); 11372 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11373 11374 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11375 return S.InvalidOperands(Loc, LHS, RHS); 11376 11377 // Check for comparisons of floating point operands using != and ==. 11378 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11379 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11380 11381 // The result of comparisons is 'bool' in C++, 'int' in C. 11382 return S.Context.getLogicalOperationType(); 11383 } 11384 11385 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11386 if (!NullE.get()->getType()->isAnyPointerType()) 11387 return; 11388 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11389 if (!E.get()->getType()->isAnyPointerType() && 11390 E.get()->isNullPointerConstant(Context, 11391 Expr::NPC_ValueDependentIsNotNull) == 11392 Expr::NPCK_ZeroExpression) { 11393 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11394 if (CL->getValue() == 0) 11395 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11396 << NullValue 11397 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11398 NullValue ? "NULL" : "(void *)0"); 11399 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11400 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11401 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11402 if (T == Context.CharTy) 11403 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11404 << NullValue 11405 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11406 NullValue ? "NULL" : "(void *)0"); 11407 } 11408 } 11409 } 11410 11411 // C99 6.5.8, C++ [expr.rel] 11412 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11413 SourceLocation Loc, 11414 BinaryOperatorKind Opc) { 11415 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11416 bool IsThreeWay = Opc == BO_Cmp; 11417 bool IsOrdered = IsRelational || IsThreeWay; 11418 auto IsAnyPointerType = [](ExprResult E) { 11419 QualType Ty = E.get()->getType(); 11420 return Ty->isPointerType() || Ty->isMemberPointerType(); 11421 }; 11422 11423 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11424 // type, array-to-pointer, ..., conversions are performed on both operands to 11425 // bring them to their composite type. 11426 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11427 // any type-related checks. 11428 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11429 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11430 if (LHS.isInvalid()) 11431 return QualType(); 11432 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11433 if (RHS.isInvalid()) 11434 return QualType(); 11435 } else { 11436 LHS = DefaultLvalueConversion(LHS.get()); 11437 if (LHS.isInvalid()) 11438 return QualType(); 11439 RHS = DefaultLvalueConversion(RHS.get()); 11440 if (RHS.isInvalid()) 11441 return QualType(); 11442 } 11443 11444 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11445 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11446 CheckPtrComparisonWithNullChar(LHS, RHS); 11447 CheckPtrComparisonWithNullChar(RHS, LHS); 11448 } 11449 11450 // Handle vector comparisons separately. 11451 if (LHS.get()->getType()->isVectorType() || 11452 RHS.get()->getType()->isVectorType()) 11453 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11454 11455 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11456 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11457 11458 QualType LHSType = LHS.get()->getType(); 11459 QualType RHSType = RHS.get()->getType(); 11460 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11461 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11462 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11463 11464 const Expr::NullPointerConstantKind LHSNullKind = 11465 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11466 const Expr::NullPointerConstantKind RHSNullKind = 11467 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11468 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11469 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11470 11471 auto computeResultTy = [&]() { 11472 if (Opc != BO_Cmp) 11473 return Context.getLogicalOperationType(); 11474 assert(getLangOpts().CPlusPlus); 11475 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11476 11477 QualType CompositeTy = LHS.get()->getType(); 11478 assert(!CompositeTy->isReferenceType()); 11479 11480 Optional<ComparisonCategoryType> CCT = 11481 getComparisonCategoryForBuiltinCmp(CompositeTy); 11482 if (!CCT) 11483 return InvalidOperands(Loc, LHS, RHS); 11484 11485 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11486 // P0946R0: Comparisons between a null pointer constant and an object 11487 // pointer result in std::strong_equality, which is ill-formed under 11488 // P1959R0. 11489 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11490 << (LHSIsNull ? LHS.get()->getSourceRange() 11491 : RHS.get()->getSourceRange()); 11492 return QualType(); 11493 } 11494 11495 return CheckComparisonCategoryType( 11496 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11497 }; 11498 11499 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11500 bool IsEquality = Opc == BO_EQ; 11501 if (RHSIsNull) 11502 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11503 RHS.get()->getSourceRange()); 11504 else 11505 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11506 LHS.get()->getSourceRange()); 11507 } 11508 11509 if ((LHSType->isIntegerType() && !LHSIsNull) || 11510 (RHSType->isIntegerType() && !RHSIsNull)) { 11511 // Skip normal pointer conversion checks in this case; we have better 11512 // diagnostics for this below. 11513 } else if (getLangOpts().CPlusPlus) { 11514 // Equality comparison of a function pointer to a void pointer is invalid, 11515 // but we allow it as an extension. 11516 // FIXME: If we really want to allow this, should it be part of composite 11517 // pointer type computation so it works in conditionals too? 11518 if (!IsOrdered && 11519 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11520 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11521 // This is a gcc extension compatibility comparison. 11522 // In a SFINAE context, we treat this as a hard error to maintain 11523 // conformance with the C++ standard. 11524 diagnoseFunctionPointerToVoidComparison( 11525 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11526 11527 if (isSFINAEContext()) 11528 return QualType(); 11529 11530 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11531 return computeResultTy(); 11532 } 11533 11534 // C++ [expr.eq]p2: 11535 // If at least one operand is a pointer [...] bring them to their 11536 // composite pointer type. 11537 // C++ [expr.spaceship]p6 11538 // If at least one of the operands is of pointer type, [...] bring them 11539 // to their composite pointer type. 11540 // C++ [expr.rel]p2: 11541 // If both operands are pointers, [...] bring them to their composite 11542 // pointer type. 11543 // For <=>, the only valid non-pointer types are arrays and functions, and 11544 // we already decayed those, so this is really the same as the relational 11545 // comparison rule. 11546 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11547 (IsOrdered ? 2 : 1) && 11548 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11549 RHSType->isObjCObjectPointerType()))) { 11550 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11551 return QualType(); 11552 return computeResultTy(); 11553 } 11554 } else if (LHSType->isPointerType() && 11555 RHSType->isPointerType()) { // C99 6.5.8p2 11556 // All of the following pointer-related warnings are GCC extensions, except 11557 // when handling null pointer constants. 11558 QualType LCanPointeeTy = 11559 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11560 QualType RCanPointeeTy = 11561 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11562 11563 // C99 6.5.9p2 and C99 6.5.8p2 11564 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11565 RCanPointeeTy.getUnqualifiedType())) { 11566 // Valid unless a relational comparison of function pointers 11567 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11568 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11569 << LHSType << RHSType << LHS.get()->getSourceRange() 11570 << RHS.get()->getSourceRange(); 11571 } 11572 } else if (!IsRelational && 11573 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11574 // Valid unless comparison between non-null pointer and function pointer 11575 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11576 && !LHSIsNull && !RHSIsNull) 11577 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11578 /*isError*/false); 11579 } else { 11580 // Invalid 11581 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11582 } 11583 if (LCanPointeeTy != RCanPointeeTy) { 11584 // Treat NULL constant as a special case in OpenCL. 11585 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11586 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11587 Diag(Loc, 11588 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11589 << LHSType << RHSType << 0 /* comparison */ 11590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11591 } 11592 } 11593 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11594 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11595 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11596 : CK_BitCast; 11597 if (LHSIsNull && !RHSIsNull) 11598 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11599 else 11600 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11601 } 11602 return computeResultTy(); 11603 } 11604 11605 if (getLangOpts().CPlusPlus) { 11606 // C++ [expr.eq]p4: 11607 // Two operands of type std::nullptr_t or one operand of type 11608 // std::nullptr_t and the other a null pointer constant compare equal. 11609 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11610 if (LHSType->isNullPtrType()) { 11611 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11612 return computeResultTy(); 11613 } 11614 if (RHSType->isNullPtrType()) { 11615 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11616 return computeResultTy(); 11617 } 11618 } 11619 11620 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11621 // These aren't covered by the composite pointer type rules. 11622 if (!IsOrdered && RHSType->isNullPtrType() && 11623 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11624 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11625 return computeResultTy(); 11626 } 11627 if (!IsOrdered && LHSType->isNullPtrType() && 11628 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11629 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11630 return computeResultTy(); 11631 } 11632 11633 if (IsRelational && 11634 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11635 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11636 // HACK: Relational comparison of nullptr_t against a pointer type is 11637 // invalid per DR583, but we allow it within std::less<> and friends, 11638 // since otherwise common uses of it break. 11639 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11640 // friends to have std::nullptr_t overload candidates. 11641 DeclContext *DC = CurContext; 11642 if (isa<FunctionDecl>(DC)) 11643 DC = DC->getParent(); 11644 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11645 if (CTSD->isInStdNamespace() && 11646 llvm::StringSwitch<bool>(CTSD->getName()) 11647 .Cases("less", "less_equal", "greater", "greater_equal", true) 11648 .Default(false)) { 11649 if (RHSType->isNullPtrType()) 11650 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11651 else 11652 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11653 return computeResultTy(); 11654 } 11655 } 11656 } 11657 11658 // C++ [expr.eq]p2: 11659 // If at least one operand is a pointer to member, [...] bring them to 11660 // their composite pointer type. 11661 if (!IsOrdered && 11662 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11663 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11664 return QualType(); 11665 else 11666 return computeResultTy(); 11667 } 11668 } 11669 11670 // Handle block pointer types. 11671 if (!IsOrdered && LHSType->isBlockPointerType() && 11672 RHSType->isBlockPointerType()) { 11673 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11674 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11675 11676 if (!LHSIsNull && !RHSIsNull && 11677 !Context.typesAreCompatible(lpointee, rpointee)) { 11678 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11679 << LHSType << RHSType << LHS.get()->getSourceRange() 11680 << RHS.get()->getSourceRange(); 11681 } 11682 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11683 return computeResultTy(); 11684 } 11685 11686 // Allow block pointers to be compared with null pointer constants. 11687 if (!IsOrdered 11688 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11689 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11690 if (!LHSIsNull && !RHSIsNull) { 11691 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11692 ->getPointeeType()->isVoidType()) 11693 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11694 ->getPointeeType()->isVoidType()))) 11695 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11696 << LHSType << RHSType << LHS.get()->getSourceRange() 11697 << RHS.get()->getSourceRange(); 11698 } 11699 if (LHSIsNull && !RHSIsNull) 11700 LHS = ImpCastExprToType(LHS.get(), RHSType, 11701 RHSType->isPointerType() ? CK_BitCast 11702 : CK_AnyPointerToBlockPointerCast); 11703 else 11704 RHS = ImpCastExprToType(RHS.get(), LHSType, 11705 LHSType->isPointerType() ? CK_BitCast 11706 : CK_AnyPointerToBlockPointerCast); 11707 return computeResultTy(); 11708 } 11709 11710 if (LHSType->isObjCObjectPointerType() || 11711 RHSType->isObjCObjectPointerType()) { 11712 const PointerType *LPT = LHSType->getAs<PointerType>(); 11713 const PointerType *RPT = RHSType->getAs<PointerType>(); 11714 if (LPT || RPT) { 11715 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11716 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11717 11718 if (!LPtrToVoid && !RPtrToVoid && 11719 !Context.typesAreCompatible(LHSType, RHSType)) { 11720 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11721 /*isError*/false); 11722 } 11723 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11724 // the RHS, but we have test coverage for this behavior. 11725 // FIXME: Consider using convertPointersToCompositeType in C++. 11726 if (LHSIsNull && !RHSIsNull) { 11727 Expr *E = LHS.get(); 11728 if (getLangOpts().ObjCAutoRefCount) 11729 CheckObjCConversion(SourceRange(), RHSType, E, 11730 CCK_ImplicitConversion); 11731 LHS = ImpCastExprToType(E, RHSType, 11732 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11733 } 11734 else { 11735 Expr *E = RHS.get(); 11736 if (getLangOpts().ObjCAutoRefCount) 11737 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11738 /*Diagnose=*/true, 11739 /*DiagnoseCFAudited=*/false, Opc); 11740 RHS = ImpCastExprToType(E, LHSType, 11741 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11742 } 11743 return computeResultTy(); 11744 } 11745 if (LHSType->isObjCObjectPointerType() && 11746 RHSType->isObjCObjectPointerType()) { 11747 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11748 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11749 /*isError*/false); 11750 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11751 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11752 11753 if (LHSIsNull && !RHSIsNull) 11754 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11755 else 11756 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11757 return computeResultTy(); 11758 } 11759 11760 if (!IsOrdered && LHSType->isBlockPointerType() && 11761 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11762 LHS = ImpCastExprToType(LHS.get(), RHSType, 11763 CK_BlockPointerToObjCPointerCast); 11764 return computeResultTy(); 11765 } else if (!IsOrdered && 11766 LHSType->isBlockCompatibleObjCPointerType(Context) && 11767 RHSType->isBlockPointerType()) { 11768 RHS = ImpCastExprToType(RHS.get(), LHSType, 11769 CK_BlockPointerToObjCPointerCast); 11770 return computeResultTy(); 11771 } 11772 } 11773 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11774 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11775 unsigned DiagID = 0; 11776 bool isError = false; 11777 if (LangOpts.DebuggerSupport) { 11778 // Under a debugger, allow the comparison of pointers to integers, 11779 // since users tend to want to compare addresses. 11780 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11781 (RHSIsNull && RHSType->isIntegerType())) { 11782 if (IsOrdered) { 11783 isError = getLangOpts().CPlusPlus; 11784 DiagID = 11785 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11786 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11787 } 11788 } else if (getLangOpts().CPlusPlus) { 11789 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11790 isError = true; 11791 } else if (IsOrdered) 11792 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11793 else 11794 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11795 11796 if (DiagID) { 11797 Diag(Loc, DiagID) 11798 << LHSType << RHSType << LHS.get()->getSourceRange() 11799 << RHS.get()->getSourceRange(); 11800 if (isError) 11801 return QualType(); 11802 } 11803 11804 if (LHSType->isIntegerType()) 11805 LHS = ImpCastExprToType(LHS.get(), RHSType, 11806 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11807 else 11808 RHS = ImpCastExprToType(RHS.get(), LHSType, 11809 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11810 return computeResultTy(); 11811 } 11812 11813 // Handle block pointers. 11814 if (!IsOrdered && RHSIsNull 11815 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11816 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11817 return computeResultTy(); 11818 } 11819 if (!IsOrdered && LHSIsNull 11820 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11821 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11822 return computeResultTy(); 11823 } 11824 11825 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11826 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11827 return computeResultTy(); 11828 } 11829 11830 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11831 return computeResultTy(); 11832 } 11833 11834 if (LHSIsNull && RHSType->isQueueT()) { 11835 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11836 return computeResultTy(); 11837 } 11838 11839 if (LHSType->isQueueT() && RHSIsNull) { 11840 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11841 return computeResultTy(); 11842 } 11843 } 11844 11845 return InvalidOperands(Loc, LHS, RHS); 11846 } 11847 11848 // Return a signed ext_vector_type that is of identical size and number of 11849 // elements. For floating point vectors, return an integer type of identical 11850 // size and number of elements. In the non ext_vector_type case, search from 11851 // the largest type to the smallest type to avoid cases where long long == long, 11852 // where long gets picked over long long. 11853 QualType Sema::GetSignedVectorType(QualType V) { 11854 const VectorType *VTy = V->castAs<VectorType>(); 11855 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11856 11857 if (isa<ExtVectorType>(VTy)) { 11858 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11859 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11860 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11861 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11862 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11863 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11864 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11865 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11866 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11867 "Unhandled vector element size in vector compare"); 11868 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11869 } 11870 11871 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11872 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11873 VectorType::GenericVector); 11874 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11875 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11876 VectorType::GenericVector); 11877 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11878 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11879 VectorType::GenericVector); 11880 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11881 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11882 VectorType::GenericVector); 11883 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11884 "Unhandled vector element size in vector compare"); 11885 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11886 VectorType::GenericVector); 11887 } 11888 11889 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11890 /// operates on extended vector types. Instead of producing an IntTy result, 11891 /// like a scalar comparison, a vector comparison produces a vector of integer 11892 /// types. 11893 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11894 SourceLocation Loc, 11895 BinaryOperatorKind Opc) { 11896 if (Opc == BO_Cmp) { 11897 Diag(Loc, diag::err_three_way_vector_comparison); 11898 return QualType(); 11899 } 11900 11901 // Check to make sure we're operating on vectors of the same type and width, 11902 // Allowing one side to be a scalar of element type. 11903 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11904 /*AllowBothBool*/true, 11905 /*AllowBoolConversions*/getLangOpts().ZVector); 11906 if (vType.isNull()) 11907 return vType; 11908 11909 QualType LHSType = LHS.get()->getType(); 11910 11911 // If AltiVec, the comparison results in a numeric type, i.e. 11912 // bool for C++, int for C 11913 if (getLangOpts().AltiVec && 11914 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11915 return Context.getLogicalOperationType(); 11916 11917 // For non-floating point types, check for self-comparisons of the form 11918 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11919 // often indicate logic errors in the program. 11920 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11921 11922 // Check for comparisons of floating point operands using != and ==. 11923 if (BinaryOperator::isEqualityOp(Opc) && 11924 LHSType->hasFloatingRepresentation()) { 11925 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11926 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11927 } 11928 11929 // Return a signed type for the vector. 11930 return GetSignedVectorType(vType); 11931 } 11932 11933 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11934 const ExprResult &XorRHS, 11935 const SourceLocation Loc) { 11936 // Do not diagnose macros. 11937 if (Loc.isMacroID()) 11938 return; 11939 11940 bool Negative = false; 11941 bool ExplicitPlus = false; 11942 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11943 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11944 11945 if (!LHSInt) 11946 return; 11947 if (!RHSInt) { 11948 // Check negative literals. 11949 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11950 UnaryOperatorKind Opc = UO->getOpcode(); 11951 if (Opc != UO_Minus && Opc != UO_Plus) 11952 return; 11953 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11954 if (!RHSInt) 11955 return; 11956 Negative = (Opc == UO_Minus); 11957 ExplicitPlus = !Negative; 11958 } else { 11959 return; 11960 } 11961 } 11962 11963 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11964 llvm::APInt RightSideValue = RHSInt->getValue(); 11965 if (LeftSideValue != 2 && LeftSideValue != 10) 11966 return; 11967 11968 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11969 return; 11970 11971 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11972 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11973 llvm::StringRef ExprStr = 11974 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11975 11976 CharSourceRange XorRange = 11977 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11978 llvm::StringRef XorStr = 11979 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11980 // Do not diagnose if xor keyword/macro is used. 11981 if (XorStr == "xor") 11982 return; 11983 11984 std::string LHSStr = std::string(Lexer::getSourceText( 11985 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11986 S.getSourceManager(), S.getLangOpts())); 11987 std::string RHSStr = std::string(Lexer::getSourceText( 11988 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11989 S.getSourceManager(), S.getLangOpts())); 11990 11991 if (Negative) { 11992 RightSideValue = -RightSideValue; 11993 RHSStr = "-" + RHSStr; 11994 } else if (ExplicitPlus) { 11995 RHSStr = "+" + RHSStr; 11996 } 11997 11998 StringRef LHSStrRef = LHSStr; 11999 StringRef RHSStrRef = RHSStr; 12000 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12001 // literals. 12002 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12003 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12004 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12005 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12006 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12007 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12008 LHSStrRef.find('\'') != StringRef::npos || 12009 RHSStrRef.find('\'') != StringRef::npos) 12010 return; 12011 12012 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12013 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12014 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12015 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12016 std::string SuggestedExpr = "1 << " + RHSStr; 12017 bool Overflow = false; 12018 llvm::APInt One = (LeftSideValue - 1); 12019 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12020 if (Overflow) { 12021 if (RightSideIntValue < 64) 12022 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12023 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12024 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12025 else if (RightSideIntValue == 64) 12026 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12027 else 12028 return; 12029 } else { 12030 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12031 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12032 << PowValue.toString(10, true) 12033 << FixItHint::CreateReplacement( 12034 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12035 } 12036 12037 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12038 } else if (LeftSideValue == 10) { 12039 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12040 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12041 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12042 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12043 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12044 } 12045 } 12046 12047 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12048 SourceLocation Loc) { 12049 // Ensure that either both operands are of the same vector type, or 12050 // one operand is of a vector type and the other is of its element type. 12051 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12052 /*AllowBothBool*/true, 12053 /*AllowBoolConversions*/false); 12054 if (vType.isNull()) 12055 return InvalidOperands(Loc, LHS, RHS); 12056 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12057 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12058 return InvalidOperands(Loc, LHS, RHS); 12059 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12060 // usage of the logical operators && and || with vectors in C. This 12061 // check could be notionally dropped. 12062 if (!getLangOpts().CPlusPlus && 12063 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12064 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12065 12066 return GetSignedVectorType(LHS.get()->getType()); 12067 } 12068 12069 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12070 SourceLocation Loc, 12071 bool IsCompAssign) { 12072 if (!IsCompAssign) { 12073 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12074 if (LHS.isInvalid()) 12075 return QualType(); 12076 } 12077 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12078 if (RHS.isInvalid()) 12079 return QualType(); 12080 12081 // For conversion purposes, we ignore any qualifiers. 12082 // For example, "const float" and "float" are equivalent. 12083 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12084 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12085 12086 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12087 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12088 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12089 12090 if (Context.hasSameType(LHSType, RHSType)) 12091 return LHSType; 12092 12093 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12094 // case we have to return InvalidOperands. 12095 ExprResult OriginalLHS = LHS; 12096 ExprResult OriginalRHS = RHS; 12097 if (LHSMatType && !RHSMatType) { 12098 if (tryConvertToTy(*this, LHSMatType->getElementType(), &RHS)) 12099 return LHSType; 12100 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12101 } 12102 12103 if (!LHSMatType && RHSMatType) { 12104 if (tryConvertToTy(*this, RHSMatType->getElementType(), &LHS)) 12105 return RHSType; 12106 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12107 } 12108 12109 return InvalidOperands(Loc, LHS, RHS); 12110 } 12111 12112 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12113 SourceLocation Loc, 12114 BinaryOperatorKind Opc) { 12115 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12116 12117 bool IsCompAssign = 12118 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12119 12120 if (LHS.get()->getType()->isVectorType() || 12121 RHS.get()->getType()->isVectorType()) { 12122 if (LHS.get()->getType()->hasIntegerRepresentation() && 12123 RHS.get()->getType()->hasIntegerRepresentation()) 12124 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12125 /*AllowBothBool*/true, 12126 /*AllowBoolConversions*/getLangOpts().ZVector); 12127 return InvalidOperands(Loc, LHS, RHS); 12128 } 12129 12130 if (Opc == BO_And) 12131 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12132 12133 if (LHS.get()->getType()->hasFloatingRepresentation() || 12134 RHS.get()->getType()->hasFloatingRepresentation()) 12135 return InvalidOperands(Loc, LHS, RHS); 12136 12137 ExprResult LHSResult = LHS, RHSResult = RHS; 12138 QualType compType = UsualArithmeticConversions( 12139 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12140 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12141 return QualType(); 12142 LHS = LHSResult.get(); 12143 RHS = RHSResult.get(); 12144 12145 if (Opc == BO_Xor) 12146 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12147 12148 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12149 return compType; 12150 return InvalidOperands(Loc, LHS, RHS); 12151 } 12152 12153 // C99 6.5.[13,14] 12154 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12155 SourceLocation Loc, 12156 BinaryOperatorKind Opc) { 12157 // Check vector operands differently. 12158 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12159 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12160 12161 bool EnumConstantInBoolContext = false; 12162 for (const ExprResult &HS : {LHS, RHS}) { 12163 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12164 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12165 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12166 EnumConstantInBoolContext = true; 12167 } 12168 } 12169 12170 if (EnumConstantInBoolContext) 12171 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12172 12173 // Diagnose cases where the user write a logical and/or but probably meant a 12174 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12175 // is a constant. 12176 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12177 !LHS.get()->getType()->isBooleanType() && 12178 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12179 // Don't warn in macros or template instantiations. 12180 !Loc.isMacroID() && !inTemplateInstantiation()) { 12181 // If the RHS can be constant folded, and if it constant folds to something 12182 // that isn't 0 or 1 (which indicate a potential logical operation that 12183 // happened to fold to true/false) then warn. 12184 // Parens on the RHS are ignored. 12185 Expr::EvalResult EVResult; 12186 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12187 llvm::APSInt Result = EVResult.Val.getInt(); 12188 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12189 !RHS.get()->getExprLoc().isMacroID()) || 12190 (Result != 0 && Result != 1)) { 12191 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12192 << RHS.get()->getSourceRange() 12193 << (Opc == BO_LAnd ? "&&" : "||"); 12194 // Suggest replacing the logical operator with the bitwise version 12195 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12196 << (Opc == BO_LAnd ? "&" : "|") 12197 << FixItHint::CreateReplacement(SourceRange( 12198 Loc, getLocForEndOfToken(Loc)), 12199 Opc == BO_LAnd ? "&" : "|"); 12200 if (Opc == BO_LAnd) 12201 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12202 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12203 << FixItHint::CreateRemoval( 12204 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12205 RHS.get()->getEndLoc())); 12206 } 12207 } 12208 } 12209 12210 if (!Context.getLangOpts().CPlusPlus) { 12211 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12212 // not operate on the built-in scalar and vector float types. 12213 if (Context.getLangOpts().OpenCL && 12214 Context.getLangOpts().OpenCLVersion < 120) { 12215 if (LHS.get()->getType()->isFloatingType() || 12216 RHS.get()->getType()->isFloatingType()) 12217 return InvalidOperands(Loc, LHS, RHS); 12218 } 12219 12220 LHS = UsualUnaryConversions(LHS.get()); 12221 if (LHS.isInvalid()) 12222 return QualType(); 12223 12224 RHS = UsualUnaryConversions(RHS.get()); 12225 if (RHS.isInvalid()) 12226 return QualType(); 12227 12228 if (!LHS.get()->getType()->isScalarType() || 12229 !RHS.get()->getType()->isScalarType()) 12230 return InvalidOperands(Loc, LHS, RHS); 12231 12232 return Context.IntTy; 12233 } 12234 12235 // The following is safe because we only use this method for 12236 // non-overloadable operands. 12237 12238 // C++ [expr.log.and]p1 12239 // C++ [expr.log.or]p1 12240 // The operands are both contextually converted to type bool. 12241 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12242 if (LHSRes.isInvalid()) 12243 return InvalidOperands(Loc, LHS, RHS); 12244 LHS = LHSRes; 12245 12246 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12247 if (RHSRes.isInvalid()) 12248 return InvalidOperands(Loc, LHS, RHS); 12249 RHS = RHSRes; 12250 12251 // C++ [expr.log.and]p2 12252 // C++ [expr.log.or]p2 12253 // The result is a bool. 12254 return Context.BoolTy; 12255 } 12256 12257 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12258 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12259 if (!ME) return false; 12260 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12261 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12262 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12263 if (!Base) return false; 12264 return Base->getMethodDecl() != nullptr; 12265 } 12266 12267 /// Is the given expression (which must be 'const') a reference to a 12268 /// variable which was originally non-const, but which has become 12269 /// 'const' due to being captured within a block? 12270 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12271 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12272 assert(E->isLValue() && E->getType().isConstQualified()); 12273 E = E->IgnoreParens(); 12274 12275 // Must be a reference to a declaration from an enclosing scope. 12276 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12277 if (!DRE) return NCCK_None; 12278 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12279 12280 // The declaration must be a variable which is not declared 'const'. 12281 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12282 if (!var) return NCCK_None; 12283 if (var->getType().isConstQualified()) return NCCK_None; 12284 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12285 12286 // Decide whether the first capture was for a block or a lambda. 12287 DeclContext *DC = S.CurContext, *Prev = nullptr; 12288 // Decide whether the first capture was for a block or a lambda. 12289 while (DC) { 12290 // For init-capture, it is possible that the variable belongs to the 12291 // template pattern of the current context. 12292 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12293 if (var->isInitCapture() && 12294 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12295 break; 12296 if (DC == var->getDeclContext()) 12297 break; 12298 Prev = DC; 12299 DC = DC->getParent(); 12300 } 12301 // Unless we have an init-capture, we've gone one step too far. 12302 if (!var->isInitCapture()) 12303 DC = Prev; 12304 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12305 } 12306 12307 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12308 Ty = Ty.getNonReferenceType(); 12309 if (IsDereference && Ty->isPointerType()) 12310 Ty = Ty->getPointeeType(); 12311 return !Ty.isConstQualified(); 12312 } 12313 12314 // Update err_typecheck_assign_const and note_typecheck_assign_const 12315 // when this enum is changed. 12316 enum { 12317 ConstFunction, 12318 ConstVariable, 12319 ConstMember, 12320 ConstMethod, 12321 NestedConstMember, 12322 ConstUnknown, // Keep as last element 12323 }; 12324 12325 /// Emit the "read-only variable not assignable" error and print notes to give 12326 /// more information about why the variable is not assignable, such as pointing 12327 /// to the declaration of a const variable, showing that a method is const, or 12328 /// that the function is returning a const reference. 12329 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12330 SourceLocation Loc) { 12331 SourceRange ExprRange = E->getSourceRange(); 12332 12333 // Only emit one error on the first const found. All other consts will emit 12334 // a note to the error. 12335 bool DiagnosticEmitted = false; 12336 12337 // Track if the current expression is the result of a dereference, and if the 12338 // next checked expression is the result of a dereference. 12339 bool IsDereference = false; 12340 bool NextIsDereference = false; 12341 12342 // Loop to process MemberExpr chains. 12343 while (true) { 12344 IsDereference = NextIsDereference; 12345 12346 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12347 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12348 NextIsDereference = ME->isArrow(); 12349 const ValueDecl *VD = ME->getMemberDecl(); 12350 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12351 // Mutable fields can be modified even if the class is const. 12352 if (Field->isMutable()) { 12353 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12354 break; 12355 } 12356 12357 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12358 if (!DiagnosticEmitted) { 12359 S.Diag(Loc, diag::err_typecheck_assign_const) 12360 << ExprRange << ConstMember << false /*static*/ << Field 12361 << Field->getType(); 12362 DiagnosticEmitted = true; 12363 } 12364 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12365 << ConstMember << false /*static*/ << Field << Field->getType() 12366 << Field->getSourceRange(); 12367 } 12368 E = ME->getBase(); 12369 continue; 12370 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12371 if (VDecl->getType().isConstQualified()) { 12372 if (!DiagnosticEmitted) { 12373 S.Diag(Loc, diag::err_typecheck_assign_const) 12374 << ExprRange << ConstMember << true /*static*/ << VDecl 12375 << VDecl->getType(); 12376 DiagnosticEmitted = true; 12377 } 12378 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12379 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12380 << VDecl->getSourceRange(); 12381 } 12382 // Static fields do not inherit constness from parents. 12383 break; 12384 } 12385 break; // End MemberExpr 12386 } else if (const ArraySubscriptExpr *ASE = 12387 dyn_cast<ArraySubscriptExpr>(E)) { 12388 E = ASE->getBase()->IgnoreParenImpCasts(); 12389 continue; 12390 } else if (const ExtVectorElementExpr *EVE = 12391 dyn_cast<ExtVectorElementExpr>(E)) { 12392 E = EVE->getBase()->IgnoreParenImpCasts(); 12393 continue; 12394 } 12395 break; 12396 } 12397 12398 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12399 // Function calls 12400 const FunctionDecl *FD = CE->getDirectCallee(); 12401 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12402 if (!DiagnosticEmitted) { 12403 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12404 << ConstFunction << FD; 12405 DiagnosticEmitted = true; 12406 } 12407 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12408 diag::note_typecheck_assign_const) 12409 << ConstFunction << FD << FD->getReturnType() 12410 << FD->getReturnTypeSourceRange(); 12411 } 12412 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12413 // Point to variable declaration. 12414 if (const ValueDecl *VD = DRE->getDecl()) { 12415 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12416 if (!DiagnosticEmitted) { 12417 S.Diag(Loc, diag::err_typecheck_assign_const) 12418 << ExprRange << ConstVariable << VD << VD->getType(); 12419 DiagnosticEmitted = true; 12420 } 12421 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12422 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12423 } 12424 } 12425 } else if (isa<CXXThisExpr>(E)) { 12426 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12427 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12428 if (MD->isConst()) { 12429 if (!DiagnosticEmitted) { 12430 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12431 << ConstMethod << MD; 12432 DiagnosticEmitted = true; 12433 } 12434 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12435 << ConstMethod << MD << MD->getSourceRange(); 12436 } 12437 } 12438 } 12439 } 12440 12441 if (DiagnosticEmitted) 12442 return; 12443 12444 // Can't determine a more specific message, so display the generic error. 12445 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12446 } 12447 12448 enum OriginalExprKind { 12449 OEK_Variable, 12450 OEK_Member, 12451 OEK_LValue 12452 }; 12453 12454 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12455 const RecordType *Ty, 12456 SourceLocation Loc, SourceRange Range, 12457 OriginalExprKind OEK, 12458 bool &DiagnosticEmitted) { 12459 std::vector<const RecordType *> RecordTypeList; 12460 RecordTypeList.push_back(Ty); 12461 unsigned NextToCheckIndex = 0; 12462 // We walk the record hierarchy breadth-first to ensure that we print 12463 // diagnostics in field nesting order. 12464 while (RecordTypeList.size() > NextToCheckIndex) { 12465 bool IsNested = NextToCheckIndex > 0; 12466 for (const FieldDecl *Field : 12467 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12468 // First, check every field for constness. 12469 QualType FieldTy = Field->getType(); 12470 if (FieldTy.isConstQualified()) { 12471 if (!DiagnosticEmitted) { 12472 S.Diag(Loc, diag::err_typecheck_assign_const) 12473 << Range << NestedConstMember << OEK << VD 12474 << IsNested << Field; 12475 DiagnosticEmitted = true; 12476 } 12477 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12478 << NestedConstMember << IsNested << Field 12479 << FieldTy << Field->getSourceRange(); 12480 } 12481 12482 // Then we append it to the list to check next in order. 12483 FieldTy = FieldTy.getCanonicalType(); 12484 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12485 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12486 RecordTypeList.push_back(FieldRecTy); 12487 } 12488 } 12489 ++NextToCheckIndex; 12490 } 12491 } 12492 12493 /// Emit an error for the case where a record we are trying to assign to has a 12494 /// const-qualified field somewhere in its hierarchy. 12495 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12496 SourceLocation Loc) { 12497 QualType Ty = E->getType(); 12498 assert(Ty->isRecordType() && "lvalue was not record?"); 12499 SourceRange Range = E->getSourceRange(); 12500 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12501 bool DiagEmitted = false; 12502 12503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12504 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12505 Range, OEK_Member, DiagEmitted); 12506 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12507 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12508 Range, OEK_Variable, DiagEmitted); 12509 else 12510 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12511 Range, OEK_LValue, DiagEmitted); 12512 if (!DiagEmitted) 12513 DiagnoseConstAssignment(S, E, Loc); 12514 } 12515 12516 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12517 /// emit an error and return true. If so, return false. 12518 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12519 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12520 12521 S.CheckShadowingDeclModification(E, Loc); 12522 12523 SourceLocation OrigLoc = Loc; 12524 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12525 &Loc); 12526 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12527 IsLV = Expr::MLV_InvalidMessageExpression; 12528 if (IsLV == Expr::MLV_Valid) 12529 return false; 12530 12531 unsigned DiagID = 0; 12532 bool NeedType = false; 12533 switch (IsLV) { // C99 6.5.16p2 12534 case Expr::MLV_ConstQualified: 12535 // Use a specialized diagnostic when we're assigning to an object 12536 // from an enclosing function or block. 12537 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12538 if (NCCK == NCCK_Block) 12539 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12540 else 12541 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12542 break; 12543 } 12544 12545 // In ARC, use some specialized diagnostics for occasions where we 12546 // infer 'const'. These are always pseudo-strong variables. 12547 if (S.getLangOpts().ObjCAutoRefCount) { 12548 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12549 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12550 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12551 12552 // Use the normal diagnostic if it's pseudo-__strong but the 12553 // user actually wrote 'const'. 12554 if (var->isARCPseudoStrong() && 12555 (!var->getTypeSourceInfo() || 12556 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12557 // There are three pseudo-strong cases: 12558 // - self 12559 ObjCMethodDecl *method = S.getCurMethodDecl(); 12560 if (method && var == method->getSelfDecl()) { 12561 DiagID = method->isClassMethod() 12562 ? diag::err_typecheck_arc_assign_self_class_method 12563 : diag::err_typecheck_arc_assign_self; 12564 12565 // - Objective-C externally_retained attribute. 12566 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12567 isa<ParmVarDecl>(var)) { 12568 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12569 12570 // - fast enumeration variables 12571 } else { 12572 DiagID = diag::err_typecheck_arr_assign_enumeration; 12573 } 12574 12575 SourceRange Assign; 12576 if (Loc != OrigLoc) 12577 Assign = SourceRange(OrigLoc, OrigLoc); 12578 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12579 // We need to preserve the AST regardless, so migration tool 12580 // can do its job. 12581 return false; 12582 } 12583 } 12584 } 12585 12586 // If none of the special cases above are triggered, then this is a 12587 // simple const assignment. 12588 if (DiagID == 0) { 12589 DiagnoseConstAssignment(S, E, Loc); 12590 return true; 12591 } 12592 12593 break; 12594 case Expr::MLV_ConstAddrSpace: 12595 DiagnoseConstAssignment(S, E, Loc); 12596 return true; 12597 case Expr::MLV_ConstQualifiedField: 12598 DiagnoseRecursiveConstFields(S, E, Loc); 12599 return true; 12600 case Expr::MLV_ArrayType: 12601 case Expr::MLV_ArrayTemporary: 12602 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12603 NeedType = true; 12604 break; 12605 case Expr::MLV_NotObjectType: 12606 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12607 NeedType = true; 12608 break; 12609 case Expr::MLV_LValueCast: 12610 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12611 break; 12612 case Expr::MLV_Valid: 12613 llvm_unreachable("did not take early return for MLV_Valid"); 12614 case Expr::MLV_InvalidExpression: 12615 case Expr::MLV_MemberFunction: 12616 case Expr::MLV_ClassTemporary: 12617 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12618 break; 12619 case Expr::MLV_IncompleteType: 12620 case Expr::MLV_IncompleteVoidType: 12621 return S.RequireCompleteType(Loc, E->getType(), 12622 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12623 case Expr::MLV_DuplicateVectorComponents: 12624 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12625 break; 12626 case Expr::MLV_NoSetterProperty: 12627 llvm_unreachable("readonly properties should be processed differently"); 12628 case Expr::MLV_InvalidMessageExpression: 12629 DiagID = diag::err_readonly_message_assignment; 12630 break; 12631 case Expr::MLV_SubObjCPropertySetting: 12632 DiagID = diag::err_no_subobject_property_setting; 12633 break; 12634 } 12635 12636 SourceRange Assign; 12637 if (Loc != OrigLoc) 12638 Assign = SourceRange(OrigLoc, OrigLoc); 12639 if (NeedType) 12640 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12641 else 12642 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12643 return true; 12644 } 12645 12646 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12647 SourceLocation Loc, 12648 Sema &Sema) { 12649 if (Sema.inTemplateInstantiation()) 12650 return; 12651 if (Sema.isUnevaluatedContext()) 12652 return; 12653 if (Loc.isInvalid() || Loc.isMacroID()) 12654 return; 12655 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12656 return; 12657 12658 // C / C++ fields 12659 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12660 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12661 if (ML && MR) { 12662 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12663 return; 12664 const ValueDecl *LHSDecl = 12665 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12666 const ValueDecl *RHSDecl = 12667 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12668 if (LHSDecl != RHSDecl) 12669 return; 12670 if (LHSDecl->getType().isVolatileQualified()) 12671 return; 12672 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12673 if (RefTy->getPointeeType().isVolatileQualified()) 12674 return; 12675 12676 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12677 } 12678 12679 // Objective-C instance variables 12680 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12681 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12682 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12683 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12684 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12685 if (RL && RR && RL->getDecl() == RR->getDecl()) 12686 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12687 } 12688 } 12689 12690 // C99 6.5.16.1 12691 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12692 SourceLocation Loc, 12693 QualType CompoundType) { 12694 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12695 12696 // Verify that LHS is a modifiable lvalue, and emit error if not. 12697 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12698 return QualType(); 12699 12700 QualType LHSType = LHSExpr->getType(); 12701 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12702 CompoundType; 12703 // OpenCL v1.2 s6.1.1.1 p2: 12704 // The half data type can only be used to declare a pointer to a buffer that 12705 // contains half values 12706 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12707 LHSType->isHalfType()) { 12708 Diag(Loc, diag::err_opencl_half_load_store) << 1 12709 << LHSType.getUnqualifiedType(); 12710 return QualType(); 12711 } 12712 12713 AssignConvertType ConvTy; 12714 if (CompoundType.isNull()) { 12715 Expr *RHSCheck = RHS.get(); 12716 12717 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12718 12719 QualType LHSTy(LHSType); 12720 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12721 if (RHS.isInvalid()) 12722 return QualType(); 12723 // Special case of NSObject attributes on c-style pointer types. 12724 if (ConvTy == IncompatiblePointer && 12725 ((Context.isObjCNSObjectType(LHSType) && 12726 RHSType->isObjCObjectPointerType()) || 12727 (Context.isObjCNSObjectType(RHSType) && 12728 LHSType->isObjCObjectPointerType()))) 12729 ConvTy = Compatible; 12730 12731 if (ConvTy == Compatible && 12732 LHSType->isObjCObjectType()) 12733 Diag(Loc, diag::err_objc_object_assignment) 12734 << LHSType; 12735 12736 // If the RHS is a unary plus or minus, check to see if they = and + are 12737 // right next to each other. If so, the user may have typo'd "x =+ 4" 12738 // instead of "x += 4". 12739 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12740 RHSCheck = ICE->getSubExpr(); 12741 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12742 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12743 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12744 // Only if the two operators are exactly adjacent. 12745 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12746 // And there is a space or other character before the subexpr of the 12747 // unary +/-. We don't want to warn on "x=-1". 12748 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12749 UO->getSubExpr()->getBeginLoc().isFileID()) { 12750 Diag(Loc, diag::warn_not_compound_assign) 12751 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12752 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12753 } 12754 } 12755 12756 if (ConvTy == Compatible) { 12757 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12758 // Warn about retain cycles where a block captures the LHS, but 12759 // not if the LHS is a simple variable into which the block is 12760 // being stored...unless that variable can be captured by reference! 12761 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12762 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12763 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12764 checkRetainCycles(LHSExpr, RHS.get()); 12765 } 12766 12767 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12768 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12769 // It is safe to assign a weak reference into a strong variable. 12770 // Although this code can still have problems: 12771 // id x = self.weakProp; 12772 // id y = self.weakProp; 12773 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12774 // paths through the function. This should be revisited if 12775 // -Wrepeated-use-of-weak is made flow-sensitive. 12776 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12777 // variable, which will be valid for the current autorelease scope. 12778 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12779 RHS.get()->getBeginLoc())) 12780 getCurFunction()->markSafeWeakUse(RHS.get()); 12781 12782 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12783 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12784 } 12785 } 12786 } else { 12787 // Compound assignment "x += y" 12788 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12789 } 12790 12791 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12792 RHS.get(), AA_Assigning)) 12793 return QualType(); 12794 12795 CheckForNullPointerDereference(*this, LHSExpr); 12796 12797 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12798 if (CompoundType.isNull()) { 12799 // C++2a [expr.ass]p5: 12800 // A simple-assignment whose left operand is of a volatile-qualified 12801 // type is deprecated unless the assignment is either a discarded-value 12802 // expression or an unevaluated operand 12803 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12804 } else { 12805 // C++2a [expr.ass]p6: 12806 // [Compound-assignment] expressions are deprecated if E1 has 12807 // volatile-qualified type 12808 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12809 } 12810 } 12811 12812 // C99 6.5.16p3: The type of an assignment expression is the type of the 12813 // left operand unless the left operand has qualified type, in which case 12814 // it is the unqualified version of the type of the left operand. 12815 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12816 // is converted to the type of the assignment expression (above). 12817 // C++ 5.17p1: the type of the assignment expression is that of its left 12818 // operand. 12819 return (getLangOpts().CPlusPlus 12820 ? LHSType : LHSType.getUnqualifiedType()); 12821 } 12822 12823 // Only ignore explicit casts to void. 12824 static bool IgnoreCommaOperand(const Expr *E) { 12825 E = E->IgnoreParens(); 12826 12827 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12828 if (CE->getCastKind() == CK_ToVoid) { 12829 return true; 12830 } 12831 12832 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12833 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12834 CE->getSubExpr()->getType()->isDependentType()) { 12835 return true; 12836 } 12837 } 12838 12839 return false; 12840 } 12841 12842 // Look for instances where it is likely the comma operator is confused with 12843 // another operator. There is a whitelist of acceptable expressions for the 12844 // left hand side of the comma operator, otherwise emit a warning. 12845 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12846 // No warnings in macros 12847 if (Loc.isMacroID()) 12848 return; 12849 12850 // Don't warn in template instantiations. 12851 if (inTemplateInstantiation()) 12852 return; 12853 12854 // Scope isn't fine-grained enough to whitelist the specific cases, so 12855 // instead, skip more than needed, then call back into here with the 12856 // CommaVisitor in SemaStmt.cpp. 12857 // The whitelisted locations are the initialization and increment portions 12858 // of a for loop. The additional checks are on the condition of 12859 // if statements, do/while loops, and for loops. 12860 // Differences in scope flags for C89 mode requires the extra logic. 12861 const unsigned ForIncrementFlags = 12862 getLangOpts().C99 || getLangOpts().CPlusPlus 12863 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12864 : Scope::ContinueScope | Scope::BreakScope; 12865 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12866 const unsigned ScopeFlags = getCurScope()->getFlags(); 12867 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12868 (ScopeFlags & ForInitFlags) == ForInitFlags) 12869 return; 12870 12871 // If there are multiple comma operators used together, get the RHS of the 12872 // of the comma operator as the LHS. 12873 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12874 if (BO->getOpcode() != BO_Comma) 12875 break; 12876 LHS = BO->getRHS(); 12877 } 12878 12879 // Only allow some expressions on LHS to not warn. 12880 if (IgnoreCommaOperand(LHS)) 12881 return; 12882 12883 Diag(Loc, diag::warn_comma_operator); 12884 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12885 << LHS->getSourceRange() 12886 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12887 LangOpts.CPlusPlus ? "static_cast<void>(" 12888 : "(void)(") 12889 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12890 ")"); 12891 } 12892 12893 // C99 6.5.17 12894 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12895 SourceLocation Loc) { 12896 LHS = S.CheckPlaceholderExpr(LHS.get()); 12897 RHS = S.CheckPlaceholderExpr(RHS.get()); 12898 if (LHS.isInvalid() || RHS.isInvalid()) 12899 return QualType(); 12900 12901 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12902 // operands, but not unary promotions. 12903 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12904 12905 // So we treat the LHS as a ignored value, and in C++ we allow the 12906 // containing site to determine what should be done with the RHS. 12907 LHS = S.IgnoredValueConversions(LHS.get()); 12908 if (LHS.isInvalid()) 12909 return QualType(); 12910 12911 S.DiagnoseUnusedExprResult(LHS.get()); 12912 12913 if (!S.getLangOpts().CPlusPlus) { 12914 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12915 if (RHS.isInvalid()) 12916 return QualType(); 12917 if (!RHS.get()->getType()->isVoidType()) 12918 S.RequireCompleteType(Loc, RHS.get()->getType(), 12919 diag::err_incomplete_type); 12920 } 12921 12922 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12923 S.DiagnoseCommaOperator(LHS.get(), Loc); 12924 12925 return RHS.get()->getType(); 12926 } 12927 12928 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12929 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12930 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12931 ExprValueKind &VK, 12932 ExprObjectKind &OK, 12933 SourceLocation OpLoc, 12934 bool IsInc, bool IsPrefix) { 12935 if (Op->isTypeDependent()) 12936 return S.Context.DependentTy; 12937 12938 QualType ResType = Op->getType(); 12939 // Atomic types can be used for increment / decrement where the non-atomic 12940 // versions can, so ignore the _Atomic() specifier for the purpose of 12941 // checking. 12942 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12943 ResType = ResAtomicType->getValueType(); 12944 12945 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12946 12947 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12948 // Decrement of bool is not allowed. 12949 if (!IsInc) { 12950 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12951 return QualType(); 12952 } 12953 // Increment of bool sets it to true, but is deprecated. 12954 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12955 : diag::warn_increment_bool) 12956 << Op->getSourceRange(); 12957 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12958 // Error on enum increments and decrements in C++ mode 12959 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12960 return QualType(); 12961 } else if (ResType->isRealType()) { 12962 // OK! 12963 } else if (ResType->isPointerType()) { 12964 // C99 6.5.2.4p2, 6.5.6p2 12965 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12966 return QualType(); 12967 } else if (ResType->isObjCObjectPointerType()) { 12968 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12969 // Otherwise, we just need a complete type. 12970 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12971 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12972 return QualType(); 12973 } else if (ResType->isAnyComplexType()) { 12974 // C99 does not support ++/-- on complex types, we allow as an extension. 12975 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12976 << ResType << Op->getSourceRange(); 12977 } else if (ResType->isPlaceholderType()) { 12978 ExprResult PR = S.CheckPlaceholderExpr(Op); 12979 if (PR.isInvalid()) return QualType(); 12980 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12981 IsInc, IsPrefix); 12982 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12983 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12984 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12985 (ResType->castAs<VectorType>()->getVectorKind() != 12986 VectorType::AltiVecBool)) { 12987 // The z vector extensions allow ++ and -- for non-bool vectors. 12988 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12989 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12990 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12991 } else { 12992 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12993 << ResType << int(IsInc) << Op->getSourceRange(); 12994 return QualType(); 12995 } 12996 // At this point, we know we have a real, complex or pointer type. 12997 // Now make sure the operand is a modifiable lvalue. 12998 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12999 return QualType(); 13000 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13001 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13002 // An operand with volatile-qualified type is deprecated 13003 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13004 << IsInc << ResType; 13005 } 13006 // In C++, a prefix increment is the same type as the operand. Otherwise 13007 // (in C or with postfix), the increment is the unqualified type of the 13008 // operand. 13009 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13010 VK = VK_LValue; 13011 OK = Op->getObjectKind(); 13012 return ResType; 13013 } else { 13014 VK = VK_RValue; 13015 return ResType.getUnqualifiedType(); 13016 } 13017 } 13018 13019 13020 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13021 /// This routine allows us to typecheck complex/recursive expressions 13022 /// where the declaration is needed for type checking. We only need to 13023 /// handle cases when the expression references a function designator 13024 /// or is an lvalue. Here are some examples: 13025 /// - &(x) => x 13026 /// - &*****f => f for f a function designator. 13027 /// - &s.xx => s 13028 /// - &s.zz[1].yy -> s, if zz is an array 13029 /// - *(x + 1) -> x, if x is an array 13030 /// - &"123"[2] -> 0 13031 /// - & __real__ x -> x 13032 /// 13033 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13034 /// members. 13035 static ValueDecl *getPrimaryDecl(Expr *E) { 13036 switch (E->getStmtClass()) { 13037 case Stmt::DeclRefExprClass: 13038 return cast<DeclRefExpr>(E)->getDecl(); 13039 case Stmt::MemberExprClass: 13040 // If this is an arrow operator, the address is an offset from 13041 // the base's value, so the object the base refers to is 13042 // irrelevant. 13043 if (cast<MemberExpr>(E)->isArrow()) 13044 return nullptr; 13045 // Otherwise, the expression refers to a part of the base 13046 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13047 case Stmt::ArraySubscriptExprClass: { 13048 // FIXME: This code shouldn't be necessary! We should catch the implicit 13049 // promotion of register arrays earlier. 13050 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13051 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13052 if (ICE->getSubExpr()->getType()->isArrayType()) 13053 return getPrimaryDecl(ICE->getSubExpr()); 13054 } 13055 return nullptr; 13056 } 13057 case Stmt::UnaryOperatorClass: { 13058 UnaryOperator *UO = cast<UnaryOperator>(E); 13059 13060 switch(UO->getOpcode()) { 13061 case UO_Real: 13062 case UO_Imag: 13063 case UO_Extension: 13064 return getPrimaryDecl(UO->getSubExpr()); 13065 default: 13066 return nullptr; 13067 } 13068 } 13069 case Stmt::ParenExprClass: 13070 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13071 case Stmt::ImplicitCastExprClass: 13072 // If the result of an implicit cast is an l-value, we care about 13073 // the sub-expression; otherwise, the result here doesn't matter. 13074 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13075 case Stmt::CXXUuidofExprClass: 13076 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13077 default: 13078 return nullptr; 13079 } 13080 } 13081 13082 namespace { 13083 enum { 13084 AO_Bit_Field = 0, 13085 AO_Vector_Element = 1, 13086 AO_Property_Expansion = 2, 13087 AO_Register_Variable = 3, 13088 AO_Matrix_Element = 4, 13089 AO_No_Error = 5 13090 }; 13091 } 13092 /// Diagnose invalid operand for address of operations. 13093 /// 13094 /// \param Type The type of operand which cannot have its address taken. 13095 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13096 Expr *E, unsigned Type) { 13097 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13098 } 13099 13100 /// CheckAddressOfOperand - The operand of & must be either a function 13101 /// designator or an lvalue designating an object. If it is an lvalue, the 13102 /// object cannot be declared with storage class register or be a bit field. 13103 /// Note: The usual conversions are *not* applied to the operand of the & 13104 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13105 /// In C++, the operand might be an overloaded function name, in which case 13106 /// we allow the '&' but retain the overloaded-function type. 13107 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13108 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13109 if (PTy->getKind() == BuiltinType::Overload) { 13110 Expr *E = OrigOp.get()->IgnoreParens(); 13111 if (!isa<OverloadExpr>(E)) { 13112 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13113 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13114 << OrigOp.get()->getSourceRange(); 13115 return QualType(); 13116 } 13117 13118 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13119 if (isa<UnresolvedMemberExpr>(Ovl)) 13120 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13121 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13122 << OrigOp.get()->getSourceRange(); 13123 return QualType(); 13124 } 13125 13126 return Context.OverloadTy; 13127 } 13128 13129 if (PTy->getKind() == BuiltinType::UnknownAny) 13130 return Context.UnknownAnyTy; 13131 13132 if (PTy->getKind() == BuiltinType::BoundMember) { 13133 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13134 << OrigOp.get()->getSourceRange(); 13135 return QualType(); 13136 } 13137 13138 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13139 if (OrigOp.isInvalid()) return QualType(); 13140 } 13141 13142 if (OrigOp.get()->isTypeDependent()) 13143 return Context.DependentTy; 13144 13145 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13146 13147 // Make sure to ignore parentheses in subsequent checks 13148 Expr *op = OrigOp.get()->IgnoreParens(); 13149 13150 // In OpenCL captures for blocks called as lambda functions 13151 // are located in the private address space. Blocks used in 13152 // enqueue_kernel can be located in a different address space 13153 // depending on a vendor implementation. Thus preventing 13154 // taking an address of the capture to avoid invalid AS casts. 13155 if (LangOpts.OpenCL) { 13156 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13157 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13158 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13159 return QualType(); 13160 } 13161 } 13162 13163 if (getLangOpts().C99) { 13164 // Implement C99-only parts of addressof rules. 13165 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13166 if (uOp->getOpcode() == UO_Deref) 13167 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13168 // (assuming the deref expression is valid). 13169 return uOp->getSubExpr()->getType(); 13170 } 13171 // Technically, there should be a check for array subscript 13172 // expressions here, but the result of one is always an lvalue anyway. 13173 } 13174 ValueDecl *dcl = getPrimaryDecl(op); 13175 13176 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13177 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13178 op->getBeginLoc())) 13179 return QualType(); 13180 13181 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13182 unsigned AddressOfError = AO_No_Error; 13183 13184 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13185 bool sfinae = (bool)isSFINAEContext(); 13186 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13187 : diag::ext_typecheck_addrof_temporary) 13188 << op->getType() << op->getSourceRange(); 13189 if (sfinae) 13190 return QualType(); 13191 // Materialize the temporary as an lvalue so that we can take its address. 13192 OrigOp = op = 13193 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13194 } else if (isa<ObjCSelectorExpr>(op)) { 13195 return Context.getPointerType(op->getType()); 13196 } else if (lval == Expr::LV_MemberFunction) { 13197 // If it's an instance method, make a member pointer. 13198 // The expression must have exactly the form &A::foo. 13199 13200 // If the underlying expression isn't a decl ref, give up. 13201 if (!isa<DeclRefExpr>(op)) { 13202 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13203 << OrigOp.get()->getSourceRange(); 13204 return QualType(); 13205 } 13206 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13207 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13208 13209 // The id-expression was parenthesized. 13210 if (OrigOp.get() != DRE) { 13211 Diag(OpLoc, diag::err_parens_pointer_member_function) 13212 << OrigOp.get()->getSourceRange(); 13213 13214 // The method was named without a qualifier. 13215 } else if (!DRE->getQualifier()) { 13216 if (MD->getParent()->getName().empty()) 13217 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13218 << op->getSourceRange(); 13219 else { 13220 SmallString<32> Str; 13221 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13222 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13223 << op->getSourceRange() 13224 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13225 } 13226 } 13227 13228 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13229 if (isa<CXXDestructorDecl>(MD)) 13230 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13231 13232 QualType MPTy = Context.getMemberPointerType( 13233 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13234 // Under the MS ABI, lock down the inheritance model now. 13235 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13236 (void)isCompleteType(OpLoc, MPTy); 13237 return MPTy; 13238 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13239 // C99 6.5.3.2p1 13240 // The operand must be either an l-value or a function designator 13241 if (!op->getType()->isFunctionType()) { 13242 // Use a special diagnostic for loads from property references. 13243 if (isa<PseudoObjectExpr>(op)) { 13244 AddressOfError = AO_Property_Expansion; 13245 } else { 13246 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13247 << op->getType() << op->getSourceRange(); 13248 return QualType(); 13249 } 13250 } 13251 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13252 // The operand cannot be a bit-field 13253 AddressOfError = AO_Bit_Field; 13254 } else if (op->getObjectKind() == OK_VectorComponent) { 13255 // The operand cannot be an element of a vector 13256 AddressOfError = AO_Vector_Element; 13257 } else if (op->getObjectKind() == OK_MatrixComponent) { 13258 // The operand cannot be an element of a matrix. 13259 AddressOfError = AO_Matrix_Element; 13260 } else if (dcl) { // C99 6.5.3.2p1 13261 // We have an lvalue with a decl. Make sure the decl is not declared 13262 // with the register storage-class specifier. 13263 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13264 // in C++ it is not error to take address of a register 13265 // variable (c++03 7.1.1P3) 13266 if (vd->getStorageClass() == SC_Register && 13267 !getLangOpts().CPlusPlus) { 13268 AddressOfError = AO_Register_Variable; 13269 } 13270 } else if (isa<MSPropertyDecl>(dcl)) { 13271 AddressOfError = AO_Property_Expansion; 13272 } else if (isa<FunctionTemplateDecl>(dcl)) { 13273 return Context.OverloadTy; 13274 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13275 // Okay: we can take the address of a field. 13276 // Could be a pointer to member, though, if there is an explicit 13277 // scope qualifier for the class. 13278 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13279 DeclContext *Ctx = dcl->getDeclContext(); 13280 if (Ctx && Ctx->isRecord()) { 13281 if (dcl->getType()->isReferenceType()) { 13282 Diag(OpLoc, 13283 diag::err_cannot_form_pointer_to_member_of_reference_type) 13284 << dcl->getDeclName() << dcl->getType(); 13285 return QualType(); 13286 } 13287 13288 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13289 Ctx = Ctx->getParent(); 13290 13291 QualType MPTy = Context.getMemberPointerType( 13292 op->getType(), 13293 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13294 // Under the MS ABI, lock down the inheritance model now. 13295 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13296 (void)isCompleteType(OpLoc, MPTy); 13297 return MPTy; 13298 } 13299 } 13300 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13301 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13302 llvm_unreachable("Unknown/unexpected decl type"); 13303 } 13304 13305 if (AddressOfError != AO_No_Error) { 13306 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13307 return QualType(); 13308 } 13309 13310 if (lval == Expr::LV_IncompleteVoidType) { 13311 // Taking the address of a void variable is technically illegal, but we 13312 // allow it in cases which are otherwise valid. 13313 // Example: "extern void x; void* y = &x;". 13314 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13315 } 13316 13317 // If the operand has type "type", the result has type "pointer to type". 13318 if (op->getType()->isObjCObjectType()) 13319 return Context.getObjCObjectPointerType(op->getType()); 13320 13321 CheckAddressOfPackedMember(op); 13322 13323 return Context.getPointerType(op->getType()); 13324 } 13325 13326 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13327 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13328 if (!DRE) 13329 return; 13330 const Decl *D = DRE->getDecl(); 13331 if (!D) 13332 return; 13333 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13334 if (!Param) 13335 return; 13336 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13337 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13338 return; 13339 if (FunctionScopeInfo *FD = S.getCurFunction()) 13340 if (!FD->ModifiedNonNullParams.count(Param)) 13341 FD->ModifiedNonNullParams.insert(Param); 13342 } 13343 13344 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13345 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13346 SourceLocation OpLoc) { 13347 if (Op->isTypeDependent()) 13348 return S.Context.DependentTy; 13349 13350 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13351 if (ConvResult.isInvalid()) 13352 return QualType(); 13353 Op = ConvResult.get(); 13354 QualType OpTy = Op->getType(); 13355 QualType Result; 13356 13357 if (isa<CXXReinterpretCastExpr>(Op)) { 13358 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13359 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13360 Op->getSourceRange()); 13361 } 13362 13363 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13364 { 13365 Result = PT->getPointeeType(); 13366 } 13367 else if (const ObjCObjectPointerType *OPT = 13368 OpTy->getAs<ObjCObjectPointerType>()) 13369 Result = OPT->getPointeeType(); 13370 else { 13371 ExprResult PR = S.CheckPlaceholderExpr(Op); 13372 if (PR.isInvalid()) return QualType(); 13373 if (PR.get() != Op) 13374 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13375 } 13376 13377 if (Result.isNull()) { 13378 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13379 << OpTy << Op->getSourceRange(); 13380 return QualType(); 13381 } 13382 13383 // Note that per both C89 and C99, indirection is always legal, even if Result 13384 // is an incomplete type or void. It would be possible to warn about 13385 // dereferencing a void pointer, but it's completely well-defined, and such a 13386 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13387 // for pointers to 'void' but is fine for any other pointer type: 13388 // 13389 // C++ [expr.unary.op]p1: 13390 // [...] the expression to which [the unary * operator] is applied shall 13391 // be a pointer to an object type, or a pointer to a function type 13392 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13393 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13394 << OpTy << Op->getSourceRange(); 13395 13396 // Dereferences are usually l-values... 13397 VK = VK_LValue; 13398 13399 // ...except that certain expressions are never l-values in C. 13400 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13401 VK = VK_RValue; 13402 13403 return Result; 13404 } 13405 13406 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13407 BinaryOperatorKind Opc; 13408 switch (Kind) { 13409 default: llvm_unreachable("Unknown binop!"); 13410 case tok::periodstar: Opc = BO_PtrMemD; break; 13411 case tok::arrowstar: Opc = BO_PtrMemI; break; 13412 case tok::star: Opc = BO_Mul; break; 13413 case tok::slash: Opc = BO_Div; break; 13414 case tok::percent: Opc = BO_Rem; break; 13415 case tok::plus: Opc = BO_Add; break; 13416 case tok::minus: Opc = BO_Sub; break; 13417 case tok::lessless: Opc = BO_Shl; break; 13418 case tok::greatergreater: Opc = BO_Shr; break; 13419 case tok::lessequal: Opc = BO_LE; break; 13420 case tok::less: Opc = BO_LT; break; 13421 case tok::greaterequal: Opc = BO_GE; break; 13422 case tok::greater: Opc = BO_GT; break; 13423 case tok::exclaimequal: Opc = BO_NE; break; 13424 case tok::equalequal: Opc = BO_EQ; break; 13425 case tok::spaceship: Opc = BO_Cmp; break; 13426 case tok::amp: Opc = BO_And; break; 13427 case tok::caret: Opc = BO_Xor; break; 13428 case tok::pipe: Opc = BO_Or; break; 13429 case tok::ampamp: Opc = BO_LAnd; break; 13430 case tok::pipepipe: Opc = BO_LOr; break; 13431 case tok::equal: Opc = BO_Assign; break; 13432 case tok::starequal: Opc = BO_MulAssign; break; 13433 case tok::slashequal: Opc = BO_DivAssign; break; 13434 case tok::percentequal: Opc = BO_RemAssign; break; 13435 case tok::plusequal: Opc = BO_AddAssign; break; 13436 case tok::minusequal: Opc = BO_SubAssign; break; 13437 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13438 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13439 case tok::ampequal: Opc = BO_AndAssign; break; 13440 case tok::caretequal: Opc = BO_XorAssign; break; 13441 case tok::pipeequal: Opc = BO_OrAssign; break; 13442 case tok::comma: Opc = BO_Comma; break; 13443 } 13444 return Opc; 13445 } 13446 13447 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13448 tok::TokenKind Kind) { 13449 UnaryOperatorKind Opc; 13450 switch (Kind) { 13451 default: llvm_unreachable("Unknown unary op!"); 13452 case tok::plusplus: Opc = UO_PreInc; break; 13453 case tok::minusminus: Opc = UO_PreDec; break; 13454 case tok::amp: Opc = UO_AddrOf; break; 13455 case tok::star: Opc = UO_Deref; break; 13456 case tok::plus: Opc = UO_Plus; break; 13457 case tok::minus: Opc = UO_Minus; break; 13458 case tok::tilde: Opc = UO_Not; break; 13459 case tok::exclaim: Opc = UO_LNot; break; 13460 case tok::kw___real: Opc = UO_Real; break; 13461 case tok::kw___imag: Opc = UO_Imag; break; 13462 case tok::kw___extension__: Opc = UO_Extension; break; 13463 } 13464 return Opc; 13465 } 13466 13467 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13468 /// This warning suppressed in the event of macro expansions. 13469 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13470 SourceLocation OpLoc, bool IsBuiltin) { 13471 if (S.inTemplateInstantiation()) 13472 return; 13473 if (S.isUnevaluatedContext()) 13474 return; 13475 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13476 return; 13477 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13478 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13479 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13480 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13481 if (!LHSDeclRef || !RHSDeclRef || 13482 LHSDeclRef->getLocation().isMacroID() || 13483 RHSDeclRef->getLocation().isMacroID()) 13484 return; 13485 const ValueDecl *LHSDecl = 13486 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13487 const ValueDecl *RHSDecl = 13488 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13489 if (LHSDecl != RHSDecl) 13490 return; 13491 if (LHSDecl->getType().isVolatileQualified()) 13492 return; 13493 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13494 if (RefTy->getPointeeType().isVolatileQualified()) 13495 return; 13496 13497 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13498 : diag::warn_self_assignment_overloaded) 13499 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13500 << RHSExpr->getSourceRange(); 13501 } 13502 13503 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13504 /// is usually indicative of introspection within the Objective-C pointer. 13505 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13506 SourceLocation OpLoc) { 13507 if (!S.getLangOpts().ObjC) 13508 return; 13509 13510 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13511 const Expr *LHS = L.get(); 13512 const Expr *RHS = R.get(); 13513 13514 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13515 ObjCPointerExpr = LHS; 13516 OtherExpr = RHS; 13517 } 13518 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13519 ObjCPointerExpr = RHS; 13520 OtherExpr = LHS; 13521 } 13522 13523 // This warning is deliberately made very specific to reduce false 13524 // positives with logic that uses '&' for hashing. This logic mainly 13525 // looks for code trying to introspect into tagged pointers, which 13526 // code should generally never do. 13527 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13528 unsigned Diag = diag::warn_objc_pointer_masking; 13529 // Determine if we are introspecting the result of performSelectorXXX. 13530 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13531 // Special case messages to -performSelector and friends, which 13532 // can return non-pointer values boxed in a pointer value. 13533 // Some clients may wish to silence warnings in this subcase. 13534 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13535 Selector S = ME->getSelector(); 13536 StringRef SelArg0 = S.getNameForSlot(0); 13537 if (SelArg0.startswith("performSelector")) 13538 Diag = diag::warn_objc_pointer_masking_performSelector; 13539 } 13540 13541 S.Diag(OpLoc, Diag) 13542 << ObjCPointerExpr->getSourceRange(); 13543 } 13544 } 13545 13546 static NamedDecl *getDeclFromExpr(Expr *E) { 13547 if (!E) 13548 return nullptr; 13549 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13550 return DRE->getDecl(); 13551 if (auto *ME = dyn_cast<MemberExpr>(E)) 13552 return ME->getMemberDecl(); 13553 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13554 return IRE->getDecl(); 13555 return nullptr; 13556 } 13557 13558 // This helper function promotes a binary operator's operands (which are of a 13559 // half vector type) to a vector of floats and then truncates the result to 13560 // a vector of either half or short. 13561 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13562 BinaryOperatorKind Opc, QualType ResultTy, 13563 ExprValueKind VK, ExprObjectKind OK, 13564 bool IsCompAssign, SourceLocation OpLoc, 13565 FPOptions FPFeatures) { 13566 auto &Context = S.getASTContext(); 13567 assert((isVector(ResultTy, Context.HalfTy) || 13568 isVector(ResultTy, Context.ShortTy)) && 13569 "Result must be a vector of half or short"); 13570 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13571 isVector(RHS.get()->getType(), Context.HalfTy) && 13572 "both operands expected to be a half vector"); 13573 13574 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13575 QualType BinOpResTy = RHS.get()->getType(); 13576 13577 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13578 // change BinOpResTy to a vector of ints. 13579 if (isVector(ResultTy, Context.ShortTy)) 13580 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13581 13582 if (IsCompAssign) 13583 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13584 ResultTy, VK, OK, OpLoc, FPFeatures, 13585 BinOpResTy, BinOpResTy); 13586 13587 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13588 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13589 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13590 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13591 } 13592 13593 static std::pair<ExprResult, ExprResult> 13594 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13595 Expr *RHSExpr) { 13596 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13597 if (!S.getLangOpts().CPlusPlus) { 13598 // C cannot handle TypoExpr nodes on either side of a binop because it 13599 // doesn't handle dependent types properly, so make sure any TypoExprs have 13600 // been dealt with before checking the operands. 13601 LHS = S.CorrectDelayedTyposInExpr(LHS); 13602 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13603 if (Opc != BO_Assign) 13604 return ExprResult(E); 13605 // Avoid correcting the RHS to the same Expr as the LHS. 13606 Decl *D = getDeclFromExpr(E); 13607 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13608 }); 13609 } 13610 return std::make_pair(LHS, RHS); 13611 } 13612 13613 /// Returns true if conversion between vectors of halfs and vectors of floats 13614 /// is needed. 13615 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13616 Expr *E0, Expr *E1 = nullptr) { 13617 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13618 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13619 return false; 13620 13621 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13622 QualType Ty = E->IgnoreImplicit()->getType(); 13623 13624 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13625 // to vectors of floats. Although the element type of the vectors is __fp16, 13626 // the vectors shouldn't be treated as storage-only types. See the 13627 // discussion here: https://reviews.llvm.org/rG825235c140e7 13628 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13629 if (VT->getVectorKind() == VectorType::NeonVector) 13630 return false; 13631 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13632 } 13633 return false; 13634 }; 13635 13636 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13637 } 13638 13639 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13640 /// operator @p Opc at location @c TokLoc. This routine only supports 13641 /// built-in operations; ActOnBinOp handles overloaded operators. 13642 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13643 BinaryOperatorKind Opc, 13644 Expr *LHSExpr, Expr *RHSExpr) { 13645 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13646 // The syntax only allows initializer lists on the RHS of assignment, 13647 // so we don't need to worry about accepting invalid code for 13648 // non-assignment operators. 13649 // C++11 5.17p9: 13650 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13651 // of x = {} is x = T(). 13652 InitializationKind Kind = InitializationKind::CreateDirectList( 13653 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13654 InitializedEntity Entity = 13655 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13656 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13657 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13658 if (Init.isInvalid()) 13659 return Init; 13660 RHSExpr = Init.get(); 13661 } 13662 13663 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13664 QualType ResultTy; // Result type of the binary operator. 13665 // The following two variables are used for compound assignment operators 13666 QualType CompLHSTy; // Type of LHS after promotions for computation 13667 QualType CompResultTy; // Type of computation result 13668 ExprValueKind VK = VK_RValue; 13669 ExprObjectKind OK = OK_Ordinary; 13670 bool ConvertHalfVec = false; 13671 13672 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13673 if (!LHS.isUsable() || !RHS.isUsable()) 13674 return ExprError(); 13675 13676 if (getLangOpts().OpenCL) { 13677 QualType LHSTy = LHSExpr->getType(); 13678 QualType RHSTy = RHSExpr->getType(); 13679 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13680 // the ATOMIC_VAR_INIT macro. 13681 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13682 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13683 if (BO_Assign == Opc) 13684 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13685 else 13686 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13687 return ExprError(); 13688 } 13689 13690 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13691 // only with a builtin functions and therefore should be disallowed here. 13692 if (LHSTy->isImageType() || RHSTy->isImageType() || 13693 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13694 LHSTy->isPipeType() || RHSTy->isPipeType() || 13695 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13696 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13697 return ExprError(); 13698 } 13699 } 13700 13701 switch (Opc) { 13702 case BO_Assign: 13703 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13704 if (getLangOpts().CPlusPlus && 13705 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13706 VK = LHS.get()->getValueKind(); 13707 OK = LHS.get()->getObjectKind(); 13708 } 13709 if (!ResultTy.isNull()) { 13710 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13711 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13712 13713 // Avoid copying a block to the heap if the block is assigned to a local 13714 // auto variable that is declared in the same scope as the block. This 13715 // optimization is unsafe if the local variable is declared in an outer 13716 // scope. For example: 13717 // 13718 // BlockTy b; 13719 // { 13720 // b = ^{...}; 13721 // } 13722 // // It is unsafe to invoke the block here if it wasn't copied to the 13723 // // heap. 13724 // b(); 13725 13726 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13727 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13728 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13729 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13730 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13731 13732 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13733 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13734 NTCUC_Assignment, NTCUK_Copy); 13735 } 13736 RecordModifiableNonNullParam(*this, LHS.get()); 13737 break; 13738 case BO_PtrMemD: 13739 case BO_PtrMemI: 13740 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13741 Opc == BO_PtrMemI); 13742 break; 13743 case BO_Mul: 13744 case BO_Div: 13745 ConvertHalfVec = true; 13746 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13747 Opc == BO_Div); 13748 break; 13749 case BO_Rem: 13750 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13751 break; 13752 case BO_Add: 13753 ConvertHalfVec = true; 13754 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13755 break; 13756 case BO_Sub: 13757 ConvertHalfVec = true; 13758 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13759 break; 13760 case BO_Shl: 13761 case BO_Shr: 13762 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13763 break; 13764 case BO_LE: 13765 case BO_LT: 13766 case BO_GE: 13767 case BO_GT: 13768 ConvertHalfVec = true; 13769 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13770 break; 13771 case BO_EQ: 13772 case BO_NE: 13773 ConvertHalfVec = true; 13774 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13775 break; 13776 case BO_Cmp: 13777 ConvertHalfVec = true; 13778 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13779 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13780 break; 13781 case BO_And: 13782 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13783 LLVM_FALLTHROUGH; 13784 case BO_Xor: 13785 case BO_Or: 13786 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13787 break; 13788 case BO_LAnd: 13789 case BO_LOr: 13790 ConvertHalfVec = true; 13791 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13792 break; 13793 case BO_MulAssign: 13794 case BO_DivAssign: 13795 ConvertHalfVec = true; 13796 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13797 Opc == BO_DivAssign); 13798 CompLHSTy = CompResultTy; 13799 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13800 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13801 break; 13802 case BO_RemAssign: 13803 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13804 CompLHSTy = CompResultTy; 13805 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13806 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13807 break; 13808 case BO_AddAssign: 13809 ConvertHalfVec = true; 13810 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13811 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13812 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13813 break; 13814 case BO_SubAssign: 13815 ConvertHalfVec = true; 13816 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13817 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13818 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13819 break; 13820 case BO_ShlAssign: 13821 case BO_ShrAssign: 13822 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13823 CompLHSTy = CompResultTy; 13824 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13825 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13826 break; 13827 case BO_AndAssign: 13828 case BO_OrAssign: // fallthrough 13829 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13830 LLVM_FALLTHROUGH; 13831 case BO_XorAssign: 13832 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13833 CompLHSTy = CompResultTy; 13834 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13835 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13836 break; 13837 case BO_Comma: 13838 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13839 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13840 VK = RHS.get()->getValueKind(); 13841 OK = RHS.get()->getObjectKind(); 13842 } 13843 break; 13844 } 13845 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13846 return ExprError(); 13847 13848 // Some of the binary operations require promoting operands of half vector to 13849 // float vectors and truncating the result back to half vector. For now, we do 13850 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13851 // arm64). 13852 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13853 isVector(LHS.get()->getType(), Context.HalfTy) && 13854 "both sides are half vectors or neither sides are"); 13855 ConvertHalfVec = 13856 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13857 13858 // Check for array bounds violations for both sides of the BinaryOperator 13859 CheckArrayAccess(LHS.get()); 13860 CheckArrayAccess(RHS.get()); 13861 13862 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13863 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13864 &Context.Idents.get("object_setClass"), 13865 SourceLocation(), LookupOrdinaryName); 13866 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13867 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13868 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13869 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13870 "object_setClass(") 13871 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13872 ",") 13873 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13874 } 13875 else 13876 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13877 } 13878 else if (const ObjCIvarRefExpr *OIRE = 13879 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13880 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13881 13882 // Opc is not a compound assignment if CompResultTy is null. 13883 if (CompResultTy.isNull()) { 13884 if (ConvertHalfVec) 13885 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13886 OpLoc, CurFPFeatures); 13887 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 13888 VK, OK, OpLoc, CurFPFeatures); 13889 } 13890 13891 // Handle compound assignments. 13892 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13893 OK_ObjCProperty) { 13894 VK = VK_LValue; 13895 OK = LHS.get()->getObjectKind(); 13896 } 13897 13898 // The LHS is not converted to the result type for fixed-point compound 13899 // assignment as the common type is computed on demand. Reset the CompLHSTy 13900 // to the LHS type we would have gotten after unary conversions. 13901 if (CompResultTy->isFixedPointType()) 13902 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 13903 13904 if (ConvertHalfVec) 13905 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13906 OpLoc, CurFPFeatures); 13907 13908 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13909 ResultTy, VK, OK, OpLoc, CurFPFeatures, 13910 CompLHSTy, CompResultTy); 13911 } 13912 13913 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13914 /// operators are mixed in a way that suggests that the programmer forgot that 13915 /// comparison operators have higher precedence. The most typical example of 13916 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13917 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13918 SourceLocation OpLoc, Expr *LHSExpr, 13919 Expr *RHSExpr) { 13920 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13921 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13922 13923 // Check that one of the sides is a comparison operator and the other isn't. 13924 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13925 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13926 if (isLeftComp == isRightComp) 13927 return; 13928 13929 // Bitwise operations are sometimes used as eager logical ops. 13930 // Don't diagnose this. 13931 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13932 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13933 if (isLeftBitwise || isRightBitwise) 13934 return; 13935 13936 SourceRange DiagRange = isLeftComp 13937 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13938 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13939 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13940 SourceRange ParensRange = 13941 isLeftComp 13942 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13943 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13944 13945 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13946 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13947 SuggestParentheses(Self, OpLoc, 13948 Self.PDiag(diag::note_precedence_silence) << OpStr, 13949 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13950 SuggestParentheses(Self, OpLoc, 13951 Self.PDiag(diag::note_precedence_bitwise_first) 13952 << BinaryOperator::getOpcodeStr(Opc), 13953 ParensRange); 13954 } 13955 13956 /// It accepts a '&&' expr that is inside a '||' one. 13957 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13958 /// in parentheses. 13959 static void 13960 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13961 BinaryOperator *Bop) { 13962 assert(Bop->getOpcode() == BO_LAnd); 13963 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13964 << Bop->getSourceRange() << OpLoc; 13965 SuggestParentheses(Self, Bop->getOperatorLoc(), 13966 Self.PDiag(diag::note_precedence_silence) 13967 << Bop->getOpcodeStr(), 13968 Bop->getSourceRange()); 13969 } 13970 13971 /// Returns true if the given expression can be evaluated as a constant 13972 /// 'true'. 13973 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13974 bool Res; 13975 return !E->isValueDependent() && 13976 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13977 } 13978 13979 /// Returns true if the given expression can be evaluated as a constant 13980 /// 'false'. 13981 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13982 bool Res; 13983 return !E->isValueDependent() && 13984 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13985 } 13986 13987 /// Look for '&&' in the left hand of a '||' expr. 13988 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13989 Expr *LHSExpr, Expr *RHSExpr) { 13990 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13991 if (Bop->getOpcode() == BO_LAnd) { 13992 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13993 if (EvaluatesAsFalse(S, RHSExpr)) 13994 return; 13995 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13996 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13997 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13998 } else if (Bop->getOpcode() == BO_LOr) { 13999 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14000 // If it's "a || b && 1 || c" we didn't warn earlier for 14001 // "a || b && 1", but warn now. 14002 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14003 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14004 } 14005 } 14006 } 14007 } 14008 14009 /// Look for '&&' in the right hand of a '||' expr. 14010 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14011 Expr *LHSExpr, Expr *RHSExpr) { 14012 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14013 if (Bop->getOpcode() == BO_LAnd) { 14014 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14015 if (EvaluatesAsFalse(S, LHSExpr)) 14016 return; 14017 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14018 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14019 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14020 } 14021 } 14022 } 14023 14024 /// Look for bitwise op in the left or right hand of a bitwise op with 14025 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14026 /// the '&' expression in parentheses. 14027 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14028 SourceLocation OpLoc, Expr *SubExpr) { 14029 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14030 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14031 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14032 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14033 << Bop->getSourceRange() << OpLoc; 14034 SuggestParentheses(S, Bop->getOperatorLoc(), 14035 S.PDiag(diag::note_precedence_silence) 14036 << Bop->getOpcodeStr(), 14037 Bop->getSourceRange()); 14038 } 14039 } 14040 } 14041 14042 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14043 Expr *SubExpr, StringRef Shift) { 14044 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14045 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14046 StringRef Op = Bop->getOpcodeStr(); 14047 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14048 << Bop->getSourceRange() << OpLoc << Shift << Op; 14049 SuggestParentheses(S, Bop->getOperatorLoc(), 14050 S.PDiag(diag::note_precedence_silence) << Op, 14051 Bop->getSourceRange()); 14052 } 14053 } 14054 } 14055 14056 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14057 Expr *LHSExpr, Expr *RHSExpr) { 14058 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14059 if (!OCE) 14060 return; 14061 14062 FunctionDecl *FD = OCE->getDirectCallee(); 14063 if (!FD || !FD->isOverloadedOperator()) 14064 return; 14065 14066 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14067 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14068 return; 14069 14070 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14071 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14072 << (Kind == OO_LessLess); 14073 SuggestParentheses(S, OCE->getOperatorLoc(), 14074 S.PDiag(diag::note_precedence_silence) 14075 << (Kind == OO_LessLess ? "<<" : ">>"), 14076 OCE->getSourceRange()); 14077 SuggestParentheses( 14078 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14079 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14080 } 14081 14082 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14083 /// precedence. 14084 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14085 SourceLocation OpLoc, Expr *LHSExpr, 14086 Expr *RHSExpr){ 14087 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14088 if (BinaryOperator::isBitwiseOp(Opc)) 14089 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14090 14091 // Diagnose "arg1 & arg2 | arg3" 14092 if ((Opc == BO_Or || Opc == BO_Xor) && 14093 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14094 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14095 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14096 } 14097 14098 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14099 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14100 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14101 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14102 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14103 } 14104 14105 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14106 || Opc == BO_Shr) { 14107 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14108 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14109 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14110 } 14111 14112 // Warn on overloaded shift operators and comparisons, such as: 14113 // cout << 5 == 4; 14114 if (BinaryOperator::isComparisonOp(Opc)) 14115 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14116 } 14117 14118 // Binary Operators. 'Tok' is the token for the operator. 14119 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14120 tok::TokenKind Kind, 14121 Expr *LHSExpr, Expr *RHSExpr) { 14122 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14123 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14124 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14125 14126 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14127 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14128 14129 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14130 } 14131 14132 /// Build an overloaded binary operator expression in the given scope. 14133 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14134 BinaryOperatorKind Opc, 14135 Expr *LHS, Expr *RHS) { 14136 switch (Opc) { 14137 case BO_Assign: 14138 case BO_DivAssign: 14139 case BO_RemAssign: 14140 case BO_SubAssign: 14141 case BO_AndAssign: 14142 case BO_OrAssign: 14143 case BO_XorAssign: 14144 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14145 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14146 break; 14147 default: 14148 break; 14149 } 14150 14151 // Find all of the overloaded operators visible from this 14152 // point. We perform both an operator-name lookup from the local 14153 // scope and an argument-dependent lookup based on the types of 14154 // the arguments. 14155 UnresolvedSet<16> Functions; 14156 OverloadedOperatorKind OverOp 14157 = BinaryOperator::getOverloadedOperator(Opc); 14158 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 14159 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 14160 RHS->getType(), Functions); 14161 14162 // In C++20 onwards, we may have a second operator to look up. 14163 if (S.getLangOpts().CPlusPlus20) { 14164 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14165 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 14166 RHS->getType(), Functions); 14167 } 14168 14169 // Build the (potentially-overloaded, potentially-dependent) 14170 // binary operation. 14171 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14172 } 14173 14174 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14175 BinaryOperatorKind Opc, 14176 Expr *LHSExpr, Expr *RHSExpr) { 14177 ExprResult LHS, RHS; 14178 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14179 if (!LHS.isUsable() || !RHS.isUsable()) 14180 return ExprError(); 14181 LHSExpr = LHS.get(); 14182 RHSExpr = RHS.get(); 14183 14184 // We want to end up calling one of checkPseudoObjectAssignment 14185 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14186 // both expressions are overloadable or either is type-dependent), 14187 // or CreateBuiltinBinOp (in any other case). We also want to get 14188 // any placeholder types out of the way. 14189 14190 // Handle pseudo-objects in the LHS. 14191 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14192 // Assignments with a pseudo-object l-value need special analysis. 14193 if (pty->getKind() == BuiltinType::PseudoObject && 14194 BinaryOperator::isAssignmentOp(Opc)) 14195 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14196 14197 // Don't resolve overloads if the other type is overloadable. 14198 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14199 // We can't actually test that if we still have a placeholder, 14200 // though. Fortunately, none of the exceptions we see in that 14201 // code below are valid when the LHS is an overload set. Note 14202 // that an overload set can be dependently-typed, but it never 14203 // instantiates to having an overloadable type. 14204 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14205 if (resolvedRHS.isInvalid()) return ExprError(); 14206 RHSExpr = resolvedRHS.get(); 14207 14208 if (RHSExpr->isTypeDependent() || 14209 RHSExpr->getType()->isOverloadableType()) 14210 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14211 } 14212 14213 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14214 // template, diagnose the missing 'template' keyword instead of diagnosing 14215 // an invalid use of a bound member function. 14216 // 14217 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14218 // to C++1z [over.over]/1.4, but we already checked for that case above. 14219 if (Opc == BO_LT && inTemplateInstantiation() && 14220 (pty->getKind() == BuiltinType::BoundMember || 14221 pty->getKind() == BuiltinType::Overload)) { 14222 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14223 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14224 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14225 return isa<FunctionTemplateDecl>(ND); 14226 })) { 14227 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14228 : OE->getNameLoc(), 14229 diag::err_template_kw_missing) 14230 << OE->getName().getAsString() << ""; 14231 return ExprError(); 14232 } 14233 } 14234 14235 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14236 if (LHS.isInvalid()) return ExprError(); 14237 LHSExpr = LHS.get(); 14238 } 14239 14240 // Handle pseudo-objects in the RHS. 14241 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14242 // An overload in the RHS can potentially be resolved by the type 14243 // being assigned to. 14244 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14245 if (getLangOpts().CPlusPlus && 14246 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14247 LHSExpr->getType()->isOverloadableType())) 14248 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14249 14250 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14251 } 14252 14253 // Don't resolve overloads if the other type is overloadable. 14254 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14255 LHSExpr->getType()->isOverloadableType()) 14256 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14257 14258 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14259 if (!resolvedRHS.isUsable()) return ExprError(); 14260 RHSExpr = resolvedRHS.get(); 14261 } 14262 14263 if (getLangOpts().CPlusPlus) { 14264 // If either expression is type-dependent, always build an 14265 // overloaded op. 14266 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14267 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14268 14269 // Otherwise, build an overloaded op if either expression has an 14270 // overloadable type. 14271 if (LHSExpr->getType()->isOverloadableType() || 14272 RHSExpr->getType()->isOverloadableType()) 14273 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14274 } 14275 14276 // Build a built-in binary operation. 14277 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14278 } 14279 14280 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14281 if (T.isNull() || T->isDependentType()) 14282 return false; 14283 14284 if (!T->isPromotableIntegerType()) 14285 return true; 14286 14287 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14288 } 14289 14290 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14291 UnaryOperatorKind Opc, 14292 Expr *InputExpr) { 14293 ExprResult Input = InputExpr; 14294 ExprValueKind VK = VK_RValue; 14295 ExprObjectKind OK = OK_Ordinary; 14296 QualType resultType; 14297 bool CanOverflow = false; 14298 14299 bool ConvertHalfVec = false; 14300 if (getLangOpts().OpenCL) { 14301 QualType Ty = InputExpr->getType(); 14302 // The only legal unary operation for atomics is '&'. 14303 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14304 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14305 // only with a builtin functions and therefore should be disallowed here. 14306 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14307 || Ty->isBlockPointerType())) { 14308 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14309 << InputExpr->getType() 14310 << Input.get()->getSourceRange()); 14311 } 14312 } 14313 14314 switch (Opc) { 14315 case UO_PreInc: 14316 case UO_PreDec: 14317 case UO_PostInc: 14318 case UO_PostDec: 14319 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14320 OpLoc, 14321 Opc == UO_PreInc || 14322 Opc == UO_PostInc, 14323 Opc == UO_PreInc || 14324 Opc == UO_PreDec); 14325 CanOverflow = isOverflowingIntegerType(Context, resultType); 14326 break; 14327 case UO_AddrOf: 14328 resultType = CheckAddressOfOperand(Input, OpLoc); 14329 CheckAddressOfNoDeref(InputExpr); 14330 RecordModifiableNonNullParam(*this, InputExpr); 14331 break; 14332 case UO_Deref: { 14333 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14334 if (Input.isInvalid()) return ExprError(); 14335 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14336 break; 14337 } 14338 case UO_Plus: 14339 case UO_Minus: 14340 CanOverflow = Opc == UO_Minus && 14341 isOverflowingIntegerType(Context, Input.get()->getType()); 14342 Input = UsualUnaryConversions(Input.get()); 14343 if (Input.isInvalid()) return ExprError(); 14344 // Unary plus and minus require promoting an operand of half vector to a 14345 // float vector and truncating the result back to a half vector. For now, we 14346 // do this only when HalfArgsAndReturns is set (that is, when the target is 14347 // arm or arm64). 14348 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14349 14350 // If the operand is a half vector, promote it to a float vector. 14351 if (ConvertHalfVec) 14352 Input = convertVector(Input.get(), Context.FloatTy, *this); 14353 resultType = Input.get()->getType(); 14354 if (resultType->isDependentType()) 14355 break; 14356 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14357 break; 14358 else if (resultType->isVectorType() && 14359 // The z vector extensions don't allow + or - with bool vectors. 14360 (!Context.getLangOpts().ZVector || 14361 resultType->castAs<VectorType>()->getVectorKind() != 14362 VectorType::AltiVecBool)) 14363 break; 14364 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14365 Opc == UO_Plus && 14366 resultType->isPointerType()) 14367 break; 14368 14369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14370 << resultType << Input.get()->getSourceRange()); 14371 14372 case UO_Not: // bitwise complement 14373 Input = UsualUnaryConversions(Input.get()); 14374 if (Input.isInvalid()) 14375 return ExprError(); 14376 resultType = Input.get()->getType(); 14377 if (resultType->isDependentType()) 14378 break; 14379 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14380 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14381 // C99 does not support '~' for complex conjugation. 14382 Diag(OpLoc, diag::ext_integer_complement_complex) 14383 << resultType << Input.get()->getSourceRange(); 14384 else if (resultType->hasIntegerRepresentation()) 14385 break; 14386 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14387 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14388 // on vector float types. 14389 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14390 if (!T->isIntegerType()) 14391 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14392 << resultType << Input.get()->getSourceRange()); 14393 } else { 14394 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14395 << resultType << Input.get()->getSourceRange()); 14396 } 14397 break; 14398 14399 case UO_LNot: // logical negation 14400 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14401 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14402 if (Input.isInvalid()) return ExprError(); 14403 resultType = Input.get()->getType(); 14404 14405 // Though we still have to promote half FP to float... 14406 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14407 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14408 resultType = Context.FloatTy; 14409 } 14410 14411 if (resultType->isDependentType()) 14412 break; 14413 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14414 // C99 6.5.3.3p1: ok, fallthrough; 14415 if (Context.getLangOpts().CPlusPlus) { 14416 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14417 // operand contextually converted to bool. 14418 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14419 ScalarTypeToBooleanCastKind(resultType)); 14420 } else if (Context.getLangOpts().OpenCL && 14421 Context.getLangOpts().OpenCLVersion < 120) { 14422 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14423 // operate on scalar float types. 14424 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14425 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14426 << resultType << Input.get()->getSourceRange()); 14427 } 14428 } else if (resultType->isExtVectorType()) { 14429 if (Context.getLangOpts().OpenCL && 14430 Context.getLangOpts().OpenCLVersion < 120 && 14431 !Context.getLangOpts().OpenCLCPlusPlus) { 14432 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14433 // operate on vector float types. 14434 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14435 if (!T->isIntegerType()) 14436 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14437 << resultType << Input.get()->getSourceRange()); 14438 } 14439 // Vector logical not returns the signed variant of the operand type. 14440 resultType = GetSignedVectorType(resultType); 14441 break; 14442 } else { 14443 // FIXME: GCC's vector extension permits the usage of '!' with a vector 14444 // type in C++. We should allow that here too. 14445 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14446 << resultType << Input.get()->getSourceRange()); 14447 } 14448 14449 // LNot always has type int. C99 6.5.3.3p5. 14450 // In C++, it's bool. C++ 5.3.1p8 14451 resultType = Context.getLogicalOperationType(); 14452 break; 14453 case UO_Real: 14454 case UO_Imag: 14455 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14456 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14457 // complex l-values to ordinary l-values and all other values to r-values. 14458 if (Input.isInvalid()) return ExprError(); 14459 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14460 if (Input.get()->getValueKind() != VK_RValue && 14461 Input.get()->getObjectKind() == OK_Ordinary) 14462 VK = Input.get()->getValueKind(); 14463 } else if (!getLangOpts().CPlusPlus) { 14464 // In C, a volatile scalar is read by __imag. In C++, it is not. 14465 Input = DefaultLvalueConversion(Input.get()); 14466 } 14467 break; 14468 case UO_Extension: 14469 resultType = Input.get()->getType(); 14470 VK = Input.get()->getValueKind(); 14471 OK = Input.get()->getObjectKind(); 14472 break; 14473 case UO_Coawait: 14474 // It's unnecessary to represent the pass-through operator co_await in the 14475 // AST; just return the input expression instead. 14476 assert(!Input.get()->getType()->isDependentType() && 14477 "the co_await expression must be non-dependant before " 14478 "building operator co_await"); 14479 return Input; 14480 } 14481 if (resultType.isNull() || Input.isInvalid()) 14482 return ExprError(); 14483 14484 // Check for array bounds violations in the operand of the UnaryOperator, 14485 // except for the '*' and '&' operators that have to be handled specially 14486 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14487 // that are explicitly defined as valid by the standard). 14488 if (Opc != UO_AddrOf && Opc != UO_Deref) 14489 CheckArrayAccess(Input.get()); 14490 14491 auto *UO = UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, 14492 OK, OpLoc, CanOverflow, CurFPFeatures); 14493 14494 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14495 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 14496 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14497 14498 // Convert the result back to a half vector. 14499 if (ConvertHalfVec) 14500 return convertVector(UO, Context.HalfTy, *this); 14501 return UO; 14502 } 14503 14504 /// Determine whether the given expression is a qualified member 14505 /// access expression, of a form that could be turned into a pointer to member 14506 /// with the address-of operator. 14507 bool Sema::isQualifiedMemberAccess(Expr *E) { 14508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14509 if (!DRE->getQualifier()) 14510 return false; 14511 14512 ValueDecl *VD = DRE->getDecl(); 14513 if (!VD->isCXXClassMember()) 14514 return false; 14515 14516 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14517 return true; 14518 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14519 return Method->isInstance(); 14520 14521 return false; 14522 } 14523 14524 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14525 if (!ULE->getQualifier()) 14526 return false; 14527 14528 for (NamedDecl *D : ULE->decls()) { 14529 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14530 if (Method->isInstance()) 14531 return true; 14532 } else { 14533 // Overload set does not contain methods. 14534 break; 14535 } 14536 } 14537 14538 return false; 14539 } 14540 14541 return false; 14542 } 14543 14544 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14545 UnaryOperatorKind Opc, Expr *Input) { 14546 // First things first: handle placeholders so that the 14547 // overloaded-operator check considers the right type. 14548 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14549 // Increment and decrement of pseudo-object references. 14550 if (pty->getKind() == BuiltinType::PseudoObject && 14551 UnaryOperator::isIncrementDecrementOp(Opc)) 14552 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14553 14554 // extension is always a builtin operator. 14555 if (Opc == UO_Extension) 14556 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14557 14558 // & gets special logic for several kinds of placeholder. 14559 // The builtin code knows what to do. 14560 if (Opc == UO_AddrOf && 14561 (pty->getKind() == BuiltinType::Overload || 14562 pty->getKind() == BuiltinType::UnknownAny || 14563 pty->getKind() == BuiltinType::BoundMember)) 14564 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14565 14566 // Anything else needs to be handled now. 14567 ExprResult Result = CheckPlaceholderExpr(Input); 14568 if (Result.isInvalid()) return ExprError(); 14569 Input = Result.get(); 14570 } 14571 14572 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14573 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14574 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14575 // Find all of the overloaded operators visible from this 14576 // point. We perform both an operator-name lookup from the local 14577 // scope and an argument-dependent lookup based on the types of 14578 // the arguments. 14579 UnresolvedSet<16> Functions; 14580 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14581 if (S && OverOp != OO_None) 14582 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14583 Functions); 14584 14585 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14586 } 14587 14588 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14589 } 14590 14591 // Unary Operators. 'Tok' is the token for the operator. 14592 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14593 tok::TokenKind Op, Expr *Input) { 14594 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14595 } 14596 14597 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14598 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14599 LabelDecl *TheDecl) { 14600 TheDecl->markUsed(Context); 14601 // Create the AST node. The address of a label always has type 'void*'. 14602 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14603 Context.getPointerType(Context.VoidTy)); 14604 } 14605 14606 void Sema::ActOnStartStmtExpr() { 14607 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14608 } 14609 14610 void Sema::ActOnStmtExprError() { 14611 // Note that function is also called by TreeTransform when leaving a 14612 // StmtExpr scope without rebuilding anything. 14613 14614 DiscardCleanupsInEvaluationContext(); 14615 PopExpressionEvaluationContext(); 14616 } 14617 14618 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14619 SourceLocation RPLoc) { 14620 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14621 } 14622 14623 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14624 SourceLocation RPLoc, unsigned TemplateDepth) { 14625 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14626 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14627 14628 if (hasAnyUnrecoverableErrorsInThisFunction()) 14629 DiscardCleanupsInEvaluationContext(); 14630 assert(!Cleanup.exprNeedsCleanups() && 14631 "cleanups within StmtExpr not correctly bound!"); 14632 PopExpressionEvaluationContext(); 14633 14634 // FIXME: there are a variety of strange constraints to enforce here, for 14635 // example, it is not possible to goto into a stmt expression apparently. 14636 // More semantic analysis is needed. 14637 14638 // If there are sub-stmts in the compound stmt, take the type of the last one 14639 // as the type of the stmtexpr. 14640 QualType Ty = Context.VoidTy; 14641 bool StmtExprMayBindToTemp = false; 14642 if (!Compound->body_empty()) { 14643 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14644 if (const auto *LastStmt = 14645 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14646 if (const Expr *Value = LastStmt->getExprStmt()) { 14647 StmtExprMayBindToTemp = true; 14648 Ty = Value->getType(); 14649 } 14650 } 14651 } 14652 14653 // FIXME: Check that expression type is complete/non-abstract; statement 14654 // expressions are not lvalues. 14655 Expr *ResStmtExpr = 14656 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14657 if (StmtExprMayBindToTemp) 14658 return MaybeBindToTemporary(ResStmtExpr); 14659 return ResStmtExpr; 14660 } 14661 14662 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14663 if (ER.isInvalid()) 14664 return ExprError(); 14665 14666 // Do function/array conversion on the last expression, but not 14667 // lvalue-to-rvalue. However, initialize an unqualified type. 14668 ER = DefaultFunctionArrayConversion(ER.get()); 14669 if (ER.isInvalid()) 14670 return ExprError(); 14671 Expr *E = ER.get(); 14672 14673 if (E->isTypeDependent()) 14674 return E; 14675 14676 // In ARC, if the final expression ends in a consume, splice 14677 // the consume out and bind it later. In the alternate case 14678 // (when dealing with a retainable type), the result 14679 // initialization will create a produce. In both cases the 14680 // result will be +1, and we'll need to balance that out with 14681 // a bind. 14682 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14683 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14684 return Cast->getSubExpr(); 14685 14686 // FIXME: Provide a better location for the initialization. 14687 return PerformCopyInitialization( 14688 InitializedEntity::InitializeStmtExprResult( 14689 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14690 SourceLocation(), E); 14691 } 14692 14693 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14694 TypeSourceInfo *TInfo, 14695 ArrayRef<OffsetOfComponent> Components, 14696 SourceLocation RParenLoc) { 14697 QualType ArgTy = TInfo->getType(); 14698 bool Dependent = ArgTy->isDependentType(); 14699 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14700 14701 // We must have at least one component that refers to the type, and the first 14702 // one is known to be a field designator. Verify that the ArgTy represents 14703 // a struct/union/class. 14704 if (!Dependent && !ArgTy->isRecordType()) 14705 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14706 << ArgTy << TypeRange); 14707 14708 // Type must be complete per C99 7.17p3 because a declaring a variable 14709 // with an incomplete type would be ill-formed. 14710 if (!Dependent 14711 && RequireCompleteType(BuiltinLoc, ArgTy, 14712 diag::err_offsetof_incomplete_type, TypeRange)) 14713 return ExprError(); 14714 14715 bool DidWarnAboutNonPOD = false; 14716 QualType CurrentType = ArgTy; 14717 SmallVector<OffsetOfNode, 4> Comps; 14718 SmallVector<Expr*, 4> Exprs; 14719 for (const OffsetOfComponent &OC : Components) { 14720 if (OC.isBrackets) { 14721 // Offset of an array sub-field. TODO: Should we allow vector elements? 14722 if (!CurrentType->isDependentType()) { 14723 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14724 if(!AT) 14725 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14726 << CurrentType); 14727 CurrentType = AT->getElementType(); 14728 } else 14729 CurrentType = Context.DependentTy; 14730 14731 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14732 if (IdxRval.isInvalid()) 14733 return ExprError(); 14734 Expr *Idx = IdxRval.get(); 14735 14736 // The expression must be an integral expression. 14737 // FIXME: An integral constant expression? 14738 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14739 !Idx->getType()->isIntegerType()) 14740 return ExprError( 14741 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14742 << Idx->getSourceRange()); 14743 14744 // Record this array index. 14745 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14746 Exprs.push_back(Idx); 14747 continue; 14748 } 14749 14750 // Offset of a field. 14751 if (CurrentType->isDependentType()) { 14752 // We have the offset of a field, but we can't look into the dependent 14753 // type. Just record the identifier of the field. 14754 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14755 CurrentType = Context.DependentTy; 14756 continue; 14757 } 14758 14759 // We need to have a complete type to look into. 14760 if (RequireCompleteType(OC.LocStart, CurrentType, 14761 diag::err_offsetof_incomplete_type)) 14762 return ExprError(); 14763 14764 // Look for the designated field. 14765 const RecordType *RC = CurrentType->getAs<RecordType>(); 14766 if (!RC) 14767 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14768 << CurrentType); 14769 RecordDecl *RD = RC->getDecl(); 14770 14771 // C++ [lib.support.types]p5: 14772 // The macro offsetof accepts a restricted set of type arguments in this 14773 // International Standard. type shall be a POD structure or a POD union 14774 // (clause 9). 14775 // C++11 [support.types]p4: 14776 // If type is not a standard-layout class (Clause 9), the results are 14777 // undefined. 14778 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14779 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14780 unsigned DiagID = 14781 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14782 : diag::ext_offsetof_non_pod_type; 14783 14784 if (!IsSafe && !DidWarnAboutNonPOD && 14785 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14786 PDiag(DiagID) 14787 << SourceRange(Components[0].LocStart, OC.LocEnd) 14788 << CurrentType)) 14789 DidWarnAboutNonPOD = true; 14790 } 14791 14792 // Look for the field. 14793 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14794 LookupQualifiedName(R, RD); 14795 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14796 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14797 if (!MemberDecl) { 14798 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14799 MemberDecl = IndirectMemberDecl->getAnonField(); 14800 } 14801 14802 if (!MemberDecl) 14803 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14804 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14805 OC.LocEnd)); 14806 14807 // C99 7.17p3: 14808 // (If the specified member is a bit-field, the behavior is undefined.) 14809 // 14810 // We diagnose this as an error. 14811 if (MemberDecl->isBitField()) { 14812 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14813 << MemberDecl->getDeclName() 14814 << SourceRange(BuiltinLoc, RParenLoc); 14815 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14816 return ExprError(); 14817 } 14818 14819 RecordDecl *Parent = MemberDecl->getParent(); 14820 if (IndirectMemberDecl) 14821 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14822 14823 // If the member was found in a base class, introduce OffsetOfNodes for 14824 // the base class indirections. 14825 CXXBasePaths Paths; 14826 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14827 Paths)) { 14828 if (Paths.getDetectedVirtual()) { 14829 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14830 << MemberDecl->getDeclName() 14831 << SourceRange(BuiltinLoc, RParenLoc); 14832 return ExprError(); 14833 } 14834 14835 CXXBasePath &Path = Paths.front(); 14836 for (const CXXBasePathElement &B : Path) 14837 Comps.push_back(OffsetOfNode(B.Base)); 14838 } 14839 14840 if (IndirectMemberDecl) { 14841 for (auto *FI : IndirectMemberDecl->chain()) { 14842 assert(isa<FieldDecl>(FI)); 14843 Comps.push_back(OffsetOfNode(OC.LocStart, 14844 cast<FieldDecl>(FI), OC.LocEnd)); 14845 } 14846 } else 14847 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14848 14849 CurrentType = MemberDecl->getType().getNonReferenceType(); 14850 } 14851 14852 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14853 Comps, Exprs, RParenLoc); 14854 } 14855 14856 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14857 SourceLocation BuiltinLoc, 14858 SourceLocation TypeLoc, 14859 ParsedType ParsedArgTy, 14860 ArrayRef<OffsetOfComponent> Components, 14861 SourceLocation RParenLoc) { 14862 14863 TypeSourceInfo *ArgTInfo; 14864 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14865 if (ArgTy.isNull()) 14866 return ExprError(); 14867 14868 if (!ArgTInfo) 14869 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14870 14871 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14872 } 14873 14874 14875 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14876 Expr *CondExpr, 14877 Expr *LHSExpr, Expr *RHSExpr, 14878 SourceLocation RPLoc) { 14879 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14880 14881 ExprValueKind VK = VK_RValue; 14882 ExprObjectKind OK = OK_Ordinary; 14883 QualType resType; 14884 bool CondIsTrue = false; 14885 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14886 resType = Context.DependentTy; 14887 } else { 14888 // The conditional expression is required to be a constant expression. 14889 llvm::APSInt condEval(32); 14890 ExprResult CondICE 14891 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14892 diag::err_typecheck_choose_expr_requires_constant, false); 14893 if (CondICE.isInvalid()) 14894 return ExprError(); 14895 CondExpr = CondICE.get(); 14896 CondIsTrue = condEval.getZExtValue(); 14897 14898 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14899 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14900 14901 resType = ActiveExpr->getType(); 14902 VK = ActiveExpr->getValueKind(); 14903 OK = ActiveExpr->getObjectKind(); 14904 } 14905 14906 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14907 resType, VK, OK, RPLoc, CondIsTrue); 14908 } 14909 14910 //===----------------------------------------------------------------------===// 14911 // Clang Extensions. 14912 //===----------------------------------------------------------------------===// 14913 14914 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14915 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14916 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14917 14918 if (LangOpts.CPlusPlus) { 14919 MangleNumberingContext *MCtx; 14920 Decl *ManglingContextDecl; 14921 std::tie(MCtx, ManglingContextDecl) = 14922 getCurrentMangleNumberContext(Block->getDeclContext()); 14923 if (MCtx) { 14924 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14925 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14926 } 14927 } 14928 14929 PushBlockScope(CurScope, Block); 14930 CurContext->addDecl(Block); 14931 if (CurScope) 14932 PushDeclContext(CurScope, Block); 14933 else 14934 CurContext = Block; 14935 14936 getCurBlock()->HasImplicitReturnType = true; 14937 14938 // Enter a new evaluation context to insulate the block from any 14939 // cleanups from the enclosing full-expression. 14940 PushExpressionEvaluationContext( 14941 ExpressionEvaluationContext::PotentiallyEvaluated); 14942 } 14943 14944 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14945 Scope *CurScope) { 14946 assert(ParamInfo.getIdentifier() == nullptr && 14947 "block-id should have no identifier!"); 14948 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14949 BlockScopeInfo *CurBlock = getCurBlock(); 14950 14951 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14952 QualType T = Sig->getType(); 14953 14954 // FIXME: We should allow unexpanded parameter packs here, but that would, 14955 // in turn, make the block expression contain unexpanded parameter packs. 14956 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14957 // Drop the parameters. 14958 FunctionProtoType::ExtProtoInfo EPI; 14959 EPI.HasTrailingReturn = false; 14960 EPI.TypeQuals.addConst(); 14961 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14962 Sig = Context.getTrivialTypeSourceInfo(T); 14963 } 14964 14965 // GetTypeForDeclarator always produces a function type for a block 14966 // literal signature. Furthermore, it is always a FunctionProtoType 14967 // unless the function was written with a typedef. 14968 assert(T->isFunctionType() && 14969 "GetTypeForDeclarator made a non-function block signature"); 14970 14971 // Look for an explicit signature in that function type. 14972 FunctionProtoTypeLoc ExplicitSignature; 14973 14974 if ((ExplicitSignature = Sig->getTypeLoc() 14975 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14976 14977 // Check whether that explicit signature was synthesized by 14978 // GetTypeForDeclarator. If so, don't save that as part of the 14979 // written signature. 14980 if (ExplicitSignature.getLocalRangeBegin() == 14981 ExplicitSignature.getLocalRangeEnd()) { 14982 // This would be much cheaper if we stored TypeLocs instead of 14983 // TypeSourceInfos. 14984 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14985 unsigned Size = Result.getFullDataSize(); 14986 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14987 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14988 14989 ExplicitSignature = FunctionProtoTypeLoc(); 14990 } 14991 } 14992 14993 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14994 CurBlock->FunctionType = T; 14995 14996 const FunctionType *Fn = T->getAs<FunctionType>(); 14997 QualType RetTy = Fn->getReturnType(); 14998 bool isVariadic = 14999 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15000 15001 CurBlock->TheDecl->setIsVariadic(isVariadic); 15002 15003 // Context.DependentTy is used as a placeholder for a missing block 15004 // return type. TODO: what should we do with declarators like: 15005 // ^ * { ... } 15006 // If the answer is "apply template argument deduction".... 15007 if (RetTy != Context.DependentTy) { 15008 CurBlock->ReturnType = RetTy; 15009 CurBlock->TheDecl->setBlockMissingReturnType(false); 15010 CurBlock->HasImplicitReturnType = false; 15011 } 15012 15013 // Push block parameters from the declarator if we had them. 15014 SmallVector<ParmVarDecl*, 8> Params; 15015 if (ExplicitSignature) { 15016 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15017 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15018 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15019 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15020 // Diagnose this as an extension in C17 and earlier. 15021 if (!getLangOpts().C2x) 15022 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15023 } 15024 Params.push_back(Param); 15025 } 15026 15027 // Fake up parameter variables if we have a typedef, like 15028 // ^ fntype { ... } 15029 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15030 for (const auto &I : Fn->param_types()) { 15031 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15032 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15033 Params.push_back(Param); 15034 } 15035 } 15036 15037 // Set the parameters on the block decl. 15038 if (!Params.empty()) { 15039 CurBlock->TheDecl->setParams(Params); 15040 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15041 /*CheckParameterNames=*/false); 15042 } 15043 15044 // Finally we can process decl attributes. 15045 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15046 15047 // Put the parameter variables in scope. 15048 for (auto AI : CurBlock->TheDecl->parameters()) { 15049 AI->setOwningFunction(CurBlock->TheDecl); 15050 15051 // If this has an identifier, add it to the scope stack. 15052 if (AI->getIdentifier()) { 15053 CheckShadow(CurBlock->TheScope, AI); 15054 15055 PushOnScopeChains(AI, CurBlock->TheScope); 15056 } 15057 } 15058 } 15059 15060 /// ActOnBlockError - If there is an error parsing a block, this callback 15061 /// is invoked to pop the information about the block from the action impl. 15062 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15063 // Leave the expression-evaluation context. 15064 DiscardCleanupsInEvaluationContext(); 15065 PopExpressionEvaluationContext(); 15066 15067 // Pop off CurBlock, handle nested blocks. 15068 PopDeclContext(); 15069 PopFunctionScopeInfo(); 15070 } 15071 15072 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15073 /// literal was successfully completed. ^(int x){...} 15074 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15075 Stmt *Body, Scope *CurScope) { 15076 // If blocks are disabled, emit an error. 15077 if (!LangOpts.Blocks) 15078 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15079 15080 // Leave the expression-evaluation context. 15081 if (hasAnyUnrecoverableErrorsInThisFunction()) 15082 DiscardCleanupsInEvaluationContext(); 15083 assert(!Cleanup.exprNeedsCleanups() && 15084 "cleanups within block not correctly bound!"); 15085 PopExpressionEvaluationContext(); 15086 15087 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15088 BlockDecl *BD = BSI->TheDecl; 15089 15090 if (BSI->HasImplicitReturnType) 15091 deduceClosureReturnType(*BSI); 15092 15093 QualType RetTy = Context.VoidTy; 15094 if (!BSI->ReturnType.isNull()) 15095 RetTy = BSI->ReturnType; 15096 15097 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15098 QualType BlockTy; 15099 15100 // If the user wrote a function type in some form, try to use that. 15101 if (!BSI->FunctionType.isNull()) { 15102 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15103 15104 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15105 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15106 15107 // Turn protoless block types into nullary block types. 15108 if (isa<FunctionNoProtoType>(FTy)) { 15109 FunctionProtoType::ExtProtoInfo EPI; 15110 EPI.ExtInfo = Ext; 15111 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15112 15113 // Otherwise, if we don't need to change anything about the function type, 15114 // preserve its sugar structure. 15115 } else if (FTy->getReturnType() == RetTy && 15116 (!NoReturn || FTy->getNoReturnAttr())) { 15117 BlockTy = BSI->FunctionType; 15118 15119 // Otherwise, make the minimal modifications to the function type. 15120 } else { 15121 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15122 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15123 EPI.TypeQuals = Qualifiers(); 15124 EPI.ExtInfo = Ext; 15125 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15126 } 15127 15128 // If we don't have a function type, just build one from nothing. 15129 } else { 15130 FunctionProtoType::ExtProtoInfo EPI; 15131 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15132 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15133 } 15134 15135 DiagnoseUnusedParameters(BD->parameters()); 15136 BlockTy = Context.getBlockPointerType(BlockTy); 15137 15138 // If needed, diagnose invalid gotos and switches in the block. 15139 if (getCurFunction()->NeedsScopeChecking() && 15140 !PP.isCodeCompletionEnabled()) 15141 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15142 15143 BD->setBody(cast<CompoundStmt>(Body)); 15144 15145 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15146 DiagnoseUnguardedAvailabilityViolations(BD); 15147 15148 // Try to apply the named return value optimization. We have to check again 15149 // if we can do this, though, because blocks keep return statements around 15150 // to deduce an implicit return type. 15151 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15152 !BD->isDependentContext()) 15153 computeNRVO(Body, BSI); 15154 15155 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15156 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15157 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15158 NTCUK_Destruct|NTCUK_Copy); 15159 15160 PopDeclContext(); 15161 15162 // Pop the block scope now but keep it alive to the end of this function. 15163 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15164 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15165 15166 // Set the captured variables on the block. 15167 SmallVector<BlockDecl::Capture, 4> Captures; 15168 for (Capture &Cap : BSI->Captures) { 15169 if (Cap.isInvalid() || Cap.isThisCapture()) 15170 continue; 15171 15172 VarDecl *Var = Cap.getVariable(); 15173 Expr *CopyExpr = nullptr; 15174 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15175 if (const RecordType *Record = 15176 Cap.getCaptureType()->getAs<RecordType>()) { 15177 // The capture logic needs the destructor, so make sure we mark it. 15178 // Usually this is unnecessary because most local variables have 15179 // their destructors marked at declaration time, but parameters are 15180 // an exception because it's technically only the call site that 15181 // actually requires the destructor. 15182 if (isa<ParmVarDecl>(Var)) 15183 FinalizeVarWithDestructor(Var, Record); 15184 15185 // Enter a separate potentially-evaluated context while building block 15186 // initializers to isolate their cleanups from those of the block 15187 // itself. 15188 // FIXME: Is this appropriate even when the block itself occurs in an 15189 // unevaluated operand? 15190 EnterExpressionEvaluationContext EvalContext( 15191 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15192 15193 SourceLocation Loc = Cap.getLocation(); 15194 15195 ExprResult Result = BuildDeclarationNameExpr( 15196 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15197 15198 // According to the blocks spec, the capture of a variable from 15199 // the stack requires a const copy constructor. This is not true 15200 // of the copy/move done to move a __block variable to the heap. 15201 if (!Result.isInvalid() && 15202 !Result.get()->getType().isConstQualified()) { 15203 Result = ImpCastExprToType(Result.get(), 15204 Result.get()->getType().withConst(), 15205 CK_NoOp, VK_LValue); 15206 } 15207 15208 if (!Result.isInvalid()) { 15209 Result = PerformCopyInitialization( 15210 InitializedEntity::InitializeBlock(Var->getLocation(), 15211 Cap.getCaptureType(), false), 15212 Loc, Result.get()); 15213 } 15214 15215 // Build a full-expression copy expression if initialization 15216 // succeeded and used a non-trivial constructor. Recover from 15217 // errors by pretending that the copy isn't necessary. 15218 if (!Result.isInvalid() && 15219 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15220 ->isTrivial()) { 15221 Result = MaybeCreateExprWithCleanups(Result); 15222 CopyExpr = Result.get(); 15223 } 15224 } 15225 } 15226 15227 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15228 CopyExpr); 15229 Captures.push_back(NewCap); 15230 } 15231 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15232 15233 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15234 15235 // If the block isn't obviously global, i.e. it captures anything at 15236 // all, then we need to do a few things in the surrounding context: 15237 if (Result->getBlockDecl()->hasCaptures()) { 15238 // First, this expression has a new cleanup object. 15239 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15240 Cleanup.setExprNeedsCleanups(true); 15241 15242 // It also gets a branch-protected scope if any of the captured 15243 // variables needs destruction. 15244 for (const auto &CI : Result->getBlockDecl()->captures()) { 15245 const VarDecl *var = CI.getVariable(); 15246 if (var->getType().isDestructedType() != QualType::DK_none) { 15247 setFunctionHasBranchProtectedScope(); 15248 break; 15249 } 15250 } 15251 } 15252 15253 if (getCurFunction()) 15254 getCurFunction()->addBlock(BD); 15255 15256 return Result; 15257 } 15258 15259 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15260 SourceLocation RPLoc) { 15261 TypeSourceInfo *TInfo; 15262 GetTypeFromParser(Ty, &TInfo); 15263 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15264 } 15265 15266 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15267 Expr *E, TypeSourceInfo *TInfo, 15268 SourceLocation RPLoc) { 15269 Expr *OrigExpr = E; 15270 bool IsMS = false; 15271 15272 // CUDA device code does not support varargs. 15273 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15274 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15275 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15276 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15277 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15278 } 15279 } 15280 15281 // NVPTX does not support va_arg expression. 15282 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15283 Context.getTargetInfo().getTriple().isNVPTX()) 15284 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15285 15286 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15287 // as Microsoft ABI on an actual Microsoft platform, where 15288 // __builtin_ms_va_list and __builtin_va_list are the same.) 15289 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15290 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15291 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15292 if (Context.hasSameType(MSVaListType, E->getType())) { 15293 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15294 return ExprError(); 15295 IsMS = true; 15296 } 15297 } 15298 15299 // Get the va_list type 15300 QualType VaListType = Context.getBuiltinVaListType(); 15301 if (!IsMS) { 15302 if (VaListType->isArrayType()) { 15303 // Deal with implicit array decay; for example, on x86-64, 15304 // va_list is an array, but it's supposed to decay to 15305 // a pointer for va_arg. 15306 VaListType = Context.getArrayDecayedType(VaListType); 15307 // Make sure the input expression also decays appropriately. 15308 ExprResult Result = UsualUnaryConversions(E); 15309 if (Result.isInvalid()) 15310 return ExprError(); 15311 E = Result.get(); 15312 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15313 // If va_list is a record type and we are compiling in C++ mode, 15314 // check the argument using reference binding. 15315 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15316 Context, Context.getLValueReferenceType(VaListType), false); 15317 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15318 if (Init.isInvalid()) 15319 return ExprError(); 15320 E = Init.getAs<Expr>(); 15321 } else { 15322 // Otherwise, the va_list argument must be an l-value because 15323 // it is modified by va_arg. 15324 if (!E->isTypeDependent() && 15325 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15326 return ExprError(); 15327 } 15328 } 15329 15330 if (!IsMS && !E->isTypeDependent() && 15331 !Context.hasSameType(VaListType, E->getType())) 15332 return ExprError( 15333 Diag(E->getBeginLoc(), 15334 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15335 << OrigExpr->getType() << E->getSourceRange()); 15336 15337 if (!TInfo->getType()->isDependentType()) { 15338 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15339 diag::err_second_parameter_to_va_arg_incomplete, 15340 TInfo->getTypeLoc())) 15341 return ExprError(); 15342 15343 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15344 TInfo->getType(), 15345 diag::err_second_parameter_to_va_arg_abstract, 15346 TInfo->getTypeLoc())) 15347 return ExprError(); 15348 15349 if (!TInfo->getType().isPODType(Context)) { 15350 Diag(TInfo->getTypeLoc().getBeginLoc(), 15351 TInfo->getType()->isObjCLifetimeType() 15352 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15353 : diag::warn_second_parameter_to_va_arg_not_pod) 15354 << TInfo->getType() 15355 << TInfo->getTypeLoc().getSourceRange(); 15356 } 15357 15358 // Check for va_arg where arguments of the given type will be promoted 15359 // (i.e. this va_arg is guaranteed to have undefined behavior). 15360 QualType PromoteType; 15361 if (TInfo->getType()->isPromotableIntegerType()) { 15362 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15363 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15364 PromoteType = QualType(); 15365 } 15366 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15367 PromoteType = Context.DoubleTy; 15368 if (!PromoteType.isNull()) 15369 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15370 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15371 << TInfo->getType() 15372 << PromoteType 15373 << TInfo->getTypeLoc().getSourceRange()); 15374 } 15375 15376 QualType T = TInfo->getType().getNonLValueExprType(Context); 15377 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15378 } 15379 15380 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15381 // The type of __null will be int or long, depending on the size of 15382 // pointers on the target. 15383 QualType Ty; 15384 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15385 if (pw == Context.getTargetInfo().getIntWidth()) 15386 Ty = Context.IntTy; 15387 else if (pw == Context.getTargetInfo().getLongWidth()) 15388 Ty = Context.LongTy; 15389 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15390 Ty = Context.LongLongTy; 15391 else { 15392 llvm_unreachable("I don't know size of pointer!"); 15393 } 15394 15395 return new (Context) GNUNullExpr(Ty, TokenLoc); 15396 } 15397 15398 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15399 SourceLocation BuiltinLoc, 15400 SourceLocation RPLoc) { 15401 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15402 } 15403 15404 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15405 SourceLocation BuiltinLoc, 15406 SourceLocation RPLoc, 15407 DeclContext *ParentContext) { 15408 return new (Context) 15409 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15410 } 15411 15412 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15413 bool Diagnose) { 15414 if (!getLangOpts().ObjC) 15415 return false; 15416 15417 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15418 if (!PT) 15419 return false; 15420 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15421 15422 // Ignore any parens, implicit casts (should only be 15423 // array-to-pointer decays), and not-so-opaque values. The last is 15424 // important for making this trigger for property assignments. 15425 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15426 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15427 if (OV->getSourceExpr()) 15428 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15429 15430 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15431 if (!PT->isObjCIdType() && 15432 !(ID && ID->getIdentifier()->isStr("NSString"))) 15433 return false; 15434 if (!SL->isAscii()) 15435 return false; 15436 15437 if (Diagnose) { 15438 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15439 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15440 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15441 } 15442 return true; 15443 } 15444 15445 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15446 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15447 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15448 !SrcExpr->isNullPointerConstant( 15449 getASTContext(), Expr::NPC_NeverValueDependent)) { 15450 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15451 return false; 15452 if (Diagnose) { 15453 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15454 << /*number*/1 15455 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15456 Expr *NumLit = 15457 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15458 if (NumLit) 15459 Exp = NumLit; 15460 } 15461 return true; 15462 } 15463 15464 return false; 15465 } 15466 15467 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15468 const Expr *SrcExpr) { 15469 if (!DstType->isFunctionPointerType() || 15470 !SrcExpr->getType()->isFunctionType()) 15471 return false; 15472 15473 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15474 if (!DRE) 15475 return false; 15476 15477 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15478 if (!FD) 15479 return false; 15480 15481 return !S.checkAddressOfFunctionIsAvailable(FD, 15482 /*Complain=*/true, 15483 SrcExpr->getBeginLoc()); 15484 } 15485 15486 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15487 SourceLocation Loc, 15488 QualType DstType, QualType SrcType, 15489 Expr *SrcExpr, AssignmentAction Action, 15490 bool *Complained) { 15491 if (Complained) 15492 *Complained = false; 15493 15494 // Decode the result (notice that AST's are still created for extensions). 15495 bool CheckInferredResultType = false; 15496 bool isInvalid = false; 15497 unsigned DiagKind = 0; 15498 FixItHint Hint; 15499 ConversionFixItGenerator ConvHints; 15500 bool MayHaveConvFixit = false; 15501 bool MayHaveFunctionDiff = false; 15502 const ObjCInterfaceDecl *IFace = nullptr; 15503 const ObjCProtocolDecl *PDecl = nullptr; 15504 15505 switch (ConvTy) { 15506 case Compatible: 15507 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15508 return false; 15509 15510 case PointerToInt: 15511 if (getLangOpts().CPlusPlus) { 15512 DiagKind = diag::err_typecheck_convert_pointer_int; 15513 isInvalid = true; 15514 } else { 15515 DiagKind = diag::ext_typecheck_convert_pointer_int; 15516 } 15517 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15518 MayHaveConvFixit = true; 15519 break; 15520 case IntToPointer: 15521 if (getLangOpts().CPlusPlus) { 15522 DiagKind = diag::err_typecheck_convert_int_pointer; 15523 isInvalid = true; 15524 } else { 15525 DiagKind = diag::ext_typecheck_convert_int_pointer; 15526 } 15527 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15528 MayHaveConvFixit = true; 15529 break; 15530 case IncompatibleFunctionPointer: 15531 if (getLangOpts().CPlusPlus) { 15532 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15533 isInvalid = true; 15534 } else { 15535 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15536 } 15537 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15538 MayHaveConvFixit = true; 15539 break; 15540 case IncompatiblePointer: 15541 if (Action == AA_Passing_CFAudited) { 15542 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15543 } else if (getLangOpts().CPlusPlus) { 15544 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15545 isInvalid = true; 15546 } else { 15547 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15548 } 15549 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15550 SrcType->isObjCObjectPointerType(); 15551 if (Hint.isNull() && !CheckInferredResultType) { 15552 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15553 } 15554 else if (CheckInferredResultType) { 15555 SrcType = SrcType.getUnqualifiedType(); 15556 DstType = DstType.getUnqualifiedType(); 15557 } 15558 MayHaveConvFixit = true; 15559 break; 15560 case IncompatiblePointerSign: 15561 if (getLangOpts().CPlusPlus) { 15562 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15563 isInvalid = true; 15564 } else { 15565 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15566 } 15567 break; 15568 case FunctionVoidPointer: 15569 if (getLangOpts().CPlusPlus) { 15570 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15571 isInvalid = true; 15572 } else { 15573 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15574 } 15575 break; 15576 case IncompatiblePointerDiscardsQualifiers: { 15577 // Perform array-to-pointer decay if necessary. 15578 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15579 15580 isInvalid = true; 15581 15582 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15583 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15584 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15585 DiagKind = diag::err_typecheck_incompatible_address_space; 15586 break; 15587 15588 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15589 DiagKind = diag::err_typecheck_incompatible_ownership; 15590 break; 15591 } 15592 15593 llvm_unreachable("unknown error case for discarding qualifiers!"); 15594 // fallthrough 15595 } 15596 case CompatiblePointerDiscardsQualifiers: 15597 // If the qualifiers lost were because we were applying the 15598 // (deprecated) C++ conversion from a string literal to a char* 15599 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15600 // Ideally, this check would be performed in 15601 // checkPointerTypesForAssignment. However, that would require a 15602 // bit of refactoring (so that the second argument is an 15603 // expression, rather than a type), which should be done as part 15604 // of a larger effort to fix checkPointerTypesForAssignment for 15605 // C++ semantics. 15606 if (getLangOpts().CPlusPlus && 15607 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15608 return false; 15609 if (getLangOpts().CPlusPlus) { 15610 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15611 isInvalid = true; 15612 } else { 15613 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15614 } 15615 15616 break; 15617 case IncompatibleNestedPointerQualifiers: 15618 if (getLangOpts().CPlusPlus) { 15619 isInvalid = true; 15620 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15621 } else { 15622 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15623 } 15624 break; 15625 case IncompatibleNestedPointerAddressSpaceMismatch: 15626 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15627 isInvalid = true; 15628 break; 15629 case IntToBlockPointer: 15630 DiagKind = diag::err_int_to_block_pointer; 15631 isInvalid = true; 15632 break; 15633 case IncompatibleBlockPointer: 15634 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15635 isInvalid = true; 15636 break; 15637 case IncompatibleObjCQualifiedId: { 15638 if (SrcType->isObjCQualifiedIdType()) { 15639 const ObjCObjectPointerType *srcOPT = 15640 SrcType->castAs<ObjCObjectPointerType>(); 15641 for (auto *srcProto : srcOPT->quals()) { 15642 PDecl = srcProto; 15643 break; 15644 } 15645 if (const ObjCInterfaceType *IFaceT = 15646 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15647 IFace = IFaceT->getDecl(); 15648 } 15649 else if (DstType->isObjCQualifiedIdType()) { 15650 const ObjCObjectPointerType *dstOPT = 15651 DstType->castAs<ObjCObjectPointerType>(); 15652 for (auto *dstProto : dstOPT->quals()) { 15653 PDecl = dstProto; 15654 break; 15655 } 15656 if (const ObjCInterfaceType *IFaceT = 15657 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15658 IFace = IFaceT->getDecl(); 15659 } 15660 if (getLangOpts().CPlusPlus) { 15661 DiagKind = diag::err_incompatible_qualified_id; 15662 isInvalid = true; 15663 } else { 15664 DiagKind = diag::warn_incompatible_qualified_id; 15665 } 15666 break; 15667 } 15668 case IncompatibleVectors: 15669 if (getLangOpts().CPlusPlus) { 15670 DiagKind = diag::err_incompatible_vectors; 15671 isInvalid = true; 15672 } else { 15673 DiagKind = diag::warn_incompatible_vectors; 15674 } 15675 break; 15676 case IncompatibleObjCWeakRef: 15677 DiagKind = diag::err_arc_weak_unavailable_assign; 15678 isInvalid = true; 15679 break; 15680 case Incompatible: 15681 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15682 if (Complained) 15683 *Complained = true; 15684 return true; 15685 } 15686 15687 DiagKind = diag::err_typecheck_convert_incompatible; 15688 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15689 MayHaveConvFixit = true; 15690 isInvalid = true; 15691 MayHaveFunctionDiff = true; 15692 break; 15693 } 15694 15695 QualType FirstType, SecondType; 15696 switch (Action) { 15697 case AA_Assigning: 15698 case AA_Initializing: 15699 // The destination type comes first. 15700 FirstType = DstType; 15701 SecondType = SrcType; 15702 break; 15703 15704 case AA_Returning: 15705 case AA_Passing: 15706 case AA_Passing_CFAudited: 15707 case AA_Converting: 15708 case AA_Sending: 15709 case AA_Casting: 15710 // The source type comes first. 15711 FirstType = SrcType; 15712 SecondType = DstType; 15713 break; 15714 } 15715 15716 PartialDiagnostic FDiag = PDiag(DiagKind); 15717 if (Action == AA_Passing_CFAudited) 15718 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15719 else 15720 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15721 15722 // If we can fix the conversion, suggest the FixIts. 15723 assert(ConvHints.isNull() || Hint.isNull()); 15724 if (!ConvHints.isNull()) { 15725 for (FixItHint &H : ConvHints.Hints) 15726 FDiag << H; 15727 } else { 15728 FDiag << Hint; 15729 } 15730 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15731 15732 if (MayHaveFunctionDiff) 15733 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15734 15735 Diag(Loc, FDiag); 15736 if ((DiagKind == diag::warn_incompatible_qualified_id || 15737 DiagKind == diag::err_incompatible_qualified_id) && 15738 PDecl && IFace && !IFace->hasDefinition()) 15739 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15740 << IFace << PDecl; 15741 15742 if (SecondType == Context.OverloadTy) 15743 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15744 FirstType, /*TakingAddress=*/true); 15745 15746 if (CheckInferredResultType) 15747 EmitRelatedResultTypeNote(SrcExpr); 15748 15749 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15750 EmitRelatedResultTypeNoteForReturn(DstType); 15751 15752 if (Complained) 15753 *Complained = true; 15754 return isInvalid; 15755 } 15756 15757 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15758 llvm::APSInt *Result) { 15759 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15760 public: 15761 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15762 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15763 } 15764 } Diagnoser; 15765 15766 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15767 } 15768 15769 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15770 llvm::APSInt *Result, 15771 unsigned DiagID, 15772 bool AllowFold) { 15773 class IDDiagnoser : public VerifyICEDiagnoser { 15774 unsigned DiagID; 15775 15776 public: 15777 IDDiagnoser(unsigned DiagID) 15778 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15779 15780 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15781 S.Diag(Loc, DiagID) << SR; 15782 } 15783 } Diagnoser(DiagID); 15784 15785 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15786 } 15787 15788 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15789 SourceRange SR) { 15790 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15791 } 15792 15793 ExprResult 15794 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15795 VerifyICEDiagnoser &Diagnoser, 15796 bool AllowFold) { 15797 SourceLocation DiagLoc = E->getBeginLoc(); 15798 15799 if (getLangOpts().CPlusPlus11) { 15800 // C++11 [expr.const]p5: 15801 // If an expression of literal class type is used in a context where an 15802 // integral constant expression is required, then that class type shall 15803 // have a single non-explicit conversion function to an integral or 15804 // unscoped enumeration type 15805 ExprResult Converted; 15806 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15807 public: 15808 CXX11ConvertDiagnoser(bool Silent) 15809 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15810 Silent, true) {} 15811 15812 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15813 QualType T) override { 15814 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15815 } 15816 15817 SemaDiagnosticBuilder diagnoseIncomplete( 15818 Sema &S, SourceLocation Loc, QualType T) override { 15819 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15820 } 15821 15822 SemaDiagnosticBuilder diagnoseExplicitConv( 15823 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15824 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15825 } 15826 15827 SemaDiagnosticBuilder noteExplicitConv( 15828 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15829 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15830 << ConvTy->isEnumeralType() << ConvTy; 15831 } 15832 15833 SemaDiagnosticBuilder diagnoseAmbiguous( 15834 Sema &S, SourceLocation Loc, QualType T) override { 15835 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15836 } 15837 15838 SemaDiagnosticBuilder noteAmbiguous( 15839 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15840 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15841 << ConvTy->isEnumeralType() << ConvTy; 15842 } 15843 15844 SemaDiagnosticBuilder diagnoseConversion( 15845 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15846 llvm_unreachable("conversion functions are permitted"); 15847 } 15848 } ConvertDiagnoser(Diagnoser.Suppress); 15849 15850 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15851 ConvertDiagnoser); 15852 if (Converted.isInvalid()) 15853 return Converted; 15854 E = Converted.get(); 15855 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15856 return ExprError(); 15857 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15858 // An ICE must be of integral or unscoped enumeration type. 15859 if (!Diagnoser.Suppress) 15860 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15861 return ExprError(); 15862 } 15863 15864 ExprResult RValueExpr = DefaultLvalueConversion(E); 15865 if (RValueExpr.isInvalid()) 15866 return ExprError(); 15867 15868 E = RValueExpr.get(); 15869 15870 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15871 // in the non-ICE case. 15872 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15873 if (Result) 15874 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15875 if (!isa<ConstantExpr>(E)) 15876 E = ConstantExpr::Create(Context, E); 15877 return E; 15878 } 15879 15880 Expr::EvalResult EvalResult; 15881 SmallVector<PartialDiagnosticAt, 8> Notes; 15882 EvalResult.Diag = &Notes; 15883 15884 // Try to evaluate the expression, and produce diagnostics explaining why it's 15885 // not a constant expression as a side-effect. 15886 bool Folded = 15887 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15888 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15889 15890 if (!isa<ConstantExpr>(E)) 15891 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15892 15893 // In C++11, we can rely on diagnostics being produced for any expression 15894 // which is not a constant expression. If no diagnostics were produced, then 15895 // this is a constant expression. 15896 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15897 if (Result) 15898 *Result = EvalResult.Val.getInt(); 15899 return E; 15900 } 15901 15902 // If our only note is the usual "invalid subexpression" note, just point 15903 // the caret at its location rather than producing an essentially 15904 // redundant note. 15905 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15906 diag::note_invalid_subexpr_in_const_expr) { 15907 DiagLoc = Notes[0].first; 15908 Notes.clear(); 15909 } 15910 15911 if (!Folded || !AllowFold) { 15912 if (!Diagnoser.Suppress) { 15913 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15914 for (const PartialDiagnosticAt &Note : Notes) 15915 Diag(Note.first, Note.second); 15916 } 15917 15918 return ExprError(); 15919 } 15920 15921 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15922 for (const PartialDiagnosticAt &Note : Notes) 15923 Diag(Note.first, Note.second); 15924 15925 if (Result) 15926 *Result = EvalResult.Val.getInt(); 15927 return E; 15928 } 15929 15930 namespace { 15931 // Handle the case where we conclude a expression which we speculatively 15932 // considered to be unevaluated is actually evaluated. 15933 class TransformToPE : public TreeTransform<TransformToPE> { 15934 typedef TreeTransform<TransformToPE> BaseTransform; 15935 15936 public: 15937 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15938 15939 // Make sure we redo semantic analysis 15940 bool AlwaysRebuild() { return true; } 15941 bool ReplacingOriginal() { return true; } 15942 15943 // We need to special-case DeclRefExprs referring to FieldDecls which 15944 // are not part of a member pointer formation; normal TreeTransforming 15945 // doesn't catch this case because of the way we represent them in the AST. 15946 // FIXME: This is a bit ugly; is it really the best way to handle this 15947 // case? 15948 // 15949 // Error on DeclRefExprs referring to FieldDecls. 15950 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15951 if (isa<FieldDecl>(E->getDecl()) && 15952 !SemaRef.isUnevaluatedContext()) 15953 return SemaRef.Diag(E->getLocation(), 15954 diag::err_invalid_non_static_member_use) 15955 << E->getDecl() << E->getSourceRange(); 15956 15957 return BaseTransform::TransformDeclRefExpr(E); 15958 } 15959 15960 // Exception: filter out member pointer formation 15961 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15962 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15963 return E; 15964 15965 return BaseTransform::TransformUnaryOperator(E); 15966 } 15967 15968 // The body of a lambda-expression is in a separate expression evaluation 15969 // context so never needs to be transformed. 15970 // FIXME: Ideally we wouldn't transform the closure type either, and would 15971 // just recreate the capture expressions and lambda expression. 15972 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15973 return SkipLambdaBody(E, Body); 15974 } 15975 }; 15976 } 15977 15978 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15979 assert(isUnevaluatedContext() && 15980 "Should only transform unevaluated expressions"); 15981 ExprEvalContexts.back().Context = 15982 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15983 if (isUnevaluatedContext()) 15984 return E; 15985 return TransformToPE(*this).TransformExpr(E); 15986 } 15987 15988 void 15989 Sema::PushExpressionEvaluationContext( 15990 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15991 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15992 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15993 LambdaContextDecl, ExprContext); 15994 Cleanup.reset(); 15995 if (!MaybeODRUseExprs.empty()) 15996 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15997 } 15998 15999 void 16000 Sema::PushExpressionEvaluationContext( 16001 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16002 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16003 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16004 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16005 } 16006 16007 namespace { 16008 16009 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16010 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16011 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16012 if (E->getOpcode() == UO_Deref) 16013 return CheckPossibleDeref(S, E->getSubExpr()); 16014 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16015 return CheckPossibleDeref(S, E->getBase()); 16016 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16017 return CheckPossibleDeref(S, E->getBase()); 16018 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16019 QualType Inner; 16020 QualType Ty = E->getType(); 16021 if (const auto *Ptr = Ty->getAs<PointerType>()) 16022 Inner = Ptr->getPointeeType(); 16023 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16024 Inner = Arr->getElementType(); 16025 else 16026 return nullptr; 16027 16028 if (Inner->hasAttr(attr::NoDeref)) 16029 return E; 16030 } 16031 return nullptr; 16032 } 16033 16034 } // namespace 16035 16036 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16037 for (const Expr *E : Rec.PossibleDerefs) { 16038 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16039 if (DeclRef) { 16040 const ValueDecl *Decl = DeclRef->getDecl(); 16041 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16042 << Decl->getName() << E->getSourceRange(); 16043 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16044 } else { 16045 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16046 << E->getSourceRange(); 16047 } 16048 } 16049 Rec.PossibleDerefs.clear(); 16050 } 16051 16052 /// Check whether E, which is either a discarded-value expression or an 16053 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16054 /// and if so, remove it from the list of volatile-qualified assignments that 16055 /// we are going to warn are deprecated. 16056 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16057 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16058 return; 16059 16060 // Note: ignoring parens here is not justified by the standard rules, but 16061 // ignoring parentheses seems like a more reasonable approach, and this only 16062 // drives a deprecation warning so doesn't affect conformance. 16063 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16064 if (BO->getOpcode() == BO_Assign) { 16065 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16066 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16067 LHSs.end()); 16068 } 16069 } 16070 } 16071 16072 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16073 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16074 RebuildingImmediateInvocation) 16075 return E; 16076 16077 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16078 /// It's OK if this fails; we'll also remove this in 16079 /// HandleImmediateInvocations, but catching it here allows us to avoid 16080 /// walking the AST looking for it in simple cases. 16081 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16082 if (auto *DeclRef = 16083 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16084 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16085 16086 E = MaybeCreateExprWithCleanups(E); 16087 16088 ConstantExpr *Res = ConstantExpr::Create( 16089 getASTContext(), E.get(), 16090 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 16091 getASTContext()), 16092 /*IsImmediateInvocation*/ true); 16093 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16094 return Res; 16095 } 16096 16097 static void EvaluateAndDiagnoseImmediateInvocation( 16098 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16099 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16100 Expr::EvalResult Eval; 16101 Eval.Diag = &Notes; 16102 ConstantExpr *CE = Candidate.getPointer(); 16103 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 16104 SemaRef.getASTContext(), true); 16105 if (!Result || !Notes.empty()) { 16106 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16107 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16108 InnerExpr = FunctionalCast->getSubExpr(); 16109 FunctionDecl *FD = nullptr; 16110 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16111 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16112 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16113 FD = Call->getConstructor(); 16114 else 16115 llvm_unreachable("unhandled decl kind"); 16116 assert(FD->isConsteval()); 16117 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16118 for (auto &Note : Notes) 16119 SemaRef.Diag(Note.first, Note.second); 16120 return; 16121 } 16122 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16123 } 16124 16125 static void RemoveNestedImmediateInvocation( 16126 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16127 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16128 struct ComplexRemove : TreeTransform<ComplexRemove> { 16129 using Base = TreeTransform<ComplexRemove>; 16130 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16131 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16132 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16133 CurrentII; 16134 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16135 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16136 SmallVector<Sema::ImmediateInvocationCandidate, 16137 4>::reverse_iterator Current) 16138 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16139 void RemoveImmediateInvocation(ConstantExpr* E) { 16140 auto It = std::find_if(CurrentII, IISet.rend(), 16141 [E](Sema::ImmediateInvocationCandidate Elem) { 16142 return Elem.getPointer() == E; 16143 }); 16144 assert(It != IISet.rend() && 16145 "ConstantExpr marked IsImmediateInvocation should " 16146 "be present"); 16147 It->setInt(1); // Mark as deleted 16148 } 16149 ExprResult TransformConstantExpr(ConstantExpr *E) { 16150 if (!E->isImmediateInvocation()) 16151 return Base::TransformConstantExpr(E); 16152 RemoveImmediateInvocation(E); 16153 return Base::TransformExpr(E->getSubExpr()); 16154 } 16155 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16156 /// we need to remove its DeclRefExpr from the DRSet. 16157 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16158 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16159 return Base::TransformCXXOperatorCallExpr(E); 16160 } 16161 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16162 /// here. 16163 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16164 if (!Init) 16165 return Init; 16166 /// ConstantExpr are the first layer of implicit node to be removed so if 16167 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16168 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16169 if (CE->isImmediateInvocation()) 16170 RemoveImmediateInvocation(CE); 16171 return Base::TransformInitializer(Init, NotCopyInit); 16172 } 16173 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16174 DRSet.erase(E); 16175 return E; 16176 } 16177 bool AlwaysRebuild() { return false; } 16178 bool ReplacingOriginal() { return true; } 16179 bool AllowSkippingCXXConstructExpr() { 16180 bool Res = AllowSkippingFirstCXXConstructExpr; 16181 AllowSkippingFirstCXXConstructExpr = true; 16182 return Res; 16183 } 16184 bool AllowSkippingFirstCXXConstructExpr = true; 16185 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16186 Rec.ImmediateInvocationCandidates, It); 16187 16188 /// CXXConstructExpr with a single argument are getting skipped by 16189 /// TreeTransform in some situtation because they could be implicit. This 16190 /// can only occur for the top-level CXXConstructExpr because it is used 16191 /// nowhere in the expression being transformed therefore will not be rebuilt. 16192 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16193 /// skipping the first CXXConstructExpr. 16194 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16195 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16196 16197 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16198 assert(Res.isUsable()); 16199 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16200 It->getPointer()->setSubExpr(Res.get()); 16201 } 16202 16203 static void 16204 HandleImmediateInvocations(Sema &SemaRef, 16205 Sema::ExpressionEvaluationContextRecord &Rec) { 16206 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16207 Rec.ReferenceToConsteval.size() == 0) || 16208 SemaRef.RebuildingImmediateInvocation) 16209 return; 16210 16211 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16212 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16213 /// need to remove ReferenceToConsteval in the immediate invocation. 16214 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16215 16216 /// Prevent sema calls during the tree transform from adding pointers that 16217 /// are already in the sets. 16218 llvm::SaveAndRestore<bool> DisableIITracking( 16219 SemaRef.RebuildingImmediateInvocation, true); 16220 16221 /// Prevent diagnostic during tree transfrom as they are duplicates 16222 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16223 16224 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16225 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16226 if (!It->getInt()) 16227 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16228 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16229 Rec.ReferenceToConsteval.size()) { 16230 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16231 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16232 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16233 bool VisitDeclRefExpr(DeclRefExpr *E) { 16234 DRSet.erase(E); 16235 return DRSet.size(); 16236 } 16237 } Visitor(Rec.ReferenceToConsteval); 16238 Visitor.TraverseStmt( 16239 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16240 } 16241 for (auto CE : Rec.ImmediateInvocationCandidates) 16242 if (!CE.getInt()) 16243 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16244 for (auto DR : Rec.ReferenceToConsteval) { 16245 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16246 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16247 << FD; 16248 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16249 } 16250 } 16251 16252 void Sema::PopExpressionEvaluationContext() { 16253 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16254 unsigned NumTypos = Rec.NumTypos; 16255 16256 if (!Rec.Lambdas.empty()) { 16257 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16258 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16259 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16260 unsigned D; 16261 if (Rec.isUnevaluated()) { 16262 // C++11 [expr.prim.lambda]p2: 16263 // A lambda-expression shall not appear in an unevaluated operand 16264 // (Clause 5). 16265 D = diag::err_lambda_unevaluated_operand; 16266 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16267 // C++1y [expr.const]p2: 16268 // A conditional-expression e is a core constant expression unless the 16269 // evaluation of e, following the rules of the abstract machine, would 16270 // evaluate [...] a lambda-expression. 16271 D = diag::err_lambda_in_constant_expression; 16272 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16273 // C++17 [expr.prim.lamda]p2: 16274 // A lambda-expression shall not appear [...] in a template-argument. 16275 D = diag::err_lambda_in_invalid_context; 16276 } else 16277 llvm_unreachable("Couldn't infer lambda error message."); 16278 16279 for (const auto *L : Rec.Lambdas) 16280 Diag(L->getBeginLoc(), D); 16281 } 16282 } 16283 16284 WarnOnPendingNoDerefs(Rec); 16285 HandleImmediateInvocations(*this, Rec); 16286 16287 // Warn on any volatile-qualified simple-assignments that are not discarded- 16288 // value expressions nor unevaluated operands (those cases get removed from 16289 // this list by CheckUnusedVolatileAssignment). 16290 for (auto *BO : Rec.VolatileAssignmentLHSs) 16291 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16292 << BO->getType(); 16293 16294 // When are coming out of an unevaluated context, clear out any 16295 // temporaries that we may have created as part of the evaluation of 16296 // the expression in that context: they aren't relevant because they 16297 // will never be constructed. 16298 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16299 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16300 ExprCleanupObjects.end()); 16301 Cleanup = Rec.ParentCleanup; 16302 CleanupVarDeclMarking(); 16303 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16304 // Otherwise, merge the contexts together. 16305 } else { 16306 Cleanup.mergeFrom(Rec.ParentCleanup); 16307 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16308 Rec.SavedMaybeODRUseExprs.end()); 16309 } 16310 16311 // Pop the current expression evaluation context off the stack. 16312 ExprEvalContexts.pop_back(); 16313 16314 // The global expression evaluation context record is never popped. 16315 ExprEvalContexts.back().NumTypos += NumTypos; 16316 } 16317 16318 void Sema::DiscardCleanupsInEvaluationContext() { 16319 ExprCleanupObjects.erase( 16320 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16321 ExprCleanupObjects.end()); 16322 Cleanup.reset(); 16323 MaybeODRUseExprs.clear(); 16324 } 16325 16326 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16327 ExprResult Result = CheckPlaceholderExpr(E); 16328 if (Result.isInvalid()) 16329 return ExprError(); 16330 E = Result.get(); 16331 if (!E->getType()->isVariablyModifiedType()) 16332 return E; 16333 return TransformToPotentiallyEvaluated(E); 16334 } 16335 16336 /// Are we in a context that is potentially constant evaluated per C++20 16337 /// [expr.const]p12? 16338 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16339 /// C++2a [expr.const]p12: 16340 // An expression or conversion is potentially constant evaluated if it is 16341 switch (SemaRef.ExprEvalContexts.back().Context) { 16342 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16343 // -- a manifestly constant-evaluated expression, 16344 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16345 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16346 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16347 // -- a potentially-evaluated expression, 16348 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16349 // -- an immediate subexpression of a braced-init-list, 16350 16351 // -- [FIXME] an expression of the form & cast-expression that occurs 16352 // within a templated entity 16353 // -- a subexpression of one of the above that is not a subexpression of 16354 // a nested unevaluated operand. 16355 return true; 16356 16357 case Sema::ExpressionEvaluationContext::Unevaluated: 16358 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16359 // Expressions in this context are never evaluated. 16360 return false; 16361 } 16362 llvm_unreachable("Invalid context"); 16363 } 16364 16365 /// Return true if this function has a calling convention that requires mangling 16366 /// in the size of the parameter pack. 16367 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16368 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16369 // we don't need parameter type sizes. 16370 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16371 if (!TT.isOSWindows() || !TT.isX86()) 16372 return false; 16373 16374 // If this is C++ and this isn't an extern "C" function, parameters do not 16375 // need to be complete. In this case, C++ mangling will apply, which doesn't 16376 // use the size of the parameters. 16377 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16378 return false; 16379 16380 // Stdcall, fastcall, and vectorcall need this special treatment. 16381 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16382 switch (CC) { 16383 case CC_X86StdCall: 16384 case CC_X86FastCall: 16385 case CC_X86VectorCall: 16386 return true; 16387 default: 16388 break; 16389 } 16390 return false; 16391 } 16392 16393 /// Require that all of the parameter types of function be complete. Normally, 16394 /// parameter types are only required to be complete when a function is called 16395 /// or defined, but to mangle functions with certain calling conventions, the 16396 /// mangler needs to know the size of the parameter list. In this situation, 16397 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16398 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16399 /// result in a linker error. Clang doesn't implement this behavior, and instead 16400 /// attempts to error at compile time. 16401 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16402 SourceLocation Loc) { 16403 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16404 FunctionDecl *FD; 16405 ParmVarDecl *Param; 16406 16407 public: 16408 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16409 : FD(FD), Param(Param) {} 16410 16411 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16412 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16413 StringRef CCName; 16414 switch (CC) { 16415 case CC_X86StdCall: 16416 CCName = "stdcall"; 16417 break; 16418 case CC_X86FastCall: 16419 CCName = "fastcall"; 16420 break; 16421 case CC_X86VectorCall: 16422 CCName = "vectorcall"; 16423 break; 16424 default: 16425 llvm_unreachable("CC does not need mangling"); 16426 } 16427 16428 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16429 << Param->getDeclName() << FD->getDeclName() << CCName; 16430 } 16431 }; 16432 16433 for (ParmVarDecl *Param : FD->parameters()) { 16434 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16435 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16436 } 16437 } 16438 16439 namespace { 16440 enum class OdrUseContext { 16441 /// Declarations in this context are not odr-used. 16442 None, 16443 /// Declarations in this context are formally odr-used, but this is a 16444 /// dependent context. 16445 Dependent, 16446 /// Declarations in this context are odr-used but not actually used (yet). 16447 FormallyOdrUsed, 16448 /// Declarations in this context are used. 16449 Used 16450 }; 16451 } 16452 16453 /// Are we within a context in which references to resolved functions or to 16454 /// variables result in odr-use? 16455 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16456 OdrUseContext Result; 16457 16458 switch (SemaRef.ExprEvalContexts.back().Context) { 16459 case Sema::ExpressionEvaluationContext::Unevaluated: 16460 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16461 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16462 return OdrUseContext::None; 16463 16464 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16465 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16466 Result = OdrUseContext::Used; 16467 break; 16468 16469 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16470 Result = OdrUseContext::FormallyOdrUsed; 16471 break; 16472 16473 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16474 // A default argument formally results in odr-use, but doesn't actually 16475 // result in a use in any real sense until it itself is used. 16476 Result = OdrUseContext::FormallyOdrUsed; 16477 break; 16478 } 16479 16480 if (SemaRef.CurContext->isDependentContext()) 16481 return OdrUseContext::Dependent; 16482 16483 return Result; 16484 } 16485 16486 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16487 return Func->isConstexpr() && 16488 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 16489 } 16490 16491 /// Mark a function referenced, and check whether it is odr-used 16492 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16493 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16494 bool MightBeOdrUse) { 16495 assert(Func && "No function?"); 16496 16497 Func->setReferenced(); 16498 16499 // Recursive functions aren't really used until they're used from some other 16500 // context. 16501 bool IsRecursiveCall = CurContext == Func; 16502 16503 // C++11 [basic.def.odr]p3: 16504 // A function whose name appears as a potentially-evaluated expression is 16505 // odr-used if it is the unique lookup result or the selected member of a 16506 // set of overloaded functions [...]. 16507 // 16508 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16509 // can just check that here. 16510 OdrUseContext OdrUse = 16511 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16512 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16513 OdrUse = OdrUseContext::FormallyOdrUsed; 16514 16515 // Trivial default constructors and destructors are never actually used. 16516 // FIXME: What about other special members? 16517 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16518 OdrUse == OdrUseContext::Used) { 16519 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16520 if (Constructor->isDefaultConstructor()) 16521 OdrUse = OdrUseContext::FormallyOdrUsed; 16522 if (isa<CXXDestructorDecl>(Func)) 16523 OdrUse = OdrUseContext::FormallyOdrUsed; 16524 } 16525 16526 // C++20 [expr.const]p12: 16527 // A function [...] is needed for constant evaluation if it is [...] a 16528 // constexpr function that is named by an expression that is potentially 16529 // constant evaluated 16530 bool NeededForConstantEvaluation = 16531 isPotentiallyConstantEvaluatedContext(*this) && 16532 isImplicitlyDefinableConstexprFunction(Func); 16533 16534 // Determine whether we require a function definition to exist, per 16535 // C++11 [temp.inst]p3: 16536 // Unless a function template specialization has been explicitly 16537 // instantiated or explicitly specialized, the function template 16538 // specialization is implicitly instantiated when the specialization is 16539 // referenced in a context that requires a function definition to exist. 16540 // C++20 [temp.inst]p7: 16541 // The existence of a definition of a [...] function is considered to 16542 // affect the semantics of the program if the [...] function is needed for 16543 // constant evaluation by an expression 16544 // C++20 [basic.def.odr]p10: 16545 // Every program shall contain exactly one definition of every non-inline 16546 // function or variable that is odr-used in that program outside of a 16547 // discarded statement 16548 // C++20 [special]p1: 16549 // The implementation will implicitly define [defaulted special members] 16550 // if they are odr-used or needed for constant evaluation. 16551 // 16552 // Note that we skip the implicit instantiation of templates that are only 16553 // used in unused default arguments or by recursive calls to themselves. 16554 // This is formally non-conforming, but seems reasonable in practice. 16555 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16556 NeededForConstantEvaluation); 16557 16558 // C++14 [temp.expl.spec]p6: 16559 // If a template [...] is explicitly specialized then that specialization 16560 // shall be declared before the first use of that specialization that would 16561 // cause an implicit instantiation to take place, in every translation unit 16562 // in which such a use occurs 16563 if (NeedDefinition && 16564 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16565 Func->getMemberSpecializationInfo())) 16566 checkSpecializationVisibility(Loc, Func); 16567 16568 if (getLangOpts().CUDA) 16569 CheckCUDACall(Loc, Func); 16570 16571 if (getLangOpts().SYCLIsDevice) 16572 checkSYCLDeviceFunction(Loc, Func); 16573 16574 // If we need a definition, try to create one. 16575 if (NeedDefinition && !Func->getBody()) { 16576 runWithSufficientStackSpace(Loc, [&] { 16577 if (CXXConstructorDecl *Constructor = 16578 dyn_cast<CXXConstructorDecl>(Func)) { 16579 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16580 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16581 if (Constructor->isDefaultConstructor()) { 16582 if (Constructor->isTrivial() && 16583 !Constructor->hasAttr<DLLExportAttr>()) 16584 return; 16585 DefineImplicitDefaultConstructor(Loc, Constructor); 16586 } else if (Constructor->isCopyConstructor()) { 16587 DefineImplicitCopyConstructor(Loc, Constructor); 16588 } else if (Constructor->isMoveConstructor()) { 16589 DefineImplicitMoveConstructor(Loc, Constructor); 16590 } 16591 } else if (Constructor->getInheritedConstructor()) { 16592 DefineInheritingConstructor(Loc, Constructor); 16593 } 16594 } else if (CXXDestructorDecl *Destructor = 16595 dyn_cast<CXXDestructorDecl>(Func)) { 16596 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16597 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16598 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16599 return; 16600 DefineImplicitDestructor(Loc, Destructor); 16601 } 16602 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16603 MarkVTableUsed(Loc, Destructor->getParent()); 16604 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16605 if (MethodDecl->isOverloadedOperator() && 16606 MethodDecl->getOverloadedOperator() == OO_Equal) { 16607 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16608 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16609 if (MethodDecl->isCopyAssignmentOperator()) 16610 DefineImplicitCopyAssignment(Loc, MethodDecl); 16611 else if (MethodDecl->isMoveAssignmentOperator()) 16612 DefineImplicitMoveAssignment(Loc, MethodDecl); 16613 } 16614 } else if (isa<CXXConversionDecl>(MethodDecl) && 16615 MethodDecl->getParent()->isLambda()) { 16616 CXXConversionDecl *Conversion = 16617 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16618 if (Conversion->isLambdaToBlockPointerConversion()) 16619 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16620 else 16621 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16622 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16623 MarkVTableUsed(Loc, MethodDecl->getParent()); 16624 } 16625 16626 if (Func->isDefaulted() && !Func->isDeleted()) { 16627 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16628 if (DCK != DefaultedComparisonKind::None) 16629 DefineDefaultedComparison(Loc, Func, DCK); 16630 } 16631 16632 // Implicit instantiation of function templates and member functions of 16633 // class templates. 16634 if (Func->isImplicitlyInstantiable()) { 16635 TemplateSpecializationKind TSK = 16636 Func->getTemplateSpecializationKindForInstantiation(); 16637 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16638 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16639 if (FirstInstantiation) { 16640 PointOfInstantiation = Loc; 16641 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16642 } else if (TSK != TSK_ImplicitInstantiation) { 16643 // Use the point of use as the point of instantiation, instead of the 16644 // point of explicit instantiation (which we track as the actual point 16645 // of instantiation). This gives better backtraces in diagnostics. 16646 PointOfInstantiation = Loc; 16647 } 16648 16649 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16650 Func->isConstexpr()) { 16651 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16652 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16653 CodeSynthesisContexts.size()) 16654 PendingLocalImplicitInstantiations.push_back( 16655 std::make_pair(Func, PointOfInstantiation)); 16656 else if (Func->isConstexpr()) 16657 // Do not defer instantiations of constexpr functions, to avoid the 16658 // expression evaluator needing to call back into Sema if it sees a 16659 // call to such a function. 16660 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16661 else { 16662 Func->setInstantiationIsPending(true); 16663 PendingInstantiations.push_back( 16664 std::make_pair(Func, PointOfInstantiation)); 16665 // Notify the consumer that a function was implicitly instantiated. 16666 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16667 } 16668 } 16669 } else { 16670 // Walk redefinitions, as some of them may be instantiable. 16671 for (auto i : Func->redecls()) { 16672 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16673 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16674 } 16675 } 16676 }); 16677 } 16678 16679 // C++14 [except.spec]p17: 16680 // An exception-specification is considered to be needed when: 16681 // - the function is odr-used or, if it appears in an unevaluated operand, 16682 // would be odr-used if the expression were potentially-evaluated; 16683 // 16684 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16685 // function is a pure virtual function we're calling, and in that case the 16686 // function was selected by overload resolution and we need to resolve its 16687 // exception specification for a different reason. 16688 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16689 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16690 ResolveExceptionSpec(Loc, FPT); 16691 16692 // If this is the first "real" use, act on that. 16693 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16694 // Keep track of used but undefined functions. 16695 if (!Func->isDefined()) { 16696 if (mightHaveNonExternalLinkage(Func)) 16697 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16698 else if (Func->getMostRecentDecl()->isInlined() && 16699 !LangOpts.GNUInline && 16700 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16701 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16702 else if (isExternalWithNoLinkageType(Func)) 16703 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16704 } 16705 16706 // Some x86 Windows calling conventions mangle the size of the parameter 16707 // pack into the name. Computing the size of the parameters requires the 16708 // parameter types to be complete. Check that now. 16709 if (funcHasParameterSizeMangling(*this, Func)) 16710 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16711 16712 // In the MS C++ ABI, the compiler emits destructor variants where they are 16713 // used. If the destructor is used here but defined elsewhere, mark the 16714 // virtual base destructors referenced. If those virtual base destructors 16715 // are inline, this will ensure they are defined when emitting the complete 16716 // destructor variant. This checking may be redundant if the destructor is 16717 // provided later in this TU. 16718 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16719 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16720 CXXRecordDecl *Parent = Dtor->getParent(); 16721 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16722 CheckCompleteDestructorVariant(Loc, Dtor); 16723 } 16724 } 16725 16726 Func->markUsed(Context); 16727 } 16728 } 16729 16730 /// Directly mark a variable odr-used. Given a choice, prefer to use 16731 /// MarkVariableReferenced since it does additional checks and then 16732 /// calls MarkVarDeclODRUsed. 16733 /// If the variable must be captured: 16734 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16735 /// - else capture it in the DeclContext that maps to the 16736 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16737 static void 16738 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16739 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16740 // Keep track of used but undefined variables. 16741 // FIXME: We shouldn't suppress this warning for static data members. 16742 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16743 (!Var->isExternallyVisible() || Var->isInline() || 16744 SemaRef.isExternalWithNoLinkageType(Var)) && 16745 !(Var->isStaticDataMember() && Var->hasInit())) { 16746 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16747 if (old.isInvalid()) 16748 old = Loc; 16749 } 16750 QualType CaptureType, DeclRefType; 16751 if (SemaRef.LangOpts.OpenMP) 16752 SemaRef.tryCaptureOpenMPLambdas(Var); 16753 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16754 /*EllipsisLoc*/ SourceLocation(), 16755 /*BuildAndDiagnose*/ true, 16756 CaptureType, DeclRefType, 16757 FunctionScopeIndexToStopAt); 16758 16759 Var->markUsed(SemaRef.Context); 16760 } 16761 16762 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16763 SourceLocation Loc, 16764 unsigned CapturingScopeIndex) { 16765 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16766 } 16767 16768 static void 16769 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16770 ValueDecl *var, DeclContext *DC) { 16771 DeclContext *VarDC = var->getDeclContext(); 16772 16773 // If the parameter still belongs to the translation unit, then 16774 // we're actually just using one parameter in the declaration of 16775 // the next. 16776 if (isa<ParmVarDecl>(var) && 16777 isa<TranslationUnitDecl>(VarDC)) 16778 return; 16779 16780 // For C code, don't diagnose about capture if we're not actually in code 16781 // right now; it's impossible to write a non-constant expression outside of 16782 // function context, so we'll get other (more useful) diagnostics later. 16783 // 16784 // For C++, things get a bit more nasty... it would be nice to suppress this 16785 // diagnostic for certain cases like using a local variable in an array bound 16786 // for a member of a local class, but the correct predicate is not obvious. 16787 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16788 return; 16789 16790 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16791 unsigned ContextKind = 3; // unknown 16792 if (isa<CXXMethodDecl>(VarDC) && 16793 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16794 ContextKind = 2; 16795 } else if (isa<FunctionDecl>(VarDC)) { 16796 ContextKind = 0; 16797 } else if (isa<BlockDecl>(VarDC)) { 16798 ContextKind = 1; 16799 } 16800 16801 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16802 << var << ValueKind << ContextKind << VarDC; 16803 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16804 << var; 16805 16806 // FIXME: Add additional diagnostic info about class etc. which prevents 16807 // capture. 16808 } 16809 16810 16811 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16812 bool &SubCapturesAreNested, 16813 QualType &CaptureType, 16814 QualType &DeclRefType) { 16815 // Check whether we've already captured it. 16816 if (CSI->CaptureMap.count(Var)) { 16817 // If we found a capture, any subcaptures are nested. 16818 SubCapturesAreNested = true; 16819 16820 // Retrieve the capture type for this variable. 16821 CaptureType = CSI->getCapture(Var).getCaptureType(); 16822 16823 // Compute the type of an expression that refers to this variable. 16824 DeclRefType = CaptureType.getNonReferenceType(); 16825 16826 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16827 // are mutable in the sense that user can change their value - they are 16828 // private instances of the captured declarations. 16829 const Capture &Cap = CSI->getCapture(Var); 16830 if (Cap.isCopyCapture() && 16831 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16832 !(isa<CapturedRegionScopeInfo>(CSI) && 16833 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16834 DeclRefType.addConst(); 16835 return true; 16836 } 16837 return false; 16838 } 16839 16840 // Only block literals, captured statements, and lambda expressions can 16841 // capture; other scopes don't work. 16842 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16843 SourceLocation Loc, 16844 const bool Diagnose, Sema &S) { 16845 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16846 return getLambdaAwareParentOfDeclContext(DC); 16847 else if (Var->hasLocalStorage()) { 16848 if (Diagnose) 16849 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16850 } 16851 return nullptr; 16852 } 16853 16854 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16855 // certain types of variables (unnamed, variably modified types etc.) 16856 // so check for eligibility. 16857 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16858 SourceLocation Loc, 16859 const bool Diagnose, Sema &S) { 16860 16861 bool IsBlock = isa<BlockScopeInfo>(CSI); 16862 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16863 16864 // Lambdas are not allowed to capture unnamed variables 16865 // (e.g. anonymous unions). 16866 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16867 // assuming that's the intent. 16868 if (IsLambda && !Var->getDeclName()) { 16869 if (Diagnose) { 16870 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16871 S.Diag(Var->getLocation(), diag::note_declared_at); 16872 } 16873 return false; 16874 } 16875 16876 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16877 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16878 if (Diagnose) { 16879 S.Diag(Loc, diag::err_ref_vm_type); 16880 S.Diag(Var->getLocation(), diag::note_previous_decl) 16881 << Var->getDeclName(); 16882 } 16883 return false; 16884 } 16885 // Prohibit structs with flexible array members too. 16886 // We cannot capture what is in the tail end of the struct. 16887 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16888 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16889 if (Diagnose) { 16890 if (IsBlock) 16891 S.Diag(Loc, diag::err_ref_flexarray_type); 16892 else 16893 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16894 << Var->getDeclName(); 16895 S.Diag(Var->getLocation(), diag::note_previous_decl) 16896 << Var->getDeclName(); 16897 } 16898 return false; 16899 } 16900 } 16901 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16902 // Lambdas and captured statements are not allowed to capture __block 16903 // variables; they don't support the expected semantics. 16904 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16905 if (Diagnose) { 16906 S.Diag(Loc, diag::err_capture_block_variable) 16907 << Var->getDeclName() << !IsLambda; 16908 S.Diag(Var->getLocation(), diag::note_previous_decl) 16909 << Var->getDeclName(); 16910 } 16911 return false; 16912 } 16913 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16914 if (S.getLangOpts().OpenCL && IsBlock && 16915 Var->getType()->isBlockPointerType()) { 16916 if (Diagnose) 16917 S.Diag(Loc, diag::err_opencl_block_ref_block); 16918 return false; 16919 } 16920 16921 return true; 16922 } 16923 16924 // Returns true if the capture by block was successful. 16925 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16926 SourceLocation Loc, 16927 const bool BuildAndDiagnose, 16928 QualType &CaptureType, 16929 QualType &DeclRefType, 16930 const bool Nested, 16931 Sema &S, bool Invalid) { 16932 bool ByRef = false; 16933 16934 // Blocks are not allowed to capture arrays, excepting OpenCL. 16935 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16936 // (decayed to pointers). 16937 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16938 if (BuildAndDiagnose) { 16939 S.Diag(Loc, diag::err_ref_array_type); 16940 S.Diag(Var->getLocation(), diag::note_previous_decl) 16941 << Var->getDeclName(); 16942 Invalid = true; 16943 } else { 16944 return false; 16945 } 16946 } 16947 16948 // Forbid the block-capture of autoreleasing variables. 16949 if (!Invalid && 16950 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16951 if (BuildAndDiagnose) { 16952 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16953 << /*block*/ 0; 16954 S.Diag(Var->getLocation(), diag::note_previous_decl) 16955 << Var->getDeclName(); 16956 Invalid = true; 16957 } else { 16958 return false; 16959 } 16960 } 16961 16962 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16963 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16964 QualType PointeeTy = PT->getPointeeType(); 16965 16966 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16967 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16968 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16969 if (BuildAndDiagnose) { 16970 SourceLocation VarLoc = Var->getLocation(); 16971 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16972 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16973 } 16974 } 16975 } 16976 16977 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16978 if (HasBlocksAttr || CaptureType->isReferenceType() || 16979 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16980 // Block capture by reference does not change the capture or 16981 // declaration reference types. 16982 ByRef = true; 16983 } else { 16984 // Block capture by copy introduces 'const'. 16985 CaptureType = CaptureType.getNonReferenceType().withConst(); 16986 DeclRefType = CaptureType; 16987 } 16988 16989 // Actually capture the variable. 16990 if (BuildAndDiagnose) 16991 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16992 CaptureType, Invalid); 16993 16994 return !Invalid; 16995 } 16996 16997 16998 /// Capture the given variable in the captured region. 16999 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17000 VarDecl *Var, 17001 SourceLocation Loc, 17002 const bool BuildAndDiagnose, 17003 QualType &CaptureType, 17004 QualType &DeclRefType, 17005 const bool RefersToCapturedVariable, 17006 Sema &S, bool Invalid) { 17007 // By default, capture variables by reference. 17008 bool ByRef = true; 17009 // Using an LValue reference type is consistent with Lambdas (see below). 17010 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17011 if (S.isOpenMPCapturedDecl(Var)) { 17012 bool HasConst = DeclRefType.isConstQualified(); 17013 DeclRefType = DeclRefType.getUnqualifiedType(); 17014 // Don't lose diagnostics about assignments to const. 17015 if (HasConst) 17016 DeclRefType.addConst(); 17017 } 17018 // Do not capture firstprivates in tasks. 17019 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17020 OMPC_unknown) 17021 return true; 17022 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17023 RSI->OpenMPCaptureLevel); 17024 } 17025 17026 if (ByRef) 17027 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17028 else 17029 CaptureType = DeclRefType; 17030 17031 // Actually capture the variable. 17032 if (BuildAndDiagnose) 17033 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17034 Loc, SourceLocation(), CaptureType, Invalid); 17035 17036 return !Invalid; 17037 } 17038 17039 /// Capture the given variable in the lambda. 17040 static bool captureInLambda(LambdaScopeInfo *LSI, 17041 VarDecl *Var, 17042 SourceLocation Loc, 17043 const bool BuildAndDiagnose, 17044 QualType &CaptureType, 17045 QualType &DeclRefType, 17046 const bool RefersToCapturedVariable, 17047 const Sema::TryCaptureKind Kind, 17048 SourceLocation EllipsisLoc, 17049 const bool IsTopScope, 17050 Sema &S, bool Invalid) { 17051 // Determine whether we are capturing by reference or by value. 17052 bool ByRef = false; 17053 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17054 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17055 } else { 17056 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17057 } 17058 17059 // Compute the type of the field that will capture this variable. 17060 if (ByRef) { 17061 // C++11 [expr.prim.lambda]p15: 17062 // An entity is captured by reference if it is implicitly or 17063 // explicitly captured but not captured by copy. It is 17064 // unspecified whether additional unnamed non-static data 17065 // members are declared in the closure type for entities 17066 // captured by reference. 17067 // 17068 // FIXME: It is not clear whether we want to build an lvalue reference 17069 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17070 // to do the former, while EDG does the latter. Core issue 1249 will 17071 // clarify, but for now we follow GCC because it's a more permissive and 17072 // easily defensible position. 17073 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17074 } else { 17075 // C++11 [expr.prim.lambda]p14: 17076 // For each entity captured by copy, an unnamed non-static 17077 // data member is declared in the closure type. The 17078 // declaration order of these members is unspecified. The type 17079 // of such a data member is the type of the corresponding 17080 // captured entity if the entity is not a reference to an 17081 // object, or the referenced type otherwise. [Note: If the 17082 // captured entity is a reference to a function, the 17083 // corresponding data member is also a reference to a 17084 // function. - end note ] 17085 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17086 if (!RefType->getPointeeType()->isFunctionType()) 17087 CaptureType = RefType->getPointeeType(); 17088 } 17089 17090 // Forbid the lambda copy-capture of autoreleasing variables. 17091 if (!Invalid && 17092 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17093 if (BuildAndDiagnose) { 17094 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17095 S.Diag(Var->getLocation(), diag::note_previous_decl) 17096 << Var->getDeclName(); 17097 Invalid = true; 17098 } else { 17099 return false; 17100 } 17101 } 17102 17103 // Make sure that by-copy captures are of a complete and non-abstract type. 17104 if (!Invalid && BuildAndDiagnose) { 17105 if (!CaptureType->isDependentType() && 17106 S.RequireCompleteSizedType( 17107 Loc, CaptureType, 17108 diag::err_capture_of_incomplete_or_sizeless_type, 17109 Var->getDeclName())) 17110 Invalid = true; 17111 else if (S.RequireNonAbstractType(Loc, CaptureType, 17112 diag::err_capture_of_abstract_type)) 17113 Invalid = true; 17114 } 17115 } 17116 17117 // Compute the type of a reference to this captured variable. 17118 if (ByRef) 17119 DeclRefType = CaptureType.getNonReferenceType(); 17120 else { 17121 // C++ [expr.prim.lambda]p5: 17122 // The closure type for a lambda-expression has a public inline 17123 // function call operator [...]. This function call operator is 17124 // declared const (9.3.1) if and only if the lambda-expression's 17125 // parameter-declaration-clause is not followed by mutable. 17126 DeclRefType = CaptureType.getNonReferenceType(); 17127 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17128 DeclRefType.addConst(); 17129 } 17130 17131 // Add the capture. 17132 if (BuildAndDiagnose) 17133 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17134 Loc, EllipsisLoc, CaptureType, Invalid); 17135 17136 return !Invalid; 17137 } 17138 17139 bool Sema::tryCaptureVariable( 17140 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17141 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17142 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17143 // An init-capture is notionally from the context surrounding its 17144 // declaration, but its parent DC is the lambda class. 17145 DeclContext *VarDC = Var->getDeclContext(); 17146 if (Var->isInitCapture()) 17147 VarDC = VarDC->getParent(); 17148 17149 DeclContext *DC = CurContext; 17150 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17151 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17152 // We need to sync up the Declaration Context with the 17153 // FunctionScopeIndexToStopAt 17154 if (FunctionScopeIndexToStopAt) { 17155 unsigned FSIndex = FunctionScopes.size() - 1; 17156 while (FSIndex != MaxFunctionScopesIndex) { 17157 DC = getLambdaAwareParentOfDeclContext(DC); 17158 --FSIndex; 17159 } 17160 } 17161 17162 17163 // If the variable is declared in the current context, there is no need to 17164 // capture it. 17165 if (VarDC == DC) return true; 17166 17167 // Capture global variables if it is required to use private copy of this 17168 // variable. 17169 bool IsGlobal = !Var->hasLocalStorage(); 17170 if (IsGlobal && 17171 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17172 MaxFunctionScopesIndex))) 17173 return true; 17174 Var = Var->getCanonicalDecl(); 17175 17176 // Walk up the stack to determine whether we can capture the variable, 17177 // performing the "simple" checks that don't depend on type. We stop when 17178 // we've either hit the declared scope of the variable or find an existing 17179 // capture of that variable. We start from the innermost capturing-entity 17180 // (the DC) and ensure that all intervening capturing-entities 17181 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17182 // declcontext can either capture the variable or have already captured 17183 // the variable. 17184 CaptureType = Var->getType(); 17185 DeclRefType = CaptureType.getNonReferenceType(); 17186 bool Nested = false; 17187 bool Explicit = (Kind != TryCapture_Implicit); 17188 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17189 do { 17190 // Only block literals, captured statements, and lambda expressions can 17191 // capture; other scopes don't work. 17192 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17193 ExprLoc, 17194 BuildAndDiagnose, 17195 *this); 17196 // We need to check for the parent *first* because, if we *have* 17197 // private-captured a global variable, we need to recursively capture it in 17198 // intermediate blocks, lambdas, etc. 17199 if (!ParentDC) { 17200 if (IsGlobal) { 17201 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17202 break; 17203 } 17204 return true; 17205 } 17206 17207 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17208 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17209 17210 17211 // Check whether we've already captured it. 17212 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17213 DeclRefType)) { 17214 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17215 break; 17216 } 17217 // If we are instantiating a generic lambda call operator body, 17218 // we do not want to capture new variables. What was captured 17219 // during either a lambdas transformation or initial parsing 17220 // should be used. 17221 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17222 if (BuildAndDiagnose) { 17223 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17224 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17225 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17226 Diag(Var->getLocation(), diag::note_previous_decl) 17227 << Var->getDeclName(); 17228 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17229 } else 17230 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17231 } 17232 return true; 17233 } 17234 17235 // Try to capture variable-length arrays types. 17236 if (Var->getType()->isVariablyModifiedType()) { 17237 // We're going to walk down into the type and look for VLA 17238 // expressions. 17239 QualType QTy = Var->getType(); 17240 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17241 QTy = PVD->getOriginalType(); 17242 captureVariablyModifiedType(Context, QTy, CSI); 17243 } 17244 17245 if (getLangOpts().OpenMP) { 17246 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17247 // OpenMP private variables should not be captured in outer scope, so 17248 // just break here. Similarly, global variables that are captured in a 17249 // target region should not be captured outside the scope of the region. 17250 if (RSI->CapRegionKind == CR_OpenMP) { 17251 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17252 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17253 // If the variable is private (i.e. not captured) and has variably 17254 // modified type, we still need to capture the type for correct 17255 // codegen in all regions, associated with the construct. Currently, 17256 // it is captured in the innermost captured region only. 17257 if (IsOpenMPPrivateDecl != OMPC_unknown && 17258 Var->getType()->isVariablyModifiedType()) { 17259 QualType QTy = Var->getType(); 17260 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17261 QTy = PVD->getOriginalType(); 17262 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17263 I < E; ++I) { 17264 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17265 FunctionScopes[FunctionScopesIndex - I]); 17266 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17267 "Wrong number of captured regions associated with the " 17268 "OpenMP construct."); 17269 captureVariablyModifiedType(Context, QTy, OuterRSI); 17270 } 17271 } 17272 bool IsTargetCap = 17273 IsOpenMPPrivateDecl != OMPC_private && 17274 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17275 RSI->OpenMPCaptureLevel); 17276 // Do not capture global if it is not privatized in outer regions. 17277 bool IsGlobalCap = 17278 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17279 RSI->OpenMPCaptureLevel); 17280 17281 // When we detect target captures we are looking from inside the 17282 // target region, therefore we need to propagate the capture from the 17283 // enclosing region. Therefore, the capture is not initially nested. 17284 if (IsTargetCap) 17285 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17286 17287 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17288 (IsGlobal && !IsGlobalCap)) { 17289 Nested = !IsTargetCap; 17290 DeclRefType = DeclRefType.getUnqualifiedType(); 17291 CaptureType = Context.getLValueReferenceType(DeclRefType); 17292 break; 17293 } 17294 } 17295 } 17296 } 17297 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17298 // No capture-default, and this is not an explicit capture 17299 // so cannot capture this variable. 17300 if (BuildAndDiagnose) { 17301 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 17302 Diag(Var->getLocation(), diag::note_previous_decl) 17303 << Var->getDeclName(); 17304 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17305 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17306 diag::note_lambda_decl); 17307 // FIXME: If we error out because an outer lambda can not implicitly 17308 // capture a variable that an inner lambda explicitly captures, we 17309 // should have the inner lambda do the explicit capture - because 17310 // it makes for cleaner diagnostics later. This would purely be done 17311 // so that the diagnostic does not misleadingly claim that a variable 17312 // can not be captured by a lambda implicitly even though it is captured 17313 // explicitly. Suggestion: 17314 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17315 // at the function head 17316 // - cache the StartingDeclContext - this must be a lambda 17317 // - captureInLambda in the innermost lambda the variable. 17318 } 17319 return true; 17320 } 17321 17322 FunctionScopesIndex--; 17323 DC = ParentDC; 17324 Explicit = false; 17325 } while (!VarDC->Equals(DC)); 17326 17327 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17328 // computing the type of the capture at each step, checking type-specific 17329 // requirements, and adding captures if requested. 17330 // If the variable had already been captured previously, we start capturing 17331 // at the lambda nested within that one. 17332 bool Invalid = false; 17333 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17334 ++I) { 17335 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17336 17337 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17338 // certain types of variables (unnamed, variably modified types etc.) 17339 // so check for eligibility. 17340 if (!Invalid) 17341 Invalid = 17342 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17343 17344 // After encountering an error, if we're actually supposed to capture, keep 17345 // capturing in nested contexts to suppress any follow-on diagnostics. 17346 if (Invalid && !BuildAndDiagnose) 17347 return true; 17348 17349 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17350 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17351 DeclRefType, Nested, *this, Invalid); 17352 Nested = true; 17353 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17354 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17355 CaptureType, DeclRefType, Nested, 17356 *this, Invalid); 17357 Nested = true; 17358 } else { 17359 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17360 Invalid = 17361 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17362 DeclRefType, Nested, Kind, EllipsisLoc, 17363 /*IsTopScope*/ I == N - 1, *this, Invalid); 17364 Nested = true; 17365 } 17366 17367 if (Invalid && !BuildAndDiagnose) 17368 return true; 17369 } 17370 return Invalid; 17371 } 17372 17373 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17374 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17375 QualType CaptureType; 17376 QualType DeclRefType; 17377 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17378 /*BuildAndDiagnose=*/true, CaptureType, 17379 DeclRefType, nullptr); 17380 } 17381 17382 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17383 QualType CaptureType; 17384 QualType DeclRefType; 17385 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17386 /*BuildAndDiagnose=*/false, CaptureType, 17387 DeclRefType, nullptr); 17388 } 17389 17390 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17391 QualType CaptureType; 17392 QualType DeclRefType; 17393 17394 // Determine whether we can capture this variable. 17395 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17396 /*BuildAndDiagnose=*/false, CaptureType, 17397 DeclRefType, nullptr)) 17398 return QualType(); 17399 17400 return DeclRefType; 17401 } 17402 17403 namespace { 17404 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17405 // The produced TemplateArgumentListInfo* points to data stored within this 17406 // object, so should only be used in contexts where the pointer will not be 17407 // used after the CopiedTemplateArgs object is destroyed. 17408 class CopiedTemplateArgs { 17409 bool HasArgs; 17410 TemplateArgumentListInfo TemplateArgStorage; 17411 public: 17412 template<typename RefExpr> 17413 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17414 if (HasArgs) 17415 E->copyTemplateArgumentsInto(TemplateArgStorage); 17416 } 17417 operator TemplateArgumentListInfo*() 17418 #ifdef __has_cpp_attribute 17419 #if __has_cpp_attribute(clang::lifetimebound) 17420 [[clang::lifetimebound]] 17421 #endif 17422 #endif 17423 { 17424 return HasArgs ? &TemplateArgStorage : nullptr; 17425 } 17426 }; 17427 } 17428 17429 /// Walk the set of potential results of an expression and mark them all as 17430 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17431 /// 17432 /// \return A new expression if we found any potential results, ExprEmpty() if 17433 /// not, and ExprError() if we diagnosed an error. 17434 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17435 NonOdrUseReason NOUR) { 17436 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17437 // an object that satisfies the requirements for appearing in a 17438 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17439 // is immediately applied." This function handles the lvalue-to-rvalue 17440 // conversion part. 17441 // 17442 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17443 // transform it into the relevant kind of non-odr-use node and rebuild the 17444 // tree of nodes leading to it. 17445 // 17446 // This is a mini-TreeTransform that only transforms a restricted subset of 17447 // nodes (and only certain operands of them). 17448 17449 // Rebuild a subexpression. 17450 auto Rebuild = [&](Expr *Sub) { 17451 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17452 }; 17453 17454 // Check whether a potential result satisfies the requirements of NOUR. 17455 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17456 // Any entity other than a VarDecl is always odr-used whenever it's named 17457 // in a potentially-evaluated expression. 17458 auto *VD = dyn_cast<VarDecl>(D); 17459 if (!VD) 17460 return true; 17461 17462 // C++2a [basic.def.odr]p4: 17463 // A variable x whose name appears as a potentially-evalauted expression 17464 // e is odr-used by e unless 17465 // -- x is a reference that is usable in constant expressions, or 17466 // -- x is a variable of non-reference type that is usable in constant 17467 // expressions and has no mutable subobjects, and e is an element of 17468 // the set of potential results of an expression of 17469 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17470 // conversion is applied, or 17471 // -- x is a variable of non-reference type, and e is an element of the 17472 // set of potential results of a discarded-value expression to which 17473 // the lvalue-to-rvalue conversion is not applied 17474 // 17475 // We check the first bullet and the "potentially-evaluated" condition in 17476 // BuildDeclRefExpr. We check the type requirements in the second bullet 17477 // in CheckLValueToRValueConversionOperand below. 17478 switch (NOUR) { 17479 case NOUR_None: 17480 case NOUR_Unevaluated: 17481 llvm_unreachable("unexpected non-odr-use-reason"); 17482 17483 case NOUR_Constant: 17484 // Constant references were handled when they were built. 17485 if (VD->getType()->isReferenceType()) 17486 return true; 17487 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17488 if (RD->hasMutableFields()) 17489 return true; 17490 if (!VD->isUsableInConstantExpressions(S.Context)) 17491 return true; 17492 break; 17493 17494 case NOUR_Discarded: 17495 if (VD->getType()->isReferenceType()) 17496 return true; 17497 break; 17498 } 17499 return false; 17500 }; 17501 17502 // Mark that this expression does not constitute an odr-use. 17503 auto MarkNotOdrUsed = [&] { 17504 S.MaybeODRUseExprs.erase(E); 17505 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17506 LSI->markVariableExprAsNonODRUsed(E); 17507 }; 17508 17509 // C++2a [basic.def.odr]p2: 17510 // The set of potential results of an expression e is defined as follows: 17511 switch (E->getStmtClass()) { 17512 // -- If e is an id-expression, ... 17513 case Expr::DeclRefExprClass: { 17514 auto *DRE = cast<DeclRefExpr>(E); 17515 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17516 break; 17517 17518 // Rebuild as a non-odr-use DeclRefExpr. 17519 MarkNotOdrUsed(); 17520 return DeclRefExpr::Create( 17521 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17522 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17523 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17524 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17525 } 17526 17527 case Expr::FunctionParmPackExprClass: { 17528 auto *FPPE = cast<FunctionParmPackExpr>(E); 17529 // If any of the declarations in the pack is odr-used, then the expression 17530 // as a whole constitutes an odr-use. 17531 for (VarDecl *D : *FPPE) 17532 if (IsPotentialResultOdrUsed(D)) 17533 return ExprEmpty(); 17534 17535 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17536 // nothing cares about whether we marked this as an odr-use, but it might 17537 // be useful for non-compiler tools. 17538 MarkNotOdrUsed(); 17539 break; 17540 } 17541 17542 // -- If e is a subscripting operation with an array operand... 17543 case Expr::ArraySubscriptExprClass: { 17544 auto *ASE = cast<ArraySubscriptExpr>(E); 17545 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17546 if (!OldBase->getType()->isArrayType()) 17547 break; 17548 ExprResult Base = Rebuild(OldBase); 17549 if (!Base.isUsable()) 17550 return Base; 17551 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17552 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17553 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17554 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17555 ASE->getRBracketLoc()); 17556 } 17557 17558 case Expr::MemberExprClass: { 17559 auto *ME = cast<MemberExpr>(E); 17560 // -- If e is a class member access expression [...] naming a non-static 17561 // data member... 17562 if (isa<FieldDecl>(ME->getMemberDecl())) { 17563 ExprResult Base = Rebuild(ME->getBase()); 17564 if (!Base.isUsable()) 17565 return Base; 17566 return MemberExpr::Create( 17567 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17568 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17569 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17570 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17571 ME->getObjectKind(), ME->isNonOdrUse()); 17572 } 17573 17574 if (ME->getMemberDecl()->isCXXInstanceMember()) 17575 break; 17576 17577 // -- If e is a class member access expression naming a static data member, 17578 // ... 17579 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17580 break; 17581 17582 // Rebuild as a non-odr-use MemberExpr. 17583 MarkNotOdrUsed(); 17584 return MemberExpr::Create( 17585 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17586 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17587 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17588 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17589 return ExprEmpty(); 17590 } 17591 17592 case Expr::BinaryOperatorClass: { 17593 auto *BO = cast<BinaryOperator>(E); 17594 Expr *LHS = BO->getLHS(); 17595 Expr *RHS = BO->getRHS(); 17596 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17597 if (BO->getOpcode() == BO_PtrMemD) { 17598 ExprResult Sub = Rebuild(LHS); 17599 if (!Sub.isUsable()) 17600 return Sub; 17601 LHS = Sub.get(); 17602 // -- If e is a comma expression, ... 17603 } else if (BO->getOpcode() == BO_Comma) { 17604 ExprResult Sub = Rebuild(RHS); 17605 if (!Sub.isUsable()) 17606 return Sub; 17607 RHS = Sub.get(); 17608 } else { 17609 break; 17610 } 17611 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17612 LHS, RHS); 17613 } 17614 17615 // -- If e has the form (e1)... 17616 case Expr::ParenExprClass: { 17617 auto *PE = cast<ParenExpr>(E); 17618 ExprResult Sub = Rebuild(PE->getSubExpr()); 17619 if (!Sub.isUsable()) 17620 return Sub; 17621 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17622 } 17623 17624 // -- If e is a glvalue conditional expression, ... 17625 // We don't apply this to a binary conditional operator. FIXME: Should we? 17626 case Expr::ConditionalOperatorClass: { 17627 auto *CO = cast<ConditionalOperator>(E); 17628 ExprResult LHS = Rebuild(CO->getLHS()); 17629 if (LHS.isInvalid()) 17630 return ExprError(); 17631 ExprResult RHS = Rebuild(CO->getRHS()); 17632 if (RHS.isInvalid()) 17633 return ExprError(); 17634 if (!LHS.isUsable() && !RHS.isUsable()) 17635 return ExprEmpty(); 17636 if (!LHS.isUsable()) 17637 LHS = CO->getLHS(); 17638 if (!RHS.isUsable()) 17639 RHS = CO->getRHS(); 17640 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17641 CO->getCond(), LHS.get(), RHS.get()); 17642 } 17643 17644 // [Clang extension] 17645 // -- If e has the form __extension__ e1... 17646 case Expr::UnaryOperatorClass: { 17647 auto *UO = cast<UnaryOperator>(E); 17648 if (UO->getOpcode() != UO_Extension) 17649 break; 17650 ExprResult Sub = Rebuild(UO->getSubExpr()); 17651 if (!Sub.isUsable()) 17652 return Sub; 17653 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17654 Sub.get()); 17655 } 17656 17657 // [Clang extension] 17658 // -- If e has the form _Generic(...), the set of potential results is the 17659 // union of the sets of potential results of the associated expressions. 17660 case Expr::GenericSelectionExprClass: { 17661 auto *GSE = cast<GenericSelectionExpr>(E); 17662 17663 SmallVector<Expr *, 4> AssocExprs; 17664 bool AnyChanged = false; 17665 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17666 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17667 if (AssocExpr.isInvalid()) 17668 return ExprError(); 17669 if (AssocExpr.isUsable()) { 17670 AssocExprs.push_back(AssocExpr.get()); 17671 AnyChanged = true; 17672 } else { 17673 AssocExprs.push_back(OrigAssocExpr); 17674 } 17675 } 17676 17677 return AnyChanged ? S.CreateGenericSelectionExpr( 17678 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17679 GSE->getRParenLoc(), GSE->getControllingExpr(), 17680 GSE->getAssocTypeSourceInfos(), AssocExprs) 17681 : ExprEmpty(); 17682 } 17683 17684 // [Clang extension] 17685 // -- If e has the form __builtin_choose_expr(...), the set of potential 17686 // results is the union of the sets of potential results of the 17687 // second and third subexpressions. 17688 case Expr::ChooseExprClass: { 17689 auto *CE = cast<ChooseExpr>(E); 17690 17691 ExprResult LHS = Rebuild(CE->getLHS()); 17692 if (LHS.isInvalid()) 17693 return ExprError(); 17694 17695 ExprResult RHS = Rebuild(CE->getLHS()); 17696 if (RHS.isInvalid()) 17697 return ExprError(); 17698 17699 if (!LHS.get() && !RHS.get()) 17700 return ExprEmpty(); 17701 if (!LHS.isUsable()) 17702 LHS = CE->getLHS(); 17703 if (!RHS.isUsable()) 17704 RHS = CE->getRHS(); 17705 17706 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17707 RHS.get(), CE->getRParenLoc()); 17708 } 17709 17710 // Step through non-syntactic nodes. 17711 case Expr::ConstantExprClass: { 17712 auto *CE = cast<ConstantExpr>(E); 17713 ExprResult Sub = Rebuild(CE->getSubExpr()); 17714 if (!Sub.isUsable()) 17715 return Sub; 17716 return ConstantExpr::Create(S.Context, Sub.get()); 17717 } 17718 17719 // We could mostly rely on the recursive rebuilding to rebuild implicit 17720 // casts, but not at the top level, so rebuild them here. 17721 case Expr::ImplicitCastExprClass: { 17722 auto *ICE = cast<ImplicitCastExpr>(E); 17723 // Only step through the narrow set of cast kinds we expect to encounter. 17724 // Anything else suggests we've left the region in which potential results 17725 // can be found. 17726 switch (ICE->getCastKind()) { 17727 case CK_NoOp: 17728 case CK_DerivedToBase: 17729 case CK_UncheckedDerivedToBase: { 17730 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17731 if (!Sub.isUsable()) 17732 return Sub; 17733 CXXCastPath Path(ICE->path()); 17734 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17735 ICE->getValueKind(), &Path); 17736 } 17737 17738 default: 17739 break; 17740 } 17741 break; 17742 } 17743 17744 default: 17745 break; 17746 } 17747 17748 // Can't traverse through this node. Nothing to do. 17749 return ExprEmpty(); 17750 } 17751 17752 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17753 // Check whether the operand is or contains an object of non-trivial C union 17754 // type. 17755 if (E->getType().isVolatileQualified() && 17756 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17757 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17758 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17759 Sema::NTCUC_LValueToRValueVolatile, 17760 NTCUK_Destruct|NTCUK_Copy); 17761 17762 // C++2a [basic.def.odr]p4: 17763 // [...] an expression of non-volatile-qualified non-class type to which 17764 // the lvalue-to-rvalue conversion is applied [...] 17765 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17766 return E; 17767 17768 ExprResult Result = 17769 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17770 if (Result.isInvalid()) 17771 return ExprError(); 17772 return Result.get() ? Result : E; 17773 } 17774 17775 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17776 Res = CorrectDelayedTyposInExpr(Res); 17777 17778 if (!Res.isUsable()) 17779 return Res; 17780 17781 // If a constant-expression is a reference to a variable where we delay 17782 // deciding whether it is an odr-use, just assume we will apply the 17783 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17784 // (a non-type template argument), we have special handling anyway. 17785 return CheckLValueToRValueConversionOperand(Res.get()); 17786 } 17787 17788 void Sema::CleanupVarDeclMarking() { 17789 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17790 // call. 17791 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17792 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17793 17794 for (Expr *E : LocalMaybeODRUseExprs) { 17795 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17796 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17797 DRE->getLocation(), *this); 17798 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17799 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17800 *this); 17801 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17802 for (VarDecl *VD : *FP) 17803 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17804 } else { 17805 llvm_unreachable("Unexpected expression"); 17806 } 17807 } 17808 17809 assert(MaybeODRUseExprs.empty() && 17810 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17811 } 17812 17813 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17814 VarDecl *Var, Expr *E) { 17815 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17816 isa<FunctionParmPackExpr>(E)) && 17817 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17818 Var->setReferenced(); 17819 17820 if (Var->isInvalidDecl()) 17821 return; 17822 17823 auto *MSI = Var->getMemberSpecializationInfo(); 17824 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17825 : Var->getTemplateSpecializationKind(); 17826 17827 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17828 bool UsableInConstantExpr = 17829 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17830 17831 // C++20 [expr.const]p12: 17832 // A variable [...] is needed for constant evaluation if it is [...] a 17833 // variable whose name appears as a potentially constant evaluated 17834 // expression that is either a contexpr variable or is of non-volatile 17835 // const-qualified integral type or of reference type 17836 bool NeededForConstantEvaluation = 17837 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17838 17839 bool NeedDefinition = 17840 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17841 17842 VarTemplateSpecializationDecl *VarSpec = 17843 dyn_cast<VarTemplateSpecializationDecl>(Var); 17844 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17845 "Can't instantiate a partial template specialization."); 17846 17847 // If this might be a member specialization of a static data member, check 17848 // the specialization is visible. We already did the checks for variable 17849 // template specializations when we created them. 17850 if (NeedDefinition && TSK != TSK_Undeclared && 17851 !isa<VarTemplateSpecializationDecl>(Var)) 17852 SemaRef.checkSpecializationVisibility(Loc, Var); 17853 17854 // Perform implicit instantiation of static data members, static data member 17855 // templates of class templates, and variable template specializations. Delay 17856 // instantiations of variable templates, except for those that could be used 17857 // in a constant expression. 17858 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17859 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17860 // instantiation declaration if a variable is usable in a constant 17861 // expression (among other cases). 17862 bool TryInstantiating = 17863 TSK == TSK_ImplicitInstantiation || 17864 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17865 17866 if (TryInstantiating) { 17867 SourceLocation PointOfInstantiation = 17868 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17869 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17870 if (FirstInstantiation) { 17871 PointOfInstantiation = Loc; 17872 if (MSI) 17873 MSI->setPointOfInstantiation(PointOfInstantiation); 17874 else 17875 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17876 } 17877 17878 bool InstantiationDependent = false; 17879 bool IsNonDependent = 17880 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17881 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17882 : true; 17883 17884 // Do not instantiate specializations that are still type-dependent. 17885 if (IsNonDependent) { 17886 if (UsableInConstantExpr) { 17887 // Do not defer instantiations of variables that could be used in a 17888 // constant expression. 17889 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17890 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17891 }); 17892 } else if (FirstInstantiation || 17893 isa<VarTemplateSpecializationDecl>(Var)) { 17894 // FIXME: For a specialization of a variable template, we don't 17895 // distinguish between "declaration and type implicitly instantiated" 17896 // and "implicit instantiation of definition requested", so we have 17897 // no direct way to avoid enqueueing the pending instantiation 17898 // multiple times. 17899 SemaRef.PendingInstantiations 17900 .push_back(std::make_pair(Var, PointOfInstantiation)); 17901 } 17902 } 17903 } 17904 } 17905 17906 // C++2a [basic.def.odr]p4: 17907 // A variable x whose name appears as a potentially-evaluated expression e 17908 // is odr-used by e unless 17909 // -- x is a reference that is usable in constant expressions 17910 // -- x is a variable of non-reference type that is usable in constant 17911 // expressions and has no mutable subobjects [FIXME], and e is an 17912 // element of the set of potential results of an expression of 17913 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17914 // conversion is applied 17915 // -- x is a variable of non-reference type, and e is an element of the set 17916 // of potential results of a discarded-value expression to which the 17917 // lvalue-to-rvalue conversion is not applied [FIXME] 17918 // 17919 // We check the first part of the second bullet here, and 17920 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17921 // FIXME: To get the third bullet right, we need to delay this even for 17922 // variables that are not usable in constant expressions. 17923 17924 // If we already know this isn't an odr-use, there's nothing more to do. 17925 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17926 if (DRE->isNonOdrUse()) 17927 return; 17928 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17929 if (ME->isNonOdrUse()) 17930 return; 17931 17932 switch (OdrUse) { 17933 case OdrUseContext::None: 17934 assert((!E || isa<FunctionParmPackExpr>(E)) && 17935 "missing non-odr-use marking for unevaluated decl ref"); 17936 break; 17937 17938 case OdrUseContext::FormallyOdrUsed: 17939 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17940 // behavior. 17941 break; 17942 17943 case OdrUseContext::Used: 17944 // If we might later find that this expression isn't actually an odr-use, 17945 // delay the marking. 17946 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17947 SemaRef.MaybeODRUseExprs.insert(E); 17948 else 17949 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17950 break; 17951 17952 case OdrUseContext::Dependent: 17953 // If this is a dependent context, we don't need to mark variables as 17954 // odr-used, but we may still need to track them for lambda capture. 17955 // FIXME: Do we also need to do this inside dependent typeid expressions 17956 // (which are modeled as unevaluated at this point)? 17957 const bool RefersToEnclosingScope = 17958 (SemaRef.CurContext != Var->getDeclContext() && 17959 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17960 if (RefersToEnclosingScope) { 17961 LambdaScopeInfo *const LSI = 17962 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17963 if (LSI && (!LSI->CallOperator || 17964 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17965 // If a variable could potentially be odr-used, defer marking it so 17966 // until we finish analyzing the full expression for any 17967 // lvalue-to-rvalue 17968 // or discarded value conversions that would obviate odr-use. 17969 // Add it to the list of potential captures that will be analyzed 17970 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17971 // unless the variable is a reference that was initialized by a constant 17972 // expression (this will never need to be captured or odr-used). 17973 // 17974 // FIXME: We can simplify this a lot after implementing P0588R1. 17975 assert(E && "Capture variable should be used in an expression."); 17976 if (!Var->getType()->isReferenceType() || 17977 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17978 LSI->addPotentialCapture(E->IgnoreParens()); 17979 } 17980 } 17981 break; 17982 } 17983 } 17984 17985 /// Mark a variable referenced, and check whether it is odr-used 17986 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17987 /// used directly for normal expressions referring to VarDecl. 17988 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17989 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17990 } 17991 17992 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17993 Decl *D, Expr *E, bool MightBeOdrUse) { 17994 if (SemaRef.isInOpenMPDeclareTargetContext()) 17995 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17996 17997 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17998 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17999 return; 18000 } 18001 18002 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18003 18004 // If this is a call to a method via a cast, also mark the method in the 18005 // derived class used in case codegen can devirtualize the call. 18006 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18007 if (!ME) 18008 return; 18009 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18010 if (!MD) 18011 return; 18012 // Only attempt to devirtualize if this is truly a virtual call. 18013 bool IsVirtualCall = MD->isVirtual() && 18014 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18015 if (!IsVirtualCall) 18016 return; 18017 18018 // If it's possible to devirtualize the call, mark the called function 18019 // referenced. 18020 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18021 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18022 if (DM) 18023 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18024 } 18025 18026 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18027 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18028 // TODO: update this with DR# once a defect report is filed. 18029 // C++11 defect. The address of a pure member should not be an ODR use, even 18030 // if it's a qualified reference. 18031 bool OdrUse = true; 18032 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18033 if (Method->isVirtual() && 18034 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18035 OdrUse = false; 18036 18037 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18038 if (!isConstantEvaluated() && FD->isConsteval() && 18039 !RebuildingImmediateInvocation) 18040 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18041 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18042 } 18043 18044 /// Perform reference-marking and odr-use handling for a MemberExpr. 18045 void Sema::MarkMemberReferenced(MemberExpr *E) { 18046 // C++11 [basic.def.odr]p2: 18047 // A non-overloaded function whose name appears as a potentially-evaluated 18048 // expression or a member of a set of candidate functions, if selected by 18049 // overload resolution when referred to from a potentially-evaluated 18050 // expression, is odr-used, unless it is a pure virtual function and its 18051 // name is not explicitly qualified. 18052 bool MightBeOdrUse = true; 18053 if (E->performsVirtualDispatch(getLangOpts())) { 18054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18055 if (Method->isPure()) 18056 MightBeOdrUse = false; 18057 } 18058 SourceLocation Loc = 18059 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18060 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18061 } 18062 18063 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18064 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18065 for (VarDecl *VD : *E) 18066 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18067 } 18068 18069 /// Perform marking for a reference to an arbitrary declaration. It 18070 /// marks the declaration referenced, and performs odr-use checking for 18071 /// functions and variables. This method should not be used when building a 18072 /// normal expression which refers to a variable. 18073 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18074 bool MightBeOdrUse) { 18075 if (MightBeOdrUse) { 18076 if (auto *VD = dyn_cast<VarDecl>(D)) { 18077 MarkVariableReferenced(Loc, VD); 18078 return; 18079 } 18080 } 18081 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18082 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18083 return; 18084 } 18085 D->setReferenced(); 18086 } 18087 18088 namespace { 18089 // Mark all of the declarations used by a type as referenced. 18090 // FIXME: Not fully implemented yet! We need to have a better understanding 18091 // of when we're entering a context we should not recurse into. 18092 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18093 // TreeTransforms rebuilding the type in a new context. Rather than 18094 // duplicating the TreeTransform logic, we should consider reusing it here. 18095 // Currently that causes problems when rebuilding LambdaExprs. 18096 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18097 Sema &S; 18098 SourceLocation Loc; 18099 18100 public: 18101 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18102 18103 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18104 18105 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18106 }; 18107 } 18108 18109 bool MarkReferencedDecls::TraverseTemplateArgument( 18110 const TemplateArgument &Arg) { 18111 { 18112 // A non-type template argument is a constant-evaluated context. 18113 EnterExpressionEvaluationContext Evaluated( 18114 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18115 if (Arg.getKind() == TemplateArgument::Declaration) { 18116 if (Decl *D = Arg.getAsDecl()) 18117 S.MarkAnyDeclReferenced(Loc, D, true); 18118 } else if (Arg.getKind() == TemplateArgument::Expression) { 18119 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18120 } 18121 } 18122 18123 return Inherited::TraverseTemplateArgument(Arg); 18124 } 18125 18126 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18127 MarkReferencedDecls Marker(*this, Loc); 18128 Marker.TraverseType(T); 18129 } 18130 18131 namespace { 18132 /// Helper class that marks all of the declarations referenced by 18133 /// potentially-evaluated subexpressions as "referenced". 18134 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18135 public: 18136 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18137 bool SkipLocalVariables; 18138 18139 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18140 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18141 18142 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18143 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18144 } 18145 18146 void VisitDeclRefExpr(DeclRefExpr *E) { 18147 // If we were asked not to visit local variables, don't. 18148 if (SkipLocalVariables) { 18149 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18150 if (VD->hasLocalStorage()) 18151 return; 18152 } 18153 S.MarkDeclRefReferenced(E); 18154 } 18155 18156 void VisitMemberExpr(MemberExpr *E) { 18157 S.MarkMemberReferenced(E); 18158 Visit(E->getBase()); 18159 } 18160 }; 18161 } // namespace 18162 18163 /// Mark any declarations that appear within this expression or any 18164 /// potentially-evaluated subexpressions as "referenced". 18165 /// 18166 /// \param SkipLocalVariables If true, don't mark local variables as 18167 /// 'referenced'. 18168 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18169 bool SkipLocalVariables) { 18170 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18171 } 18172 18173 /// Emit a diagnostic that describes an effect on the run-time behavior 18174 /// of the program being compiled. 18175 /// 18176 /// This routine emits the given diagnostic when the code currently being 18177 /// type-checked is "potentially evaluated", meaning that there is a 18178 /// possibility that the code will actually be executable. Code in sizeof() 18179 /// expressions, code used only during overload resolution, etc., are not 18180 /// potentially evaluated. This routine will suppress such diagnostics or, 18181 /// in the absolutely nutty case of potentially potentially evaluated 18182 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18183 /// later. 18184 /// 18185 /// This routine should be used for all diagnostics that describe the run-time 18186 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18187 /// Failure to do so will likely result in spurious diagnostics or failures 18188 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18189 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18190 const PartialDiagnostic &PD) { 18191 switch (ExprEvalContexts.back().Context) { 18192 case ExpressionEvaluationContext::Unevaluated: 18193 case ExpressionEvaluationContext::UnevaluatedList: 18194 case ExpressionEvaluationContext::UnevaluatedAbstract: 18195 case ExpressionEvaluationContext::DiscardedStatement: 18196 // The argument will never be evaluated, so don't complain. 18197 break; 18198 18199 case ExpressionEvaluationContext::ConstantEvaluated: 18200 // Relevant diagnostics should be produced by constant evaluation. 18201 break; 18202 18203 case ExpressionEvaluationContext::PotentiallyEvaluated: 18204 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18205 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18206 FunctionScopes.back()->PossiblyUnreachableDiags. 18207 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18208 return true; 18209 } 18210 18211 // The initializer of a constexpr variable or of the first declaration of a 18212 // static data member is not syntactically a constant evaluated constant, 18213 // but nonetheless is always required to be a constant expression, so we 18214 // can skip diagnosing. 18215 // FIXME: Using the mangling context here is a hack. 18216 if (auto *VD = dyn_cast_or_null<VarDecl>( 18217 ExprEvalContexts.back().ManglingContextDecl)) { 18218 if (VD->isConstexpr() || 18219 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18220 break; 18221 // FIXME: For any other kind of variable, we should build a CFG for its 18222 // initializer and check whether the context in question is reachable. 18223 } 18224 18225 Diag(Loc, PD); 18226 return true; 18227 } 18228 18229 return false; 18230 } 18231 18232 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18233 const PartialDiagnostic &PD) { 18234 return DiagRuntimeBehavior( 18235 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18236 } 18237 18238 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18239 CallExpr *CE, FunctionDecl *FD) { 18240 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18241 return false; 18242 18243 // If we're inside a decltype's expression, don't check for a valid return 18244 // type or construct temporaries until we know whether this is the last call. 18245 if (ExprEvalContexts.back().ExprContext == 18246 ExpressionEvaluationContextRecord::EK_Decltype) { 18247 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18248 return false; 18249 } 18250 18251 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18252 FunctionDecl *FD; 18253 CallExpr *CE; 18254 18255 public: 18256 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18257 : FD(FD), CE(CE) { } 18258 18259 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18260 if (!FD) { 18261 S.Diag(Loc, diag::err_call_incomplete_return) 18262 << T << CE->getSourceRange(); 18263 return; 18264 } 18265 18266 S.Diag(Loc, diag::err_call_function_incomplete_return) 18267 << CE->getSourceRange() << FD->getDeclName() << T; 18268 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18269 << FD->getDeclName(); 18270 } 18271 } Diagnoser(FD, CE); 18272 18273 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18274 return true; 18275 18276 return false; 18277 } 18278 18279 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18280 // will prevent this condition from triggering, which is what we want. 18281 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18282 SourceLocation Loc; 18283 18284 unsigned diagnostic = diag::warn_condition_is_assignment; 18285 bool IsOrAssign = false; 18286 18287 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18288 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18289 return; 18290 18291 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18292 18293 // Greylist some idioms by putting them into a warning subcategory. 18294 if (ObjCMessageExpr *ME 18295 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18296 Selector Sel = ME->getSelector(); 18297 18298 // self = [<foo> init...] 18299 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18300 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18301 18302 // <foo> = [<bar> nextObject] 18303 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18304 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18305 } 18306 18307 Loc = Op->getOperatorLoc(); 18308 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18309 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18310 return; 18311 18312 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18313 Loc = Op->getOperatorLoc(); 18314 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18315 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18316 else { 18317 // Not an assignment. 18318 return; 18319 } 18320 18321 Diag(Loc, diagnostic) << E->getSourceRange(); 18322 18323 SourceLocation Open = E->getBeginLoc(); 18324 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18325 Diag(Loc, diag::note_condition_assign_silence) 18326 << FixItHint::CreateInsertion(Open, "(") 18327 << FixItHint::CreateInsertion(Close, ")"); 18328 18329 if (IsOrAssign) 18330 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18331 << FixItHint::CreateReplacement(Loc, "!="); 18332 else 18333 Diag(Loc, diag::note_condition_assign_to_comparison) 18334 << FixItHint::CreateReplacement(Loc, "=="); 18335 } 18336 18337 /// Redundant parentheses over an equality comparison can indicate 18338 /// that the user intended an assignment used as condition. 18339 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18340 // Don't warn if the parens came from a macro. 18341 SourceLocation parenLoc = ParenE->getBeginLoc(); 18342 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18343 return; 18344 // Don't warn for dependent expressions. 18345 if (ParenE->isTypeDependent()) 18346 return; 18347 18348 Expr *E = ParenE->IgnoreParens(); 18349 18350 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18351 if (opE->getOpcode() == BO_EQ && 18352 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18353 == Expr::MLV_Valid) { 18354 SourceLocation Loc = opE->getOperatorLoc(); 18355 18356 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18357 SourceRange ParenERange = ParenE->getSourceRange(); 18358 Diag(Loc, diag::note_equality_comparison_silence) 18359 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18360 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18361 Diag(Loc, diag::note_equality_comparison_to_assign) 18362 << FixItHint::CreateReplacement(Loc, "="); 18363 } 18364 } 18365 18366 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18367 bool IsConstexpr) { 18368 DiagnoseAssignmentAsCondition(E); 18369 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18370 DiagnoseEqualityWithExtraParens(parenE); 18371 18372 ExprResult result = CheckPlaceholderExpr(E); 18373 if (result.isInvalid()) return ExprError(); 18374 E = result.get(); 18375 18376 if (!E->isTypeDependent()) { 18377 if (getLangOpts().CPlusPlus) 18378 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18379 18380 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18381 if (ERes.isInvalid()) 18382 return ExprError(); 18383 E = ERes.get(); 18384 18385 QualType T = E->getType(); 18386 if (!T->isScalarType()) { // C99 6.8.4.1p1 18387 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18388 << T << E->getSourceRange(); 18389 return ExprError(); 18390 } 18391 CheckBoolLikeConversion(E, Loc); 18392 } 18393 18394 return E; 18395 } 18396 18397 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18398 Expr *SubExpr, ConditionKind CK) { 18399 // Empty conditions are valid in for-statements. 18400 if (!SubExpr) 18401 return ConditionResult(); 18402 18403 ExprResult Cond; 18404 switch (CK) { 18405 case ConditionKind::Boolean: 18406 Cond = CheckBooleanCondition(Loc, SubExpr); 18407 break; 18408 18409 case ConditionKind::ConstexprIf: 18410 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18411 break; 18412 18413 case ConditionKind::Switch: 18414 Cond = CheckSwitchCondition(Loc, SubExpr); 18415 break; 18416 } 18417 if (Cond.isInvalid()) 18418 return ConditionError(); 18419 18420 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18421 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18422 if (!FullExpr.get()) 18423 return ConditionError(); 18424 18425 return ConditionResult(*this, nullptr, FullExpr, 18426 CK == ConditionKind::ConstexprIf); 18427 } 18428 18429 namespace { 18430 /// A visitor for rebuilding a call to an __unknown_any expression 18431 /// to have an appropriate type. 18432 struct RebuildUnknownAnyFunction 18433 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18434 18435 Sema &S; 18436 18437 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18438 18439 ExprResult VisitStmt(Stmt *S) { 18440 llvm_unreachable("unexpected statement!"); 18441 } 18442 18443 ExprResult VisitExpr(Expr *E) { 18444 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18445 << E->getSourceRange(); 18446 return ExprError(); 18447 } 18448 18449 /// Rebuild an expression which simply semantically wraps another 18450 /// expression which it shares the type and value kind of. 18451 template <class T> ExprResult rebuildSugarExpr(T *E) { 18452 ExprResult SubResult = Visit(E->getSubExpr()); 18453 if (SubResult.isInvalid()) return ExprError(); 18454 18455 Expr *SubExpr = SubResult.get(); 18456 E->setSubExpr(SubExpr); 18457 E->setType(SubExpr->getType()); 18458 E->setValueKind(SubExpr->getValueKind()); 18459 assert(E->getObjectKind() == OK_Ordinary); 18460 return E; 18461 } 18462 18463 ExprResult VisitParenExpr(ParenExpr *E) { 18464 return rebuildSugarExpr(E); 18465 } 18466 18467 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18468 return rebuildSugarExpr(E); 18469 } 18470 18471 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18472 ExprResult SubResult = Visit(E->getSubExpr()); 18473 if (SubResult.isInvalid()) return ExprError(); 18474 18475 Expr *SubExpr = SubResult.get(); 18476 E->setSubExpr(SubExpr); 18477 E->setType(S.Context.getPointerType(SubExpr->getType())); 18478 assert(E->getValueKind() == VK_RValue); 18479 assert(E->getObjectKind() == OK_Ordinary); 18480 return E; 18481 } 18482 18483 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18484 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18485 18486 E->setType(VD->getType()); 18487 18488 assert(E->getValueKind() == VK_RValue); 18489 if (S.getLangOpts().CPlusPlus && 18490 !(isa<CXXMethodDecl>(VD) && 18491 cast<CXXMethodDecl>(VD)->isInstance())) 18492 E->setValueKind(VK_LValue); 18493 18494 return E; 18495 } 18496 18497 ExprResult VisitMemberExpr(MemberExpr *E) { 18498 return resolveDecl(E, E->getMemberDecl()); 18499 } 18500 18501 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18502 return resolveDecl(E, E->getDecl()); 18503 } 18504 }; 18505 } 18506 18507 /// Given a function expression of unknown-any type, try to rebuild it 18508 /// to have a function type. 18509 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18510 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18511 if (Result.isInvalid()) return ExprError(); 18512 return S.DefaultFunctionArrayConversion(Result.get()); 18513 } 18514 18515 namespace { 18516 /// A visitor for rebuilding an expression of type __unknown_anytype 18517 /// into one which resolves the type directly on the referring 18518 /// expression. Strict preservation of the original source 18519 /// structure is not a goal. 18520 struct RebuildUnknownAnyExpr 18521 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18522 18523 Sema &S; 18524 18525 /// The current destination type. 18526 QualType DestType; 18527 18528 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18529 : S(S), DestType(CastType) {} 18530 18531 ExprResult VisitStmt(Stmt *S) { 18532 llvm_unreachable("unexpected statement!"); 18533 } 18534 18535 ExprResult VisitExpr(Expr *E) { 18536 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18537 << E->getSourceRange(); 18538 return ExprError(); 18539 } 18540 18541 ExprResult VisitCallExpr(CallExpr *E); 18542 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18543 18544 /// Rebuild an expression which simply semantically wraps another 18545 /// expression which it shares the type and value kind of. 18546 template <class T> ExprResult rebuildSugarExpr(T *E) { 18547 ExprResult SubResult = Visit(E->getSubExpr()); 18548 if (SubResult.isInvalid()) return ExprError(); 18549 Expr *SubExpr = SubResult.get(); 18550 E->setSubExpr(SubExpr); 18551 E->setType(SubExpr->getType()); 18552 E->setValueKind(SubExpr->getValueKind()); 18553 assert(E->getObjectKind() == OK_Ordinary); 18554 return E; 18555 } 18556 18557 ExprResult VisitParenExpr(ParenExpr *E) { 18558 return rebuildSugarExpr(E); 18559 } 18560 18561 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18562 return rebuildSugarExpr(E); 18563 } 18564 18565 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18566 const PointerType *Ptr = DestType->getAs<PointerType>(); 18567 if (!Ptr) { 18568 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18569 << E->getSourceRange(); 18570 return ExprError(); 18571 } 18572 18573 if (isa<CallExpr>(E->getSubExpr())) { 18574 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18575 << E->getSourceRange(); 18576 return ExprError(); 18577 } 18578 18579 assert(E->getValueKind() == VK_RValue); 18580 assert(E->getObjectKind() == OK_Ordinary); 18581 E->setType(DestType); 18582 18583 // Build the sub-expression as if it were an object of the pointee type. 18584 DestType = Ptr->getPointeeType(); 18585 ExprResult SubResult = Visit(E->getSubExpr()); 18586 if (SubResult.isInvalid()) return ExprError(); 18587 E->setSubExpr(SubResult.get()); 18588 return E; 18589 } 18590 18591 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18592 18593 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18594 18595 ExprResult VisitMemberExpr(MemberExpr *E) { 18596 return resolveDecl(E, E->getMemberDecl()); 18597 } 18598 18599 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18600 return resolveDecl(E, E->getDecl()); 18601 } 18602 }; 18603 } 18604 18605 /// Rebuilds a call expression which yielded __unknown_anytype. 18606 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18607 Expr *CalleeExpr = E->getCallee(); 18608 18609 enum FnKind { 18610 FK_MemberFunction, 18611 FK_FunctionPointer, 18612 FK_BlockPointer 18613 }; 18614 18615 FnKind Kind; 18616 QualType CalleeType = CalleeExpr->getType(); 18617 if (CalleeType == S.Context.BoundMemberTy) { 18618 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18619 Kind = FK_MemberFunction; 18620 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18621 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18622 CalleeType = Ptr->getPointeeType(); 18623 Kind = FK_FunctionPointer; 18624 } else { 18625 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18626 Kind = FK_BlockPointer; 18627 } 18628 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18629 18630 // Verify that this is a legal result type of a function. 18631 if (DestType->isArrayType() || DestType->isFunctionType()) { 18632 unsigned diagID = diag::err_func_returning_array_function; 18633 if (Kind == FK_BlockPointer) 18634 diagID = diag::err_block_returning_array_function; 18635 18636 S.Diag(E->getExprLoc(), diagID) 18637 << DestType->isFunctionType() << DestType; 18638 return ExprError(); 18639 } 18640 18641 // Otherwise, go ahead and set DestType as the call's result. 18642 E->setType(DestType.getNonLValueExprType(S.Context)); 18643 E->setValueKind(Expr::getValueKindForType(DestType)); 18644 assert(E->getObjectKind() == OK_Ordinary); 18645 18646 // Rebuild the function type, replacing the result type with DestType. 18647 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18648 if (Proto) { 18649 // __unknown_anytype(...) is a special case used by the debugger when 18650 // it has no idea what a function's signature is. 18651 // 18652 // We want to build this call essentially under the K&R 18653 // unprototyped rules, but making a FunctionNoProtoType in C++ 18654 // would foul up all sorts of assumptions. However, we cannot 18655 // simply pass all arguments as variadic arguments, nor can we 18656 // portably just call the function under a non-variadic type; see 18657 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18658 // However, it turns out that in practice it is generally safe to 18659 // call a function declared as "A foo(B,C,D);" under the prototype 18660 // "A foo(B,C,D,...);". The only known exception is with the 18661 // Windows ABI, where any variadic function is implicitly cdecl 18662 // regardless of its normal CC. Therefore we change the parameter 18663 // types to match the types of the arguments. 18664 // 18665 // This is a hack, but it is far superior to moving the 18666 // corresponding target-specific code from IR-gen to Sema/AST. 18667 18668 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18669 SmallVector<QualType, 8> ArgTypes; 18670 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18671 ArgTypes.reserve(E->getNumArgs()); 18672 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18673 Expr *Arg = E->getArg(i); 18674 QualType ArgType = Arg->getType(); 18675 if (E->isLValue()) { 18676 ArgType = S.Context.getLValueReferenceType(ArgType); 18677 } else if (E->isXValue()) { 18678 ArgType = S.Context.getRValueReferenceType(ArgType); 18679 } 18680 ArgTypes.push_back(ArgType); 18681 } 18682 ParamTypes = ArgTypes; 18683 } 18684 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18685 Proto->getExtProtoInfo()); 18686 } else { 18687 DestType = S.Context.getFunctionNoProtoType(DestType, 18688 FnType->getExtInfo()); 18689 } 18690 18691 // Rebuild the appropriate pointer-to-function type. 18692 switch (Kind) { 18693 case FK_MemberFunction: 18694 // Nothing to do. 18695 break; 18696 18697 case FK_FunctionPointer: 18698 DestType = S.Context.getPointerType(DestType); 18699 break; 18700 18701 case FK_BlockPointer: 18702 DestType = S.Context.getBlockPointerType(DestType); 18703 break; 18704 } 18705 18706 // Finally, we can recurse. 18707 ExprResult CalleeResult = Visit(CalleeExpr); 18708 if (!CalleeResult.isUsable()) return ExprError(); 18709 E->setCallee(CalleeResult.get()); 18710 18711 // Bind a temporary if necessary. 18712 return S.MaybeBindToTemporary(E); 18713 } 18714 18715 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18716 // Verify that this is a legal result type of a call. 18717 if (DestType->isArrayType() || DestType->isFunctionType()) { 18718 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18719 << DestType->isFunctionType() << DestType; 18720 return ExprError(); 18721 } 18722 18723 // Rewrite the method result type if available. 18724 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18725 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18726 Method->setReturnType(DestType); 18727 } 18728 18729 // Change the type of the message. 18730 E->setType(DestType.getNonReferenceType()); 18731 E->setValueKind(Expr::getValueKindForType(DestType)); 18732 18733 return S.MaybeBindToTemporary(E); 18734 } 18735 18736 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18737 // The only case we should ever see here is a function-to-pointer decay. 18738 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18739 assert(E->getValueKind() == VK_RValue); 18740 assert(E->getObjectKind() == OK_Ordinary); 18741 18742 E->setType(DestType); 18743 18744 // Rebuild the sub-expression as the pointee (function) type. 18745 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18746 18747 ExprResult Result = Visit(E->getSubExpr()); 18748 if (!Result.isUsable()) return ExprError(); 18749 18750 E->setSubExpr(Result.get()); 18751 return E; 18752 } else if (E->getCastKind() == CK_LValueToRValue) { 18753 assert(E->getValueKind() == VK_RValue); 18754 assert(E->getObjectKind() == OK_Ordinary); 18755 18756 assert(isa<BlockPointerType>(E->getType())); 18757 18758 E->setType(DestType); 18759 18760 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18761 DestType = S.Context.getLValueReferenceType(DestType); 18762 18763 ExprResult Result = Visit(E->getSubExpr()); 18764 if (!Result.isUsable()) return ExprError(); 18765 18766 E->setSubExpr(Result.get()); 18767 return E; 18768 } else { 18769 llvm_unreachable("Unhandled cast type!"); 18770 } 18771 } 18772 18773 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18774 ExprValueKind ValueKind = VK_LValue; 18775 QualType Type = DestType; 18776 18777 // We know how to make this work for certain kinds of decls: 18778 18779 // - functions 18780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18781 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18782 DestType = Ptr->getPointeeType(); 18783 ExprResult Result = resolveDecl(E, VD); 18784 if (Result.isInvalid()) return ExprError(); 18785 return S.ImpCastExprToType(Result.get(), Type, 18786 CK_FunctionToPointerDecay, VK_RValue); 18787 } 18788 18789 if (!Type->isFunctionType()) { 18790 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18791 << VD << E->getSourceRange(); 18792 return ExprError(); 18793 } 18794 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18795 // We must match the FunctionDecl's type to the hack introduced in 18796 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18797 // type. See the lengthy commentary in that routine. 18798 QualType FDT = FD->getType(); 18799 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18800 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18801 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18802 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18803 SourceLocation Loc = FD->getLocation(); 18804 FunctionDecl *NewFD = FunctionDecl::Create( 18805 S.Context, FD->getDeclContext(), Loc, Loc, 18806 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18807 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18808 /*ConstexprKind*/ CSK_unspecified); 18809 18810 if (FD->getQualifier()) 18811 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18812 18813 SmallVector<ParmVarDecl*, 16> Params; 18814 for (const auto &AI : FT->param_types()) { 18815 ParmVarDecl *Param = 18816 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18817 Param->setScopeInfo(0, Params.size()); 18818 Params.push_back(Param); 18819 } 18820 NewFD->setParams(Params); 18821 DRE->setDecl(NewFD); 18822 VD = DRE->getDecl(); 18823 } 18824 } 18825 18826 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18827 if (MD->isInstance()) { 18828 ValueKind = VK_RValue; 18829 Type = S.Context.BoundMemberTy; 18830 } 18831 18832 // Function references aren't l-values in C. 18833 if (!S.getLangOpts().CPlusPlus) 18834 ValueKind = VK_RValue; 18835 18836 // - variables 18837 } else if (isa<VarDecl>(VD)) { 18838 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18839 Type = RefTy->getPointeeType(); 18840 } else if (Type->isFunctionType()) { 18841 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18842 << VD << E->getSourceRange(); 18843 return ExprError(); 18844 } 18845 18846 // - nothing else 18847 } else { 18848 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18849 << VD << E->getSourceRange(); 18850 return ExprError(); 18851 } 18852 18853 // Modifying the declaration like this is friendly to IR-gen but 18854 // also really dangerous. 18855 VD->setType(DestType); 18856 E->setType(Type); 18857 E->setValueKind(ValueKind); 18858 return E; 18859 } 18860 18861 /// Check a cast of an unknown-any type. We intentionally only 18862 /// trigger this for C-style casts. 18863 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18864 Expr *CastExpr, CastKind &CastKind, 18865 ExprValueKind &VK, CXXCastPath &Path) { 18866 // The type we're casting to must be either void or complete. 18867 if (!CastType->isVoidType() && 18868 RequireCompleteType(TypeRange.getBegin(), CastType, 18869 diag::err_typecheck_cast_to_incomplete)) 18870 return ExprError(); 18871 18872 // Rewrite the casted expression from scratch. 18873 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18874 if (!result.isUsable()) return ExprError(); 18875 18876 CastExpr = result.get(); 18877 VK = CastExpr->getValueKind(); 18878 CastKind = CK_NoOp; 18879 18880 return CastExpr; 18881 } 18882 18883 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18884 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18885 } 18886 18887 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18888 Expr *arg, QualType ¶mType) { 18889 // If the syntactic form of the argument is not an explicit cast of 18890 // any sort, just do default argument promotion. 18891 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18892 if (!castArg) { 18893 ExprResult result = DefaultArgumentPromotion(arg); 18894 if (result.isInvalid()) return ExprError(); 18895 paramType = result.get()->getType(); 18896 return result; 18897 } 18898 18899 // Otherwise, use the type that was written in the explicit cast. 18900 assert(!arg->hasPlaceholderType()); 18901 paramType = castArg->getTypeAsWritten(); 18902 18903 // Copy-initialize a parameter of that type. 18904 InitializedEntity entity = 18905 InitializedEntity::InitializeParameter(Context, paramType, 18906 /*consumed*/ false); 18907 return PerformCopyInitialization(entity, callLoc, arg); 18908 } 18909 18910 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18911 Expr *orig = E; 18912 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18913 while (true) { 18914 E = E->IgnoreParenImpCasts(); 18915 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18916 E = call->getCallee(); 18917 diagID = diag::err_uncasted_call_of_unknown_any; 18918 } else { 18919 break; 18920 } 18921 } 18922 18923 SourceLocation loc; 18924 NamedDecl *d; 18925 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18926 loc = ref->getLocation(); 18927 d = ref->getDecl(); 18928 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18929 loc = mem->getMemberLoc(); 18930 d = mem->getMemberDecl(); 18931 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18932 diagID = diag::err_uncasted_call_of_unknown_any; 18933 loc = msg->getSelectorStartLoc(); 18934 d = msg->getMethodDecl(); 18935 if (!d) { 18936 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18937 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18938 << orig->getSourceRange(); 18939 return ExprError(); 18940 } 18941 } else { 18942 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18943 << E->getSourceRange(); 18944 return ExprError(); 18945 } 18946 18947 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18948 18949 // Never recoverable. 18950 return ExprError(); 18951 } 18952 18953 /// Check for operands with placeholder types and complain if found. 18954 /// Returns ExprError() if there was an error and no recovery was possible. 18955 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18956 if (!getLangOpts().CPlusPlus) { 18957 // C cannot handle TypoExpr nodes on either side of a binop because it 18958 // doesn't handle dependent types properly, so make sure any TypoExprs have 18959 // been dealt with before checking the operands. 18960 ExprResult Result = CorrectDelayedTyposInExpr(E); 18961 if (!Result.isUsable()) return ExprError(); 18962 E = Result.get(); 18963 } 18964 18965 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18966 if (!placeholderType) return E; 18967 18968 switch (placeholderType->getKind()) { 18969 18970 // Overloaded expressions. 18971 case BuiltinType::Overload: { 18972 // Try to resolve a single function template specialization. 18973 // This is obligatory. 18974 ExprResult Result = E; 18975 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18976 return Result; 18977 18978 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18979 // leaves Result unchanged on failure. 18980 Result = E; 18981 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18982 return Result; 18983 18984 // If that failed, try to recover with a call. 18985 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18986 /*complain*/ true); 18987 return Result; 18988 } 18989 18990 // Bound member functions. 18991 case BuiltinType::BoundMember: { 18992 ExprResult result = E; 18993 const Expr *BME = E->IgnoreParens(); 18994 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18995 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18996 if (isa<CXXPseudoDestructorExpr>(BME)) { 18997 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18998 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18999 if (ME->getMemberNameInfo().getName().getNameKind() == 19000 DeclarationName::CXXDestructorName) 19001 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19002 } 19003 tryToRecoverWithCall(result, PD, 19004 /*complain*/ true); 19005 return result; 19006 } 19007 19008 // ARC unbridged casts. 19009 case BuiltinType::ARCUnbridgedCast: { 19010 Expr *realCast = stripARCUnbridgedCast(E); 19011 diagnoseARCUnbridgedCast(realCast); 19012 return realCast; 19013 } 19014 19015 // Expressions of unknown type. 19016 case BuiltinType::UnknownAny: 19017 return diagnoseUnknownAnyExpr(*this, E); 19018 19019 // Pseudo-objects. 19020 case BuiltinType::PseudoObject: 19021 return checkPseudoObjectRValue(E); 19022 19023 case BuiltinType::BuiltinFn: { 19024 // Accept __noop without parens by implicitly converting it to a call expr. 19025 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19026 if (DRE) { 19027 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19028 if (FD->getBuiltinID() == Builtin::BI__noop) { 19029 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19030 CK_BuiltinFnToFnPtr) 19031 .get(); 19032 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19033 VK_RValue, SourceLocation()); 19034 } 19035 } 19036 19037 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19038 return ExprError(); 19039 } 19040 19041 case BuiltinType::IncompleteMatrixIdx: 19042 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19043 ->getRowIdx() 19044 ->getBeginLoc(), 19045 diag::err_matrix_incomplete_index); 19046 return ExprError(); 19047 19048 // Expressions of unknown type. 19049 case BuiltinType::OMPArraySection: 19050 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19051 return ExprError(); 19052 19053 // Expressions of unknown type. 19054 case BuiltinType::OMPArrayShaping: 19055 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19056 19057 case BuiltinType::OMPIterator: 19058 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19059 19060 // Everything else should be impossible. 19061 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19062 case BuiltinType::Id: 19063 #include "clang/Basic/OpenCLImageTypes.def" 19064 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19065 case BuiltinType::Id: 19066 #include "clang/Basic/OpenCLExtensionTypes.def" 19067 #define SVE_TYPE(Name, Id, SingletonId) \ 19068 case BuiltinType::Id: 19069 #include "clang/Basic/AArch64SVEACLETypes.def" 19070 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19071 #define PLACEHOLDER_TYPE(Id, SingletonId) 19072 #include "clang/AST/BuiltinTypes.def" 19073 break; 19074 } 19075 19076 llvm_unreachable("invalid placeholder type!"); 19077 } 19078 19079 bool Sema::CheckCaseExpression(Expr *E) { 19080 if (E->isTypeDependent()) 19081 return true; 19082 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19083 return E->getType()->isIntegralOrEnumerationType(); 19084 return false; 19085 } 19086 19087 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19088 ExprResult 19089 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19090 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19091 "Unknown Objective-C Boolean value!"); 19092 QualType BoolT = Context.ObjCBuiltinBoolTy; 19093 if (!Context.getBOOLDecl()) { 19094 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19095 Sema::LookupOrdinaryName); 19096 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19097 NamedDecl *ND = Result.getFoundDecl(); 19098 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19099 Context.setBOOLDecl(TD); 19100 } 19101 } 19102 if (Context.getBOOLDecl()) 19103 BoolT = Context.getBOOLType(); 19104 return new (Context) 19105 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19106 } 19107 19108 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19109 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19110 SourceLocation RParen) { 19111 19112 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19113 19114 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19115 return Spec.getPlatform() == Platform; 19116 }); 19117 19118 VersionTuple Version; 19119 if (Spec != AvailSpecs.end()) 19120 Version = Spec->getVersion(); 19121 19122 // The use of `@available` in the enclosing function should be analyzed to 19123 // warn when it's used inappropriately (i.e. not if(@available)). 19124 if (getCurFunctionOrMethodDecl()) 19125 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19126 else if (getCurBlock() || getCurLambda()) 19127 getCurFunction()->HasPotentialAvailabilityViolations = true; 19128 19129 return new (Context) 19130 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19131 } 19132 19133 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19134 ArrayRef<Expr *> SubExprs, QualType T) { 19135 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 19136 // bogus diagnostics and this trick does not work in C. 19137 // FIXME: use containsErrors() to suppress unwanted diags in C. 19138 if (!Context.getLangOpts().RecoveryAST) 19139 return ExprError(); 19140 19141 if (isSFINAEContext()) 19142 return ExprError(); 19143 19144 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19145 // We don't know the concrete type, fallback to dependent type. 19146 T = Context.DependentTy; 19147 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19148 } 19149