1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/FixedPoint.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 69 // See if this is an aligned allocation/deallocation function that is 70 // unavailable. 71 if (TreatUnavailableAsInvalid && 72 isUnavailableAlignedAllocationFunction(*FD)) 73 return false; 74 } 75 76 // See if this function is unavailable. 77 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 78 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 79 return false; 80 81 return true; 82 } 83 84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 85 // Warn if this is used but marked unused. 86 if (const auto *A = D->getAttr<UnusedAttr>()) { 87 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 88 // should diagnose them. 89 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 90 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 91 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 92 if (DC && !DC->hasAttr<UnusedAttr>()) 93 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 94 } 95 } 96 } 97 98 /// Emit a note explaining that this function is deleted. 99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 100 assert(Decl->isDeleted()); 101 102 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 103 104 if (Method && Method->isDeleted() && Method->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Method->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 CXXSpecialMember CSM = getSpecialMember(Method); 112 if (CSM != CXXInvalid) 113 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 114 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 // See if this is a deleted function. 253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // If the function has a deduced return type, and we can't deduce it, 267 // then we can't use it either. 268 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 269 DeduceReturnType(FD, Loc)) 270 return true; 271 272 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 273 return true; 274 } 275 276 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 277 // Lambdas are only default-constructible or assignable in C++2a onwards. 278 if (MD->getParent()->isLambda() && 279 ((isa<CXXConstructorDecl>(MD) && 280 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 281 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 282 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 283 << !isa<CXXConstructorDecl>(MD); 284 } 285 } 286 287 auto getReferencedObjCProp = [](const NamedDecl *D) -> 288 const ObjCPropertyDecl * { 289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 290 return MD->findPropertyDecl(); 291 return nullptr; 292 }; 293 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 294 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 295 return true; 296 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 297 return true; 298 } 299 300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 301 // Only the variables omp_in and omp_out are allowed in the combiner. 302 // Only the variables omp_priv and omp_orig are allowed in the 303 // initializer-clause. 304 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 305 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 306 isa<VarDecl>(D)) { 307 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 308 << getCurFunction()->HasOMPDeclareReductionCombiner; 309 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 310 return true; 311 } 312 313 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 314 // List-items in map clauses on this construct may only refer to the declared 315 // variable var and entities that could be referenced by a procedure defined 316 // at the same location 317 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 318 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 319 isa<VarDecl>(D)) { 320 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 321 << DMD->getVarName().getAsString(); 322 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 323 return true; 324 } 325 326 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 327 AvoidPartialAvailabilityChecks, ClassReceiver); 328 329 DiagnoseUnusedOfDecl(*this, D, Loc); 330 331 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 332 333 return false; 334 } 335 336 /// DiagnoseSentinelCalls - This routine checks whether a call or 337 /// message-send is to a declaration with the sentinel attribute, and 338 /// if so, it checks that the requirements of the sentinel are 339 /// satisfied. 340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 341 ArrayRef<Expr *> Args) { 342 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 343 if (!attr) 344 return; 345 346 // The number of formal parameters of the declaration. 347 unsigned numFormalParams; 348 349 // The kind of declaration. This is also an index into a %select in 350 // the diagnostic. 351 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 352 353 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 354 numFormalParams = MD->param_size(); 355 calleeType = CT_Method; 356 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 357 numFormalParams = FD->param_size(); 358 calleeType = CT_Function; 359 } else if (isa<VarDecl>(D)) { 360 QualType type = cast<ValueDecl>(D)->getType(); 361 const FunctionType *fn = nullptr; 362 if (const PointerType *ptr = type->getAs<PointerType>()) { 363 fn = ptr->getPointeeType()->getAs<FunctionType>(); 364 if (!fn) return; 365 calleeType = CT_Function; 366 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 367 fn = ptr->getPointeeType()->castAs<FunctionType>(); 368 calleeType = CT_Block; 369 } else { 370 return; 371 } 372 373 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 374 numFormalParams = proto->getNumParams(); 375 } else { 376 numFormalParams = 0; 377 } 378 } else { 379 return; 380 } 381 382 // "nullPos" is the number of formal parameters at the end which 383 // effectively count as part of the variadic arguments. This is 384 // useful if you would prefer to not have *any* formal parameters, 385 // but the language forces you to have at least one. 386 unsigned nullPos = attr->getNullPos(); 387 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 388 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 389 390 // The number of arguments which should follow the sentinel. 391 unsigned numArgsAfterSentinel = attr->getSentinel(); 392 393 // If there aren't enough arguments for all the formal parameters, 394 // the sentinel, and the args after the sentinel, complain. 395 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 396 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 397 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 398 return; 399 } 400 401 // Otherwise, find the sentinel expression. 402 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 403 if (!sentinelExpr) return; 404 if (sentinelExpr->isValueDependent()) return; 405 if (Context.isSentinelNullExpr(sentinelExpr)) return; 406 407 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 408 // or 'NULL' if those are actually defined in the context. Only use 409 // 'nil' for ObjC methods, where it's much more likely that the 410 // variadic arguments form a list of object pointers. 411 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 412 std::string NullValue; 413 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 414 NullValue = "nil"; 415 else if (getLangOpts().CPlusPlus11) 416 NullValue = "nullptr"; 417 else if (PP.isMacroDefined("NULL")) 418 NullValue = "NULL"; 419 else 420 NullValue = "(void*) 0"; 421 422 if (MissingNilLoc.isInvalid()) 423 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 424 else 425 Diag(MissingNilLoc, diag::warn_missing_sentinel) 426 << int(calleeType) 427 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 } 430 431 SourceRange Sema::getExprRange(Expr *E) const { 432 return E ? E->getSourceRange() : SourceRange(); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Standard Promotions and Conversions 437 //===----------------------------------------------------------------------===// 438 439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 441 // Handle any placeholder expressions which made it here. 442 if (E->getType()->isPlaceholderType()) { 443 ExprResult result = CheckPlaceholderExpr(E); 444 if (result.isInvalid()) return ExprError(); 445 E = result.get(); 446 } 447 448 QualType Ty = E->getType(); 449 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 450 451 if (Ty->isFunctionType()) { 452 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 453 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 454 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 455 return ExprError(); 456 457 E = ImpCastExprToType(E, Context.getPointerType(Ty), 458 CK_FunctionToPointerDecay).get(); 459 } else if (Ty->isArrayType()) { 460 // In C90 mode, arrays only promote to pointers if the array expression is 461 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 462 // type 'array of type' is converted to an expression that has type 'pointer 463 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 464 // that has type 'array of type' ...". The relevant change is "an lvalue" 465 // (C90) to "an expression" (C99). 466 // 467 // C++ 4.2p1: 468 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 469 // T" can be converted to an rvalue of type "pointer to T". 470 // 471 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 472 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 473 CK_ArrayToPointerDecay).get(); 474 } 475 return E; 476 } 477 478 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 479 // Check to see if we are dereferencing a null pointer. If so, 480 // and if not volatile-qualified, this is undefined behavior that the 481 // optimizer will delete, so warn about it. People sometimes try to use this 482 // to get a deterministic trap and are surprised by clang's behavior. This 483 // only handles the pattern "*null", which is a very syntactic check. 484 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 485 if (UO->getOpcode() == UO_Deref && 486 UO->getSubExpr()->IgnoreParenCasts()-> 487 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 488 !UO->getType().isVolatileQualified()) { 489 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 490 S.PDiag(diag::warn_indirection_through_null) 491 << UO->getSubExpr()->getSourceRange()); 492 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 493 S.PDiag(diag::note_indirection_through_null)); 494 } 495 } 496 497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 498 SourceLocation AssignLoc, 499 const Expr* RHS) { 500 const ObjCIvarDecl *IV = OIRE->getDecl(); 501 if (!IV) 502 return; 503 504 DeclarationName MemberName = IV->getDeclName(); 505 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 506 if (!Member || !Member->isStr("isa")) 507 return; 508 509 const Expr *Base = OIRE->getBase(); 510 QualType BaseType = Base->getType(); 511 if (OIRE->isArrow()) 512 BaseType = BaseType->getPointeeType(); 513 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 514 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 515 ObjCInterfaceDecl *ClassDeclared = nullptr; 516 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 517 if (!ClassDeclared->getSuperClass() 518 && (*ClassDeclared->ivar_begin()) == IV) { 519 if (RHS) { 520 NamedDecl *ObjectSetClass = 521 S.LookupSingleName(S.TUScope, 522 &S.Context.Idents.get("object_setClass"), 523 SourceLocation(), S.LookupOrdinaryName); 524 if (ObjectSetClass) { 525 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 526 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 527 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 528 "object_setClass(") 529 << FixItHint::CreateReplacement( 530 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 531 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 532 } 533 else 534 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 535 } else { 536 NamedDecl *ObjectGetClass = 537 S.LookupSingleName(S.TUScope, 538 &S.Context.Idents.get("object_getClass"), 539 SourceLocation(), S.LookupOrdinaryName); 540 if (ObjectGetClass) 541 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 542 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 543 "object_getClass(") 544 << FixItHint::CreateReplacement( 545 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 546 else 547 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 548 } 549 S.Diag(IV->getLocation(), diag::note_ivar_decl); 550 } 551 } 552 } 553 554 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 555 // Handle any placeholder expressions which made it here. 556 if (E->getType()->isPlaceholderType()) { 557 ExprResult result = CheckPlaceholderExpr(E); 558 if (result.isInvalid()) return ExprError(); 559 E = result.get(); 560 } 561 562 // C++ [conv.lval]p1: 563 // A glvalue of a non-function, non-array type T can be 564 // converted to a prvalue. 565 if (!E->isGLValue()) return E; 566 567 QualType T = E->getType(); 568 assert(!T.isNull() && "r-value conversion on typeless expression?"); 569 570 // We don't want to throw lvalue-to-rvalue casts on top of 571 // expressions of certain types in C++. 572 if (getLangOpts().CPlusPlus && 573 (E->getType() == Context.OverloadTy || 574 T->isDependentType() || 575 T->isRecordType())) 576 return E; 577 578 // The C standard is actually really unclear on this point, and 579 // DR106 tells us what the result should be but not why. It's 580 // generally best to say that void types just doesn't undergo 581 // lvalue-to-rvalue at all. Note that expressions of unqualified 582 // 'void' type are never l-values, but qualified void can be. 583 if (T->isVoidType()) 584 return E; 585 586 // OpenCL usually rejects direct accesses to values of 'half' type. 587 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 588 T->isHalfType()) { 589 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 590 << 0 << T; 591 return ExprError(); 592 } 593 594 CheckForNullPointerDereference(*this, E); 595 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 596 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 597 &Context.Idents.get("object_getClass"), 598 SourceLocation(), LookupOrdinaryName); 599 if (ObjectGetClass) 600 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 601 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 602 << FixItHint::CreateReplacement( 603 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 604 else 605 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 606 } 607 else if (const ObjCIvarRefExpr *OIRE = 608 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 609 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 610 611 // C++ [conv.lval]p1: 612 // [...] If T is a non-class type, the type of the prvalue is the 613 // cv-unqualified version of T. Otherwise, the type of the 614 // rvalue is T. 615 // 616 // C99 6.3.2.1p2: 617 // If the lvalue has qualified type, the value has the unqualified 618 // version of the type of the lvalue; otherwise, the value has the 619 // type of the lvalue. 620 if (T.hasQualifiers()) 621 T = T.getUnqualifiedType(); 622 623 // Under the MS ABI, lock down the inheritance model now. 624 if (T->isMemberPointerType() && 625 Context.getTargetInfo().getCXXABI().isMicrosoft()) 626 (void)isCompleteType(E->getExprLoc(), T); 627 628 ExprResult Res = CheckLValueToRValueConversionOperand(E); 629 if (Res.isInvalid()) 630 return Res; 631 E = Res.get(); 632 633 // Loading a __weak object implicitly retains the value, so we need a cleanup to 634 // balance that. 635 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 636 Cleanup.setExprNeedsCleanups(true); 637 638 // C++ [conv.lval]p3: 639 // If T is cv std::nullptr_t, the result is a null pointer constant. 640 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 641 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 642 643 // C11 6.3.2.1p2: 644 // ... if the lvalue has atomic type, the value has the non-atomic version 645 // of the type of the lvalue ... 646 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 647 T = Atomic->getValueType().getUnqualifiedType(); 648 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 649 nullptr, VK_RValue); 650 } 651 652 return Res; 653 } 654 655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 656 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 657 if (Res.isInvalid()) 658 return ExprError(); 659 Res = DefaultLvalueConversion(Res.get()); 660 if (Res.isInvalid()) 661 return ExprError(); 662 return Res; 663 } 664 665 /// CallExprUnaryConversions - a special case of an unary conversion 666 /// performed on a function designator of a call expression. 667 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 668 QualType Ty = E->getType(); 669 ExprResult Res = E; 670 // Only do implicit cast for a function type, but not for a pointer 671 // to function type. 672 if (Ty->isFunctionType()) { 673 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 674 CK_FunctionToPointerDecay).get(); 675 if (Res.isInvalid()) 676 return ExprError(); 677 } 678 Res = DefaultLvalueConversion(Res.get()); 679 if (Res.isInvalid()) 680 return ExprError(); 681 return Res.get(); 682 } 683 684 /// UsualUnaryConversions - Performs various conversions that are common to most 685 /// operators (C99 6.3). The conversions of array and function types are 686 /// sometimes suppressed. For example, the array->pointer conversion doesn't 687 /// apply if the array is an argument to the sizeof or address (&) operators. 688 /// In these instances, this routine should *not* be called. 689 ExprResult Sema::UsualUnaryConversions(Expr *E) { 690 // First, convert to an r-value. 691 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 692 if (Res.isInvalid()) 693 return ExprError(); 694 E = Res.get(); 695 696 QualType Ty = E->getType(); 697 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 698 699 // Half FP have to be promoted to float unless it is natively supported 700 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 701 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 702 703 // Try to perform integral promotions if the object has a theoretically 704 // promotable type. 705 if (Ty->isIntegralOrUnscopedEnumerationType()) { 706 // C99 6.3.1.1p2: 707 // 708 // The following may be used in an expression wherever an int or 709 // unsigned int may be used: 710 // - an object or expression with an integer type whose integer 711 // conversion rank is less than or equal to the rank of int 712 // and unsigned int. 713 // - A bit-field of type _Bool, int, signed int, or unsigned int. 714 // 715 // If an int can represent all values of the original type, the 716 // value is converted to an int; otherwise, it is converted to an 717 // unsigned int. These are called the integer promotions. All 718 // other types are unchanged by the integer promotions. 719 720 QualType PTy = Context.isPromotableBitField(E); 721 if (!PTy.isNull()) { 722 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 723 return E; 724 } 725 if (Ty->isPromotableIntegerType()) { 726 QualType PT = Context.getPromotedIntegerType(Ty); 727 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 728 return E; 729 } 730 } 731 return E; 732 } 733 734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 735 /// do not have a prototype. Arguments that have type float or __fp16 736 /// are promoted to double. All other argument types are converted by 737 /// UsualUnaryConversions(). 738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 739 QualType Ty = E->getType(); 740 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 741 742 ExprResult Res = UsualUnaryConversions(E); 743 if (Res.isInvalid()) 744 return ExprError(); 745 E = Res.get(); 746 747 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 748 // promote to double. 749 // Note that default argument promotion applies only to float (and 750 // half/fp16); it does not apply to _Float16. 751 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 752 if (BTy && (BTy->getKind() == BuiltinType::Half || 753 BTy->getKind() == BuiltinType::Float)) { 754 if (getLangOpts().OpenCL && 755 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 756 if (BTy->getKind() == BuiltinType::Half) { 757 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 758 } 759 } else { 760 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 761 } 762 } 763 764 // C++ performs lvalue-to-rvalue conversion as a default argument 765 // promotion, even on class types, but note: 766 // C++11 [conv.lval]p2: 767 // When an lvalue-to-rvalue conversion occurs in an unevaluated 768 // operand or a subexpression thereof the value contained in the 769 // referenced object is not accessed. Otherwise, if the glvalue 770 // has a class type, the conversion copy-initializes a temporary 771 // of type T from the glvalue and the result of the conversion 772 // is a prvalue for the temporary. 773 // FIXME: add some way to gate this entire thing for correctness in 774 // potentially potentially evaluated contexts. 775 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 776 ExprResult Temp = PerformCopyInitialization( 777 InitializedEntity::InitializeTemporary(E->getType()), 778 E->getExprLoc(), E); 779 if (Temp.isInvalid()) 780 return ExprError(); 781 E = Temp.get(); 782 } 783 784 return E; 785 } 786 787 /// Determine the degree of POD-ness for an expression. 788 /// Incomplete types are considered POD, since this check can be performed 789 /// when we're in an unevaluated context. 790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 791 if (Ty->isIncompleteType()) { 792 // C++11 [expr.call]p7: 793 // After these conversions, if the argument does not have arithmetic, 794 // enumeration, pointer, pointer to member, or class type, the program 795 // is ill-formed. 796 // 797 // Since we've already performed array-to-pointer and function-to-pointer 798 // decay, the only such type in C++ is cv void. This also handles 799 // initializer lists as variadic arguments. 800 if (Ty->isVoidType()) 801 return VAK_Invalid; 802 803 if (Ty->isObjCObjectType()) 804 return VAK_Invalid; 805 return VAK_Valid; 806 } 807 808 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 809 return VAK_Invalid; 810 811 if (Ty.isCXX98PODType(Context)) 812 return VAK_Valid; 813 814 // C++11 [expr.call]p7: 815 // Passing a potentially-evaluated argument of class type (Clause 9) 816 // having a non-trivial copy constructor, a non-trivial move constructor, 817 // or a non-trivial destructor, with no corresponding parameter, 818 // is conditionally-supported with implementation-defined semantics. 819 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 820 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 821 if (!Record->hasNonTrivialCopyConstructor() && 822 !Record->hasNonTrivialMoveConstructor() && 823 !Record->hasNonTrivialDestructor()) 824 return VAK_ValidInCXX11; 825 826 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 827 return VAK_Valid; 828 829 if (Ty->isObjCObjectType()) 830 return VAK_Invalid; 831 832 if (getLangOpts().MSVCCompat) 833 return VAK_MSVCUndefined; 834 835 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 836 // permitted to reject them. We should consider doing so. 837 return VAK_Undefined; 838 } 839 840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 841 // Don't allow one to pass an Objective-C interface to a vararg. 842 const QualType &Ty = E->getType(); 843 VarArgKind VAK = isValidVarArgType(Ty); 844 845 // Complain about passing non-POD types through varargs. 846 switch (VAK) { 847 case VAK_ValidInCXX11: 848 DiagRuntimeBehavior( 849 E->getBeginLoc(), nullptr, 850 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 851 LLVM_FALLTHROUGH; 852 case VAK_Valid: 853 if (Ty->isRecordType()) { 854 // This is unlikely to be what the user intended. If the class has a 855 // 'c_str' member function, the user probably meant to call that. 856 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 857 PDiag(diag::warn_pass_class_arg_to_vararg) 858 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 859 } 860 break; 861 862 case VAK_Undefined: 863 case VAK_MSVCUndefined: 864 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 865 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 866 << getLangOpts().CPlusPlus11 << Ty << CT); 867 break; 868 869 case VAK_Invalid: 870 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 871 Diag(E->getBeginLoc(), 872 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 873 << Ty << CT; 874 else if (Ty->isObjCObjectType()) 875 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 876 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 877 << Ty << CT); 878 else 879 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 880 << isa<InitListExpr>(E) << Ty << CT; 881 break; 882 } 883 } 884 885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 886 /// will create a trap if the resulting type is not a POD type. 887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 888 FunctionDecl *FDecl) { 889 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 890 // Strip the unbridged-cast placeholder expression off, if applicable. 891 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 892 (CT == VariadicMethod || 893 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 894 E = stripARCUnbridgedCast(E); 895 896 // Otherwise, do normal placeholder checking. 897 } else { 898 ExprResult ExprRes = CheckPlaceholderExpr(E); 899 if (ExprRes.isInvalid()) 900 return ExprError(); 901 E = ExprRes.get(); 902 } 903 } 904 905 ExprResult ExprRes = DefaultArgumentPromotion(E); 906 if (ExprRes.isInvalid()) 907 return ExprError(); 908 E = ExprRes.get(); 909 910 // Diagnostics regarding non-POD argument types are 911 // emitted along with format string checking in Sema::CheckFunctionCall(). 912 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 913 // Turn this into a trap. 914 CXXScopeSpec SS; 915 SourceLocation TemplateKWLoc; 916 UnqualifiedId Name; 917 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 918 E->getBeginLoc()); 919 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 920 /*HasTrailingLParen=*/true, 921 /*IsAddressOfOperand=*/false); 922 if (TrapFn.isInvalid()) 923 return ExprError(); 924 925 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 926 None, E->getEndLoc()); 927 if (Call.isInvalid()) 928 return ExprError(); 929 930 ExprResult Comma = 931 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 932 if (Comma.isInvalid()) 933 return ExprError(); 934 return Comma.get(); 935 } 936 937 if (!getLangOpts().CPlusPlus && 938 RequireCompleteType(E->getExprLoc(), E->getType(), 939 diag::err_call_incomplete_argument)) 940 return ExprError(); 941 942 return E; 943 } 944 945 /// Converts an integer to complex float type. Helper function of 946 /// UsualArithmeticConversions() 947 /// 948 /// \return false if the integer expression is an integer type and is 949 /// successfully converted to the complex type. 950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 951 ExprResult &ComplexExpr, 952 QualType IntTy, 953 QualType ComplexTy, 954 bool SkipCast) { 955 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 956 if (SkipCast) return false; 957 if (IntTy->isIntegerType()) { 958 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 959 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 960 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 961 CK_FloatingRealToComplex); 962 } else { 963 assert(IntTy->isComplexIntegerType()); 964 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 965 CK_IntegralComplexToFloatingComplex); 966 } 967 return false; 968 } 969 970 /// Handle arithmetic conversion with complex types. Helper function of 971 /// UsualArithmeticConversions() 972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 973 ExprResult &RHS, QualType LHSType, 974 QualType RHSType, 975 bool IsCompAssign) { 976 // if we have an integer operand, the result is the complex type. 977 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 978 /*skipCast*/false)) 979 return LHSType; 980 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 981 /*skipCast*/IsCompAssign)) 982 return RHSType; 983 984 // This handles complex/complex, complex/float, or float/complex. 985 // When both operands are complex, the shorter operand is converted to the 986 // type of the longer, and that is the type of the result. This corresponds 987 // to what is done when combining two real floating-point operands. 988 // The fun begins when size promotion occur across type domains. 989 // From H&S 6.3.4: When one operand is complex and the other is a real 990 // floating-point type, the less precise type is converted, within it's 991 // real or complex domain, to the precision of the other type. For example, 992 // when combining a "long double" with a "double _Complex", the 993 // "double _Complex" is promoted to "long double _Complex". 994 995 // Compute the rank of the two types, regardless of whether they are complex. 996 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 997 998 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 999 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1000 QualType LHSElementType = 1001 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1002 QualType RHSElementType = 1003 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1004 1005 QualType ResultType = S.Context.getComplexType(LHSElementType); 1006 if (Order < 0) { 1007 // Promote the precision of the LHS if not an assignment. 1008 ResultType = S.Context.getComplexType(RHSElementType); 1009 if (!IsCompAssign) { 1010 if (LHSComplexType) 1011 LHS = 1012 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1013 else 1014 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1015 } 1016 } else if (Order > 0) { 1017 // Promote the precision of the RHS. 1018 if (RHSComplexType) 1019 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1020 else 1021 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1022 } 1023 return ResultType; 1024 } 1025 1026 /// Handle arithmetic conversion from integer to float. Helper function 1027 /// of UsualArithmeticConversions() 1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1029 ExprResult &IntExpr, 1030 QualType FloatTy, QualType IntTy, 1031 bool ConvertFloat, bool ConvertInt) { 1032 if (IntTy->isIntegerType()) { 1033 if (ConvertInt) 1034 // Convert intExpr to the lhs floating point type. 1035 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1036 CK_IntegralToFloating); 1037 return FloatTy; 1038 } 1039 1040 // Convert both sides to the appropriate complex float. 1041 assert(IntTy->isComplexIntegerType()); 1042 QualType result = S.Context.getComplexType(FloatTy); 1043 1044 // _Complex int -> _Complex float 1045 if (ConvertInt) 1046 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1047 CK_IntegralComplexToFloatingComplex); 1048 1049 // float -> _Complex float 1050 if (ConvertFloat) 1051 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1052 CK_FloatingRealToComplex); 1053 1054 return result; 1055 } 1056 1057 /// Handle arithmethic conversion with floating point types. Helper 1058 /// function of UsualArithmeticConversions() 1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1060 ExprResult &RHS, QualType LHSType, 1061 QualType RHSType, bool IsCompAssign) { 1062 bool LHSFloat = LHSType->isRealFloatingType(); 1063 bool RHSFloat = RHSType->isRealFloatingType(); 1064 1065 // If we have two real floating types, convert the smaller operand 1066 // to the bigger result. 1067 if (LHSFloat && RHSFloat) { 1068 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1069 if (order > 0) { 1070 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1071 return LHSType; 1072 } 1073 1074 assert(order < 0 && "illegal float comparison"); 1075 if (!IsCompAssign) 1076 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1077 return RHSType; 1078 } 1079 1080 if (LHSFloat) { 1081 // Half FP has to be promoted to float unless it is natively supported 1082 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1083 LHSType = S.Context.FloatTy; 1084 1085 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1086 /*ConvertFloat=*/!IsCompAssign, 1087 /*ConvertInt=*/ true); 1088 } 1089 assert(RHSFloat); 1090 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1091 /*convertInt=*/ true, 1092 /*convertFloat=*/!IsCompAssign); 1093 } 1094 1095 /// Diagnose attempts to convert between __float128 and long double if 1096 /// there is no support for such conversion. Helper function of 1097 /// UsualArithmeticConversions(). 1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1099 QualType RHSType) { 1100 /* No issue converting if at least one of the types is not a floating point 1101 type or the two types have the same rank. 1102 */ 1103 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1104 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1105 return false; 1106 1107 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1108 "The remaining types must be floating point types."); 1109 1110 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1111 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1112 1113 QualType LHSElemType = LHSComplex ? 1114 LHSComplex->getElementType() : LHSType; 1115 QualType RHSElemType = RHSComplex ? 1116 RHSComplex->getElementType() : RHSType; 1117 1118 // No issue if the two types have the same representation 1119 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1120 &S.Context.getFloatTypeSemantics(RHSElemType)) 1121 return false; 1122 1123 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1124 RHSElemType == S.Context.LongDoubleTy); 1125 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1126 RHSElemType == S.Context.Float128Ty); 1127 1128 // We've handled the situation where __float128 and long double have the same 1129 // representation. We allow all conversions for all possible long double types 1130 // except PPC's double double. 1131 return Float128AndLongDouble && 1132 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1133 &llvm::APFloat::PPCDoubleDouble()); 1134 } 1135 1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1137 1138 namespace { 1139 /// These helper callbacks are placed in an anonymous namespace to 1140 /// permit their use as function template parameters. 1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1142 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1143 } 1144 1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1146 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1147 CK_IntegralComplexCast); 1148 } 1149 } 1150 1151 /// Handle integer arithmetic conversions. Helper function of 1152 /// UsualArithmeticConversions() 1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1155 ExprResult &RHS, QualType LHSType, 1156 QualType RHSType, bool IsCompAssign) { 1157 // The rules for this case are in C99 6.3.1.8 1158 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1159 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1160 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1161 if (LHSSigned == RHSSigned) { 1162 // Same signedness; use the higher-ranked type 1163 if (order >= 0) { 1164 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1165 return LHSType; 1166 } else if (!IsCompAssign) 1167 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1168 return RHSType; 1169 } else if (order != (LHSSigned ? 1 : -1)) { 1170 // The unsigned type has greater than or equal rank to the 1171 // signed type, so use the unsigned type 1172 if (RHSSigned) { 1173 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1174 return LHSType; 1175 } else if (!IsCompAssign) 1176 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1177 return RHSType; 1178 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1179 // The two types are different widths; if we are here, that 1180 // means the signed type is larger than the unsigned type, so 1181 // use the signed type. 1182 if (LHSSigned) { 1183 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1184 return LHSType; 1185 } else if (!IsCompAssign) 1186 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1187 return RHSType; 1188 } else { 1189 // The signed type is higher-ranked than the unsigned type, 1190 // but isn't actually any bigger (like unsigned int and long 1191 // on most 32-bit systems). Use the unsigned type corresponding 1192 // to the signed type. 1193 QualType result = 1194 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1195 RHS = (*doRHSCast)(S, RHS.get(), result); 1196 if (!IsCompAssign) 1197 LHS = (*doLHSCast)(S, LHS.get(), result); 1198 return result; 1199 } 1200 } 1201 1202 /// Handle conversions with GCC complex int extension. Helper function 1203 /// of UsualArithmeticConversions() 1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1205 ExprResult &RHS, QualType LHSType, 1206 QualType RHSType, 1207 bool IsCompAssign) { 1208 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1209 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1210 1211 if (LHSComplexInt && RHSComplexInt) { 1212 QualType LHSEltType = LHSComplexInt->getElementType(); 1213 QualType RHSEltType = RHSComplexInt->getElementType(); 1214 QualType ScalarType = 1215 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1216 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1217 1218 return S.Context.getComplexType(ScalarType); 1219 } 1220 1221 if (LHSComplexInt) { 1222 QualType LHSEltType = LHSComplexInt->getElementType(); 1223 QualType ScalarType = 1224 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1225 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1226 QualType ComplexType = S.Context.getComplexType(ScalarType); 1227 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1228 CK_IntegralRealToComplex); 1229 1230 return ComplexType; 1231 } 1232 1233 assert(RHSComplexInt); 1234 1235 QualType RHSEltType = RHSComplexInt->getElementType(); 1236 QualType ScalarType = 1237 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1238 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1239 QualType ComplexType = S.Context.getComplexType(ScalarType); 1240 1241 if (!IsCompAssign) 1242 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1243 CK_IntegralRealToComplex); 1244 return ComplexType; 1245 } 1246 1247 /// Return the rank of a given fixed point or integer type. The value itself 1248 /// doesn't matter, but the values must be increasing with proper increasing 1249 /// rank as described in N1169 4.1.1. 1250 static unsigned GetFixedPointRank(QualType Ty) { 1251 const auto *BTy = Ty->getAs<BuiltinType>(); 1252 assert(BTy && "Expected a builtin type."); 1253 1254 switch (BTy->getKind()) { 1255 case BuiltinType::ShortFract: 1256 case BuiltinType::UShortFract: 1257 case BuiltinType::SatShortFract: 1258 case BuiltinType::SatUShortFract: 1259 return 1; 1260 case BuiltinType::Fract: 1261 case BuiltinType::UFract: 1262 case BuiltinType::SatFract: 1263 case BuiltinType::SatUFract: 1264 return 2; 1265 case BuiltinType::LongFract: 1266 case BuiltinType::ULongFract: 1267 case BuiltinType::SatLongFract: 1268 case BuiltinType::SatULongFract: 1269 return 3; 1270 case BuiltinType::ShortAccum: 1271 case BuiltinType::UShortAccum: 1272 case BuiltinType::SatShortAccum: 1273 case BuiltinType::SatUShortAccum: 1274 return 4; 1275 case BuiltinType::Accum: 1276 case BuiltinType::UAccum: 1277 case BuiltinType::SatAccum: 1278 case BuiltinType::SatUAccum: 1279 return 5; 1280 case BuiltinType::LongAccum: 1281 case BuiltinType::ULongAccum: 1282 case BuiltinType::SatLongAccum: 1283 case BuiltinType::SatULongAccum: 1284 return 6; 1285 default: 1286 if (BTy->isInteger()) 1287 return 0; 1288 llvm_unreachable("Unexpected fixed point or integer type"); 1289 } 1290 } 1291 1292 /// handleFixedPointConversion - Fixed point operations between fixed 1293 /// point types and integers or other fixed point types do not fall under 1294 /// usual arithmetic conversion since these conversions could result in loss 1295 /// of precsision (N1169 4.1.4). These operations should be calculated with 1296 /// the full precision of their result type (N1169 4.1.6.2.1). 1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1298 QualType RHSTy) { 1299 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1300 "Expected at least one of the operands to be a fixed point type"); 1301 assert((LHSTy->isFixedPointOrIntegerType() || 1302 RHSTy->isFixedPointOrIntegerType()) && 1303 "Special fixed point arithmetic operation conversions are only " 1304 "applied to ints or other fixed point types"); 1305 1306 // If one operand has signed fixed-point type and the other operand has 1307 // unsigned fixed-point type, then the unsigned fixed-point operand is 1308 // converted to its corresponding signed fixed-point type and the resulting 1309 // type is the type of the converted operand. 1310 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1311 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1312 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1313 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1314 1315 // The result type is the type with the highest rank, whereby a fixed-point 1316 // conversion rank is always greater than an integer conversion rank; if the 1317 // type of either of the operands is a saturating fixedpoint type, the result 1318 // type shall be the saturating fixed-point type corresponding to the type 1319 // with the highest rank; the resulting value is converted (taking into 1320 // account rounding and overflow) to the precision of the resulting type. 1321 // Same ranks between signed and unsigned types are resolved earlier, so both 1322 // types are either signed or both unsigned at this point. 1323 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1324 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1325 1326 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1327 1328 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1329 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1330 1331 return ResultTy; 1332 } 1333 1334 /// UsualArithmeticConversions - Performs various conversions that are common to 1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1336 /// routine returns the first non-arithmetic type found. The client is 1337 /// responsible for emitting appropriate error diagnostics. 1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1339 bool IsCompAssign) { 1340 if (!IsCompAssign) { 1341 LHS = UsualUnaryConversions(LHS.get()); 1342 if (LHS.isInvalid()) 1343 return QualType(); 1344 } 1345 1346 RHS = UsualUnaryConversions(RHS.get()); 1347 if (RHS.isInvalid()) 1348 return QualType(); 1349 1350 // For conversion purposes, we ignore any qualifiers. 1351 // For example, "const float" and "float" are equivalent. 1352 QualType LHSType = 1353 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1354 QualType RHSType = 1355 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1356 1357 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1358 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1359 LHSType = AtomicLHS->getValueType(); 1360 1361 // If both types are identical, no conversion is needed. 1362 if (LHSType == RHSType) 1363 return LHSType; 1364 1365 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1366 // The caller can deal with this (e.g. pointer + int). 1367 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1368 return QualType(); 1369 1370 // Apply unary and bitfield promotions to the LHS's type. 1371 QualType LHSUnpromotedType = LHSType; 1372 if (LHSType->isPromotableIntegerType()) 1373 LHSType = Context.getPromotedIntegerType(LHSType); 1374 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1375 if (!LHSBitfieldPromoteTy.isNull()) 1376 LHSType = LHSBitfieldPromoteTy; 1377 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1378 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1379 1380 // If both types are identical, no conversion is needed. 1381 if (LHSType == RHSType) 1382 return LHSType; 1383 1384 // At this point, we have two different arithmetic types. 1385 1386 // Diagnose attempts to convert between __float128 and long double where 1387 // such conversions currently can't be handled. 1388 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1389 return QualType(); 1390 1391 // Handle complex types first (C99 6.3.1.8p1). 1392 if (LHSType->isComplexType() || RHSType->isComplexType()) 1393 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1394 IsCompAssign); 1395 1396 // Now handle "real" floating types (i.e. float, double, long double). 1397 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1398 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 // Handle GCC complex int extension. 1402 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1403 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1404 IsCompAssign); 1405 1406 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1407 return handleFixedPointConversion(*this, LHSType, RHSType); 1408 1409 // Finally, we have two differing integer types. 1410 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1411 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // Semantic Analysis for various Expression Types 1416 //===----------------------------------------------------------------------===// 1417 1418 1419 ExprResult 1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1421 SourceLocation DefaultLoc, 1422 SourceLocation RParenLoc, 1423 Expr *ControllingExpr, 1424 ArrayRef<ParsedType> ArgTypes, 1425 ArrayRef<Expr *> ArgExprs) { 1426 unsigned NumAssocs = ArgTypes.size(); 1427 assert(NumAssocs == ArgExprs.size()); 1428 1429 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1430 for (unsigned i = 0; i < NumAssocs; ++i) { 1431 if (ArgTypes[i]) 1432 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1433 else 1434 Types[i] = nullptr; 1435 } 1436 1437 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1438 ControllingExpr, 1439 llvm::makeArrayRef(Types, NumAssocs), 1440 ArgExprs); 1441 delete [] Types; 1442 return ER; 1443 } 1444 1445 ExprResult 1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1447 SourceLocation DefaultLoc, 1448 SourceLocation RParenLoc, 1449 Expr *ControllingExpr, 1450 ArrayRef<TypeSourceInfo *> Types, 1451 ArrayRef<Expr *> Exprs) { 1452 unsigned NumAssocs = Types.size(); 1453 assert(NumAssocs == Exprs.size()); 1454 1455 // Decay and strip qualifiers for the controlling expression type, and handle 1456 // placeholder type replacement. See committee discussion from WG14 DR423. 1457 { 1458 EnterExpressionEvaluationContext Unevaluated( 1459 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1460 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1461 if (R.isInvalid()) 1462 return ExprError(); 1463 ControllingExpr = R.get(); 1464 } 1465 1466 // The controlling expression is an unevaluated operand, so side effects are 1467 // likely unintended. 1468 if (!inTemplateInstantiation() && 1469 ControllingExpr->HasSideEffects(Context, false)) 1470 Diag(ControllingExpr->getExprLoc(), 1471 diag::warn_side_effects_unevaluated_context); 1472 1473 bool TypeErrorFound = false, 1474 IsResultDependent = ControllingExpr->isTypeDependent(), 1475 ContainsUnexpandedParameterPack 1476 = ControllingExpr->containsUnexpandedParameterPack(); 1477 1478 for (unsigned i = 0; i < NumAssocs; ++i) { 1479 if (Exprs[i]->containsUnexpandedParameterPack()) 1480 ContainsUnexpandedParameterPack = true; 1481 1482 if (Types[i]) { 1483 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1484 ContainsUnexpandedParameterPack = true; 1485 1486 if (Types[i]->getType()->isDependentType()) { 1487 IsResultDependent = true; 1488 } else { 1489 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1490 // complete object type other than a variably modified type." 1491 unsigned D = 0; 1492 if (Types[i]->getType()->isIncompleteType()) 1493 D = diag::err_assoc_type_incomplete; 1494 else if (!Types[i]->getType()->isObjectType()) 1495 D = diag::err_assoc_type_nonobject; 1496 else if (Types[i]->getType()->isVariablyModifiedType()) 1497 D = diag::err_assoc_type_variably_modified; 1498 1499 if (D != 0) { 1500 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1501 << Types[i]->getTypeLoc().getSourceRange() 1502 << Types[i]->getType(); 1503 TypeErrorFound = true; 1504 } 1505 1506 // C11 6.5.1.1p2 "No two generic associations in the same generic 1507 // selection shall specify compatible types." 1508 for (unsigned j = i+1; j < NumAssocs; ++j) 1509 if (Types[j] && !Types[j]->getType()->isDependentType() && 1510 Context.typesAreCompatible(Types[i]->getType(), 1511 Types[j]->getType())) { 1512 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1513 diag::err_assoc_compatible_types) 1514 << Types[j]->getTypeLoc().getSourceRange() 1515 << Types[j]->getType() 1516 << Types[i]->getType(); 1517 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1518 diag::note_compat_assoc) 1519 << Types[i]->getTypeLoc().getSourceRange() 1520 << Types[i]->getType(); 1521 TypeErrorFound = true; 1522 } 1523 } 1524 } 1525 } 1526 if (TypeErrorFound) 1527 return ExprError(); 1528 1529 // If we determined that the generic selection is result-dependent, don't 1530 // try to compute the result expression. 1531 if (IsResultDependent) 1532 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1533 Exprs, DefaultLoc, RParenLoc, 1534 ContainsUnexpandedParameterPack); 1535 1536 SmallVector<unsigned, 1> CompatIndices; 1537 unsigned DefaultIndex = -1U; 1538 for (unsigned i = 0; i < NumAssocs; ++i) { 1539 if (!Types[i]) 1540 DefaultIndex = i; 1541 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1542 Types[i]->getType())) 1543 CompatIndices.push_back(i); 1544 } 1545 1546 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1547 // type compatible with at most one of the types named in its generic 1548 // association list." 1549 if (CompatIndices.size() > 1) { 1550 // We strip parens here because the controlling expression is typically 1551 // parenthesized in macro definitions. 1552 ControllingExpr = ControllingExpr->IgnoreParens(); 1553 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1554 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1555 << (unsigned)CompatIndices.size(); 1556 for (unsigned I : CompatIndices) { 1557 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1558 diag::note_compat_assoc) 1559 << Types[I]->getTypeLoc().getSourceRange() 1560 << Types[I]->getType(); 1561 } 1562 return ExprError(); 1563 } 1564 1565 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1566 // its controlling expression shall have type compatible with exactly one of 1567 // the types named in its generic association list." 1568 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1569 // We strip parens here because the controlling expression is typically 1570 // parenthesized in macro definitions. 1571 ControllingExpr = ControllingExpr->IgnoreParens(); 1572 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1573 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1574 return ExprError(); 1575 } 1576 1577 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1578 // type name that is compatible with the type of the controlling expression, 1579 // then the result expression of the generic selection is the expression 1580 // in that generic association. Otherwise, the result expression of the 1581 // generic selection is the expression in the default generic association." 1582 unsigned ResultIndex = 1583 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1584 1585 return GenericSelectionExpr::Create( 1586 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1587 ContainsUnexpandedParameterPack, ResultIndex); 1588 } 1589 1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1591 /// location of the token and the offset of the ud-suffix within it. 1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1593 unsigned Offset) { 1594 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1595 S.getLangOpts()); 1596 } 1597 1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1601 IdentifierInfo *UDSuffix, 1602 SourceLocation UDSuffixLoc, 1603 ArrayRef<Expr*> Args, 1604 SourceLocation LitEndLoc) { 1605 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1606 1607 QualType ArgTy[2]; 1608 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1609 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1610 if (ArgTy[ArgIdx]->isArrayType()) 1611 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1612 } 1613 1614 DeclarationName OpName = 1615 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1616 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1617 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1618 1619 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1620 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1621 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1622 /*AllowStringTemplate*/ false, 1623 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1624 return ExprError(); 1625 1626 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1627 } 1628 1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1630 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1632 /// multiple tokens. However, the common case is that StringToks points to one 1633 /// string. 1634 /// 1635 ExprResult 1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1637 assert(!StringToks.empty() && "Must have at least one string!"); 1638 1639 StringLiteralParser Literal(StringToks, PP); 1640 if (Literal.hadError) 1641 return ExprError(); 1642 1643 SmallVector<SourceLocation, 4> StringTokLocs; 1644 for (const Token &Tok : StringToks) 1645 StringTokLocs.push_back(Tok.getLocation()); 1646 1647 QualType CharTy = Context.CharTy; 1648 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1649 if (Literal.isWide()) { 1650 CharTy = Context.getWideCharType(); 1651 Kind = StringLiteral::Wide; 1652 } else if (Literal.isUTF8()) { 1653 if (getLangOpts().Char8) 1654 CharTy = Context.Char8Ty; 1655 Kind = StringLiteral::UTF8; 1656 } else if (Literal.isUTF16()) { 1657 CharTy = Context.Char16Ty; 1658 Kind = StringLiteral::UTF16; 1659 } else if (Literal.isUTF32()) { 1660 CharTy = Context.Char32Ty; 1661 Kind = StringLiteral::UTF32; 1662 } else if (Literal.isPascal()) { 1663 CharTy = Context.UnsignedCharTy; 1664 } 1665 1666 // Warn on initializing an array of char from a u8 string literal; this 1667 // becomes ill-formed in C++2a. 1668 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1669 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1670 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1671 1672 // Create removals for all 'u8' prefixes in the string literal(s). This 1673 // ensures C++2a compatibility (but may change the program behavior when 1674 // built by non-Clang compilers for which the execution character set is 1675 // not always UTF-8). 1676 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1677 SourceLocation RemovalDiagLoc; 1678 for (const Token &Tok : StringToks) { 1679 if (Tok.getKind() == tok::utf8_string_literal) { 1680 if (RemovalDiagLoc.isInvalid()) 1681 RemovalDiagLoc = Tok.getLocation(); 1682 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1683 Tok.getLocation(), 1684 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1685 getSourceManager(), getLangOpts()))); 1686 } 1687 } 1688 Diag(RemovalDiagLoc, RemovalDiag); 1689 } 1690 1691 QualType StrTy = 1692 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1693 1694 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1695 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1696 Kind, Literal.Pascal, StrTy, 1697 &StringTokLocs[0], 1698 StringTokLocs.size()); 1699 if (Literal.getUDSuffix().empty()) 1700 return Lit; 1701 1702 // We're building a user-defined literal. 1703 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1704 SourceLocation UDSuffixLoc = 1705 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1706 Literal.getUDSuffixOffset()); 1707 1708 // Make sure we're allowed user-defined literals here. 1709 if (!UDLScope) 1710 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1711 1712 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1713 // operator "" X (str, len) 1714 QualType SizeType = Context.getSizeType(); 1715 1716 DeclarationName OpName = 1717 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1718 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1719 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1720 1721 QualType ArgTy[] = { 1722 Context.getArrayDecayedType(StrTy), SizeType 1723 }; 1724 1725 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1726 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1727 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1728 /*AllowStringTemplate*/ true, 1729 /*DiagnoseMissing*/ true)) { 1730 1731 case LOLR_Cooked: { 1732 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1733 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1734 StringTokLocs[0]); 1735 Expr *Args[] = { Lit, LenArg }; 1736 1737 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1738 } 1739 1740 case LOLR_StringTemplate: { 1741 TemplateArgumentListInfo ExplicitArgs; 1742 1743 unsigned CharBits = Context.getIntWidth(CharTy); 1744 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1745 llvm::APSInt Value(CharBits, CharIsUnsigned); 1746 1747 TemplateArgument TypeArg(CharTy); 1748 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1749 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1750 1751 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1752 Value = Lit->getCodeUnit(I); 1753 TemplateArgument Arg(Context, Value, CharTy); 1754 TemplateArgumentLocInfo ArgInfo; 1755 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1756 } 1757 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1758 &ExplicitArgs); 1759 } 1760 case LOLR_Raw: 1761 case LOLR_Template: 1762 case LOLR_ErrorNoDiagnostic: 1763 llvm_unreachable("unexpected literal operator lookup result"); 1764 case LOLR_Error: 1765 return ExprError(); 1766 } 1767 llvm_unreachable("unexpected literal operator lookup result"); 1768 } 1769 1770 DeclRefExpr * 1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1772 SourceLocation Loc, 1773 const CXXScopeSpec *SS) { 1774 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1775 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1776 } 1777 1778 DeclRefExpr * 1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1780 const DeclarationNameInfo &NameInfo, 1781 const CXXScopeSpec *SS, NamedDecl *FoundD, 1782 SourceLocation TemplateKWLoc, 1783 const TemplateArgumentListInfo *TemplateArgs) { 1784 NestedNameSpecifierLoc NNS = 1785 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1786 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1787 TemplateArgs); 1788 } 1789 1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1791 // A declaration named in an unevaluated operand never constitutes an odr-use. 1792 if (isUnevaluatedContext()) 1793 return NOUR_Unevaluated; 1794 1795 // C++2a [basic.def.odr]p4: 1796 // A variable x whose name appears as a potentially-evaluated expression e 1797 // is odr-used by e unless [...] x is a reference that is usable in 1798 // constant expressions. 1799 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1800 if (VD->getType()->isReferenceType() && 1801 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1802 VD->isUsableInConstantExpressions(Context)) 1803 return NOUR_Constant; 1804 } 1805 1806 // All remaining non-variable cases constitute an odr-use. For variables, we 1807 // need to wait and see how the expression is used. 1808 return NOUR_None; 1809 } 1810 1811 /// BuildDeclRefExpr - Build an expression that references a 1812 /// declaration that does not require a closure capture. 1813 DeclRefExpr * 1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1815 const DeclarationNameInfo &NameInfo, 1816 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1817 SourceLocation TemplateKWLoc, 1818 const TemplateArgumentListInfo *TemplateArgs) { 1819 bool RefersToCapturedVariable = 1820 isa<VarDecl>(D) && 1821 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1822 1823 DeclRefExpr *E = DeclRefExpr::Create( 1824 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1825 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1826 MarkDeclRefReferenced(E); 1827 1828 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1829 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1830 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1831 getCurFunction()->recordUseOfWeak(E); 1832 1833 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1834 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1835 FD = IFD->getAnonField(); 1836 if (FD) { 1837 UnusedPrivateFields.remove(FD); 1838 // Just in case we're building an illegal pointer-to-member. 1839 if (FD->isBitField()) 1840 E->setObjectKind(OK_BitField); 1841 } 1842 1843 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1844 // designates a bit-field. 1845 if (auto *BD = dyn_cast<BindingDecl>(D)) 1846 if (auto *BE = BD->getBinding()) 1847 E->setObjectKind(BE->getObjectKind()); 1848 1849 return E; 1850 } 1851 1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1853 /// possibly a list of template arguments. 1854 /// 1855 /// If this produces template arguments, it is permitted to call 1856 /// DecomposeTemplateName. 1857 /// 1858 /// This actually loses a lot of source location information for 1859 /// non-standard name kinds; we should consider preserving that in 1860 /// some way. 1861 void 1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1863 TemplateArgumentListInfo &Buffer, 1864 DeclarationNameInfo &NameInfo, 1865 const TemplateArgumentListInfo *&TemplateArgs) { 1866 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1867 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1868 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1869 1870 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1871 Id.TemplateId->NumArgs); 1872 translateTemplateArguments(TemplateArgsPtr, Buffer); 1873 1874 TemplateName TName = Id.TemplateId->Template.get(); 1875 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1876 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1877 TemplateArgs = &Buffer; 1878 } else { 1879 NameInfo = GetNameFromUnqualifiedId(Id); 1880 TemplateArgs = nullptr; 1881 } 1882 } 1883 1884 static void emitEmptyLookupTypoDiagnostic( 1885 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1886 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1887 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1888 DeclContext *Ctx = 1889 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1890 if (!TC) { 1891 // Emit a special diagnostic for failed member lookups. 1892 // FIXME: computing the declaration context might fail here (?) 1893 if (Ctx) 1894 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1895 << SS.getRange(); 1896 else 1897 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1898 return; 1899 } 1900 1901 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1902 bool DroppedSpecifier = 1903 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1904 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1905 ? diag::note_implicit_param_decl 1906 : diag::note_previous_decl; 1907 if (!Ctx) 1908 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1909 SemaRef.PDiag(NoteID)); 1910 else 1911 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1912 << Typo << Ctx << DroppedSpecifier 1913 << SS.getRange(), 1914 SemaRef.PDiag(NoteID)); 1915 } 1916 1917 /// Diagnose an empty lookup. 1918 /// 1919 /// \return false if new lookup candidates were found 1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1921 CorrectionCandidateCallback &CCC, 1922 TemplateArgumentListInfo *ExplicitTemplateArgs, 1923 ArrayRef<Expr *> Args, TypoExpr **Out) { 1924 DeclarationName Name = R.getLookupName(); 1925 1926 unsigned diagnostic = diag::err_undeclared_var_use; 1927 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1928 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1929 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1930 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1931 diagnostic = diag::err_undeclared_use; 1932 diagnostic_suggest = diag::err_undeclared_use_suggest; 1933 } 1934 1935 // If the original lookup was an unqualified lookup, fake an 1936 // unqualified lookup. This is useful when (for example) the 1937 // original lookup would not have found something because it was a 1938 // dependent name. 1939 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1940 while (DC) { 1941 if (isa<CXXRecordDecl>(DC)) { 1942 LookupQualifiedName(R, DC); 1943 1944 if (!R.empty()) { 1945 // Don't give errors about ambiguities in this lookup. 1946 R.suppressDiagnostics(); 1947 1948 // During a default argument instantiation the CurContext points 1949 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1950 // function parameter list, hence add an explicit check. 1951 bool isDefaultArgument = 1952 !CodeSynthesisContexts.empty() && 1953 CodeSynthesisContexts.back().Kind == 1954 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1955 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1956 bool isInstance = CurMethod && 1957 CurMethod->isInstance() && 1958 DC == CurMethod->getParent() && !isDefaultArgument; 1959 1960 // Give a code modification hint to insert 'this->'. 1961 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1962 // Actually quite difficult! 1963 if (getLangOpts().MSVCCompat) 1964 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1965 if (isInstance) { 1966 Diag(R.getNameLoc(), diagnostic) << Name 1967 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1968 CheckCXXThisCapture(R.getNameLoc()); 1969 } else { 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 } 1972 1973 // Do we really want to note all of these? 1974 for (NamedDecl *D : R) 1975 Diag(D->getLocation(), diag::note_dependent_var_use); 1976 1977 // Return true if we are inside a default argument instantiation 1978 // and the found name refers to an instance member function, otherwise 1979 // the function calling DiagnoseEmptyLookup will try to create an 1980 // implicit member call and this is wrong for default argument. 1981 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1982 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1983 return true; 1984 } 1985 1986 // Tell the callee to try to recover. 1987 return false; 1988 } 1989 1990 R.clear(); 1991 } 1992 1993 DC = DC->getLookupParent(); 1994 } 1995 1996 // We didn't find anything, so try to correct for a typo. 1997 TypoCorrection Corrected; 1998 if (S && Out) { 1999 SourceLocation TypoLoc = R.getNameLoc(); 2000 assert(!ExplicitTemplateArgs && 2001 "Diagnosing an empty lookup with explicit template args!"); 2002 *Out = CorrectTypoDelayed( 2003 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2004 [=](const TypoCorrection &TC) { 2005 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2006 diagnostic, diagnostic_suggest); 2007 }, 2008 nullptr, CTK_ErrorRecovery); 2009 if (*Out) 2010 return true; 2011 } else if (S && 2012 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2013 S, &SS, CCC, CTK_ErrorRecovery))) { 2014 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2015 bool DroppedSpecifier = 2016 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2017 R.setLookupName(Corrected.getCorrection()); 2018 2019 bool AcceptableWithRecovery = false; 2020 bool AcceptableWithoutRecovery = false; 2021 NamedDecl *ND = Corrected.getFoundDecl(); 2022 if (ND) { 2023 if (Corrected.isOverloaded()) { 2024 OverloadCandidateSet OCS(R.getNameLoc(), 2025 OverloadCandidateSet::CSK_Normal); 2026 OverloadCandidateSet::iterator Best; 2027 for (NamedDecl *CD : Corrected) { 2028 if (FunctionTemplateDecl *FTD = 2029 dyn_cast<FunctionTemplateDecl>(CD)) 2030 AddTemplateOverloadCandidate( 2031 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2032 Args, OCS); 2033 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2034 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2035 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2036 Args, OCS); 2037 } 2038 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2039 case OR_Success: 2040 ND = Best->FoundDecl; 2041 Corrected.setCorrectionDecl(ND); 2042 break; 2043 default: 2044 // FIXME: Arbitrarily pick the first declaration for the note. 2045 Corrected.setCorrectionDecl(ND); 2046 break; 2047 } 2048 } 2049 R.addDecl(ND); 2050 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2051 CXXRecordDecl *Record = nullptr; 2052 if (Corrected.getCorrectionSpecifier()) { 2053 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2054 Record = Ty->getAsCXXRecordDecl(); 2055 } 2056 if (!Record) 2057 Record = cast<CXXRecordDecl>( 2058 ND->getDeclContext()->getRedeclContext()); 2059 R.setNamingClass(Record); 2060 } 2061 2062 auto *UnderlyingND = ND->getUnderlyingDecl(); 2063 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2064 isa<FunctionTemplateDecl>(UnderlyingND); 2065 // FIXME: If we ended up with a typo for a type name or 2066 // Objective-C class name, we're in trouble because the parser 2067 // is in the wrong place to recover. Suggest the typo 2068 // correction, but don't make it a fix-it since we're not going 2069 // to recover well anyway. 2070 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2071 getAsTypeTemplateDecl(UnderlyingND) || 2072 isa<ObjCInterfaceDecl>(UnderlyingND); 2073 } else { 2074 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2075 // because we aren't able to recover. 2076 AcceptableWithoutRecovery = true; 2077 } 2078 2079 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2080 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2081 ? diag::note_implicit_param_decl 2082 : diag::note_previous_decl; 2083 if (SS.isEmpty()) 2084 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2085 PDiag(NoteID), AcceptableWithRecovery); 2086 else 2087 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2088 << Name << computeDeclContext(SS, false) 2089 << DroppedSpecifier << SS.getRange(), 2090 PDiag(NoteID), AcceptableWithRecovery); 2091 2092 // Tell the callee whether to try to recover. 2093 return !AcceptableWithRecovery; 2094 } 2095 } 2096 R.clear(); 2097 2098 // Emit a special diagnostic for failed member lookups. 2099 // FIXME: computing the declaration context might fail here (?) 2100 if (!SS.isEmpty()) { 2101 Diag(R.getNameLoc(), diag::err_no_member) 2102 << Name << computeDeclContext(SS, false) 2103 << SS.getRange(); 2104 return true; 2105 } 2106 2107 // Give up, we can't recover. 2108 Diag(R.getNameLoc(), diagnostic) << Name; 2109 return true; 2110 } 2111 2112 /// In Microsoft mode, if we are inside a template class whose parent class has 2113 /// dependent base classes, and we can't resolve an unqualified identifier, then 2114 /// assume the identifier is a member of a dependent base class. We can only 2115 /// recover successfully in static methods, instance methods, and other contexts 2116 /// where 'this' is available. This doesn't precisely match MSVC's 2117 /// instantiation model, but it's close enough. 2118 static Expr * 2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2120 DeclarationNameInfo &NameInfo, 2121 SourceLocation TemplateKWLoc, 2122 const TemplateArgumentListInfo *TemplateArgs) { 2123 // Only try to recover from lookup into dependent bases in static methods or 2124 // contexts where 'this' is available. 2125 QualType ThisType = S.getCurrentThisType(); 2126 const CXXRecordDecl *RD = nullptr; 2127 if (!ThisType.isNull()) 2128 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2129 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2130 RD = MD->getParent(); 2131 if (!RD || !RD->hasAnyDependentBases()) 2132 return nullptr; 2133 2134 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2135 // is available, suggest inserting 'this->' as a fixit. 2136 SourceLocation Loc = NameInfo.getLoc(); 2137 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2138 DB << NameInfo.getName() << RD; 2139 2140 if (!ThisType.isNull()) { 2141 DB << FixItHint::CreateInsertion(Loc, "this->"); 2142 return CXXDependentScopeMemberExpr::Create( 2143 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2144 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2145 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2146 } 2147 2148 // Synthesize a fake NNS that points to the derived class. This will 2149 // perform name lookup during template instantiation. 2150 CXXScopeSpec SS; 2151 auto *NNS = 2152 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2153 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2154 return DependentScopeDeclRefExpr::Create( 2155 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2156 TemplateArgs); 2157 } 2158 2159 ExprResult 2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2161 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2162 bool HasTrailingLParen, bool IsAddressOfOperand, 2163 CorrectionCandidateCallback *CCC, 2164 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2165 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2166 "cannot be direct & operand and have a trailing lparen"); 2167 if (SS.isInvalid()) 2168 return ExprError(); 2169 2170 TemplateArgumentListInfo TemplateArgsBuffer; 2171 2172 // Decompose the UnqualifiedId into the following data. 2173 DeclarationNameInfo NameInfo; 2174 const TemplateArgumentListInfo *TemplateArgs; 2175 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2176 2177 DeclarationName Name = NameInfo.getName(); 2178 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2179 SourceLocation NameLoc = NameInfo.getLoc(); 2180 2181 if (II && II->isEditorPlaceholder()) { 2182 // FIXME: When typed placeholders are supported we can create a typed 2183 // placeholder expression node. 2184 return ExprError(); 2185 } 2186 2187 // C++ [temp.dep.expr]p3: 2188 // An id-expression is type-dependent if it contains: 2189 // -- an identifier that was declared with a dependent type, 2190 // (note: handled after lookup) 2191 // -- a template-id that is dependent, 2192 // (note: handled in BuildTemplateIdExpr) 2193 // -- a conversion-function-id that specifies a dependent type, 2194 // -- a nested-name-specifier that contains a class-name that 2195 // names a dependent type. 2196 // Determine whether this is a member of an unknown specialization; 2197 // we need to handle these differently. 2198 bool DependentID = false; 2199 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2200 Name.getCXXNameType()->isDependentType()) { 2201 DependentID = true; 2202 } else if (SS.isSet()) { 2203 if (DeclContext *DC = computeDeclContext(SS, false)) { 2204 if (RequireCompleteDeclContext(SS, DC)) 2205 return ExprError(); 2206 } else { 2207 DependentID = true; 2208 } 2209 } 2210 2211 if (DependentID) 2212 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2213 IsAddressOfOperand, TemplateArgs); 2214 2215 // Perform the required lookup. 2216 LookupResult R(*this, NameInfo, 2217 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2218 ? LookupObjCImplicitSelfParam 2219 : LookupOrdinaryName); 2220 if (TemplateKWLoc.isValid() || TemplateArgs) { 2221 // Lookup the template name again to correctly establish the context in 2222 // which it was found. This is really unfortunate as we already did the 2223 // lookup to determine that it was a template name in the first place. If 2224 // this becomes a performance hit, we can work harder to preserve those 2225 // results until we get here but it's likely not worth it. 2226 bool MemberOfUnknownSpecialization; 2227 AssumedTemplateKind AssumedTemplate; 2228 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2229 MemberOfUnknownSpecialization, TemplateKWLoc, 2230 &AssumedTemplate)) 2231 return ExprError(); 2232 2233 if (MemberOfUnknownSpecialization || 2234 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2235 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2236 IsAddressOfOperand, TemplateArgs); 2237 } else { 2238 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2239 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2240 2241 // If the result might be in a dependent base class, this is a dependent 2242 // id-expression. 2243 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2244 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2245 IsAddressOfOperand, TemplateArgs); 2246 2247 // If this reference is in an Objective-C method, then we need to do 2248 // some special Objective-C lookup, too. 2249 if (IvarLookupFollowUp) { 2250 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2251 if (E.isInvalid()) 2252 return ExprError(); 2253 2254 if (Expr *Ex = E.getAs<Expr>()) 2255 return Ex; 2256 } 2257 } 2258 2259 if (R.isAmbiguous()) 2260 return ExprError(); 2261 2262 // This could be an implicitly declared function reference (legal in C90, 2263 // extension in C99, forbidden in C++). 2264 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2265 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2266 if (D) R.addDecl(D); 2267 } 2268 2269 // Determine whether this name might be a candidate for 2270 // argument-dependent lookup. 2271 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2272 2273 if (R.empty() && !ADL) { 2274 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2275 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2276 TemplateKWLoc, TemplateArgs)) 2277 return E; 2278 } 2279 2280 // Don't diagnose an empty lookup for inline assembly. 2281 if (IsInlineAsmIdentifier) 2282 return ExprError(); 2283 2284 // If this name wasn't predeclared and if this is not a function 2285 // call, diagnose the problem. 2286 TypoExpr *TE = nullptr; 2287 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2288 : nullptr); 2289 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2290 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2291 "Typo correction callback misconfigured"); 2292 if (CCC) { 2293 // Make sure the callback knows what the typo being diagnosed is. 2294 CCC->setTypoName(II); 2295 if (SS.isValid()) 2296 CCC->setTypoNNS(SS.getScopeRep()); 2297 } 2298 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2299 // a template name, but we happen to have always already looked up the name 2300 // before we get here if it must be a template name. 2301 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2302 None, &TE)) { 2303 if (TE && KeywordReplacement) { 2304 auto &State = getTypoExprState(TE); 2305 auto BestTC = State.Consumer->getNextCorrection(); 2306 if (BestTC.isKeyword()) { 2307 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2308 if (State.DiagHandler) 2309 State.DiagHandler(BestTC); 2310 KeywordReplacement->startToken(); 2311 KeywordReplacement->setKind(II->getTokenID()); 2312 KeywordReplacement->setIdentifierInfo(II); 2313 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2314 // Clean up the state associated with the TypoExpr, since it has 2315 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2316 clearDelayedTypo(TE); 2317 // Signal that a correction to a keyword was performed by returning a 2318 // valid-but-null ExprResult. 2319 return (Expr*)nullptr; 2320 } 2321 State.Consumer->resetCorrectionStream(); 2322 } 2323 return TE ? TE : ExprError(); 2324 } 2325 2326 assert(!R.empty() && 2327 "DiagnoseEmptyLookup returned false but added no results"); 2328 2329 // If we found an Objective-C instance variable, let 2330 // LookupInObjCMethod build the appropriate expression to 2331 // reference the ivar. 2332 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2333 R.clear(); 2334 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2335 // In a hopelessly buggy code, Objective-C instance variable 2336 // lookup fails and no expression will be built to reference it. 2337 if (!E.isInvalid() && !E.get()) 2338 return ExprError(); 2339 return E; 2340 } 2341 } 2342 2343 // This is guaranteed from this point on. 2344 assert(!R.empty() || ADL); 2345 2346 // Check whether this might be a C++ implicit instance member access. 2347 // C++ [class.mfct.non-static]p3: 2348 // When an id-expression that is not part of a class member access 2349 // syntax and not used to form a pointer to member is used in the 2350 // body of a non-static member function of class X, if name lookup 2351 // resolves the name in the id-expression to a non-static non-type 2352 // member of some class C, the id-expression is transformed into a 2353 // class member access expression using (*this) as the 2354 // postfix-expression to the left of the . operator. 2355 // 2356 // But we don't actually need to do this for '&' operands if R 2357 // resolved to a function or overloaded function set, because the 2358 // expression is ill-formed if it actually works out to be a 2359 // non-static member function: 2360 // 2361 // C++ [expr.ref]p4: 2362 // Otherwise, if E1.E2 refers to a non-static member function. . . 2363 // [t]he expression can be used only as the left-hand operand of a 2364 // member function call. 2365 // 2366 // There are other safeguards against such uses, but it's important 2367 // to get this right here so that we don't end up making a 2368 // spuriously dependent expression if we're inside a dependent 2369 // instance method. 2370 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2371 bool MightBeImplicitMember; 2372 if (!IsAddressOfOperand) 2373 MightBeImplicitMember = true; 2374 else if (!SS.isEmpty()) 2375 MightBeImplicitMember = false; 2376 else if (R.isOverloadedResult()) 2377 MightBeImplicitMember = false; 2378 else if (R.isUnresolvableResult()) 2379 MightBeImplicitMember = true; 2380 else 2381 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2382 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2383 isa<MSPropertyDecl>(R.getFoundDecl()); 2384 2385 if (MightBeImplicitMember) 2386 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2387 R, TemplateArgs, S); 2388 } 2389 2390 if (TemplateArgs || TemplateKWLoc.isValid()) { 2391 2392 // In C++1y, if this is a variable template id, then check it 2393 // in BuildTemplateIdExpr(). 2394 // The single lookup result must be a variable template declaration. 2395 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2396 Id.TemplateId->Kind == TNK_Var_template) { 2397 assert(R.getAsSingle<VarTemplateDecl>() && 2398 "There should only be one declaration found."); 2399 } 2400 2401 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2402 } 2403 2404 return BuildDeclarationNameExpr(SS, R, ADL); 2405 } 2406 2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2408 /// declaration name, generally during template instantiation. 2409 /// There's a large number of things which don't need to be done along 2410 /// this path. 2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2412 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2413 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2414 DeclContext *DC = computeDeclContext(SS, false); 2415 if (!DC) 2416 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2417 NameInfo, /*TemplateArgs=*/nullptr); 2418 2419 if (RequireCompleteDeclContext(SS, DC)) 2420 return ExprError(); 2421 2422 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2423 LookupQualifiedName(R, DC); 2424 2425 if (R.isAmbiguous()) 2426 return ExprError(); 2427 2428 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2429 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2430 NameInfo, /*TemplateArgs=*/nullptr); 2431 2432 if (R.empty()) { 2433 Diag(NameInfo.getLoc(), diag::err_no_member) 2434 << NameInfo.getName() << DC << SS.getRange(); 2435 return ExprError(); 2436 } 2437 2438 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2439 // Diagnose a missing typename if this resolved unambiguously to a type in 2440 // a dependent context. If we can recover with a type, downgrade this to 2441 // a warning in Microsoft compatibility mode. 2442 unsigned DiagID = diag::err_typename_missing; 2443 if (RecoveryTSI && getLangOpts().MSVCCompat) 2444 DiagID = diag::ext_typename_missing; 2445 SourceLocation Loc = SS.getBeginLoc(); 2446 auto D = Diag(Loc, DiagID); 2447 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2448 << SourceRange(Loc, NameInfo.getEndLoc()); 2449 2450 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2451 // context. 2452 if (!RecoveryTSI) 2453 return ExprError(); 2454 2455 // Only issue the fixit if we're prepared to recover. 2456 D << FixItHint::CreateInsertion(Loc, "typename "); 2457 2458 // Recover by pretending this was an elaborated type. 2459 QualType Ty = Context.getTypeDeclType(TD); 2460 TypeLocBuilder TLB; 2461 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2462 2463 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2464 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2465 QTL.setElaboratedKeywordLoc(SourceLocation()); 2466 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2467 2468 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2469 2470 return ExprEmpty(); 2471 } 2472 2473 // Defend against this resolving to an implicit member access. We usually 2474 // won't get here if this might be a legitimate a class member (we end up in 2475 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2476 // a pointer-to-member or in an unevaluated context in C++11. 2477 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2478 return BuildPossibleImplicitMemberExpr(SS, 2479 /*TemplateKWLoc=*/SourceLocation(), 2480 R, /*TemplateArgs=*/nullptr, S); 2481 2482 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2483 } 2484 2485 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2486 /// detected that we're currently inside an ObjC method. Perform some 2487 /// additional lookup. 2488 /// 2489 /// Ideally, most of this would be done by lookup, but there's 2490 /// actually quite a lot of extra work involved. 2491 /// 2492 /// Returns a null sentinel to indicate trivial success. 2493 ExprResult 2494 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2495 IdentifierInfo *II, bool AllowBuiltinCreation) { 2496 SourceLocation Loc = Lookup.getNameLoc(); 2497 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2498 2499 // Check for error condition which is already reported. 2500 if (!CurMethod) 2501 return ExprError(); 2502 2503 // There are two cases to handle here. 1) scoped lookup could have failed, 2504 // in which case we should look for an ivar. 2) scoped lookup could have 2505 // found a decl, but that decl is outside the current instance method (i.e. 2506 // a global variable). In these two cases, we do a lookup for an ivar with 2507 // this name, if the lookup sucedes, we replace it our current decl. 2508 2509 // If we're in a class method, we don't normally want to look for 2510 // ivars. But if we don't find anything else, and there's an 2511 // ivar, that's an error. 2512 bool IsClassMethod = CurMethod->isClassMethod(); 2513 2514 bool LookForIvars; 2515 if (Lookup.empty()) 2516 LookForIvars = true; 2517 else if (IsClassMethod) 2518 LookForIvars = false; 2519 else 2520 LookForIvars = (Lookup.isSingleResult() && 2521 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2522 ObjCInterfaceDecl *IFace = nullptr; 2523 if (LookForIvars) { 2524 IFace = CurMethod->getClassInterface(); 2525 ObjCInterfaceDecl *ClassDeclared; 2526 ObjCIvarDecl *IV = nullptr; 2527 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2528 // Diagnose using an ivar in a class method. 2529 if (IsClassMethod) 2530 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2531 << IV->getDeclName()); 2532 2533 // If we're referencing an invalid decl, just return this as a silent 2534 // error node. The error diagnostic was already emitted on the decl. 2535 if (IV->isInvalidDecl()) 2536 return ExprError(); 2537 2538 // Check if referencing a field with __attribute__((deprecated)). 2539 if (DiagnoseUseOfDecl(IV, Loc)) 2540 return ExprError(); 2541 2542 // Diagnose the use of an ivar outside of the declaring class. 2543 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2544 !declaresSameEntity(ClassDeclared, IFace) && 2545 !getLangOpts().DebuggerSupport) 2546 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2547 2548 // FIXME: This should use a new expr for a direct reference, don't 2549 // turn this into Self->ivar, just return a BareIVarExpr or something. 2550 IdentifierInfo &II = Context.Idents.get("self"); 2551 UnqualifiedId SelfName; 2552 SelfName.setIdentifier(&II, SourceLocation()); 2553 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2554 CXXScopeSpec SelfScopeSpec; 2555 SourceLocation TemplateKWLoc; 2556 ExprResult SelfExpr = 2557 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2558 /*HasTrailingLParen=*/false, 2559 /*IsAddressOfOperand=*/false); 2560 if (SelfExpr.isInvalid()) 2561 return ExprError(); 2562 2563 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2564 if (SelfExpr.isInvalid()) 2565 return ExprError(); 2566 2567 MarkAnyDeclReferenced(Loc, IV, true); 2568 2569 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2570 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2571 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2572 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2573 2574 ObjCIvarRefExpr *Result = new (Context) 2575 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2576 IV->getLocation(), SelfExpr.get(), true, true); 2577 2578 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2579 if (!isUnevaluatedContext() && 2580 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2581 getCurFunction()->recordUseOfWeak(Result); 2582 } 2583 if (getLangOpts().ObjCAutoRefCount) 2584 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2585 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2586 2587 return Result; 2588 } 2589 } else if (CurMethod->isInstanceMethod()) { 2590 // We should warn if a local variable hides an ivar. 2591 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2592 ObjCInterfaceDecl *ClassDeclared; 2593 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2594 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2595 declaresSameEntity(IFace, ClassDeclared)) 2596 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2597 } 2598 } 2599 } else if (Lookup.isSingleResult() && 2600 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2601 // If accessing a stand-alone ivar in a class method, this is an error. 2602 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2603 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2604 << IV->getDeclName()); 2605 } 2606 2607 if (Lookup.empty() && II && AllowBuiltinCreation) { 2608 // FIXME. Consolidate this with similar code in LookupName. 2609 if (unsigned BuiltinID = II->getBuiltinID()) { 2610 if (!(getLangOpts().CPlusPlus && 2611 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2612 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2613 S, Lookup.isForRedeclaration(), 2614 Lookup.getNameLoc()); 2615 if (D) Lookup.addDecl(D); 2616 } 2617 } 2618 } 2619 // Sentinel value saying that we didn't do anything special. 2620 return ExprResult((Expr *)nullptr); 2621 } 2622 2623 /// Cast a base object to a member's actual type. 2624 /// 2625 /// Logically this happens in three phases: 2626 /// 2627 /// * First we cast from the base type to the naming class. 2628 /// The naming class is the class into which we were looking 2629 /// when we found the member; it's the qualifier type if a 2630 /// qualifier was provided, and otherwise it's the base type. 2631 /// 2632 /// * Next we cast from the naming class to the declaring class. 2633 /// If the member we found was brought into a class's scope by 2634 /// a using declaration, this is that class; otherwise it's 2635 /// the class declaring the member. 2636 /// 2637 /// * Finally we cast from the declaring class to the "true" 2638 /// declaring class of the member. This conversion does not 2639 /// obey access control. 2640 ExprResult 2641 Sema::PerformObjectMemberConversion(Expr *From, 2642 NestedNameSpecifier *Qualifier, 2643 NamedDecl *FoundDecl, 2644 NamedDecl *Member) { 2645 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2646 if (!RD) 2647 return From; 2648 2649 QualType DestRecordType; 2650 QualType DestType; 2651 QualType FromRecordType; 2652 QualType FromType = From->getType(); 2653 bool PointerConversions = false; 2654 if (isa<FieldDecl>(Member)) { 2655 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2656 auto FromPtrType = FromType->getAs<PointerType>(); 2657 DestRecordType = Context.getAddrSpaceQualType( 2658 DestRecordType, FromPtrType 2659 ? FromType->getPointeeType().getAddressSpace() 2660 : FromType.getAddressSpace()); 2661 2662 if (FromPtrType) { 2663 DestType = Context.getPointerType(DestRecordType); 2664 FromRecordType = FromPtrType->getPointeeType(); 2665 PointerConversions = true; 2666 } else { 2667 DestType = DestRecordType; 2668 FromRecordType = FromType; 2669 } 2670 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2671 if (Method->isStatic()) 2672 return From; 2673 2674 DestType = Method->getThisType(); 2675 DestRecordType = DestType->getPointeeType(); 2676 2677 if (FromType->getAs<PointerType>()) { 2678 FromRecordType = FromType->getPointeeType(); 2679 PointerConversions = true; 2680 } else { 2681 FromRecordType = FromType; 2682 DestType = DestRecordType; 2683 } 2684 } else { 2685 // No conversion necessary. 2686 return From; 2687 } 2688 2689 if (DestType->isDependentType() || FromType->isDependentType()) 2690 return From; 2691 2692 // If the unqualified types are the same, no conversion is necessary. 2693 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2694 return From; 2695 2696 SourceRange FromRange = From->getSourceRange(); 2697 SourceLocation FromLoc = FromRange.getBegin(); 2698 2699 ExprValueKind VK = From->getValueKind(); 2700 2701 // C++ [class.member.lookup]p8: 2702 // [...] Ambiguities can often be resolved by qualifying a name with its 2703 // class name. 2704 // 2705 // If the member was a qualified name and the qualified referred to a 2706 // specific base subobject type, we'll cast to that intermediate type 2707 // first and then to the object in which the member is declared. That allows 2708 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2709 // 2710 // class Base { public: int x; }; 2711 // class Derived1 : public Base { }; 2712 // class Derived2 : public Base { }; 2713 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2714 // 2715 // void VeryDerived::f() { 2716 // x = 17; // error: ambiguous base subobjects 2717 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2718 // } 2719 if (Qualifier && Qualifier->getAsType()) { 2720 QualType QType = QualType(Qualifier->getAsType(), 0); 2721 assert(QType->isRecordType() && "lookup done with non-record type"); 2722 2723 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2724 2725 // In C++98, the qualifier type doesn't actually have to be a base 2726 // type of the object type, in which case we just ignore it. 2727 // Otherwise build the appropriate casts. 2728 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2729 CXXCastPath BasePath; 2730 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2731 FromLoc, FromRange, &BasePath)) 2732 return ExprError(); 2733 2734 if (PointerConversions) 2735 QType = Context.getPointerType(QType); 2736 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2737 VK, &BasePath).get(); 2738 2739 FromType = QType; 2740 FromRecordType = QRecordType; 2741 2742 // If the qualifier type was the same as the destination type, 2743 // we're done. 2744 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2745 return From; 2746 } 2747 } 2748 2749 bool IgnoreAccess = false; 2750 2751 // If we actually found the member through a using declaration, cast 2752 // down to the using declaration's type. 2753 // 2754 // Pointer equality is fine here because only one declaration of a 2755 // class ever has member declarations. 2756 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2757 assert(isa<UsingShadowDecl>(FoundDecl)); 2758 QualType URecordType = Context.getTypeDeclType( 2759 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2760 2761 // We only need to do this if the naming-class to declaring-class 2762 // conversion is non-trivial. 2763 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2764 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2765 CXXCastPath BasePath; 2766 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2767 FromLoc, FromRange, &BasePath)) 2768 return ExprError(); 2769 2770 QualType UType = URecordType; 2771 if (PointerConversions) 2772 UType = Context.getPointerType(UType); 2773 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2774 VK, &BasePath).get(); 2775 FromType = UType; 2776 FromRecordType = URecordType; 2777 } 2778 2779 // We don't do access control for the conversion from the 2780 // declaring class to the true declaring class. 2781 IgnoreAccess = true; 2782 } 2783 2784 CXXCastPath BasePath; 2785 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2786 FromLoc, FromRange, &BasePath, 2787 IgnoreAccess)) 2788 return ExprError(); 2789 2790 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2791 VK, &BasePath); 2792 } 2793 2794 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2795 const LookupResult &R, 2796 bool HasTrailingLParen) { 2797 // Only when used directly as the postfix-expression of a call. 2798 if (!HasTrailingLParen) 2799 return false; 2800 2801 // Never if a scope specifier was provided. 2802 if (SS.isSet()) 2803 return false; 2804 2805 // Only in C++ or ObjC++. 2806 if (!getLangOpts().CPlusPlus) 2807 return false; 2808 2809 // Turn off ADL when we find certain kinds of declarations during 2810 // normal lookup: 2811 for (NamedDecl *D : R) { 2812 // C++0x [basic.lookup.argdep]p3: 2813 // -- a declaration of a class member 2814 // Since using decls preserve this property, we check this on the 2815 // original decl. 2816 if (D->isCXXClassMember()) 2817 return false; 2818 2819 // C++0x [basic.lookup.argdep]p3: 2820 // -- a block-scope function declaration that is not a 2821 // using-declaration 2822 // NOTE: we also trigger this for function templates (in fact, we 2823 // don't check the decl type at all, since all other decl types 2824 // turn off ADL anyway). 2825 if (isa<UsingShadowDecl>(D)) 2826 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2827 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2828 return false; 2829 2830 // C++0x [basic.lookup.argdep]p3: 2831 // -- a declaration that is neither a function or a function 2832 // template 2833 // And also for builtin functions. 2834 if (isa<FunctionDecl>(D)) { 2835 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2836 2837 // But also builtin functions. 2838 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2839 return false; 2840 } else if (!isa<FunctionTemplateDecl>(D)) 2841 return false; 2842 } 2843 2844 return true; 2845 } 2846 2847 2848 /// Diagnoses obvious problems with the use of the given declaration 2849 /// as an expression. This is only actually called for lookups that 2850 /// were not overloaded, and it doesn't promise that the declaration 2851 /// will in fact be used. 2852 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2853 if (D->isInvalidDecl()) 2854 return true; 2855 2856 if (isa<TypedefNameDecl>(D)) { 2857 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2858 return true; 2859 } 2860 2861 if (isa<ObjCInterfaceDecl>(D)) { 2862 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2863 return true; 2864 } 2865 2866 if (isa<NamespaceDecl>(D)) { 2867 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2868 return true; 2869 } 2870 2871 return false; 2872 } 2873 2874 // Certain multiversion types should be treated as overloaded even when there is 2875 // only one result. 2876 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2877 assert(R.isSingleResult() && "Expected only a single result"); 2878 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2879 return FD && 2880 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2881 } 2882 2883 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2884 LookupResult &R, bool NeedsADL, 2885 bool AcceptInvalidDecl) { 2886 // If this is a single, fully-resolved result and we don't need ADL, 2887 // just build an ordinary singleton decl ref. 2888 if (!NeedsADL && R.isSingleResult() && 2889 !R.getAsSingle<FunctionTemplateDecl>() && 2890 !ShouldLookupResultBeMultiVersionOverload(R)) 2891 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2892 R.getRepresentativeDecl(), nullptr, 2893 AcceptInvalidDecl); 2894 2895 // We only need to check the declaration if there's exactly one 2896 // result, because in the overloaded case the results can only be 2897 // functions and function templates. 2898 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2899 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2900 return ExprError(); 2901 2902 // Otherwise, just build an unresolved lookup expression. Suppress 2903 // any lookup-related diagnostics; we'll hash these out later, when 2904 // we've picked a target. 2905 R.suppressDiagnostics(); 2906 2907 UnresolvedLookupExpr *ULE 2908 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2909 SS.getWithLocInContext(Context), 2910 R.getLookupNameInfo(), 2911 NeedsADL, R.isOverloadedResult(), 2912 R.begin(), R.end()); 2913 2914 return ULE; 2915 } 2916 2917 static void 2918 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2919 ValueDecl *var, DeclContext *DC); 2920 2921 /// Complete semantic analysis for a reference to the given declaration. 2922 ExprResult Sema::BuildDeclarationNameExpr( 2923 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2924 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2925 bool AcceptInvalidDecl) { 2926 assert(D && "Cannot refer to a NULL declaration"); 2927 assert(!isa<FunctionTemplateDecl>(D) && 2928 "Cannot refer unambiguously to a function template"); 2929 2930 SourceLocation Loc = NameInfo.getLoc(); 2931 if (CheckDeclInExpr(*this, Loc, D)) 2932 return ExprError(); 2933 2934 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2935 // Specifically diagnose references to class templates that are missing 2936 // a template argument list. 2937 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2938 return ExprError(); 2939 } 2940 2941 // Make sure that we're referring to a value. 2942 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2943 if (!VD) { 2944 Diag(Loc, diag::err_ref_non_value) 2945 << D << SS.getRange(); 2946 Diag(D->getLocation(), diag::note_declared_at); 2947 return ExprError(); 2948 } 2949 2950 // Check whether this declaration can be used. Note that we suppress 2951 // this check when we're going to perform argument-dependent lookup 2952 // on this function name, because this might not be the function 2953 // that overload resolution actually selects. 2954 if (DiagnoseUseOfDecl(VD, Loc)) 2955 return ExprError(); 2956 2957 // Only create DeclRefExpr's for valid Decl's. 2958 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2959 return ExprError(); 2960 2961 // Handle members of anonymous structs and unions. If we got here, 2962 // and the reference is to a class member indirect field, then this 2963 // must be the subject of a pointer-to-member expression. 2964 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2965 if (!indirectField->isCXXClassMember()) 2966 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2967 indirectField); 2968 2969 { 2970 QualType type = VD->getType(); 2971 if (type.isNull()) 2972 return ExprError(); 2973 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2974 // C++ [except.spec]p17: 2975 // An exception-specification is considered to be needed when: 2976 // - in an expression, the function is the unique lookup result or 2977 // the selected member of a set of overloaded functions. 2978 ResolveExceptionSpec(Loc, FPT); 2979 type = VD->getType(); 2980 } 2981 ExprValueKind valueKind = VK_RValue; 2982 2983 switch (D->getKind()) { 2984 // Ignore all the non-ValueDecl kinds. 2985 #define ABSTRACT_DECL(kind) 2986 #define VALUE(type, base) 2987 #define DECL(type, base) \ 2988 case Decl::type: 2989 #include "clang/AST/DeclNodes.inc" 2990 llvm_unreachable("invalid value decl kind"); 2991 2992 // These shouldn't make it here. 2993 case Decl::ObjCAtDefsField: 2994 llvm_unreachable("forming non-member reference to ivar?"); 2995 2996 // Enum constants are always r-values and never references. 2997 // Unresolved using declarations are dependent. 2998 case Decl::EnumConstant: 2999 case Decl::UnresolvedUsingValue: 3000 case Decl::OMPDeclareReduction: 3001 case Decl::OMPDeclareMapper: 3002 valueKind = VK_RValue; 3003 break; 3004 3005 // Fields and indirect fields that got here must be for 3006 // pointer-to-member expressions; we just call them l-values for 3007 // internal consistency, because this subexpression doesn't really 3008 // exist in the high-level semantics. 3009 case Decl::Field: 3010 case Decl::IndirectField: 3011 case Decl::ObjCIvar: 3012 assert(getLangOpts().CPlusPlus && 3013 "building reference to field in C?"); 3014 3015 // These can't have reference type in well-formed programs, but 3016 // for internal consistency we do this anyway. 3017 type = type.getNonReferenceType(); 3018 valueKind = VK_LValue; 3019 break; 3020 3021 // Non-type template parameters are either l-values or r-values 3022 // depending on the type. 3023 case Decl::NonTypeTemplateParm: { 3024 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3025 type = reftype->getPointeeType(); 3026 valueKind = VK_LValue; // even if the parameter is an r-value reference 3027 break; 3028 } 3029 3030 // For non-references, we need to strip qualifiers just in case 3031 // the template parameter was declared as 'const int' or whatever. 3032 valueKind = VK_RValue; 3033 type = type.getUnqualifiedType(); 3034 break; 3035 } 3036 3037 case Decl::Var: 3038 case Decl::VarTemplateSpecialization: 3039 case Decl::VarTemplatePartialSpecialization: 3040 case Decl::Decomposition: 3041 case Decl::OMPCapturedExpr: 3042 // In C, "extern void blah;" is valid and is an r-value. 3043 if (!getLangOpts().CPlusPlus && 3044 !type.hasQualifiers() && 3045 type->isVoidType()) { 3046 valueKind = VK_RValue; 3047 break; 3048 } 3049 LLVM_FALLTHROUGH; 3050 3051 case Decl::ImplicitParam: 3052 case Decl::ParmVar: { 3053 // These are always l-values. 3054 valueKind = VK_LValue; 3055 type = type.getNonReferenceType(); 3056 3057 // FIXME: Does the addition of const really only apply in 3058 // potentially-evaluated contexts? Since the variable isn't actually 3059 // captured in an unevaluated context, it seems that the answer is no. 3060 if (!isUnevaluatedContext()) { 3061 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3062 if (!CapturedType.isNull()) 3063 type = CapturedType; 3064 } 3065 3066 break; 3067 } 3068 3069 case Decl::Binding: { 3070 // These are always lvalues. 3071 valueKind = VK_LValue; 3072 type = type.getNonReferenceType(); 3073 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3074 // decides how that's supposed to work. 3075 auto *BD = cast<BindingDecl>(VD); 3076 if (BD->getDeclContext() != CurContext) { 3077 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3078 if (DD && DD->hasLocalStorage()) 3079 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3080 } 3081 break; 3082 } 3083 3084 case Decl::Function: { 3085 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3086 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3087 type = Context.BuiltinFnTy; 3088 valueKind = VK_RValue; 3089 break; 3090 } 3091 } 3092 3093 const FunctionType *fty = type->castAs<FunctionType>(); 3094 3095 // If we're referring to a function with an __unknown_anytype 3096 // result type, make the entire expression __unknown_anytype. 3097 if (fty->getReturnType() == Context.UnknownAnyTy) { 3098 type = Context.UnknownAnyTy; 3099 valueKind = VK_RValue; 3100 break; 3101 } 3102 3103 // Functions are l-values in C++. 3104 if (getLangOpts().CPlusPlus) { 3105 valueKind = VK_LValue; 3106 break; 3107 } 3108 3109 // C99 DR 316 says that, if a function type comes from a 3110 // function definition (without a prototype), that type is only 3111 // used for checking compatibility. Therefore, when referencing 3112 // the function, we pretend that we don't have the full function 3113 // type. 3114 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3115 isa<FunctionProtoType>(fty)) 3116 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3117 fty->getExtInfo()); 3118 3119 // Functions are r-values in C. 3120 valueKind = VK_RValue; 3121 break; 3122 } 3123 3124 case Decl::CXXDeductionGuide: 3125 llvm_unreachable("building reference to deduction guide"); 3126 3127 case Decl::MSProperty: 3128 valueKind = VK_LValue; 3129 break; 3130 3131 case Decl::CXXMethod: 3132 // If we're referring to a method with an __unknown_anytype 3133 // result type, make the entire expression __unknown_anytype. 3134 // This should only be possible with a type written directly. 3135 if (const FunctionProtoType *proto 3136 = dyn_cast<FunctionProtoType>(VD->getType())) 3137 if (proto->getReturnType() == Context.UnknownAnyTy) { 3138 type = Context.UnknownAnyTy; 3139 valueKind = VK_RValue; 3140 break; 3141 } 3142 3143 // C++ methods are l-values if static, r-values if non-static. 3144 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3145 valueKind = VK_LValue; 3146 break; 3147 } 3148 LLVM_FALLTHROUGH; 3149 3150 case Decl::CXXConversion: 3151 case Decl::CXXDestructor: 3152 case Decl::CXXConstructor: 3153 valueKind = VK_RValue; 3154 break; 3155 } 3156 3157 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3158 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3159 TemplateArgs); 3160 } 3161 } 3162 3163 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3164 SmallString<32> &Target) { 3165 Target.resize(CharByteWidth * (Source.size() + 1)); 3166 char *ResultPtr = &Target[0]; 3167 const llvm::UTF8 *ErrorPtr; 3168 bool success = 3169 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3170 (void)success; 3171 assert(success); 3172 Target.resize(ResultPtr - &Target[0]); 3173 } 3174 3175 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3176 PredefinedExpr::IdentKind IK) { 3177 // Pick the current block, lambda, captured statement or function. 3178 Decl *currentDecl = nullptr; 3179 if (const BlockScopeInfo *BSI = getCurBlock()) 3180 currentDecl = BSI->TheDecl; 3181 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3182 currentDecl = LSI->CallOperator; 3183 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3184 currentDecl = CSI->TheCapturedDecl; 3185 else 3186 currentDecl = getCurFunctionOrMethodDecl(); 3187 3188 if (!currentDecl) { 3189 Diag(Loc, diag::ext_predef_outside_function); 3190 currentDecl = Context.getTranslationUnitDecl(); 3191 } 3192 3193 QualType ResTy; 3194 StringLiteral *SL = nullptr; 3195 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3196 ResTy = Context.DependentTy; 3197 else { 3198 // Pre-defined identifiers are of type char[x], where x is the length of 3199 // the string. 3200 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3201 unsigned Length = Str.length(); 3202 3203 llvm::APInt LengthI(32, Length + 1); 3204 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3205 ResTy = 3206 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3207 SmallString<32> RawChars; 3208 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3209 Str, RawChars); 3210 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3211 /*IndexTypeQuals*/ 0); 3212 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3213 /*Pascal*/ false, ResTy, Loc); 3214 } else { 3215 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3216 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3217 /*IndexTypeQuals*/ 0); 3218 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3219 /*Pascal*/ false, ResTy, Loc); 3220 } 3221 } 3222 3223 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3224 } 3225 3226 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3227 PredefinedExpr::IdentKind IK; 3228 3229 switch (Kind) { 3230 default: llvm_unreachable("Unknown simple primary expr!"); 3231 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3232 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3233 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3234 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3235 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3236 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3237 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3238 } 3239 3240 return BuildPredefinedExpr(Loc, IK); 3241 } 3242 3243 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3244 SmallString<16> CharBuffer; 3245 bool Invalid = false; 3246 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3247 if (Invalid) 3248 return ExprError(); 3249 3250 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3251 PP, Tok.getKind()); 3252 if (Literal.hadError()) 3253 return ExprError(); 3254 3255 QualType Ty; 3256 if (Literal.isWide()) 3257 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3258 else if (Literal.isUTF8() && getLangOpts().Char8) 3259 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3260 else if (Literal.isUTF16()) 3261 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3262 else if (Literal.isUTF32()) 3263 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3264 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3265 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3266 else 3267 Ty = Context.CharTy; // 'x' -> char in C++ 3268 3269 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3270 if (Literal.isWide()) 3271 Kind = CharacterLiteral::Wide; 3272 else if (Literal.isUTF16()) 3273 Kind = CharacterLiteral::UTF16; 3274 else if (Literal.isUTF32()) 3275 Kind = CharacterLiteral::UTF32; 3276 else if (Literal.isUTF8()) 3277 Kind = CharacterLiteral::UTF8; 3278 3279 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3280 Tok.getLocation()); 3281 3282 if (Literal.getUDSuffix().empty()) 3283 return Lit; 3284 3285 // We're building a user-defined literal. 3286 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3287 SourceLocation UDSuffixLoc = 3288 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3289 3290 // Make sure we're allowed user-defined literals here. 3291 if (!UDLScope) 3292 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3293 3294 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3295 // operator "" X (ch) 3296 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3297 Lit, Tok.getLocation()); 3298 } 3299 3300 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3301 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3302 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3303 Context.IntTy, Loc); 3304 } 3305 3306 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3307 QualType Ty, SourceLocation Loc) { 3308 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3309 3310 using llvm::APFloat; 3311 APFloat Val(Format); 3312 3313 APFloat::opStatus result = Literal.GetFloatValue(Val); 3314 3315 // Overflow is always an error, but underflow is only an error if 3316 // we underflowed to zero (APFloat reports denormals as underflow). 3317 if ((result & APFloat::opOverflow) || 3318 ((result & APFloat::opUnderflow) && Val.isZero())) { 3319 unsigned diagnostic; 3320 SmallString<20> buffer; 3321 if (result & APFloat::opOverflow) { 3322 diagnostic = diag::warn_float_overflow; 3323 APFloat::getLargest(Format).toString(buffer); 3324 } else { 3325 diagnostic = diag::warn_float_underflow; 3326 APFloat::getSmallest(Format).toString(buffer); 3327 } 3328 3329 S.Diag(Loc, diagnostic) 3330 << Ty 3331 << StringRef(buffer.data(), buffer.size()); 3332 } 3333 3334 bool isExact = (result == APFloat::opOK); 3335 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3336 } 3337 3338 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3339 assert(E && "Invalid expression"); 3340 3341 if (E->isValueDependent()) 3342 return false; 3343 3344 QualType QT = E->getType(); 3345 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3346 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3347 return true; 3348 } 3349 3350 llvm::APSInt ValueAPS; 3351 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3352 3353 if (R.isInvalid()) 3354 return true; 3355 3356 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3357 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3358 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3359 << ValueAPS.toString(10) << ValueIsPositive; 3360 return true; 3361 } 3362 3363 return false; 3364 } 3365 3366 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3367 // Fast path for a single digit (which is quite common). A single digit 3368 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3369 if (Tok.getLength() == 1) { 3370 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3371 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3372 } 3373 3374 SmallString<128> SpellingBuffer; 3375 // NumericLiteralParser wants to overread by one character. Add padding to 3376 // the buffer in case the token is copied to the buffer. If getSpelling() 3377 // returns a StringRef to the memory buffer, it should have a null char at 3378 // the EOF, so it is also safe. 3379 SpellingBuffer.resize(Tok.getLength() + 1); 3380 3381 // Get the spelling of the token, which eliminates trigraphs, etc. 3382 bool Invalid = false; 3383 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3384 if (Invalid) 3385 return ExprError(); 3386 3387 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3388 if (Literal.hadError) 3389 return ExprError(); 3390 3391 if (Literal.hasUDSuffix()) { 3392 // We're building a user-defined literal. 3393 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3394 SourceLocation UDSuffixLoc = 3395 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3396 3397 // Make sure we're allowed user-defined literals here. 3398 if (!UDLScope) 3399 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3400 3401 QualType CookedTy; 3402 if (Literal.isFloatingLiteral()) { 3403 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3404 // long double, the literal is treated as a call of the form 3405 // operator "" X (f L) 3406 CookedTy = Context.LongDoubleTy; 3407 } else { 3408 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3409 // unsigned long long, the literal is treated as a call of the form 3410 // operator "" X (n ULL) 3411 CookedTy = Context.UnsignedLongLongTy; 3412 } 3413 3414 DeclarationName OpName = 3415 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3416 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3417 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3418 3419 SourceLocation TokLoc = Tok.getLocation(); 3420 3421 // Perform literal operator lookup to determine if we're building a raw 3422 // literal or a cooked one. 3423 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3424 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3425 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3426 /*AllowStringTemplate*/ false, 3427 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3428 case LOLR_ErrorNoDiagnostic: 3429 // Lookup failure for imaginary constants isn't fatal, there's still the 3430 // GNU extension producing _Complex types. 3431 break; 3432 case LOLR_Error: 3433 return ExprError(); 3434 case LOLR_Cooked: { 3435 Expr *Lit; 3436 if (Literal.isFloatingLiteral()) { 3437 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3438 } else { 3439 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3440 if (Literal.GetIntegerValue(ResultVal)) 3441 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3442 << /* Unsigned */ 1; 3443 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3444 Tok.getLocation()); 3445 } 3446 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3447 } 3448 3449 case LOLR_Raw: { 3450 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3451 // literal is treated as a call of the form 3452 // operator "" X ("n") 3453 unsigned Length = Literal.getUDSuffixOffset(); 3454 QualType StrTy = Context.getConstantArrayType( 3455 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3456 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3457 Expr *Lit = StringLiteral::Create( 3458 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3459 /*Pascal*/false, StrTy, &TokLoc, 1); 3460 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3461 } 3462 3463 case LOLR_Template: { 3464 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3465 // template), L is treated as a call fo the form 3466 // operator "" X <'c1', 'c2', ... 'ck'>() 3467 // where n is the source character sequence c1 c2 ... ck. 3468 TemplateArgumentListInfo ExplicitArgs; 3469 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3470 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3471 llvm::APSInt Value(CharBits, CharIsUnsigned); 3472 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3473 Value = TokSpelling[I]; 3474 TemplateArgument Arg(Context, Value, Context.CharTy); 3475 TemplateArgumentLocInfo ArgInfo; 3476 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3477 } 3478 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3479 &ExplicitArgs); 3480 } 3481 case LOLR_StringTemplate: 3482 llvm_unreachable("unexpected literal operator lookup result"); 3483 } 3484 } 3485 3486 Expr *Res; 3487 3488 if (Literal.isFixedPointLiteral()) { 3489 QualType Ty; 3490 3491 if (Literal.isAccum) { 3492 if (Literal.isHalf) { 3493 Ty = Context.ShortAccumTy; 3494 } else if (Literal.isLong) { 3495 Ty = Context.LongAccumTy; 3496 } else { 3497 Ty = Context.AccumTy; 3498 } 3499 } else if (Literal.isFract) { 3500 if (Literal.isHalf) { 3501 Ty = Context.ShortFractTy; 3502 } else if (Literal.isLong) { 3503 Ty = Context.LongFractTy; 3504 } else { 3505 Ty = Context.FractTy; 3506 } 3507 } 3508 3509 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3510 3511 bool isSigned = !Literal.isUnsigned; 3512 unsigned scale = Context.getFixedPointScale(Ty); 3513 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3514 3515 llvm::APInt Val(bit_width, 0, isSigned); 3516 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3517 bool ValIsZero = Val.isNullValue() && !Overflowed; 3518 3519 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3520 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3521 // Clause 6.4.4 - The value of a constant shall be in the range of 3522 // representable values for its type, with exception for constants of a 3523 // fract type with a value of exactly 1; such a constant shall denote 3524 // the maximal value for the type. 3525 --Val; 3526 else if (Val.ugt(MaxVal) || Overflowed) 3527 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3528 3529 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3530 Tok.getLocation(), scale); 3531 } else if (Literal.isFloatingLiteral()) { 3532 QualType Ty; 3533 if (Literal.isHalf){ 3534 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3535 Ty = Context.HalfTy; 3536 else { 3537 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3538 return ExprError(); 3539 } 3540 } else if (Literal.isFloat) 3541 Ty = Context.FloatTy; 3542 else if (Literal.isLong) 3543 Ty = Context.LongDoubleTy; 3544 else if (Literal.isFloat16) 3545 Ty = Context.Float16Ty; 3546 else if (Literal.isFloat128) 3547 Ty = Context.Float128Ty; 3548 else 3549 Ty = Context.DoubleTy; 3550 3551 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3552 3553 if (Ty == Context.DoubleTy) { 3554 if (getLangOpts().SinglePrecisionConstants) { 3555 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3556 if (BTy->getKind() != BuiltinType::Float) { 3557 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3558 } 3559 } else if (getLangOpts().OpenCL && 3560 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3561 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3562 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3563 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3564 } 3565 } 3566 } else if (!Literal.isIntegerLiteral()) { 3567 return ExprError(); 3568 } else { 3569 QualType Ty; 3570 3571 // 'long long' is a C99 or C++11 feature. 3572 if (!getLangOpts().C99 && Literal.isLongLong) { 3573 if (getLangOpts().CPlusPlus) 3574 Diag(Tok.getLocation(), 3575 getLangOpts().CPlusPlus11 ? 3576 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3577 else 3578 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3579 } 3580 3581 // Get the value in the widest-possible width. 3582 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3583 llvm::APInt ResultVal(MaxWidth, 0); 3584 3585 if (Literal.GetIntegerValue(ResultVal)) { 3586 // If this value didn't fit into uintmax_t, error and force to ull. 3587 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3588 << /* Unsigned */ 1; 3589 Ty = Context.UnsignedLongLongTy; 3590 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3591 "long long is not intmax_t?"); 3592 } else { 3593 // If this value fits into a ULL, try to figure out what else it fits into 3594 // according to the rules of C99 6.4.4.1p5. 3595 3596 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3597 // be an unsigned int. 3598 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3599 3600 // Check from smallest to largest, picking the smallest type we can. 3601 unsigned Width = 0; 3602 3603 // Microsoft specific integer suffixes are explicitly sized. 3604 if (Literal.MicrosoftInteger) { 3605 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3606 Width = 8; 3607 Ty = Context.CharTy; 3608 } else { 3609 Width = Literal.MicrosoftInteger; 3610 Ty = Context.getIntTypeForBitwidth(Width, 3611 /*Signed=*/!Literal.isUnsigned); 3612 } 3613 } 3614 3615 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3616 // Are int/unsigned possibilities? 3617 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3618 3619 // Does it fit in a unsigned int? 3620 if (ResultVal.isIntN(IntSize)) { 3621 // Does it fit in a signed int? 3622 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3623 Ty = Context.IntTy; 3624 else if (AllowUnsigned) 3625 Ty = Context.UnsignedIntTy; 3626 Width = IntSize; 3627 } 3628 } 3629 3630 // Are long/unsigned long possibilities? 3631 if (Ty.isNull() && !Literal.isLongLong) { 3632 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3633 3634 // Does it fit in a unsigned long? 3635 if (ResultVal.isIntN(LongSize)) { 3636 // Does it fit in a signed long? 3637 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3638 Ty = Context.LongTy; 3639 else if (AllowUnsigned) 3640 Ty = Context.UnsignedLongTy; 3641 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3642 // is compatible. 3643 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3644 const unsigned LongLongSize = 3645 Context.getTargetInfo().getLongLongWidth(); 3646 Diag(Tok.getLocation(), 3647 getLangOpts().CPlusPlus 3648 ? Literal.isLong 3649 ? diag::warn_old_implicitly_unsigned_long_cxx 3650 : /*C++98 UB*/ diag:: 3651 ext_old_implicitly_unsigned_long_cxx 3652 : diag::warn_old_implicitly_unsigned_long) 3653 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3654 : /*will be ill-formed*/ 1); 3655 Ty = Context.UnsignedLongTy; 3656 } 3657 Width = LongSize; 3658 } 3659 } 3660 3661 // Check long long if needed. 3662 if (Ty.isNull()) { 3663 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3664 3665 // Does it fit in a unsigned long long? 3666 if (ResultVal.isIntN(LongLongSize)) { 3667 // Does it fit in a signed long long? 3668 // To be compatible with MSVC, hex integer literals ending with the 3669 // LL or i64 suffix are always signed in Microsoft mode. 3670 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3671 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3672 Ty = Context.LongLongTy; 3673 else if (AllowUnsigned) 3674 Ty = Context.UnsignedLongLongTy; 3675 Width = LongLongSize; 3676 } 3677 } 3678 3679 // If we still couldn't decide a type, we probably have something that 3680 // does not fit in a signed long long, but has no U suffix. 3681 if (Ty.isNull()) { 3682 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3683 Ty = Context.UnsignedLongLongTy; 3684 Width = Context.getTargetInfo().getLongLongWidth(); 3685 } 3686 3687 if (ResultVal.getBitWidth() != Width) 3688 ResultVal = ResultVal.trunc(Width); 3689 } 3690 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3691 } 3692 3693 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3694 if (Literal.isImaginary) { 3695 Res = new (Context) ImaginaryLiteral(Res, 3696 Context.getComplexType(Res->getType())); 3697 3698 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3699 } 3700 return Res; 3701 } 3702 3703 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3704 assert(E && "ActOnParenExpr() missing expr"); 3705 return new (Context) ParenExpr(L, R, E); 3706 } 3707 3708 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3709 SourceLocation Loc, 3710 SourceRange ArgRange) { 3711 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3712 // scalar or vector data type argument..." 3713 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3714 // type (C99 6.2.5p18) or void. 3715 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3716 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3717 << T << ArgRange; 3718 return true; 3719 } 3720 3721 assert((T->isVoidType() || !T->isIncompleteType()) && 3722 "Scalar types should always be complete"); 3723 return false; 3724 } 3725 3726 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3727 SourceLocation Loc, 3728 SourceRange ArgRange, 3729 UnaryExprOrTypeTrait TraitKind) { 3730 // Invalid types must be hard errors for SFINAE in C++. 3731 if (S.LangOpts.CPlusPlus) 3732 return true; 3733 3734 // C99 6.5.3.4p1: 3735 if (T->isFunctionType() && 3736 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3737 TraitKind == UETT_PreferredAlignOf)) { 3738 // sizeof(function)/alignof(function) is allowed as an extension. 3739 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3740 << TraitKind << ArgRange; 3741 return false; 3742 } 3743 3744 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3745 // this is an error (OpenCL v1.1 s6.3.k) 3746 if (T->isVoidType()) { 3747 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3748 : diag::ext_sizeof_alignof_void_type; 3749 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3750 return false; 3751 } 3752 3753 return true; 3754 } 3755 3756 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3757 SourceLocation Loc, 3758 SourceRange ArgRange, 3759 UnaryExprOrTypeTrait TraitKind) { 3760 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3761 // runtime doesn't allow it. 3762 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3763 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3764 << T << (TraitKind == UETT_SizeOf) 3765 << ArgRange; 3766 return true; 3767 } 3768 3769 return false; 3770 } 3771 3772 /// Check whether E is a pointer from a decayed array type (the decayed 3773 /// pointer type is equal to T) and emit a warning if it is. 3774 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3775 Expr *E) { 3776 // Don't warn if the operation changed the type. 3777 if (T != E->getType()) 3778 return; 3779 3780 // Now look for array decays. 3781 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3782 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3783 return; 3784 3785 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3786 << ICE->getType() 3787 << ICE->getSubExpr()->getType(); 3788 } 3789 3790 /// Check the constraints on expression operands to unary type expression 3791 /// and type traits. 3792 /// 3793 /// Completes any types necessary and validates the constraints on the operand 3794 /// expression. The logic mostly mirrors the type-based overload, but may modify 3795 /// the expression as it completes the type for that expression through template 3796 /// instantiation, etc. 3797 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3798 UnaryExprOrTypeTrait ExprKind) { 3799 QualType ExprTy = E->getType(); 3800 assert(!ExprTy->isReferenceType()); 3801 3802 if (ExprKind == UETT_VecStep) 3803 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3804 E->getSourceRange()); 3805 3806 // Whitelist some types as extensions 3807 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3808 E->getSourceRange(), ExprKind)) 3809 return false; 3810 3811 // 'alignof' applied to an expression only requires the base element type of 3812 // the expression to be complete. 'sizeof' requires the expression's type to 3813 // be complete (and will attempt to complete it if it's an array of unknown 3814 // bound). 3815 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3816 if (RequireCompleteType(E->getExprLoc(), 3817 Context.getBaseElementType(E->getType()), 3818 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3819 E->getSourceRange())) 3820 return true; 3821 } else { 3822 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3823 ExprKind, E->getSourceRange())) 3824 return true; 3825 } 3826 3827 // Completing the expression's type may have changed it. 3828 ExprTy = E->getType(); 3829 assert(!ExprTy->isReferenceType()); 3830 3831 if (ExprTy->isFunctionType()) { 3832 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3833 << ExprKind << E->getSourceRange(); 3834 return true; 3835 } 3836 3837 // The operand for sizeof and alignof is in an unevaluated expression context, 3838 // so side effects could result in unintended consequences. 3839 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3840 ExprKind == UETT_PreferredAlignOf) && 3841 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3842 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3843 3844 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3845 E->getSourceRange(), ExprKind)) 3846 return true; 3847 3848 if (ExprKind == UETT_SizeOf) { 3849 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3850 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3851 QualType OType = PVD->getOriginalType(); 3852 QualType Type = PVD->getType(); 3853 if (Type->isPointerType() && OType->isArrayType()) { 3854 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3855 << Type << OType; 3856 Diag(PVD->getLocation(), diag::note_declared_at); 3857 } 3858 } 3859 } 3860 3861 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3862 // decays into a pointer and returns an unintended result. This is most 3863 // likely a typo for "sizeof(array) op x". 3864 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3865 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3866 BO->getLHS()); 3867 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3868 BO->getRHS()); 3869 } 3870 } 3871 3872 return false; 3873 } 3874 3875 /// Check the constraints on operands to unary expression and type 3876 /// traits. 3877 /// 3878 /// This will complete any types necessary, and validate the various constraints 3879 /// on those operands. 3880 /// 3881 /// The UsualUnaryConversions() function is *not* called by this routine. 3882 /// C99 6.3.2.1p[2-4] all state: 3883 /// Except when it is the operand of the sizeof operator ... 3884 /// 3885 /// C++ [expr.sizeof]p4 3886 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3887 /// standard conversions are not applied to the operand of sizeof. 3888 /// 3889 /// This policy is followed for all of the unary trait expressions. 3890 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3891 SourceLocation OpLoc, 3892 SourceRange ExprRange, 3893 UnaryExprOrTypeTrait ExprKind) { 3894 if (ExprType->isDependentType()) 3895 return false; 3896 3897 // C++ [expr.sizeof]p2: 3898 // When applied to a reference or a reference type, the result 3899 // is the size of the referenced type. 3900 // C++11 [expr.alignof]p3: 3901 // When alignof is applied to a reference type, the result 3902 // shall be the alignment of the referenced type. 3903 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3904 ExprType = Ref->getPointeeType(); 3905 3906 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3907 // When alignof or _Alignof is applied to an array type, the result 3908 // is the alignment of the element type. 3909 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3910 ExprKind == UETT_OpenMPRequiredSimdAlign) 3911 ExprType = Context.getBaseElementType(ExprType); 3912 3913 if (ExprKind == UETT_VecStep) 3914 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3915 3916 // Whitelist some types as extensions 3917 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3918 ExprKind)) 3919 return false; 3920 3921 if (RequireCompleteType(OpLoc, ExprType, 3922 diag::err_sizeof_alignof_incomplete_type, 3923 ExprKind, ExprRange)) 3924 return true; 3925 3926 if (ExprType->isFunctionType()) { 3927 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3928 << ExprKind << ExprRange; 3929 return true; 3930 } 3931 3932 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3933 ExprKind)) 3934 return true; 3935 3936 return false; 3937 } 3938 3939 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3940 E = E->IgnoreParens(); 3941 3942 // Cannot know anything else if the expression is dependent. 3943 if (E->isTypeDependent()) 3944 return false; 3945 3946 if (E->getObjectKind() == OK_BitField) { 3947 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3948 << 1 << E->getSourceRange(); 3949 return true; 3950 } 3951 3952 ValueDecl *D = nullptr; 3953 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3954 D = DRE->getDecl(); 3955 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3956 D = ME->getMemberDecl(); 3957 } 3958 3959 // If it's a field, require the containing struct to have a 3960 // complete definition so that we can compute the layout. 3961 // 3962 // This can happen in C++11 onwards, either by naming the member 3963 // in a way that is not transformed into a member access expression 3964 // (in an unevaluated operand, for instance), or by naming the member 3965 // in a trailing-return-type. 3966 // 3967 // For the record, since __alignof__ on expressions is a GCC 3968 // extension, GCC seems to permit this but always gives the 3969 // nonsensical answer 0. 3970 // 3971 // We don't really need the layout here --- we could instead just 3972 // directly check for all the appropriate alignment-lowing 3973 // attributes --- but that would require duplicating a lot of 3974 // logic that just isn't worth duplicating for such a marginal 3975 // use-case. 3976 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3977 // Fast path this check, since we at least know the record has a 3978 // definition if we can find a member of it. 3979 if (!FD->getParent()->isCompleteDefinition()) { 3980 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3981 << E->getSourceRange(); 3982 return true; 3983 } 3984 3985 // Otherwise, if it's a field, and the field doesn't have 3986 // reference type, then it must have a complete type (or be a 3987 // flexible array member, which we explicitly want to 3988 // white-list anyway), which makes the following checks trivial. 3989 if (!FD->getType()->isReferenceType()) 3990 return false; 3991 } 3992 3993 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3994 } 3995 3996 bool Sema::CheckVecStepExpr(Expr *E) { 3997 E = E->IgnoreParens(); 3998 3999 // Cannot know anything else if the expression is dependent. 4000 if (E->isTypeDependent()) 4001 return false; 4002 4003 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4004 } 4005 4006 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4007 CapturingScopeInfo *CSI) { 4008 assert(T->isVariablyModifiedType()); 4009 assert(CSI != nullptr); 4010 4011 // We're going to walk down into the type and look for VLA expressions. 4012 do { 4013 const Type *Ty = T.getTypePtr(); 4014 switch (Ty->getTypeClass()) { 4015 #define TYPE(Class, Base) 4016 #define ABSTRACT_TYPE(Class, Base) 4017 #define NON_CANONICAL_TYPE(Class, Base) 4018 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4019 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4020 #include "clang/AST/TypeNodes.def" 4021 T = QualType(); 4022 break; 4023 // These types are never variably-modified. 4024 case Type::Builtin: 4025 case Type::Complex: 4026 case Type::Vector: 4027 case Type::ExtVector: 4028 case Type::Record: 4029 case Type::Enum: 4030 case Type::Elaborated: 4031 case Type::TemplateSpecialization: 4032 case Type::ObjCObject: 4033 case Type::ObjCInterface: 4034 case Type::ObjCObjectPointer: 4035 case Type::ObjCTypeParam: 4036 case Type::Pipe: 4037 llvm_unreachable("type class is never variably-modified!"); 4038 case Type::Adjusted: 4039 T = cast<AdjustedType>(Ty)->getOriginalType(); 4040 break; 4041 case Type::Decayed: 4042 T = cast<DecayedType>(Ty)->getPointeeType(); 4043 break; 4044 case Type::Pointer: 4045 T = cast<PointerType>(Ty)->getPointeeType(); 4046 break; 4047 case Type::BlockPointer: 4048 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4049 break; 4050 case Type::LValueReference: 4051 case Type::RValueReference: 4052 T = cast<ReferenceType>(Ty)->getPointeeType(); 4053 break; 4054 case Type::MemberPointer: 4055 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4056 break; 4057 case Type::ConstantArray: 4058 case Type::IncompleteArray: 4059 // Losing element qualification here is fine. 4060 T = cast<ArrayType>(Ty)->getElementType(); 4061 break; 4062 case Type::VariableArray: { 4063 // Losing element qualification here is fine. 4064 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4065 4066 // Unknown size indication requires no size computation. 4067 // Otherwise, evaluate and record it. 4068 auto Size = VAT->getSizeExpr(); 4069 if (Size && !CSI->isVLATypeCaptured(VAT) && 4070 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4071 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4072 4073 T = VAT->getElementType(); 4074 break; 4075 } 4076 case Type::FunctionProto: 4077 case Type::FunctionNoProto: 4078 T = cast<FunctionType>(Ty)->getReturnType(); 4079 break; 4080 case Type::Paren: 4081 case Type::TypeOf: 4082 case Type::UnaryTransform: 4083 case Type::Attributed: 4084 case Type::SubstTemplateTypeParm: 4085 case Type::PackExpansion: 4086 case Type::MacroQualified: 4087 // Keep walking after single level desugaring. 4088 T = T.getSingleStepDesugaredType(Context); 4089 break; 4090 case Type::Typedef: 4091 T = cast<TypedefType>(Ty)->desugar(); 4092 break; 4093 case Type::Decltype: 4094 T = cast<DecltypeType>(Ty)->desugar(); 4095 break; 4096 case Type::Auto: 4097 case Type::DeducedTemplateSpecialization: 4098 T = cast<DeducedType>(Ty)->getDeducedType(); 4099 break; 4100 case Type::TypeOfExpr: 4101 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4102 break; 4103 case Type::Atomic: 4104 T = cast<AtomicType>(Ty)->getValueType(); 4105 break; 4106 } 4107 } while (!T.isNull() && T->isVariablyModifiedType()); 4108 } 4109 4110 /// Build a sizeof or alignof expression given a type operand. 4111 ExprResult 4112 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4113 SourceLocation OpLoc, 4114 UnaryExprOrTypeTrait ExprKind, 4115 SourceRange R) { 4116 if (!TInfo) 4117 return ExprError(); 4118 4119 QualType T = TInfo->getType(); 4120 4121 if (!T->isDependentType() && 4122 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4123 return ExprError(); 4124 4125 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4126 if (auto *TT = T->getAs<TypedefType>()) { 4127 for (auto I = FunctionScopes.rbegin(), 4128 E = std::prev(FunctionScopes.rend()); 4129 I != E; ++I) { 4130 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4131 if (CSI == nullptr) 4132 break; 4133 DeclContext *DC = nullptr; 4134 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4135 DC = LSI->CallOperator; 4136 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4137 DC = CRSI->TheCapturedDecl; 4138 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4139 DC = BSI->TheDecl; 4140 if (DC) { 4141 if (DC->containsDecl(TT->getDecl())) 4142 break; 4143 captureVariablyModifiedType(Context, T, CSI); 4144 } 4145 } 4146 } 4147 } 4148 4149 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4150 return new (Context) UnaryExprOrTypeTraitExpr( 4151 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4152 } 4153 4154 /// Build a sizeof or alignof expression given an expression 4155 /// operand. 4156 ExprResult 4157 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4158 UnaryExprOrTypeTrait ExprKind) { 4159 ExprResult PE = CheckPlaceholderExpr(E); 4160 if (PE.isInvalid()) 4161 return ExprError(); 4162 4163 E = PE.get(); 4164 4165 // Verify that the operand is valid. 4166 bool isInvalid = false; 4167 if (E->isTypeDependent()) { 4168 // Delay type-checking for type-dependent expressions. 4169 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4170 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4171 } else if (ExprKind == UETT_VecStep) { 4172 isInvalid = CheckVecStepExpr(E); 4173 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4174 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4175 isInvalid = true; 4176 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4177 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4178 isInvalid = true; 4179 } else { 4180 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4181 } 4182 4183 if (isInvalid) 4184 return ExprError(); 4185 4186 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4187 PE = TransformToPotentiallyEvaluated(E); 4188 if (PE.isInvalid()) return ExprError(); 4189 E = PE.get(); 4190 } 4191 4192 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4193 return new (Context) UnaryExprOrTypeTraitExpr( 4194 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4195 } 4196 4197 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4198 /// expr and the same for @c alignof and @c __alignof 4199 /// Note that the ArgRange is invalid if isType is false. 4200 ExprResult 4201 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4202 UnaryExprOrTypeTrait ExprKind, bool IsType, 4203 void *TyOrEx, SourceRange ArgRange) { 4204 // If error parsing type, ignore. 4205 if (!TyOrEx) return ExprError(); 4206 4207 if (IsType) { 4208 TypeSourceInfo *TInfo; 4209 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4210 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4211 } 4212 4213 Expr *ArgEx = (Expr *)TyOrEx; 4214 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4215 return Result; 4216 } 4217 4218 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4219 bool IsReal) { 4220 if (V.get()->isTypeDependent()) 4221 return S.Context.DependentTy; 4222 4223 // _Real and _Imag are only l-values for normal l-values. 4224 if (V.get()->getObjectKind() != OK_Ordinary) { 4225 V = S.DefaultLvalueConversion(V.get()); 4226 if (V.isInvalid()) 4227 return QualType(); 4228 } 4229 4230 // These operators return the element type of a complex type. 4231 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4232 return CT->getElementType(); 4233 4234 // Otherwise they pass through real integer and floating point types here. 4235 if (V.get()->getType()->isArithmeticType()) 4236 return V.get()->getType(); 4237 4238 // Test for placeholders. 4239 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4240 if (PR.isInvalid()) return QualType(); 4241 if (PR.get() != V.get()) { 4242 V = PR; 4243 return CheckRealImagOperand(S, V, Loc, IsReal); 4244 } 4245 4246 // Reject anything else. 4247 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4248 << (IsReal ? "__real" : "__imag"); 4249 return QualType(); 4250 } 4251 4252 4253 4254 ExprResult 4255 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4256 tok::TokenKind Kind, Expr *Input) { 4257 UnaryOperatorKind Opc; 4258 switch (Kind) { 4259 default: llvm_unreachable("Unknown unary op!"); 4260 case tok::plusplus: Opc = UO_PostInc; break; 4261 case tok::minusminus: Opc = UO_PostDec; break; 4262 } 4263 4264 // Since this might is a postfix expression, get rid of ParenListExprs. 4265 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4266 if (Result.isInvalid()) return ExprError(); 4267 Input = Result.get(); 4268 4269 return BuildUnaryOp(S, OpLoc, Opc, Input); 4270 } 4271 4272 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4273 /// 4274 /// \return true on error 4275 static bool checkArithmeticOnObjCPointer(Sema &S, 4276 SourceLocation opLoc, 4277 Expr *op) { 4278 assert(op->getType()->isObjCObjectPointerType()); 4279 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4280 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4281 return false; 4282 4283 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4284 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4285 << op->getSourceRange(); 4286 return true; 4287 } 4288 4289 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4290 auto *BaseNoParens = Base->IgnoreParens(); 4291 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4292 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4293 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4294 } 4295 4296 ExprResult 4297 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4298 Expr *idx, SourceLocation rbLoc) { 4299 if (base && !base->getType().isNull() && 4300 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4301 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4302 /*Length=*/nullptr, rbLoc); 4303 4304 // Since this might be a postfix expression, get rid of ParenListExprs. 4305 if (isa<ParenListExpr>(base)) { 4306 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4307 if (result.isInvalid()) return ExprError(); 4308 base = result.get(); 4309 } 4310 4311 // A comma-expression as the index is deprecated in C++2a onwards. 4312 if (getLangOpts().CPlusPlus2a && 4313 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4314 (isa<CXXOperatorCallExpr>(idx) && 4315 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4316 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4317 << SourceRange(base->getBeginLoc(), rbLoc); 4318 } 4319 4320 // Handle any non-overload placeholder types in the base and index 4321 // expressions. We can't handle overloads here because the other 4322 // operand might be an overloadable type, in which case the overload 4323 // resolution for the operator overload should get the first crack 4324 // at the overload. 4325 bool IsMSPropertySubscript = false; 4326 if (base->getType()->isNonOverloadPlaceholderType()) { 4327 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4328 if (!IsMSPropertySubscript) { 4329 ExprResult result = CheckPlaceholderExpr(base); 4330 if (result.isInvalid()) 4331 return ExprError(); 4332 base = result.get(); 4333 } 4334 } 4335 if (idx->getType()->isNonOverloadPlaceholderType()) { 4336 ExprResult result = CheckPlaceholderExpr(idx); 4337 if (result.isInvalid()) return ExprError(); 4338 idx = result.get(); 4339 } 4340 4341 // Build an unanalyzed expression if either operand is type-dependent. 4342 if (getLangOpts().CPlusPlus && 4343 (base->isTypeDependent() || idx->isTypeDependent())) { 4344 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4345 VK_LValue, OK_Ordinary, rbLoc); 4346 } 4347 4348 // MSDN, property (C++) 4349 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4350 // This attribute can also be used in the declaration of an empty array in a 4351 // class or structure definition. For example: 4352 // __declspec(property(get=GetX, put=PutX)) int x[]; 4353 // The above statement indicates that x[] can be used with one or more array 4354 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4355 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4356 if (IsMSPropertySubscript) { 4357 // Build MS property subscript expression if base is MS property reference 4358 // or MS property subscript. 4359 return new (Context) MSPropertySubscriptExpr( 4360 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4361 } 4362 4363 // Use C++ overloaded-operator rules if either operand has record 4364 // type. The spec says to do this if either type is *overloadable*, 4365 // but enum types can't declare subscript operators or conversion 4366 // operators, so there's nothing interesting for overload resolution 4367 // to do if there aren't any record types involved. 4368 // 4369 // ObjC pointers have their own subscripting logic that is not tied 4370 // to overload resolution and so should not take this path. 4371 if (getLangOpts().CPlusPlus && 4372 (base->getType()->isRecordType() || 4373 (!base->getType()->isObjCObjectPointerType() && 4374 idx->getType()->isRecordType()))) { 4375 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4376 } 4377 4378 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4379 4380 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4381 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4382 4383 return Res; 4384 } 4385 4386 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4387 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4388 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4389 4390 // For expressions like `&(*s).b`, the base is recorded and what should be 4391 // checked. 4392 const MemberExpr *Member = nullptr; 4393 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4394 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4395 4396 LastRecord.PossibleDerefs.erase(StrippedExpr); 4397 } 4398 4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4400 QualType ResultTy = E->getType(); 4401 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4402 4403 // Bail if the element is an array since it is not memory access. 4404 if (isa<ArrayType>(ResultTy)) 4405 return; 4406 4407 if (ResultTy->hasAttr(attr::NoDeref)) { 4408 LastRecord.PossibleDerefs.insert(E); 4409 return; 4410 } 4411 4412 // Check if the base type is a pointer to a member access of a struct 4413 // marked with noderef. 4414 const Expr *Base = E->getBase(); 4415 QualType BaseTy = Base->getType(); 4416 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4417 // Not a pointer access 4418 return; 4419 4420 const MemberExpr *Member = nullptr; 4421 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4422 Member->isArrow()) 4423 Base = Member->getBase(); 4424 4425 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4426 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4427 LastRecord.PossibleDerefs.insert(E); 4428 } 4429 } 4430 4431 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4432 Expr *LowerBound, 4433 SourceLocation ColonLoc, Expr *Length, 4434 SourceLocation RBLoc) { 4435 if (Base->getType()->isPlaceholderType() && 4436 !Base->getType()->isSpecificPlaceholderType( 4437 BuiltinType::OMPArraySection)) { 4438 ExprResult Result = CheckPlaceholderExpr(Base); 4439 if (Result.isInvalid()) 4440 return ExprError(); 4441 Base = Result.get(); 4442 } 4443 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4444 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4445 if (Result.isInvalid()) 4446 return ExprError(); 4447 Result = DefaultLvalueConversion(Result.get()); 4448 if (Result.isInvalid()) 4449 return ExprError(); 4450 LowerBound = Result.get(); 4451 } 4452 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4453 ExprResult Result = CheckPlaceholderExpr(Length); 4454 if (Result.isInvalid()) 4455 return ExprError(); 4456 Result = DefaultLvalueConversion(Result.get()); 4457 if (Result.isInvalid()) 4458 return ExprError(); 4459 Length = Result.get(); 4460 } 4461 4462 // Build an unanalyzed expression if either operand is type-dependent. 4463 if (Base->isTypeDependent() || 4464 (LowerBound && 4465 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4466 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4467 return new (Context) 4468 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4469 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4470 } 4471 4472 // Perform default conversions. 4473 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4474 QualType ResultTy; 4475 if (OriginalTy->isAnyPointerType()) { 4476 ResultTy = OriginalTy->getPointeeType(); 4477 } else if (OriginalTy->isArrayType()) { 4478 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4479 } else { 4480 return ExprError( 4481 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4482 << Base->getSourceRange()); 4483 } 4484 // C99 6.5.2.1p1 4485 if (LowerBound) { 4486 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4487 LowerBound); 4488 if (Res.isInvalid()) 4489 return ExprError(Diag(LowerBound->getExprLoc(), 4490 diag::err_omp_typecheck_section_not_integer) 4491 << 0 << LowerBound->getSourceRange()); 4492 LowerBound = Res.get(); 4493 4494 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4495 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4496 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4497 << 0 << LowerBound->getSourceRange(); 4498 } 4499 if (Length) { 4500 auto Res = 4501 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4502 if (Res.isInvalid()) 4503 return ExprError(Diag(Length->getExprLoc(), 4504 diag::err_omp_typecheck_section_not_integer) 4505 << 1 << Length->getSourceRange()); 4506 Length = Res.get(); 4507 4508 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4509 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4510 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4511 << 1 << Length->getSourceRange(); 4512 } 4513 4514 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4515 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4516 // type. Note that functions are not objects, and that (in C99 parlance) 4517 // incomplete types are not object types. 4518 if (ResultTy->isFunctionType()) { 4519 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4520 << ResultTy << Base->getSourceRange(); 4521 return ExprError(); 4522 } 4523 4524 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4525 diag::err_omp_section_incomplete_type, Base)) 4526 return ExprError(); 4527 4528 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4529 Expr::EvalResult Result; 4530 if (LowerBound->EvaluateAsInt(Result, Context)) { 4531 // OpenMP 4.5, [2.4 Array Sections] 4532 // The array section must be a subset of the original array. 4533 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4534 if (LowerBoundValue.isNegative()) { 4535 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4536 << LowerBound->getSourceRange(); 4537 return ExprError(); 4538 } 4539 } 4540 } 4541 4542 if (Length) { 4543 Expr::EvalResult Result; 4544 if (Length->EvaluateAsInt(Result, Context)) { 4545 // OpenMP 4.5, [2.4 Array Sections] 4546 // The length must evaluate to non-negative integers. 4547 llvm::APSInt LengthValue = Result.Val.getInt(); 4548 if (LengthValue.isNegative()) { 4549 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4550 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4551 << Length->getSourceRange(); 4552 return ExprError(); 4553 } 4554 } 4555 } else if (ColonLoc.isValid() && 4556 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4557 !OriginalTy->isVariableArrayType()))) { 4558 // OpenMP 4.5, [2.4 Array Sections] 4559 // When the size of the array dimension is not known, the length must be 4560 // specified explicitly. 4561 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4562 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4563 return ExprError(); 4564 } 4565 4566 if (!Base->getType()->isSpecificPlaceholderType( 4567 BuiltinType::OMPArraySection)) { 4568 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4569 if (Result.isInvalid()) 4570 return ExprError(); 4571 Base = Result.get(); 4572 } 4573 return new (Context) 4574 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4575 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4576 } 4577 4578 ExprResult 4579 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4580 Expr *Idx, SourceLocation RLoc) { 4581 Expr *LHSExp = Base; 4582 Expr *RHSExp = Idx; 4583 4584 ExprValueKind VK = VK_LValue; 4585 ExprObjectKind OK = OK_Ordinary; 4586 4587 // Per C++ core issue 1213, the result is an xvalue if either operand is 4588 // a non-lvalue array, and an lvalue otherwise. 4589 if (getLangOpts().CPlusPlus11) { 4590 for (auto *Op : {LHSExp, RHSExp}) { 4591 Op = Op->IgnoreImplicit(); 4592 if (Op->getType()->isArrayType() && !Op->isLValue()) 4593 VK = VK_XValue; 4594 } 4595 } 4596 4597 // Perform default conversions. 4598 if (!LHSExp->getType()->getAs<VectorType>()) { 4599 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4600 if (Result.isInvalid()) 4601 return ExprError(); 4602 LHSExp = Result.get(); 4603 } 4604 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4605 if (Result.isInvalid()) 4606 return ExprError(); 4607 RHSExp = Result.get(); 4608 4609 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4610 4611 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4612 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4613 // in the subscript position. As a result, we need to derive the array base 4614 // and index from the expression types. 4615 Expr *BaseExpr, *IndexExpr; 4616 QualType ResultType; 4617 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4618 BaseExpr = LHSExp; 4619 IndexExpr = RHSExp; 4620 ResultType = Context.DependentTy; 4621 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4622 BaseExpr = LHSExp; 4623 IndexExpr = RHSExp; 4624 ResultType = PTy->getPointeeType(); 4625 } else if (const ObjCObjectPointerType *PTy = 4626 LHSTy->getAs<ObjCObjectPointerType>()) { 4627 BaseExpr = LHSExp; 4628 IndexExpr = RHSExp; 4629 4630 // Use custom logic if this should be the pseudo-object subscript 4631 // expression. 4632 if (!LangOpts.isSubscriptPointerArithmetic()) 4633 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4634 nullptr); 4635 4636 ResultType = PTy->getPointeeType(); 4637 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4638 // Handle the uncommon case of "123[Ptr]". 4639 BaseExpr = RHSExp; 4640 IndexExpr = LHSExp; 4641 ResultType = PTy->getPointeeType(); 4642 } else if (const ObjCObjectPointerType *PTy = 4643 RHSTy->getAs<ObjCObjectPointerType>()) { 4644 // Handle the uncommon case of "123[Ptr]". 4645 BaseExpr = RHSExp; 4646 IndexExpr = LHSExp; 4647 ResultType = PTy->getPointeeType(); 4648 if (!LangOpts.isSubscriptPointerArithmetic()) { 4649 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4650 << ResultType << BaseExpr->getSourceRange(); 4651 return ExprError(); 4652 } 4653 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4654 BaseExpr = LHSExp; // vectors: V[123] 4655 IndexExpr = RHSExp; 4656 // We apply C++ DR1213 to vector subscripting too. 4657 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4658 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4659 if (Materialized.isInvalid()) 4660 return ExprError(); 4661 LHSExp = Materialized.get(); 4662 } 4663 VK = LHSExp->getValueKind(); 4664 if (VK != VK_RValue) 4665 OK = OK_VectorComponent; 4666 4667 ResultType = VTy->getElementType(); 4668 QualType BaseType = BaseExpr->getType(); 4669 Qualifiers BaseQuals = BaseType.getQualifiers(); 4670 Qualifiers MemberQuals = ResultType.getQualifiers(); 4671 Qualifiers Combined = BaseQuals + MemberQuals; 4672 if (Combined != MemberQuals) 4673 ResultType = Context.getQualifiedType(ResultType, Combined); 4674 } else if (LHSTy->isArrayType()) { 4675 // If we see an array that wasn't promoted by 4676 // DefaultFunctionArrayLvalueConversion, it must be an array that 4677 // wasn't promoted because of the C90 rule that doesn't 4678 // allow promoting non-lvalue arrays. Warn, then 4679 // force the promotion here. 4680 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4681 << LHSExp->getSourceRange(); 4682 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4683 CK_ArrayToPointerDecay).get(); 4684 LHSTy = LHSExp->getType(); 4685 4686 BaseExpr = LHSExp; 4687 IndexExpr = RHSExp; 4688 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4689 } else if (RHSTy->isArrayType()) { 4690 // Same as previous, except for 123[f().a] case 4691 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4692 << RHSExp->getSourceRange(); 4693 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4694 CK_ArrayToPointerDecay).get(); 4695 RHSTy = RHSExp->getType(); 4696 4697 BaseExpr = RHSExp; 4698 IndexExpr = LHSExp; 4699 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4700 } else { 4701 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4702 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4703 } 4704 // C99 6.5.2.1p1 4705 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4706 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4707 << IndexExpr->getSourceRange()); 4708 4709 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4710 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4711 && !IndexExpr->isTypeDependent()) 4712 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4713 4714 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4715 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4716 // type. Note that Functions are not objects, and that (in C99 parlance) 4717 // incomplete types are not object types. 4718 if (ResultType->isFunctionType()) { 4719 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4720 << ResultType << BaseExpr->getSourceRange(); 4721 return ExprError(); 4722 } 4723 4724 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4725 // GNU extension: subscripting on pointer to void 4726 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4727 << BaseExpr->getSourceRange(); 4728 4729 // C forbids expressions of unqualified void type from being l-values. 4730 // See IsCForbiddenLValueType. 4731 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4732 } else if (!ResultType->isDependentType() && 4733 RequireCompleteType(LLoc, ResultType, 4734 diag::err_subscript_incomplete_type, BaseExpr)) 4735 return ExprError(); 4736 4737 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4738 !ResultType.isCForbiddenLValueType()); 4739 4740 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4741 FunctionScopes.size() > 1) { 4742 if (auto *TT = 4743 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4744 for (auto I = FunctionScopes.rbegin(), 4745 E = std::prev(FunctionScopes.rend()); 4746 I != E; ++I) { 4747 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4748 if (CSI == nullptr) 4749 break; 4750 DeclContext *DC = nullptr; 4751 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4752 DC = LSI->CallOperator; 4753 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4754 DC = CRSI->TheCapturedDecl; 4755 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4756 DC = BSI->TheDecl; 4757 if (DC) { 4758 if (DC->containsDecl(TT->getDecl())) 4759 break; 4760 captureVariablyModifiedType( 4761 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4762 } 4763 } 4764 } 4765 } 4766 4767 return new (Context) 4768 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4769 } 4770 4771 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4772 ParmVarDecl *Param) { 4773 if (Param->hasUnparsedDefaultArg()) { 4774 Diag(CallLoc, 4775 diag::err_use_of_default_argument_to_function_declared_later) << 4776 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4777 Diag(UnparsedDefaultArgLocs[Param], 4778 diag::note_default_argument_declared_here); 4779 return true; 4780 } 4781 4782 if (Param->hasUninstantiatedDefaultArg()) { 4783 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4784 4785 EnterExpressionEvaluationContext EvalContext( 4786 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4787 4788 // Instantiate the expression. 4789 // 4790 // FIXME: Pass in a correct Pattern argument, otherwise 4791 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4792 // 4793 // template<typename T> 4794 // struct A { 4795 // static int FooImpl(); 4796 // 4797 // template<typename Tp> 4798 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4799 // // template argument list [[T], [Tp]], should be [[Tp]]. 4800 // friend A<Tp> Foo(int a); 4801 // }; 4802 // 4803 // template<typename T> 4804 // A<T> Foo(int a = A<T>::FooImpl()); 4805 MultiLevelTemplateArgumentList MutiLevelArgList 4806 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4807 4808 InstantiatingTemplate Inst(*this, CallLoc, Param, 4809 MutiLevelArgList.getInnermost()); 4810 if (Inst.isInvalid()) 4811 return true; 4812 if (Inst.isAlreadyInstantiating()) { 4813 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4814 Param->setInvalidDecl(); 4815 return true; 4816 } 4817 4818 ExprResult Result; 4819 { 4820 // C++ [dcl.fct.default]p5: 4821 // The names in the [default argument] expression are bound, and 4822 // the semantic constraints are checked, at the point where the 4823 // default argument expression appears. 4824 ContextRAII SavedContext(*this, FD); 4825 LocalInstantiationScope Local(*this); 4826 runWithSufficientStackSpace(CallLoc, [&] { 4827 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4828 /*DirectInit*/false); 4829 }); 4830 } 4831 if (Result.isInvalid()) 4832 return true; 4833 4834 // Check the expression as an initializer for the parameter. 4835 InitializedEntity Entity 4836 = InitializedEntity::InitializeParameter(Context, Param); 4837 InitializationKind Kind = InitializationKind::CreateCopy( 4838 Param->getLocation(), 4839 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4840 Expr *ResultE = Result.getAs<Expr>(); 4841 4842 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4843 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4844 if (Result.isInvalid()) 4845 return true; 4846 4847 Result = 4848 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4849 /*DiscardedValue*/ false); 4850 if (Result.isInvalid()) 4851 return true; 4852 4853 // Remember the instantiated default argument. 4854 Param->setDefaultArg(Result.getAs<Expr>()); 4855 if (ASTMutationListener *L = getASTMutationListener()) { 4856 L->DefaultArgumentInstantiated(Param); 4857 } 4858 } 4859 4860 // If the default argument expression is not set yet, we are building it now. 4861 if (!Param->hasInit()) { 4862 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4863 Param->setInvalidDecl(); 4864 return true; 4865 } 4866 4867 // If the default expression creates temporaries, we need to 4868 // push them to the current stack of expression temporaries so they'll 4869 // be properly destroyed. 4870 // FIXME: We should really be rebuilding the default argument with new 4871 // bound temporaries; see the comment in PR5810. 4872 // We don't need to do that with block decls, though, because 4873 // blocks in default argument expression can never capture anything. 4874 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4875 // Set the "needs cleanups" bit regardless of whether there are 4876 // any explicit objects. 4877 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4878 4879 // Append all the objects to the cleanup list. Right now, this 4880 // should always be a no-op, because blocks in default argument 4881 // expressions should never be able to capture anything. 4882 assert(!Init->getNumObjects() && 4883 "default argument expression has capturing blocks?"); 4884 } 4885 4886 // We already type-checked the argument, so we know it works. 4887 // Just mark all of the declarations in this potentially-evaluated expression 4888 // as being "referenced". 4889 EnterExpressionEvaluationContext EvalContext( 4890 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4891 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4892 /*SkipLocalVariables=*/true); 4893 return false; 4894 } 4895 4896 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4897 FunctionDecl *FD, ParmVarDecl *Param) { 4898 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4899 return ExprError(); 4900 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4901 } 4902 4903 Sema::VariadicCallType 4904 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4905 Expr *Fn) { 4906 if (Proto && Proto->isVariadic()) { 4907 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4908 return VariadicConstructor; 4909 else if (Fn && Fn->getType()->isBlockPointerType()) 4910 return VariadicBlock; 4911 else if (FDecl) { 4912 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4913 if (Method->isInstance()) 4914 return VariadicMethod; 4915 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4916 return VariadicMethod; 4917 return VariadicFunction; 4918 } 4919 return VariadicDoesNotApply; 4920 } 4921 4922 namespace { 4923 class FunctionCallCCC final : public FunctionCallFilterCCC { 4924 public: 4925 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4926 unsigned NumArgs, MemberExpr *ME) 4927 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4928 FunctionName(FuncName) {} 4929 4930 bool ValidateCandidate(const TypoCorrection &candidate) override { 4931 if (!candidate.getCorrectionSpecifier() || 4932 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4933 return false; 4934 } 4935 4936 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4937 } 4938 4939 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4940 return std::make_unique<FunctionCallCCC>(*this); 4941 } 4942 4943 private: 4944 const IdentifierInfo *const FunctionName; 4945 }; 4946 } 4947 4948 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4949 FunctionDecl *FDecl, 4950 ArrayRef<Expr *> Args) { 4951 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4952 DeclarationName FuncName = FDecl->getDeclName(); 4953 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4954 4955 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4956 if (TypoCorrection Corrected = S.CorrectTypo( 4957 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4958 S.getScopeForContext(S.CurContext), nullptr, CCC, 4959 Sema::CTK_ErrorRecovery)) { 4960 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4961 if (Corrected.isOverloaded()) { 4962 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4963 OverloadCandidateSet::iterator Best; 4964 for (NamedDecl *CD : Corrected) { 4965 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4966 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4967 OCS); 4968 } 4969 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4970 case OR_Success: 4971 ND = Best->FoundDecl; 4972 Corrected.setCorrectionDecl(ND); 4973 break; 4974 default: 4975 break; 4976 } 4977 } 4978 ND = ND->getUnderlyingDecl(); 4979 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4980 return Corrected; 4981 } 4982 } 4983 return TypoCorrection(); 4984 } 4985 4986 /// ConvertArgumentsForCall - Converts the arguments specified in 4987 /// Args/NumArgs to the parameter types of the function FDecl with 4988 /// function prototype Proto. Call is the call expression itself, and 4989 /// Fn is the function expression. For a C++ member function, this 4990 /// routine does not attempt to convert the object argument. Returns 4991 /// true if the call is ill-formed. 4992 bool 4993 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4994 FunctionDecl *FDecl, 4995 const FunctionProtoType *Proto, 4996 ArrayRef<Expr *> Args, 4997 SourceLocation RParenLoc, 4998 bool IsExecConfig) { 4999 // Bail out early if calling a builtin with custom typechecking. 5000 if (FDecl) 5001 if (unsigned ID = FDecl->getBuiltinID()) 5002 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5003 return false; 5004 5005 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5006 // assignment, to the types of the corresponding parameter, ... 5007 unsigned NumParams = Proto->getNumParams(); 5008 bool Invalid = false; 5009 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5010 unsigned FnKind = Fn->getType()->isBlockPointerType() 5011 ? 1 /* block */ 5012 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5013 : 0 /* function */); 5014 5015 // If too few arguments are available (and we don't have default 5016 // arguments for the remaining parameters), don't make the call. 5017 if (Args.size() < NumParams) { 5018 if (Args.size() < MinArgs) { 5019 TypoCorrection TC; 5020 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5021 unsigned diag_id = 5022 MinArgs == NumParams && !Proto->isVariadic() 5023 ? diag::err_typecheck_call_too_few_args_suggest 5024 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5025 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5026 << static_cast<unsigned>(Args.size()) 5027 << TC.getCorrectionRange()); 5028 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5029 Diag(RParenLoc, 5030 MinArgs == NumParams && !Proto->isVariadic() 5031 ? diag::err_typecheck_call_too_few_args_one 5032 : diag::err_typecheck_call_too_few_args_at_least_one) 5033 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5034 else 5035 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5036 ? diag::err_typecheck_call_too_few_args 5037 : diag::err_typecheck_call_too_few_args_at_least) 5038 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5039 << Fn->getSourceRange(); 5040 5041 // Emit the location of the prototype. 5042 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5043 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5044 5045 return true; 5046 } 5047 // We reserve space for the default arguments when we create 5048 // the call expression, before calling ConvertArgumentsForCall. 5049 assert((Call->getNumArgs() == NumParams) && 5050 "We should have reserved space for the default arguments before!"); 5051 } 5052 5053 // If too many are passed and not variadic, error on the extras and drop 5054 // them. 5055 if (Args.size() > NumParams) { 5056 if (!Proto->isVariadic()) { 5057 TypoCorrection TC; 5058 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5059 unsigned diag_id = 5060 MinArgs == NumParams && !Proto->isVariadic() 5061 ? diag::err_typecheck_call_too_many_args_suggest 5062 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5063 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5064 << static_cast<unsigned>(Args.size()) 5065 << TC.getCorrectionRange()); 5066 } else if (NumParams == 1 && FDecl && 5067 FDecl->getParamDecl(0)->getDeclName()) 5068 Diag(Args[NumParams]->getBeginLoc(), 5069 MinArgs == NumParams 5070 ? diag::err_typecheck_call_too_many_args_one 5071 : diag::err_typecheck_call_too_many_args_at_most_one) 5072 << FnKind << FDecl->getParamDecl(0) 5073 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5074 << SourceRange(Args[NumParams]->getBeginLoc(), 5075 Args.back()->getEndLoc()); 5076 else 5077 Diag(Args[NumParams]->getBeginLoc(), 5078 MinArgs == NumParams 5079 ? diag::err_typecheck_call_too_many_args 5080 : diag::err_typecheck_call_too_many_args_at_most) 5081 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5082 << Fn->getSourceRange() 5083 << SourceRange(Args[NumParams]->getBeginLoc(), 5084 Args.back()->getEndLoc()); 5085 5086 // Emit the location of the prototype. 5087 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5088 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5089 5090 // This deletes the extra arguments. 5091 Call->shrinkNumArgs(NumParams); 5092 return true; 5093 } 5094 } 5095 SmallVector<Expr *, 8> AllArgs; 5096 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5097 5098 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5099 AllArgs, CallType); 5100 if (Invalid) 5101 return true; 5102 unsigned TotalNumArgs = AllArgs.size(); 5103 for (unsigned i = 0; i < TotalNumArgs; ++i) 5104 Call->setArg(i, AllArgs[i]); 5105 5106 return false; 5107 } 5108 5109 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5110 const FunctionProtoType *Proto, 5111 unsigned FirstParam, ArrayRef<Expr *> Args, 5112 SmallVectorImpl<Expr *> &AllArgs, 5113 VariadicCallType CallType, bool AllowExplicit, 5114 bool IsListInitialization) { 5115 unsigned NumParams = Proto->getNumParams(); 5116 bool Invalid = false; 5117 size_t ArgIx = 0; 5118 // Continue to check argument types (even if we have too few/many args). 5119 for (unsigned i = FirstParam; i < NumParams; i++) { 5120 QualType ProtoArgType = Proto->getParamType(i); 5121 5122 Expr *Arg; 5123 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5124 if (ArgIx < Args.size()) { 5125 Arg = Args[ArgIx++]; 5126 5127 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5128 diag::err_call_incomplete_argument, Arg)) 5129 return true; 5130 5131 // Strip the unbridged-cast placeholder expression off, if applicable. 5132 bool CFAudited = false; 5133 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5134 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5135 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5136 Arg = stripARCUnbridgedCast(Arg); 5137 else if (getLangOpts().ObjCAutoRefCount && 5138 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5139 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5140 CFAudited = true; 5141 5142 if (Proto->getExtParameterInfo(i).isNoEscape()) 5143 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5144 BE->getBlockDecl()->setDoesNotEscape(); 5145 5146 InitializedEntity Entity = 5147 Param ? InitializedEntity::InitializeParameter(Context, Param, 5148 ProtoArgType) 5149 : InitializedEntity::InitializeParameter( 5150 Context, ProtoArgType, Proto->isParamConsumed(i)); 5151 5152 // Remember that parameter belongs to a CF audited API. 5153 if (CFAudited) 5154 Entity.setParameterCFAudited(); 5155 5156 ExprResult ArgE = PerformCopyInitialization( 5157 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5158 if (ArgE.isInvalid()) 5159 return true; 5160 5161 Arg = ArgE.getAs<Expr>(); 5162 } else { 5163 assert(Param && "can't use default arguments without a known callee"); 5164 5165 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5166 if (ArgExpr.isInvalid()) 5167 return true; 5168 5169 Arg = ArgExpr.getAs<Expr>(); 5170 } 5171 5172 // Check for array bounds violations for each argument to the call. This 5173 // check only triggers warnings when the argument isn't a more complex Expr 5174 // with its own checking, such as a BinaryOperator. 5175 CheckArrayAccess(Arg); 5176 5177 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5178 CheckStaticArrayArgument(CallLoc, Param, Arg); 5179 5180 AllArgs.push_back(Arg); 5181 } 5182 5183 // If this is a variadic call, handle args passed through "...". 5184 if (CallType != VariadicDoesNotApply) { 5185 // Assume that extern "C" functions with variadic arguments that 5186 // return __unknown_anytype aren't *really* variadic. 5187 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5188 FDecl->isExternC()) { 5189 for (Expr *A : Args.slice(ArgIx)) { 5190 QualType paramType; // ignored 5191 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5192 Invalid |= arg.isInvalid(); 5193 AllArgs.push_back(arg.get()); 5194 } 5195 5196 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5197 } else { 5198 for (Expr *A : Args.slice(ArgIx)) { 5199 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5200 Invalid |= Arg.isInvalid(); 5201 AllArgs.push_back(Arg.get()); 5202 } 5203 } 5204 5205 // Check for array bounds violations. 5206 for (Expr *A : Args.slice(ArgIx)) 5207 CheckArrayAccess(A); 5208 } 5209 return Invalid; 5210 } 5211 5212 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5213 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5214 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5215 TL = DTL.getOriginalLoc(); 5216 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5217 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5218 << ATL.getLocalSourceRange(); 5219 } 5220 5221 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5222 /// array parameter, check that it is non-null, and that if it is formed by 5223 /// array-to-pointer decay, the underlying array is sufficiently large. 5224 /// 5225 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5226 /// array type derivation, then for each call to the function, the value of the 5227 /// corresponding actual argument shall provide access to the first element of 5228 /// an array with at least as many elements as specified by the size expression. 5229 void 5230 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5231 ParmVarDecl *Param, 5232 const Expr *ArgExpr) { 5233 // Static array parameters are not supported in C++. 5234 if (!Param || getLangOpts().CPlusPlus) 5235 return; 5236 5237 QualType OrigTy = Param->getOriginalType(); 5238 5239 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5240 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5241 return; 5242 5243 if (ArgExpr->isNullPointerConstant(Context, 5244 Expr::NPC_NeverValueDependent)) { 5245 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5246 DiagnoseCalleeStaticArrayParam(*this, Param); 5247 return; 5248 } 5249 5250 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5251 if (!CAT) 5252 return; 5253 5254 const ConstantArrayType *ArgCAT = 5255 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5256 if (!ArgCAT) 5257 return; 5258 5259 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5260 ArgCAT->getElementType())) { 5261 if (ArgCAT->getSize().ult(CAT->getSize())) { 5262 Diag(CallLoc, diag::warn_static_array_too_small) 5263 << ArgExpr->getSourceRange() 5264 << (unsigned)ArgCAT->getSize().getZExtValue() 5265 << (unsigned)CAT->getSize().getZExtValue() << 0; 5266 DiagnoseCalleeStaticArrayParam(*this, Param); 5267 } 5268 return; 5269 } 5270 5271 Optional<CharUnits> ArgSize = 5272 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5273 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5274 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5275 Diag(CallLoc, diag::warn_static_array_too_small) 5276 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5277 << (unsigned)ParmSize->getQuantity() << 1; 5278 DiagnoseCalleeStaticArrayParam(*this, Param); 5279 } 5280 } 5281 5282 /// Given a function expression of unknown-any type, try to rebuild it 5283 /// to have a function type. 5284 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5285 5286 /// Is the given type a placeholder that we need to lower out 5287 /// immediately during argument processing? 5288 static bool isPlaceholderToRemoveAsArg(QualType type) { 5289 // Placeholders are never sugared. 5290 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5291 if (!placeholder) return false; 5292 5293 switch (placeholder->getKind()) { 5294 // Ignore all the non-placeholder types. 5295 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5296 case BuiltinType::Id: 5297 #include "clang/Basic/OpenCLImageTypes.def" 5298 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5299 case BuiltinType::Id: 5300 #include "clang/Basic/OpenCLExtensionTypes.def" 5301 // In practice we'll never use this, since all SVE types are sugared 5302 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5303 #define SVE_TYPE(Name, Id, SingletonId) \ 5304 case BuiltinType::Id: 5305 #include "clang/Basic/AArch64SVEACLETypes.def" 5306 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5307 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5308 #include "clang/AST/BuiltinTypes.def" 5309 return false; 5310 5311 // We cannot lower out overload sets; they might validly be resolved 5312 // by the call machinery. 5313 case BuiltinType::Overload: 5314 return false; 5315 5316 // Unbridged casts in ARC can be handled in some call positions and 5317 // should be left in place. 5318 case BuiltinType::ARCUnbridgedCast: 5319 return false; 5320 5321 // Pseudo-objects should be converted as soon as possible. 5322 case BuiltinType::PseudoObject: 5323 return true; 5324 5325 // The debugger mode could theoretically but currently does not try 5326 // to resolve unknown-typed arguments based on known parameter types. 5327 case BuiltinType::UnknownAny: 5328 return true; 5329 5330 // These are always invalid as call arguments and should be reported. 5331 case BuiltinType::BoundMember: 5332 case BuiltinType::BuiltinFn: 5333 case BuiltinType::OMPArraySection: 5334 return true; 5335 5336 } 5337 llvm_unreachable("bad builtin type kind"); 5338 } 5339 5340 /// Check an argument list for placeholders that we won't try to 5341 /// handle later. 5342 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5343 // Apply this processing to all the arguments at once instead of 5344 // dying at the first failure. 5345 bool hasInvalid = false; 5346 for (size_t i = 0, e = args.size(); i != e; i++) { 5347 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5348 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5349 if (result.isInvalid()) hasInvalid = true; 5350 else args[i] = result.get(); 5351 } else if (hasInvalid) { 5352 (void)S.CorrectDelayedTyposInExpr(args[i]); 5353 } 5354 } 5355 return hasInvalid; 5356 } 5357 5358 /// If a builtin function has a pointer argument with no explicit address 5359 /// space, then it should be able to accept a pointer to any address 5360 /// space as input. In order to do this, we need to replace the 5361 /// standard builtin declaration with one that uses the same address space 5362 /// as the call. 5363 /// 5364 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5365 /// it does not contain any pointer arguments without 5366 /// an address space qualifer. Otherwise the rewritten 5367 /// FunctionDecl is returned. 5368 /// TODO: Handle pointer return types. 5369 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5370 FunctionDecl *FDecl, 5371 MultiExprArg ArgExprs) { 5372 5373 QualType DeclType = FDecl->getType(); 5374 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5375 5376 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5377 ArgExprs.size() < FT->getNumParams()) 5378 return nullptr; 5379 5380 bool NeedsNewDecl = false; 5381 unsigned i = 0; 5382 SmallVector<QualType, 8> OverloadParams; 5383 5384 for (QualType ParamType : FT->param_types()) { 5385 5386 // Convert array arguments to pointer to simplify type lookup. 5387 ExprResult ArgRes = 5388 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5389 if (ArgRes.isInvalid()) 5390 return nullptr; 5391 Expr *Arg = ArgRes.get(); 5392 QualType ArgType = Arg->getType(); 5393 if (!ParamType->isPointerType() || 5394 ParamType.getQualifiers().hasAddressSpace() || 5395 !ArgType->isPointerType() || 5396 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5397 OverloadParams.push_back(ParamType); 5398 continue; 5399 } 5400 5401 QualType PointeeType = ParamType->getPointeeType(); 5402 if (PointeeType.getQualifiers().hasAddressSpace()) 5403 continue; 5404 5405 NeedsNewDecl = true; 5406 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5407 5408 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5409 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5410 } 5411 5412 if (!NeedsNewDecl) 5413 return nullptr; 5414 5415 FunctionProtoType::ExtProtoInfo EPI; 5416 EPI.Variadic = FT->isVariadic(); 5417 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5418 OverloadParams, EPI); 5419 DeclContext *Parent = FDecl->getParent(); 5420 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5421 FDecl->getLocation(), 5422 FDecl->getLocation(), 5423 FDecl->getIdentifier(), 5424 OverloadTy, 5425 /*TInfo=*/nullptr, 5426 SC_Extern, false, 5427 /*hasPrototype=*/true); 5428 SmallVector<ParmVarDecl*, 16> Params; 5429 FT = cast<FunctionProtoType>(OverloadTy); 5430 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5431 QualType ParamType = FT->getParamType(i); 5432 ParmVarDecl *Parm = 5433 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5434 SourceLocation(), nullptr, ParamType, 5435 /*TInfo=*/nullptr, SC_None, nullptr); 5436 Parm->setScopeInfo(0, i); 5437 Params.push_back(Parm); 5438 } 5439 OverloadDecl->setParams(Params); 5440 return OverloadDecl; 5441 } 5442 5443 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5444 FunctionDecl *Callee, 5445 MultiExprArg ArgExprs) { 5446 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5447 // similar attributes) really don't like it when functions are called with an 5448 // invalid number of args. 5449 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5450 /*PartialOverloading=*/false) && 5451 !Callee->isVariadic()) 5452 return; 5453 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5454 return; 5455 5456 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5457 S.Diag(Fn->getBeginLoc(), 5458 isa<CXXMethodDecl>(Callee) 5459 ? diag::err_ovl_no_viable_member_function_in_call 5460 : diag::err_ovl_no_viable_function_in_call) 5461 << Callee << Callee->getSourceRange(); 5462 S.Diag(Callee->getLocation(), 5463 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5464 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5465 return; 5466 } 5467 } 5468 5469 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5470 const UnresolvedMemberExpr *const UME, Sema &S) { 5471 5472 const auto GetFunctionLevelDCIfCXXClass = 5473 [](Sema &S) -> const CXXRecordDecl * { 5474 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5475 if (!DC || !DC->getParent()) 5476 return nullptr; 5477 5478 // If the call to some member function was made from within a member 5479 // function body 'M' return return 'M's parent. 5480 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5481 return MD->getParent()->getCanonicalDecl(); 5482 // else the call was made from within a default member initializer of a 5483 // class, so return the class. 5484 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5485 return RD->getCanonicalDecl(); 5486 return nullptr; 5487 }; 5488 // If our DeclContext is neither a member function nor a class (in the 5489 // case of a lambda in a default member initializer), we can't have an 5490 // enclosing 'this'. 5491 5492 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5493 if (!CurParentClass) 5494 return false; 5495 5496 // The naming class for implicit member functions call is the class in which 5497 // name lookup starts. 5498 const CXXRecordDecl *const NamingClass = 5499 UME->getNamingClass()->getCanonicalDecl(); 5500 assert(NamingClass && "Must have naming class even for implicit access"); 5501 5502 // If the unresolved member functions were found in a 'naming class' that is 5503 // related (either the same or derived from) to the class that contains the 5504 // member function that itself contained the implicit member access. 5505 5506 return CurParentClass == NamingClass || 5507 CurParentClass->isDerivedFrom(NamingClass); 5508 } 5509 5510 static void 5511 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5512 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5513 5514 if (!UME) 5515 return; 5516 5517 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5518 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5519 // already been captured, or if this is an implicit member function call (if 5520 // it isn't, an attempt to capture 'this' should already have been made). 5521 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5522 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5523 return; 5524 5525 // Check if the naming class in which the unresolved members were found is 5526 // related (same as or is a base of) to the enclosing class. 5527 5528 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5529 return; 5530 5531 5532 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5533 // If the enclosing function is not dependent, then this lambda is 5534 // capture ready, so if we can capture this, do so. 5535 if (!EnclosingFunctionCtx->isDependentContext()) { 5536 // If the current lambda and all enclosing lambdas can capture 'this' - 5537 // then go ahead and capture 'this' (since our unresolved overload set 5538 // contains at least one non-static member function). 5539 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5540 S.CheckCXXThisCapture(CallLoc); 5541 } else if (S.CurContext->isDependentContext()) { 5542 // ... since this is an implicit member reference, that might potentially 5543 // involve a 'this' capture, mark 'this' for potential capture in 5544 // enclosing lambdas. 5545 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5546 CurLSI->addPotentialThisCapture(CallLoc); 5547 } 5548 } 5549 5550 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5551 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5552 Expr *ExecConfig) { 5553 ExprResult Call = 5554 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5555 if (Call.isInvalid()) 5556 return Call; 5557 5558 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5559 // language modes. 5560 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5561 if (ULE->hasExplicitTemplateArgs() && 5562 ULE->decls_begin() == ULE->decls_end()) { 5563 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5564 ? diag::warn_cxx17_compat_adl_only_template_id 5565 : diag::ext_adl_only_template_id) 5566 << ULE->getName(); 5567 } 5568 } 5569 5570 return Call; 5571 } 5572 5573 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5574 /// This provides the location of the left/right parens and a list of comma 5575 /// locations. 5576 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5577 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5578 Expr *ExecConfig, bool IsExecConfig) { 5579 // Since this might be a postfix expression, get rid of ParenListExprs. 5580 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5581 if (Result.isInvalid()) return ExprError(); 5582 Fn = Result.get(); 5583 5584 if (checkArgsForPlaceholders(*this, ArgExprs)) 5585 return ExprError(); 5586 5587 if (getLangOpts().CPlusPlus) { 5588 // If this is a pseudo-destructor expression, build the call immediately. 5589 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5590 if (!ArgExprs.empty()) { 5591 // Pseudo-destructor calls should not have any arguments. 5592 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5593 << FixItHint::CreateRemoval( 5594 SourceRange(ArgExprs.front()->getBeginLoc(), 5595 ArgExprs.back()->getEndLoc())); 5596 } 5597 5598 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5599 VK_RValue, RParenLoc); 5600 } 5601 if (Fn->getType() == Context.PseudoObjectTy) { 5602 ExprResult result = CheckPlaceholderExpr(Fn); 5603 if (result.isInvalid()) return ExprError(); 5604 Fn = result.get(); 5605 } 5606 5607 // Determine whether this is a dependent call inside a C++ template, 5608 // in which case we won't do any semantic analysis now. 5609 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5610 if (ExecConfig) { 5611 return CUDAKernelCallExpr::Create( 5612 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5613 Context.DependentTy, VK_RValue, RParenLoc); 5614 } else { 5615 5616 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5617 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5618 Fn->getBeginLoc()); 5619 5620 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5621 VK_RValue, RParenLoc); 5622 } 5623 } 5624 5625 // Determine whether this is a call to an object (C++ [over.call.object]). 5626 if (Fn->getType()->isRecordType()) 5627 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5628 RParenLoc); 5629 5630 if (Fn->getType() == Context.UnknownAnyTy) { 5631 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5632 if (result.isInvalid()) return ExprError(); 5633 Fn = result.get(); 5634 } 5635 5636 if (Fn->getType() == Context.BoundMemberTy) { 5637 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5638 RParenLoc); 5639 } 5640 } 5641 5642 // Check for overloaded calls. This can happen even in C due to extensions. 5643 if (Fn->getType() == Context.OverloadTy) { 5644 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5645 5646 // We aren't supposed to apply this logic if there's an '&' involved. 5647 if (!find.HasFormOfMemberPointer) { 5648 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5649 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5650 VK_RValue, RParenLoc); 5651 OverloadExpr *ovl = find.Expression; 5652 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5653 return BuildOverloadedCallExpr( 5654 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5655 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5656 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5657 RParenLoc); 5658 } 5659 } 5660 5661 // If we're directly calling a function, get the appropriate declaration. 5662 if (Fn->getType() == Context.UnknownAnyTy) { 5663 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5664 if (result.isInvalid()) return ExprError(); 5665 Fn = result.get(); 5666 } 5667 5668 Expr *NakedFn = Fn->IgnoreParens(); 5669 5670 bool CallingNDeclIndirectly = false; 5671 NamedDecl *NDecl = nullptr; 5672 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5673 if (UnOp->getOpcode() == UO_AddrOf) { 5674 CallingNDeclIndirectly = true; 5675 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5676 } 5677 } 5678 5679 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5680 NDecl = DRE->getDecl(); 5681 5682 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5683 if (FDecl && FDecl->getBuiltinID()) { 5684 // Rewrite the function decl for this builtin by replacing parameters 5685 // with no explicit address space with the address space of the arguments 5686 // in ArgExprs. 5687 if ((FDecl = 5688 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5689 NDecl = FDecl; 5690 Fn = DeclRefExpr::Create( 5691 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5692 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5693 nullptr, DRE->isNonOdrUse()); 5694 } 5695 } 5696 } else if (isa<MemberExpr>(NakedFn)) 5697 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5698 5699 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5700 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5701 FD, /*Complain=*/true, Fn->getBeginLoc())) 5702 return ExprError(); 5703 5704 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5705 return ExprError(); 5706 5707 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5708 } 5709 5710 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5711 ExecConfig, IsExecConfig); 5712 } 5713 5714 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5715 /// 5716 /// __builtin_astype( value, dst type ) 5717 /// 5718 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5719 SourceLocation BuiltinLoc, 5720 SourceLocation RParenLoc) { 5721 ExprValueKind VK = VK_RValue; 5722 ExprObjectKind OK = OK_Ordinary; 5723 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5724 QualType SrcTy = E->getType(); 5725 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5726 return ExprError(Diag(BuiltinLoc, 5727 diag::err_invalid_astype_of_different_size) 5728 << DstTy 5729 << SrcTy 5730 << E->getSourceRange()); 5731 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5732 } 5733 5734 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5735 /// provided arguments. 5736 /// 5737 /// __builtin_convertvector( value, dst type ) 5738 /// 5739 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5740 SourceLocation BuiltinLoc, 5741 SourceLocation RParenLoc) { 5742 TypeSourceInfo *TInfo; 5743 GetTypeFromParser(ParsedDestTy, &TInfo); 5744 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5745 } 5746 5747 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5748 /// i.e. an expression not of \p OverloadTy. The expression should 5749 /// unary-convert to an expression of function-pointer or 5750 /// block-pointer type. 5751 /// 5752 /// \param NDecl the declaration being called, if available 5753 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5754 SourceLocation LParenLoc, 5755 ArrayRef<Expr *> Args, 5756 SourceLocation RParenLoc, Expr *Config, 5757 bool IsExecConfig, ADLCallKind UsesADL) { 5758 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5759 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5760 5761 // Functions with 'interrupt' attribute cannot be called directly. 5762 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5763 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5764 return ExprError(); 5765 } 5766 5767 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5768 // so there's some risk when calling out to non-interrupt handler functions 5769 // that the callee might not preserve them. This is easy to diagnose here, 5770 // but can be very challenging to debug. 5771 if (auto *Caller = getCurFunctionDecl()) 5772 if (Caller->hasAttr<ARMInterruptAttr>()) { 5773 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5774 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5775 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5776 } 5777 5778 // Promote the function operand. 5779 // We special-case function promotion here because we only allow promoting 5780 // builtin functions to function pointers in the callee of a call. 5781 ExprResult Result; 5782 QualType ResultTy; 5783 if (BuiltinID && 5784 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5785 // Extract the return type from the (builtin) function pointer type. 5786 // FIXME Several builtins still have setType in 5787 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5788 // Builtins.def to ensure they are correct before removing setType calls. 5789 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5790 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5791 ResultTy = FDecl->getCallResultType(); 5792 } else { 5793 Result = CallExprUnaryConversions(Fn); 5794 ResultTy = Context.BoolTy; 5795 } 5796 if (Result.isInvalid()) 5797 return ExprError(); 5798 Fn = Result.get(); 5799 5800 // Check for a valid function type, but only if it is not a builtin which 5801 // requires custom type checking. These will be handled by 5802 // CheckBuiltinFunctionCall below just after creation of the call expression. 5803 const FunctionType *FuncT = nullptr; 5804 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5805 retry: 5806 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5807 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5808 // have type pointer to function". 5809 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5810 if (!FuncT) 5811 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5812 << Fn->getType() << Fn->getSourceRange()); 5813 } else if (const BlockPointerType *BPT = 5814 Fn->getType()->getAs<BlockPointerType>()) { 5815 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5816 } else { 5817 // Handle calls to expressions of unknown-any type. 5818 if (Fn->getType() == Context.UnknownAnyTy) { 5819 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5820 if (rewrite.isInvalid()) 5821 return ExprError(); 5822 Fn = rewrite.get(); 5823 goto retry; 5824 } 5825 5826 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5827 << Fn->getType() << Fn->getSourceRange()); 5828 } 5829 } 5830 5831 // Get the number of parameters in the function prototype, if any. 5832 // We will allocate space for max(Args.size(), NumParams) arguments 5833 // in the call expression. 5834 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5835 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5836 5837 CallExpr *TheCall; 5838 if (Config) { 5839 assert(UsesADL == ADLCallKind::NotADL && 5840 "CUDAKernelCallExpr should not use ADL"); 5841 TheCall = 5842 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5843 ResultTy, VK_RValue, RParenLoc, NumParams); 5844 } else { 5845 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5846 RParenLoc, NumParams, UsesADL); 5847 } 5848 5849 if (!getLangOpts().CPlusPlus) { 5850 // Forget about the nulled arguments since typo correction 5851 // do not handle them well. 5852 TheCall->shrinkNumArgs(Args.size()); 5853 // C cannot always handle TypoExpr nodes in builtin calls and direct 5854 // function calls as their argument checking don't necessarily handle 5855 // dependent types properly, so make sure any TypoExprs have been 5856 // dealt with. 5857 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5858 if (!Result.isUsable()) return ExprError(); 5859 CallExpr *TheOldCall = TheCall; 5860 TheCall = dyn_cast<CallExpr>(Result.get()); 5861 bool CorrectedTypos = TheCall != TheOldCall; 5862 if (!TheCall) return Result; 5863 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5864 5865 // A new call expression node was created if some typos were corrected. 5866 // However it may not have been constructed with enough storage. In this 5867 // case, rebuild the node with enough storage. The waste of space is 5868 // immaterial since this only happens when some typos were corrected. 5869 if (CorrectedTypos && Args.size() < NumParams) { 5870 if (Config) 5871 TheCall = CUDAKernelCallExpr::Create( 5872 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5873 RParenLoc, NumParams); 5874 else 5875 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5876 RParenLoc, NumParams, UsesADL); 5877 } 5878 // We can now handle the nulled arguments for the default arguments. 5879 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5880 } 5881 5882 // Bail out early if calling a builtin with custom type checking. 5883 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5884 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5885 5886 if (getLangOpts().CUDA) { 5887 if (Config) { 5888 // CUDA: Kernel calls must be to global functions 5889 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5890 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5891 << FDecl << Fn->getSourceRange()); 5892 5893 // CUDA: Kernel function must have 'void' return type 5894 if (!FuncT->getReturnType()->isVoidType()) 5895 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5896 << Fn->getType() << Fn->getSourceRange()); 5897 } else { 5898 // CUDA: Calls to global functions must be configured 5899 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5900 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5901 << FDecl << Fn->getSourceRange()); 5902 } 5903 } 5904 5905 // Check for a valid return type 5906 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5907 FDecl)) 5908 return ExprError(); 5909 5910 // We know the result type of the call, set it. 5911 TheCall->setType(FuncT->getCallResultType(Context)); 5912 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5913 5914 if (Proto) { 5915 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5916 IsExecConfig)) 5917 return ExprError(); 5918 } else { 5919 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5920 5921 if (FDecl) { 5922 // Check if we have too few/too many template arguments, based 5923 // on our knowledge of the function definition. 5924 const FunctionDecl *Def = nullptr; 5925 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5926 Proto = Def->getType()->getAs<FunctionProtoType>(); 5927 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5928 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5929 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5930 } 5931 5932 // If the function we're calling isn't a function prototype, but we have 5933 // a function prototype from a prior declaratiom, use that prototype. 5934 if (!FDecl->hasPrototype()) 5935 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5936 } 5937 5938 // Promote the arguments (C99 6.5.2.2p6). 5939 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5940 Expr *Arg = Args[i]; 5941 5942 if (Proto && i < Proto->getNumParams()) { 5943 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5944 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5945 ExprResult ArgE = 5946 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5947 if (ArgE.isInvalid()) 5948 return true; 5949 5950 Arg = ArgE.getAs<Expr>(); 5951 5952 } else { 5953 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5954 5955 if (ArgE.isInvalid()) 5956 return true; 5957 5958 Arg = ArgE.getAs<Expr>(); 5959 } 5960 5961 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5962 diag::err_call_incomplete_argument, Arg)) 5963 return ExprError(); 5964 5965 TheCall->setArg(i, Arg); 5966 } 5967 } 5968 5969 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5970 if (!Method->isStatic()) 5971 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5972 << Fn->getSourceRange()); 5973 5974 // Check for sentinels 5975 if (NDecl) 5976 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5977 5978 // Do special checking on direct calls to functions. 5979 if (FDecl) { 5980 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5981 return ExprError(); 5982 5983 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 5984 5985 if (BuiltinID) 5986 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5987 } else if (NDecl) { 5988 if (CheckPointerCall(NDecl, TheCall, Proto)) 5989 return ExprError(); 5990 } else { 5991 if (CheckOtherCall(TheCall, Proto)) 5992 return ExprError(); 5993 } 5994 5995 return MaybeBindToTemporary(TheCall); 5996 } 5997 5998 ExprResult 5999 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6000 SourceLocation RParenLoc, Expr *InitExpr) { 6001 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6002 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6003 6004 TypeSourceInfo *TInfo; 6005 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6006 if (!TInfo) 6007 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6008 6009 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6010 } 6011 6012 ExprResult 6013 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6014 SourceLocation RParenLoc, Expr *LiteralExpr) { 6015 QualType literalType = TInfo->getType(); 6016 6017 if (literalType->isArrayType()) { 6018 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6019 diag::err_illegal_decl_array_incomplete_type, 6020 SourceRange(LParenLoc, 6021 LiteralExpr->getSourceRange().getEnd()))) 6022 return ExprError(); 6023 if (literalType->isVariableArrayType()) 6024 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6025 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6026 } else if (!literalType->isDependentType() && 6027 RequireCompleteType(LParenLoc, literalType, 6028 diag::err_typecheck_decl_incomplete_type, 6029 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6030 return ExprError(); 6031 6032 InitializedEntity Entity 6033 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6034 InitializationKind Kind 6035 = InitializationKind::CreateCStyleCast(LParenLoc, 6036 SourceRange(LParenLoc, RParenLoc), 6037 /*InitList=*/true); 6038 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6039 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6040 &literalType); 6041 if (Result.isInvalid()) 6042 return ExprError(); 6043 LiteralExpr = Result.get(); 6044 6045 bool isFileScope = !CurContext->isFunctionOrMethod(); 6046 6047 // In C, compound literals are l-values for some reason. 6048 // For GCC compatibility, in C++, file-scope array compound literals with 6049 // constant initializers are also l-values, and compound literals are 6050 // otherwise prvalues. 6051 // 6052 // (GCC also treats C++ list-initialized file-scope array prvalues with 6053 // constant initializers as l-values, but that's non-conforming, so we don't 6054 // follow it there.) 6055 // 6056 // FIXME: It would be better to handle the lvalue cases as materializing and 6057 // lifetime-extending a temporary object, but our materialized temporaries 6058 // representation only supports lifetime extension from a variable, not "out 6059 // of thin air". 6060 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6061 // is bound to the result of applying array-to-pointer decay to the compound 6062 // literal. 6063 // FIXME: GCC supports compound literals of reference type, which should 6064 // obviously have a value kind derived from the kind of reference involved. 6065 ExprValueKind VK = 6066 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6067 ? VK_RValue 6068 : VK_LValue; 6069 6070 if (isFileScope) 6071 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6072 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6073 Expr *Init = ILE->getInit(i); 6074 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6075 } 6076 6077 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6078 VK, LiteralExpr, isFileScope); 6079 if (isFileScope) { 6080 if (!LiteralExpr->isTypeDependent() && 6081 !LiteralExpr->isValueDependent() && 6082 !literalType->isDependentType()) // C99 6.5.2.5p3 6083 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6084 return ExprError(); 6085 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6086 literalType.getAddressSpace() != LangAS::Default) { 6087 // Embedded-C extensions to C99 6.5.2.5: 6088 // "If the compound literal occurs inside the body of a function, the 6089 // type name shall not be qualified by an address-space qualifier." 6090 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6091 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6092 return ExprError(); 6093 } 6094 6095 // Compound literals that have automatic storage duration are destroyed at 6096 // the end of the scope. Emit diagnostics if it is or contains a C union type 6097 // that is non-trivial to destruct. 6098 if (!isFileScope) 6099 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6100 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6101 NTCUC_CompoundLiteral, NTCUK_Destruct); 6102 6103 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6104 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6105 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6106 E->getInitializer()->getExprLoc()); 6107 6108 return MaybeBindToTemporary(E); 6109 } 6110 6111 ExprResult 6112 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6113 SourceLocation RBraceLoc) { 6114 // Only produce each kind of designated initialization diagnostic once. 6115 SourceLocation FirstDesignator; 6116 bool DiagnosedArrayDesignator = false; 6117 bool DiagnosedNestedDesignator = false; 6118 bool DiagnosedMixedDesignator = false; 6119 6120 // Check that any designated initializers are syntactically valid in the 6121 // current language mode. 6122 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6123 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6124 if (FirstDesignator.isInvalid()) 6125 FirstDesignator = DIE->getBeginLoc(); 6126 6127 if (!getLangOpts().CPlusPlus) 6128 break; 6129 6130 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6131 DiagnosedNestedDesignator = true; 6132 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6133 << DIE->getDesignatorsSourceRange(); 6134 } 6135 6136 for (auto &Desig : DIE->designators()) { 6137 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6138 DiagnosedArrayDesignator = true; 6139 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6140 << Desig.getSourceRange(); 6141 } 6142 } 6143 6144 if (!DiagnosedMixedDesignator && 6145 !isa<DesignatedInitExpr>(InitArgList[0])) { 6146 DiagnosedMixedDesignator = true; 6147 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6148 << DIE->getSourceRange(); 6149 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6150 << InitArgList[0]->getSourceRange(); 6151 } 6152 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6153 isa<DesignatedInitExpr>(InitArgList[0])) { 6154 DiagnosedMixedDesignator = true; 6155 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6156 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6157 << DIE->getSourceRange(); 6158 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6159 << InitArgList[I]->getSourceRange(); 6160 } 6161 } 6162 6163 if (FirstDesignator.isValid()) { 6164 // Only diagnose designated initiaization as a C++20 extension if we didn't 6165 // already diagnose use of (non-C++20) C99 designator syntax. 6166 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6167 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6168 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6169 ? diag::warn_cxx17_compat_designated_init 6170 : diag::ext_cxx_designated_init); 6171 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6172 Diag(FirstDesignator, diag::ext_designated_init); 6173 } 6174 } 6175 6176 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6177 } 6178 6179 ExprResult 6180 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6181 SourceLocation RBraceLoc) { 6182 // Semantic analysis for initializers is done by ActOnDeclarator() and 6183 // CheckInitializer() - it requires knowledge of the object being initialized. 6184 6185 // Immediately handle non-overload placeholders. Overloads can be 6186 // resolved contextually, but everything else here can't. 6187 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6188 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6189 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6190 6191 // Ignore failures; dropping the entire initializer list because 6192 // of one failure would be terrible for indexing/etc. 6193 if (result.isInvalid()) continue; 6194 6195 InitArgList[I] = result.get(); 6196 } 6197 } 6198 6199 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6200 RBraceLoc); 6201 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6202 return E; 6203 } 6204 6205 /// Do an explicit extend of the given block pointer if we're in ARC. 6206 void Sema::maybeExtendBlockObject(ExprResult &E) { 6207 assert(E.get()->getType()->isBlockPointerType()); 6208 assert(E.get()->isRValue()); 6209 6210 // Only do this in an r-value context. 6211 if (!getLangOpts().ObjCAutoRefCount) return; 6212 6213 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6214 CK_ARCExtendBlockObject, E.get(), 6215 /*base path*/ nullptr, VK_RValue); 6216 Cleanup.setExprNeedsCleanups(true); 6217 } 6218 6219 /// Prepare a conversion of the given expression to an ObjC object 6220 /// pointer type. 6221 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6222 QualType type = E.get()->getType(); 6223 if (type->isObjCObjectPointerType()) { 6224 return CK_BitCast; 6225 } else if (type->isBlockPointerType()) { 6226 maybeExtendBlockObject(E); 6227 return CK_BlockPointerToObjCPointerCast; 6228 } else { 6229 assert(type->isPointerType()); 6230 return CK_CPointerToObjCPointerCast; 6231 } 6232 } 6233 6234 /// Prepares for a scalar cast, performing all the necessary stages 6235 /// except the final cast and returning the kind required. 6236 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6237 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6238 // Also, callers should have filtered out the invalid cases with 6239 // pointers. Everything else should be possible. 6240 6241 QualType SrcTy = Src.get()->getType(); 6242 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6243 return CK_NoOp; 6244 6245 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6246 case Type::STK_MemberPointer: 6247 llvm_unreachable("member pointer type in C"); 6248 6249 case Type::STK_CPointer: 6250 case Type::STK_BlockPointer: 6251 case Type::STK_ObjCObjectPointer: 6252 switch (DestTy->getScalarTypeKind()) { 6253 case Type::STK_CPointer: { 6254 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6255 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6256 if (SrcAS != DestAS) 6257 return CK_AddressSpaceConversion; 6258 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6259 return CK_NoOp; 6260 return CK_BitCast; 6261 } 6262 case Type::STK_BlockPointer: 6263 return (SrcKind == Type::STK_BlockPointer 6264 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6265 case Type::STK_ObjCObjectPointer: 6266 if (SrcKind == Type::STK_ObjCObjectPointer) 6267 return CK_BitCast; 6268 if (SrcKind == Type::STK_CPointer) 6269 return CK_CPointerToObjCPointerCast; 6270 maybeExtendBlockObject(Src); 6271 return CK_BlockPointerToObjCPointerCast; 6272 case Type::STK_Bool: 6273 return CK_PointerToBoolean; 6274 case Type::STK_Integral: 6275 return CK_PointerToIntegral; 6276 case Type::STK_Floating: 6277 case Type::STK_FloatingComplex: 6278 case Type::STK_IntegralComplex: 6279 case Type::STK_MemberPointer: 6280 case Type::STK_FixedPoint: 6281 llvm_unreachable("illegal cast from pointer"); 6282 } 6283 llvm_unreachable("Should have returned before this"); 6284 6285 case Type::STK_FixedPoint: 6286 switch (DestTy->getScalarTypeKind()) { 6287 case Type::STK_FixedPoint: 6288 return CK_FixedPointCast; 6289 case Type::STK_Bool: 6290 return CK_FixedPointToBoolean; 6291 case Type::STK_Integral: 6292 return CK_FixedPointToIntegral; 6293 case Type::STK_Floating: 6294 case Type::STK_IntegralComplex: 6295 case Type::STK_FloatingComplex: 6296 Diag(Src.get()->getExprLoc(), 6297 diag::err_unimplemented_conversion_with_fixed_point_type) 6298 << DestTy; 6299 return CK_IntegralCast; 6300 case Type::STK_CPointer: 6301 case Type::STK_ObjCObjectPointer: 6302 case Type::STK_BlockPointer: 6303 case Type::STK_MemberPointer: 6304 llvm_unreachable("illegal cast to pointer type"); 6305 } 6306 llvm_unreachable("Should have returned before this"); 6307 6308 case Type::STK_Bool: // casting from bool is like casting from an integer 6309 case Type::STK_Integral: 6310 switch (DestTy->getScalarTypeKind()) { 6311 case Type::STK_CPointer: 6312 case Type::STK_ObjCObjectPointer: 6313 case Type::STK_BlockPointer: 6314 if (Src.get()->isNullPointerConstant(Context, 6315 Expr::NPC_ValueDependentIsNull)) 6316 return CK_NullToPointer; 6317 return CK_IntegralToPointer; 6318 case Type::STK_Bool: 6319 return CK_IntegralToBoolean; 6320 case Type::STK_Integral: 6321 return CK_IntegralCast; 6322 case Type::STK_Floating: 6323 return CK_IntegralToFloating; 6324 case Type::STK_IntegralComplex: 6325 Src = ImpCastExprToType(Src.get(), 6326 DestTy->castAs<ComplexType>()->getElementType(), 6327 CK_IntegralCast); 6328 return CK_IntegralRealToComplex; 6329 case Type::STK_FloatingComplex: 6330 Src = ImpCastExprToType(Src.get(), 6331 DestTy->castAs<ComplexType>()->getElementType(), 6332 CK_IntegralToFloating); 6333 return CK_FloatingRealToComplex; 6334 case Type::STK_MemberPointer: 6335 llvm_unreachable("member pointer type in C"); 6336 case Type::STK_FixedPoint: 6337 return CK_IntegralToFixedPoint; 6338 } 6339 llvm_unreachable("Should have returned before this"); 6340 6341 case Type::STK_Floating: 6342 switch (DestTy->getScalarTypeKind()) { 6343 case Type::STK_Floating: 6344 return CK_FloatingCast; 6345 case Type::STK_Bool: 6346 return CK_FloatingToBoolean; 6347 case Type::STK_Integral: 6348 return CK_FloatingToIntegral; 6349 case Type::STK_FloatingComplex: 6350 Src = ImpCastExprToType(Src.get(), 6351 DestTy->castAs<ComplexType>()->getElementType(), 6352 CK_FloatingCast); 6353 return CK_FloatingRealToComplex; 6354 case Type::STK_IntegralComplex: 6355 Src = ImpCastExprToType(Src.get(), 6356 DestTy->castAs<ComplexType>()->getElementType(), 6357 CK_FloatingToIntegral); 6358 return CK_IntegralRealToComplex; 6359 case Type::STK_CPointer: 6360 case Type::STK_ObjCObjectPointer: 6361 case Type::STK_BlockPointer: 6362 llvm_unreachable("valid float->pointer cast?"); 6363 case Type::STK_MemberPointer: 6364 llvm_unreachable("member pointer type in C"); 6365 case Type::STK_FixedPoint: 6366 Diag(Src.get()->getExprLoc(), 6367 diag::err_unimplemented_conversion_with_fixed_point_type) 6368 << SrcTy; 6369 return CK_IntegralCast; 6370 } 6371 llvm_unreachable("Should have returned before this"); 6372 6373 case Type::STK_FloatingComplex: 6374 switch (DestTy->getScalarTypeKind()) { 6375 case Type::STK_FloatingComplex: 6376 return CK_FloatingComplexCast; 6377 case Type::STK_IntegralComplex: 6378 return CK_FloatingComplexToIntegralComplex; 6379 case Type::STK_Floating: { 6380 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6381 if (Context.hasSameType(ET, DestTy)) 6382 return CK_FloatingComplexToReal; 6383 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6384 return CK_FloatingCast; 6385 } 6386 case Type::STK_Bool: 6387 return CK_FloatingComplexToBoolean; 6388 case Type::STK_Integral: 6389 Src = ImpCastExprToType(Src.get(), 6390 SrcTy->castAs<ComplexType>()->getElementType(), 6391 CK_FloatingComplexToReal); 6392 return CK_FloatingToIntegral; 6393 case Type::STK_CPointer: 6394 case Type::STK_ObjCObjectPointer: 6395 case Type::STK_BlockPointer: 6396 llvm_unreachable("valid complex float->pointer cast?"); 6397 case Type::STK_MemberPointer: 6398 llvm_unreachable("member pointer type in C"); 6399 case Type::STK_FixedPoint: 6400 Diag(Src.get()->getExprLoc(), 6401 diag::err_unimplemented_conversion_with_fixed_point_type) 6402 << SrcTy; 6403 return CK_IntegralCast; 6404 } 6405 llvm_unreachable("Should have returned before this"); 6406 6407 case Type::STK_IntegralComplex: 6408 switch (DestTy->getScalarTypeKind()) { 6409 case Type::STK_FloatingComplex: 6410 return CK_IntegralComplexToFloatingComplex; 6411 case Type::STK_IntegralComplex: 6412 return CK_IntegralComplexCast; 6413 case Type::STK_Integral: { 6414 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6415 if (Context.hasSameType(ET, DestTy)) 6416 return CK_IntegralComplexToReal; 6417 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6418 return CK_IntegralCast; 6419 } 6420 case Type::STK_Bool: 6421 return CK_IntegralComplexToBoolean; 6422 case Type::STK_Floating: 6423 Src = ImpCastExprToType(Src.get(), 6424 SrcTy->castAs<ComplexType>()->getElementType(), 6425 CK_IntegralComplexToReal); 6426 return CK_IntegralToFloating; 6427 case Type::STK_CPointer: 6428 case Type::STK_ObjCObjectPointer: 6429 case Type::STK_BlockPointer: 6430 llvm_unreachable("valid complex int->pointer cast?"); 6431 case Type::STK_MemberPointer: 6432 llvm_unreachable("member pointer type in C"); 6433 case Type::STK_FixedPoint: 6434 Diag(Src.get()->getExprLoc(), 6435 diag::err_unimplemented_conversion_with_fixed_point_type) 6436 << SrcTy; 6437 return CK_IntegralCast; 6438 } 6439 llvm_unreachable("Should have returned before this"); 6440 } 6441 6442 llvm_unreachable("Unhandled scalar cast"); 6443 } 6444 6445 static bool breakDownVectorType(QualType type, uint64_t &len, 6446 QualType &eltType) { 6447 // Vectors are simple. 6448 if (const VectorType *vecType = type->getAs<VectorType>()) { 6449 len = vecType->getNumElements(); 6450 eltType = vecType->getElementType(); 6451 assert(eltType->isScalarType()); 6452 return true; 6453 } 6454 6455 // We allow lax conversion to and from non-vector types, but only if 6456 // they're real types (i.e. non-complex, non-pointer scalar types). 6457 if (!type->isRealType()) return false; 6458 6459 len = 1; 6460 eltType = type; 6461 return true; 6462 } 6463 6464 /// Are the two types lax-compatible vector types? That is, given 6465 /// that one of them is a vector, do they have equal storage sizes, 6466 /// where the storage size is the number of elements times the element 6467 /// size? 6468 /// 6469 /// This will also return false if either of the types is neither a 6470 /// vector nor a real type. 6471 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6472 assert(destTy->isVectorType() || srcTy->isVectorType()); 6473 6474 // Disallow lax conversions between scalars and ExtVectors (these 6475 // conversions are allowed for other vector types because common headers 6476 // depend on them). Most scalar OP ExtVector cases are handled by the 6477 // splat path anyway, which does what we want (convert, not bitcast). 6478 // What this rules out for ExtVectors is crazy things like char4*float. 6479 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6480 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6481 6482 uint64_t srcLen, destLen; 6483 QualType srcEltTy, destEltTy; 6484 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6485 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6486 6487 // ASTContext::getTypeSize will return the size rounded up to a 6488 // power of 2, so instead of using that, we need to use the raw 6489 // element size multiplied by the element count. 6490 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6491 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6492 6493 return (srcLen * srcEltSize == destLen * destEltSize); 6494 } 6495 6496 /// Is this a legal conversion between two types, one of which is 6497 /// known to be a vector type? 6498 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6499 assert(destTy->isVectorType() || srcTy->isVectorType()); 6500 6501 switch (Context.getLangOpts().getLaxVectorConversions()) { 6502 case LangOptions::LaxVectorConversionKind::None: 6503 return false; 6504 6505 case LangOptions::LaxVectorConversionKind::Integer: 6506 if (!srcTy->isIntegralOrEnumerationType()) { 6507 auto *Vec = srcTy->getAs<VectorType>(); 6508 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6509 return false; 6510 } 6511 if (!destTy->isIntegralOrEnumerationType()) { 6512 auto *Vec = destTy->getAs<VectorType>(); 6513 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6514 return false; 6515 } 6516 // OK, integer (vector) -> integer (vector) bitcast. 6517 break; 6518 6519 case LangOptions::LaxVectorConversionKind::All: 6520 break; 6521 } 6522 6523 return areLaxCompatibleVectorTypes(srcTy, destTy); 6524 } 6525 6526 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6527 CastKind &Kind) { 6528 assert(VectorTy->isVectorType() && "Not a vector type!"); 6529 6530 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6531 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6532 return Diag(R.getBegin(), 6533 Ty->isVectorType() ? 6534 diag::err_invalid_conversion_between_vectors : 6535 diag::err_invalid_conversion_between_vector_and_integer) 6536 << VectorTy << Ty << R; 6537 } else 6538 return Diag(R.getBegin(), 6539 diag::err_invalid_conversion_between_vector_and_scalar) 6540 << VectorTy << Ty << R; 6541 6542 Kind = CK_BitCast; 6543 return false; 6544 } 6545 6546 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6547 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6548 6549 if (DestElemTy == SplattedExpr->getType()) 6550 return SplattedExpr; 6551 6552 assert(DestElemTy->isFloatingType() || 6553 DestElemTy->isIntegralOrEnumerationType()); 6554 6555 CastKind CK; 6556 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6557 // OpenCL requires that we convert `true` boolean expressions to -1, but 6558 // only when splatting vectors. 6559 if (DestElemTy->isFloatingType()) { 6560 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6561 // in two steps: boolean to signed integral, then to floating. 6562 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6563 CK_BooleanToSignedIntegral); 6564 SplattedExpr = CastExprRes.get(); 6565 CK = CK_IntegralToFloating; 6566 } else { 6567 CK = CK_BooleanToSignedIntegral; 6568 } 6569 } else { 6570 ExprResult CastExprRes = SplattedExpr; 6571 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6572 if (CastExprRes.isInvalid()) 6573 return ExprError(); 6574 SplattedExpr = CastExprRes.get(); 6575 } 6576 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6577 } 6578 6579 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6580 Expr *CastExpr, CastKind &Kind) { 6581 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6582 6583 QualType SrcTy = CastExpr->getType(); 6584 6585 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6586 // an ExtVectorType. 6587 // In OpenCL, casts between vectors of different types are not allowed. 6588 // (See OpenCL 6.2). 6589 if (SrcTy->isVectorType()) { 6590 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6591 (getLangOpts().OpenCL && 6592 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6593 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6594 << DestTy << SrcTy << R; 6595 return ExprError(); 6596 } 6597 Kind = CK_BitCast; 6598 return CastExpr; 6599 } 6600 6601 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6602 // conversion will take place first from scalar to elt type, and then 6603 // splat from elt type to vector. 6604 if (SrcTy->isPointerType()) 6605 return Diag(R.getBegin(), 6606 diag::err_invalid_conversion_between_vector_and_scalar) 6607 << DestTy << SrcTy << R; 6608 6609 Kind = CK_VectorSplat; 6610 return prepareVectorSplat(DestTy, CastExpr); 6611 } 6612 6613 ExprResult 6614 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6615 Declarator &D, ParsedType &Ty, 6616 SourceLocation RParenLoc, Expr *CastExpr) { 6617 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6618 "ActOnCastExpr(): missing type or expr"); 6619 6620 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6621 if (D.isInvalidType()) 6622 return ExprError(); 6623 6624 if (getLangOpts().CPlusPlus) { 6625 // Check that there are no default arguments (C++ only). 6626 CheckExtraCXXDefaultArguments(D); 6627 } else { 6628 // Make sure any TypoExprs have been dealt with. 6629 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6630 if (!Res.isUsable()) 6631 return ExprError(); 6632 CastExpr = Res.get(); 6633 } 6634 6635 checkUnusedDeclAttributes(D); 6636 6637 QualType castType = castTInfo->getType(); 6638 Ty = CreateParsedType(castType, castTInfo); 6639 6640 bool isVectorLiteral = false; 6641 6642 // Check for an altivec or OpenCL literal, 6643 // i.e. all the elements are integer constants. 6644 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6645 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6646 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6647 && castType->isVectorType() && (PE || PLE)) { 6648 if (PLE && PLE->getNumExprs() == 0) { 6649 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6650 return ExprError(); 6651 } 6652 if (PE || PLE->getNumExprs() == 1) { 6653 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6654 if (!E->getType()->isVectorType()) 6655 isVectorLiteral = true; 6656 } 6657 else 6658 isVectorLiteral = true; 6659 } 6660 6661 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6662 // then handle it as such. 6663 if (isVectorLiteral) 6664 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6665 6666 // If the Expr being casted is a ParenListExpr, handle it specially. 6667 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6668 // sequence of BinOp comma operators. 6669 if (isa<ParenListExpr>(CastExpr)) { 6670 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6671 if (Result.isInvalid()) return ExprError(); 6672 CastExpr = Result.get(); 6673 } 6674 6675 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6676 !getSourceManager().isInSystemMacro(LParenLoc)) 6677 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6678 6679 CheckTollFreeBridgeCast(castType, CastExpr); 6680 6681 CheckObjCBridgeRelatedCast(castType, CastExpr); 6682 6683 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6684 6685 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6686 } 6687 6688 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6689 SourceLocation RParenLoc, Expr *E, 6690 TypeSourceInfo *TInfo) { 6691 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6692 "Expected paren or paren list expression"); 6693 6694 Expr **exprs; 6695 unsigned numExprs; 6696 Expr *subExpr; 6697 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6698 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6699 LiteralLParenLoc = PE->getLParenLoc(); 6700 LiteralRParenLoc = PE->getRParenLoc(); 6701 exprs = PE->getExprs(); 6702 numExprs = PE->getNumExprs(); 6703 } else { // isa<ParenExpr> by assertion at function entrance 6704 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6705 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6706 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6707 exprs = &subExpr; 6708 numExprs = 1; 6709 } 6710 6711 QualType Ty = TInfo->getType(); 6712 assert(Ty->isVectorType() && "Expected vector type"); 6713 6714 SmallVector<Expr *, 8> initExprs; 6715 const VectorType *VTy = Ty->getAs<VectorType>(); 6716 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6717 6718 // '(...)' form of vector initialization in AltiVec: the number of 6719 // initializers must be one or must match the size of the vector. 6720 // If a single value is specified in the initializer then it will be 6721 // replicated to all the components of the vector 6722 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6723 // The number of initializers must be one or must match the size of the 6724 // vector. If a single value is specified in the initializer then it will 6725 // be replicated to all the components of the vector 6726 if (numExprs == 1) { 6727 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6728 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6729 if (Literal.isInvalid()) 6730 return ExprError(); 6731 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6732 PrepareScalarCast(Literal, ElemTy)); 6733 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6734 } 6735 else if (numExprs < numElems) { 6736 Diag(E->getExprLoc(), 6737 diag::err_incorrect_number_of_vector_initializers); 6738 return ExprError(); 6739 } 6740 else 6741 initExprs.append(exprs, exprs + numExprs); 6742 } 6743 else { 6744 // For OpenCL, when the number of initializers is a single value, 6745 // it will be replicated to all components of the vector. 6746 if (getLangOpts().OpenCL && 6747 VTy->getVectorKind() == VectorType::GenericVector && 6748 numExprs == 1) { 6749 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6750 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6751 if (Literal.isInvalid()) 6752 return ExprError(); 6753 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6754 PrepareScalarCast(Literal, ElemTy)); 6755 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6756 } 6757 6758 initExprs.append(exprs, exprs + numExprs); 6759 } 6760 // FIXME: This means that pretty-printing the final AST will produce curly 6761 // braces instead of the original commas. 6762 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6763 initExprs, LiteralRParenLoc); 6764 initE->setType(Ty); 6765 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6766 } 6767 6768 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6769 /// the ParenListExpr into a sequence of comma binary operators. 6770 ExprResult 6771 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6772 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6773 if (!E) 6774 return OrigExpr; 6775 6776 ExprResult Result(E->getExpr(0)); 6777 6778 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6779 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6780 E->getExpr(i)); 6781 6782 if (Result.isInvalid()) return ExprError(); 6783 6784 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6785 } 6786 6787 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6788 SourceLocation R, 6789 MultiExprArg Val) { 6790 return ParenListExpr::Create(Context, L, Val, R); 6791 } 6792 6793 /// Emit a specialized diagnostic when one expression is a null pointer 6794 /// constant and the other is not a pointer. Returns true if a diagnostic is 6795 /// emitted. 6796 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6797 SourceLocation QuestionLoc) { 6798 Expr *NullExpr = LHSExpr; 6799 Expr *NonPointerExpr = RHSExpr; 6800 Expr::NullPointerConstantKind NullKind = 6801 NullExpr->isNullPointerConstant(Context, 6802 Expr::NPC_ValueDependentIsNotNull); 6803 6804 if (NullKind == Expr::NPCK_NotNull) { 6805 NullExpr = RHSExpr; 6806 NonPointerExpr = LHSExpr; 6807 NullKind = 6808 NullExpr->isNullPointerConstant(Context, 6809 Expr::NPC_ValueDependentIsNotNull); 6810 } 6811 6812 if (NullKind == Expr::NPCK_NotNull) 6813 return false; 6814 6815 if (NullKind == Expr::NPCK_ZeroExpression) 6816 return false; 6817 6818 if (NullKind == Expr::NPCK_ZeroLiteral) { 6819 // In this case, check to make sure that we got here from a "NULL" 6820 // string in the source code. 6821 NullExpr = NullExpr->IgnoreParenImpCasts(); 6822 SourceLocation loc = NullExpr->getExprLoc(); 6823 if (!findMacroSpelling(loc, "NULL")) 6824 return false; 6825 } 6826 6827 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6828 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6829 << NonPointerExpr->getType() << DiagType 6830 << NonPointerExpr->getSourceRange(); 6831 return true; 6832 } 6833 6834 /// Return false if the condition expression is valid, true otherwise. 6835 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6836 QualType CondTy = Cond->getType(); 6837 6838 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6839 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6840 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6841 << CondTy << Cond->getSourceRange(); 6842 return true; 6843 } 6844 6845 // C99 6.5.15p2 6846 if (CondTy->isScalarType()) return false; 6847 6848 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6849 << CondTy << Cond->getSourceRange(); 6850 return true; 6851 } 6852 6853 /// Handle when one or both operands are void type. 6854 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6855 ExprResult &RHS) { 6856 Expr *LHSExpr = LHS.get(); 6857 Expr *RHSExpr = RHS.get(); 6858 6859 if (!LHSExpr->getType()->isVoidType()) 6860 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6861 << RHSExpr->getSourceRange(); 6862 if (!RHSExpr->getType()->isVoidType()) 6863 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6864 << LHSExpr->getSourceRange(); 6865 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6866 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6867 return S.Context.VoidTy; 6868 } 6869 6870 /// Return false if the NullExpr can be promoted to PointerTy, 6871 /// true otherwise. 6872 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6873 QualType PointerTy) { 6874 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6875 !NullExpr.get()->isNullPointerConstant(S.Context, 6876 Expr::NPC_ValueDependentIsNull)) 6877 return true; 6878 6879 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6880 return false; 6881 } 6882 6883 /// Checks compatibility between two pointers and return the resulting 6884 /// type. 6885 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6886 ExprResult &RHS, 6887 SourceLocation Loc) { 6888 QualType LHSTy = LHS.get()->getType(); 6889 QualType RHSTy = RHS.get()->getType(); 6890 6891 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6892 // Two identical pointers types are always compatible. 6893 return LHSTy; 6894 } 6895 6896 QualType lhptee, rhptee; 6897 6898 // Get the pointee types. 6899 bool IsBlockPointer = false; 6900 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6901 lhptee = LHSBTy->getPointeeType(); 6902 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6903 IsBlockPointer = true; 6904 } else { 6905 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6906 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6907 } 6908 6909 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6910 // differently qualified versions of compatible types, the result type is 6911 // a pointer to an appropriately qualified version of the composite 6912 // type. 6913 6914 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6915 // clause doesn't make sense for our extensions. E.g. address space 2 should 6916 // be incompatible with address space 3: they may live on different devices or 6917 // anything. 6918 Qualifiers lhQual = lhptee.getQualifiers(); 6919 Qualifiers rhQual = rhptee.getQualifiers(); 6920 6921 LangAS ResultAddrSpace = LangAS::Default; 6922 LangAS LAddrSpace = lhQual.getAddressSpace(); 6923 LangAS RAddrSpace = rhQual.getAddressSpace(); 6924 6925 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6926 // spaces is disallowed. 6927 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6928 ResultAddrSpace = LAddrSpace; 6929 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6930 ResultAddrSpace = RAddrSpace; 6931 else { 6932 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6933 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6934 << RHS.get()->getSourceRange(); 6935 return QualType(); 6936 } 6937 6938 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6939 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6940 lhQual.removeCVRQualifiers(); 6941 rhQual.removeCVRQualifiers(); 6942 6943 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6944 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6945 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6946 // qual types are compatible iff 6947 // * corresponded types are compatible 6948 // * CVR qualifiers are equal 6949 // * address spaces are equal 6950 // Thus for conditional operator we merge CVR and address space unqualified 6951 // pointees and if there is a composite type we return a pointer to it with 6952 // merged qualifiers. 6953 LHSCastKind = 6954 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6955 RHSCastKind = 6956 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6957 lhQual.removeAddressSpace(); 6958 rhQual.removeAddressSpace(); 6959 6960 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6961 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6962 6963 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6964 6965 if (CompositeTy.isNull()) { 6966 // In this situation, we assume void* type. No especially good 6967 // reason, but this is what gcc does, and we do have to pick 6968 // to get a consistent AST. 6969 QualType incompatTy; 6970 incompatTy = S.Context.getPointerType( 6971 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6972 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6973 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6974 6975 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6976 // for casts between types with incompatible address space qualifiers. 6977 // For the following code the compiler produces casts between global and 6978 // local address spaces of the corresponded innermost pointees: 6979 // local int *global *a; 6980 // global int *global *b; 6981 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6982 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6983 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6984 << RHS.get()->getSourceRange(); 6985 6986 return incompatTy; 6987 } 6988 6989 // The pointer types are compatible. 6990 // In case of OpenCL ResultTy should have the address space qualifier 6991 // which is a superset of address spaces of both the 2nd and the 3rd 6992 // operands of the conditional operator. 6993 QualType ResultTy = [&, ResultAddrSpace]() { 6994 if (S.getLangOpts().OpenCL) { 6995 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6996 CompositeQuals.setAddressSpace(ResultAddrSpace); 6997 return S.Context 6998 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6999 .withCVRQualifiers(MergedCVRQual); 7000 } 7001 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7002 }(); 7003 if (IsBlockPointer) 7004 ResultTy = S.Context.getBlockPointerType(ResultTy); 7005 else 7006 ResultTy = S.Context.getPointerType(ResultTy); 7007 7008 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7009 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7010 return ResultTy; 7011 } 7012 7013 /// Return the resulting type when the operands are both block pointers. 7014 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7015 ExprResult &LHS, 7016 ExprResult &RHS, 7017 SourceLocation Loc) { 7018 QualType LHSTy = LHS.get()->getType(); 7019 QualType RHSTy = RHS.get()->getType(); 7020 7021 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7022 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7023 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7024 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7025 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7026 return destType; 7027 } 7028 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7029 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7030 << RHS.get()->getSourceRange(); 7031 return QualType(); 7032 } 7033 7034 // We have 2 block pointer types. 7035 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7036 } 7037 7038 /// Return the resulting type when the operands are both pointers. 7039 static QualType 7040 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7041 ExprResult &RHS, 7042 SourceLocation Loc) { 7043 // get the pointer types 7044 QualType LHSTy = LHS.get()->getType(); 7045 QualType RHSTy = RHS.get()->getType(); 7046 7047 // get the "pointed to" types 7048 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7049 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7050 7051 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7052 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7053 // Figure out necessary qualifiers (C99 6.5.15p6) 7054 QualType destPointee 7055 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7056 QualType destType = S.Context.getPointerType(destPointee); 7057 // Add qualifiers if necessary. 7058 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7059 // Promote to void*. 7060 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7061 return destType; 7062 } 7063 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7064 QualType destPointee 7065 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7066 QualType destType = S.Context.getPointerType(destPointee); 7067 // Add qualifiers if necessary. 7068 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7069 // Promote to void*. 7070 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7071 return destType; 7072 } 7073 7074 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7075 } 7076 7077 /// Return false if the first expression is not an integer and the second 7078 /// expression is not a pointer, true otherwise. 7079 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7080 Expr* PointerExpr, SourceLocation Loc, 7081 bool IsIntFirstExpr) { 7082 if (!PointerExpr->getType()->isPointerType() || 7083 !Int.get()->getType()->isIntegerType()) 7084 return false; 7085 7086 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7087 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7088 7089 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7090 << Expr1->getType() << Expr2->getType() 7091 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7092 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7093 CK_IntegralToPointer); 7094 return true; 7095 } 7096 7097 /// Simple conversion between integer and floating point types. 7098 /// 7099 /// Used when handling the OpenCL conditional operator where the 7100 /// condition is a vector while the other operands are scalar. 7101 /// 7102 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7103 /// types are either integer or floating type. Between the two 7104 /// operands, the type with the higher rank is defined as the "result 7105 /// type". The other operand needs to be promoted to the same type. No 7106 /// other type promotion is allowed. We cannot use 7107 /// UsualArithmeticConversions() for this purpose, since it always 7108 /// promotes promotable types. 7109 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7110 ExprResult &RHS, 7111 SourceLocation QuestionLoc) { 7112 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7113 if (LHS.isInvalid()) 7114 return QualType(); 7115 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7116 if (RHS.isInvalid()) 7117 return QualType(); 7118 7119 // For conversion purposes, we ignore any qualifiers. 7120 // For example, "const float" and "float" are equivalent. 7121 QualType LHSType = 7122 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7123 QualType RHSType = 7124 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7125 7126 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7127 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7128 << LHSType << LHS.get()->getSourceRange(); 7129 return QualType(); 7130 } 7131 7132 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7133 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7134 << RHSType << RHS.get()->getSourceRange(); 7135 return QualType(); 7136 } 7137 7138 // If both types are identical, no conversion is needed. 7139 if (LHSType == RHSType) 7140 return LHSType; 7141 7142 // Now handle "real" floating types (i.e. float, double, long double). 7143 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7144 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7145 /*IsCompAssign = */ false); 7146 7147 // Finally, we have two differing integer types. 7148 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7149 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7150 } 7151 7152 /// Convert scalar operands to a vector that matches the 7153 /// condition in length. 7154 /// 7155 /// Used when handling the OpenCL conditional operator where the 7156 /// condition is a vector while the other operands are scalar. 7157 /// 7158 /// We first compute the "result type" for the scalar operands 7159 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7160 /// into a vector of that type where the length matches the condition 7161 /// vector type. s6.11.6 requires that the element types of the result 7162 /// and the condition must have the same number of bits. 7163 static QualType 7164 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7165 QualType CondTy, SourceLocation QuestionLoc) { 7166 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7167 if (ResTy.isNull()) return QualType(); 7168 7169 const VectorType *CV = CondTy->getAs<VectorType>(); 7170 assert(CV); 7171 7172 // Determine the vector result type 7173 unsigned NumElements = CV->getNumElements(); 7174 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7175 7176 // Ensure that all types have the same number of bits 7177 if (S.Context.getTypeSize(CV->getElementType()) 7178 != S.Context.getTypeSize(ResTy)) { 7179 // Since VectorTy is created internally, it does not pretty print 7180 // with an OpenCL name. Instead, we just print a description. 7181 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7182 SmallString<64> Str; 7183 llvm::raw_svector_ostream OS(Str); 7184 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7185 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7186 << CondTy << OS.str(); 7187 return QualType(); 7188 } 7189 7190 // Convert operands to the vector result type 7191 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7192 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7193 7194 return VectorTy; 7195 } 7196 7197 /// Return false if this is a valid OpenCL condition vector 7198 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7199 SourceLocation QuestionLoc) { 7200 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7201 // integral type. 7202 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7203 assert(CondTy); 7204 QualType EleTy = CondTy->getElementType(); 7205 if (EleTy->isIntegerType()) return false; 7206 7207 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7208 << Cond->getType() << Cond->getSourceRange(); 7209 return true; 7210 } 7211 7212 /// Return false if the vector condition type and the vector 7213 /// result type are compatible. 7214 /// 7215 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7216 /// number of elements, and their element types have the same number 7217 /// of bits. 7218 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7219 SourceLocation QuestionLoc) { 7220 const VectorType *CV = CondTy->getAs<VectorType>(); 7221 const VectorType *RV = VecResTy->getAs<VectorType>(); 7222 assert(CV && RV); 7223 7224 if (CV->getNumElements() != RV->getNumElements()) { 7225 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7226 << CondTy << VecResTy; 7227 return true; 7228 } 7229 7230 QualType CVE = CV->getElementType(); 7231 QualType RVE = RV->getElementType(); 7232 7233 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7234 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7235 << CondTy << VecResTy; 7236 return true; 7237 } 7238 7239 return false; 7240 } 7241 7242 /// Return the resulting type for the conditional operator in 7243 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7244 /// s6.3.i) when the condition is a vector type. 7245 static QualType 7246 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7247 ExprResult &LHS, ExprResult &RHS, 7248 SourceLocation QuestionLoc) { 7249 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7250 if (Cond.isInvalid()) 7251 return QualType(); 7252 QualType CondTy = Cond.get()->getType(); 7253 7254 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7255 return QualType(); 7256 7257 // If either operand is a vector then find the vector type of the 7258 // result as specified in OpenCL v1.1 s6.3.i. 7259 if (LHS.get()->getType()->isVectorType() || 7260 RHS.get()->getType()->isVectorType()) { 7261 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7262 /*isCompAssign*/false, 7263 /*AllowBothBool*/true, 7264 /*AllowBoolConversions*/false); 7265 if (VecResTy.isNull()) return QualType(); 7266 // The result type must match the condition type as specified in 7267 // OpenCL v1.1 s6.11.6. 7268 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7269 return QualType(); 7270 return VecResTy; 7271 } 7272 7273 // Both operands are scalar. 7274 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7275 } 7276 7277 /// Return true if the Expr is block type 7278 static bool checkBlockType(Sema &S, const Expr *E) { 7279 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7280 QualType Ty = CE->getCallee()->getType(); 7281 if (Ty->isBlockPointerType()) { 7282 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7283 return true; 7284 } 7285 } 7286 return false; 7287 } 7288 7289 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7290 /// In that case, LHS = cond. 7291 /// C99 6.5.15 7292 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7293 ExprResult &RHS, ExprValueKind &VK, 7294 ExprObjectKind &OK, 7295 SourceLocation QuestionLoc) { 7296 7297 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7298 if (!LHSResult.isUsable()) return QualType(); 7299 LHS = LHSResult; 7300 7301 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7302 if (!RHSResult.isUsable()) return QualType(); 7303 RHS = RHSResult; 7304 7305 // C++ is sufficiently different to merit its own checker. 7306 if (getLangOpts().CPlusPlus) 7307 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7308 7309 VK = VK_RValue; 7310 OK = OK_Ordinary; 7311 7312 // The OpenCL operator with a vector condition is sufficiently 7313 // different to merit its own checker. 7314 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7315 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7316 7317 // First, check the condition. 7318 Cond = UsualUnaryConversions(Cond.get()); 7319 if (Cond.isInvalid()) 7320 return QualType(); 7321 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7322 return QualType(); 7323 7324 // Now check the two expressions. 7325 if (LHS.get()->getType()->isVectorType() || 7326 RHS.get()->getType()->isVectorType()) 7327 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7328 /*AllowBothBool*/true, 7329 /*AllowBoolConversions*/false); 7330 7331 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7332 if (LHS.isInvalid() || RHS.isInvalid()) 7333 return QualType(); 7334 7335 QualType LHSTy = LHS.get()->getType(); 7336 QualType RHSTy = RHS.get()->getType(); 7337 7338 // Diagnose attempts to convert between __float128 and long double where 7339 // such conversions currently can't be handled. 7340 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7341 Diag(QuestionLoc, 7342 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7344 return QualType(); 7345 } 7346 7347 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7348 // selection operator (?:). 7349 if (getLangOpts().OpenCL && 7350 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7351 return QualType(); 7352 } 7353 7354 // If both operands have arithmetic type, do the usual arithmetic conversions 7355 // to find a common type: C99 6.5.15p3,5. 7356 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7357 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7358 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7359 7360 return ResTy; 7361 } 7362 7363 // If both operands are the same structure or union type, the result is that 7364 // type. 7365 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7366 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7367 if (LHSRT->getDecl() == RHSRT->getDecl()) 7368 // "If both the operands have structure or union type, the result has 7369 // that type." This implies that CV qualifiers are dropped. 7370 return LHSTy.getUnqualifiedType(); 7371 // FIXME: Type of conditional expression must be complete in C mode. 7372 } 7373 7374 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7375 // The following || allows only one side to be void (a GCC-ism). 7376 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7377 return checkConditionalVoidType(*this, LHS, RHS); 7378 } 7379 7380 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7381 // the type of the other operand." 7382 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7383 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7384 7385 // All objective-c pointer type analysis is done here. 7386 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7387 QuestionLoc); 7388 if (LHS.isInvalid() || RHS.isInvalid()) 7389 return QualType(); 7390 if (!compositeType.isNull()) 7391 return compositeType; 7392 7393 7394 // Handle block pointer types. 7395 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7396 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7397 QuestionLoc); 7398 7399 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7400 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7401 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7402 QuestionLoc); 7403 7404 // GCC compatibility: soften pointer/integer mismatch. Note that 7405 // null pointers have been filtered out by this point. 7406 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7407 /*IsIntFirstExpr=*/true)) 7408 return RHSTy; 7409 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7410 /*IsIntFirstExpr=*/false)) 7411 return LHSTy; 7412 7413 // Emit a better diagnostic if one of the expressions is a null pointer 7414 // constant and the other is not a pointer type. In this case, the user most 7415 // likely forgot to take the address of the other expression. 7416 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7417 return QualType(); 7418 7419 // Otherwise, the operands are not compatible. 7420 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7421 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7422 << RHS.get()->getSourceRange(); 7423 return QualType(); 7424 } 7425 7426 /// FindCompositeObjCPointerType - Helper method to find composite type of 7427 /// two objective-c pointer types of the two input expressions. 7428 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7429 SourceLocation QuestionLoc) { 7430 QualType LHSTy = LHS.get()->getType(); 7431 QualType RHSTy = RHS.get()->getType(); 7432 7433 // Handle things like Class and struct objc_class*. Here we case the result 7434 // to the pseudo-builtin, because that will be implicitly cast back to the 7435 // redefinition type if an attempt is made to access its fields. 7436 if (LHSTy->isObjCClassType() && 7437 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7438 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7439 return LHSTy; 7440 } 7441 if (RHSTy->isObjCClassType() && 7442 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7443 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7444 return RHSTy; 7445 } 7446 // And the same for struct objc_object* / id 7447 if (LHSTy->isObjCIdType() && 7448 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7449 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7450 return LHSTy; 7451 } 7452 if (RHSTy->isObjCIdType() && 7453 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7454 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7455 return RHSTy; 7456 } 7457 // And the same for struct objc_selector* / SEL 7458 if (Context.isObjCSelType(LHSTy) && 7459 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7460 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7461 return LHSTy; 7462 } 7463 if (Context.isObjCSelType(RHSTy) && 7464 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7465 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7466 return RHSTy; 7467 } 7468 // Check constraints for Objective-C object pointers types. 7469 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7470 7471 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7472 // Two identical object pointer types are always compatible. 7473 return LHSTy; 7474 } 7475 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7476 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7477 QualType compositeType = LHSTy; 7478 7479 // If both operands are interfaces and either operand can be 7480 // assigned to the other, use that type as the composite 7481 // type. This allows 7482 // xxx ? (A*) a : (B*) b 7483 // where B is a subclass of A. 7484 // 7485 // Additionally, as for assignment, if either type is 'id' 7486 // allow silent coercion. Finally, if the types are 7487 // incompatible then make sure to use 'id' as the composite 7488 // type so the result is acceptable for sending messages to. 7489 7490 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7491 // It could return the composite type. 7492 if (!(compositeType = 7493 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7494 // Nothing more to do. 7495 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7496 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7497 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7498 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7499 } else if ((LHSTy->isObjCQualifiedIdType() || 7500 RHSTy->isObjCQualifiedIdType()) && 7501 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7502 // Need to handle "id<xx>" explicitly. 7503 // GCC allows qualified id and any Objective-C type to devolve to 7504 // id. Currently localizing to here until clear this should be 7505 // part of ObjCQualifiedIdTypesAreCompatible. 7506 compositeType = Context.getObjCIdType(); 7507 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7508 compositeType = Context.getObjCIdType(); 7509 } else { 7510 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7511 << LHSTy << RHSTy 7512 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7513 QualType incompatTy = Context.getObjCIdType(); 7514 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7515 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7516 return incompatTy; 7517 } 7518 // The object pointer types are compatible. 7519 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7520 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7521 return compositeType; 7522 } 7523 // Check Objective-C object pointer types and 'void *' 7524 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7525 if (getLangOpts().ObjCAutoRefCount) { 7526 // ARC forbids the implicit conversion of object pointers to 'void *', 7527 // so these types are not compatible. 7528 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7529 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7530 LHS = RHS = true; 7531 return QualType(); 7532 } 7533 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7534 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7535 QualType destPointee 7536 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7537 QualType destType = Context.getPointerType(destPointee); 7538 // Add qualifiers if necessary. 7539 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7540 // Promote to void*. 7541 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7542 return destType; 7543 } 7544 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7545 if (getLangOpts().ObjCAutoRefCount) { 7546 // ARC forbids the implicit conversion of object pointers to 'void *', 7547 // so these types are not compatible. 7548 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7550 LHS = RHS = true; 7551 return QualType(); 7552 } 7553 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7554 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7555 QualType destPointee 7556 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7557 QualType destType = Context.getPointerType(destPointee); 7558 // Add qualifiers if necessary. 7559 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7560 // Promote to void*. 7561 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7562 return destType; 7563 } 7564 return QualType(); 7565 } 7566 7567 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7568 /// ParenRange in parentheses. 7569 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7570 const PartialDiagnostic &Note, 7571 SourceRange ParenRange) { 7572 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7573 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7574 EndLoc.isValid()) { 7575 Self.Diag(Loc, Note) 7576 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7577 << FixItHint::CreateInsertion(EndLoc, ")"); 7578 } else { 7579 // We can't display the parentheses, so just show the bare note. 7580 Self.Diag(Loc, Note) << ParenRange; 7581 } 7582 } 7583 7584 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7585 return BinaryOperator::isAdditiveOp(Opc) || 7586 BinaryOperator::isMultiplicativeOp(Opc) || 7587 BinaryOperator::isShiftOp(Opc); 7588 } 7589 7590 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7591 /// expression, either using a built-in or overloaded operator, 7592 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7593 /// expression. 7594 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7595 Expr **RHSExprs) { 7596 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7597 E = E->IgnoreImpCasts(); 7598 E = E->IgnoreConversionOperator(); 7599 E = E->IgnoreImpCasts(); 7600 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7601 E = MTE->GetTemporaryExpr(); 7602 E = E->IgnoreImpCasts(); 7603 } 7604 7605 // Built-in binary operator. 7606 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7607 if (IsArithmeticOp(OP->getOpcode())) { 7608 *Opcode = OP->getOpcode(); 7609 *RHSExprs = OP->getRHS(); 7610 return true; 7611 } 7612 } 7613 7614 // Overloaded operator. 7615 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7616 if (Call->getNumArgs() != 2) 7617 return false; 7618 7619 // Make sure this is really a binary operator that is safe to pass into 7620 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7621 OverloadedOperatorKind OO = Call->getOperator(); 7622 if (OO < OO_Plus || OO > OO_Arrow || 7623 OO == OO_PlusPlus || OO == OO_MinusMinus) 7624 return false; 7625 7626 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7627 if (IsArithmeticOp(OpKind)) { 7628 *Opcode = OpKind; 7629 *RHSExprs = Call->getArg(1); 7630 return true; 7631 } 7632 } 7633 7634 return false; 7635 } 7636 7637 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7638 /// or is a logical expression such as (x==y) which has int type, but is 7639 /// commonly interpreted as boolean. 7640 static bool ExprLooksBoolean(Expr *E) { 7641 E = E->IgnoreParenImpCasts(); 7642 7643 if (E->getType()->isBooleanType()) 7644 return true; 7645 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7646 return OP->isComparisonOp() || OP->isLogicalOp(); 7647 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7648 return OP->getOpcode() == UO_LNot; 7649 if (E->getType()->isPointerType()) 7650 return true; 7651 // FIXME: What about overloaded operator calls returning "unspecified boolean 7652 // type"s (commonly pointer-to-members)? 7653 7654 return false; 7655 } 7656 7657 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7658 /// and binary operator are mixed in a way that suggests the programmer assumed 7659 /// the conditional operator has higher precedence, for example: 7660 /// "int x = a + someBinaryCondition ? 1 : 2". 7661 static void DiagnoseConditionalPrecedence(Sema &Self, 7662 SourceLocation OpLoc, 7663 Expr *Condition, 7664 Expr *LHSExpr, 7665 Expr *RHSExpr) { 7666 BinaryOperatorKind CondOpcode; 7667 Expr *CondRHS; 7668 7669 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7670 return; 7671 if (!ExprLooksBoolean(CondRHS)) 7672 return; 7673 7674 // The condition is an arithmetic binary expression, with a right- 7675 // hand side that looks boolean, so warn. 7676 7677 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7678 << Condition->getSourceRange() 7679 << BinaryOperator::getOpcodeStr(CondOpcode); 7680 7681 SuggestParentheses( 7682 Self, OpLoc, 7683 Self.PDiag(diag::note_precedence_silence) 7684 << BinaryOperator::getOpcodeStr(CondOpcode), 7685 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7686 7687 SuggestParentheses(Self, OpLoc, 7688 Self.PDiag(diag::note_precedence_conditional_first), 7689 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7690 } 7691 7692 /// Compute the nullability of a conditional expression. 7693 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7694 QualType LHSTy, QualType RHSTy, 7695 ASTContext &Ctx) { 7696 if (!ResTy->isAnyPointerType()) 7697 return ResTy; 7698 7699 auto GetNullability = [&Ctx](QualType Ty) { 7700 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7701 if (Kind) 7702 return *Kind; 7703 return NullabilityKind::Unspecified; 7704 }; 7705 7706 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7707 NullabilityKind MergedKind; 7708 7709 // Compute nullability of a binary conditional expression. 7710 if (IsBin) { 7711 if (LHSKind == NullabilityKind::NonNull) 7712 MergedKind = NullabilityKind::NonNull; 7713 else 7714 MergedKind = RHSKind; 7715 // Compute nullability of a normal conditional expression. 7716 } else { 7717 if (LHSKind == NullabilityKind::Nullable || 7718 RHSKind == NullabilityKind::Nullable) 7719 MergedKind = NullabilityKind::Nullable; 7720 else if (LHSKind == NullabilityKind::NonNull) 7721 MergedKind = RHSKind; 7722 else if (RHSKind == NullabilityKind::NonNull) 7723 MergedKind = LHSKind; 7724 else 7725 MergedKind = NullabilityKind::Unspecified; 7726 } 7727 7728 // Return if ResTy already has the correct nullability. 7729 if (GetNullability(ResTy) == MergedKind) 7730 return ResTy; 7731 7732 // Strip all nullability from ResTy. 7733 while (ResTy->getNullability(Ctx)) 7734 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7735 7736 // Create a new AttributedType with the new nullability kind. 7737 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7738 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7739 } 7740 7741 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7742 /// in the case of a the GNU conditional expr extension. 7743 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7744 SourceLocation ColonLoc, 7745 Expr *CondExpr, Expr *LHSExpr, 7746 Expr *RHSExpr) { 7747 if (!getLangOpts().CPlusPlus) { 7748 // C cannot handle TypoExpr nodes in the condition because it 7749 // doesn't handle dependent types properly, so make sure any TypoExprs have 7750 // been dealt with before checking the operands. 7751 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7752 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7753 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7754 7755 if (!CondResult.isUsable()) 7756 return ExprError(); 7757 7758 if (LHSExpr) { 7759 if (!LHSResult.isUsable()) 7760 return ExprError(); 7761 } 7762 7763 if (!RHSResult.isUsable()) 7764 return ExprError(); 7765 7766 CondExpr = CondResult.get(); 7767 LHSExpr = LHSResult.get(); 7768 RHSExpr = RHSResult.get(); 7769 } 7770 7771 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7772 // was the condition. 7773 OpaqueValueExpr *opaqueValue = nullptr; 7774 Expr *commonExpr = nullptr; 7775 if (!LHSExpr) { 7776 commonExpr = CondExpr; 7777 // Lower out placeholder types first. This is important so that we don't 7778 // try to capture a placeholder. This happens in few cases in C++; such 7779 // as Objective-C++'s dictionary subscripting syntax. 7780 if (commonExpr->hasPlaceholderType()) { 7781 ExprResult result = CheckPlaceholderExpr(commonExpr); 7782 if (!result.isUsable()) return ExprError(); 7783 commonExpr = result.get(); 7784 } 7785 // We usually want to apply unary conversions *before* saving, except 7786 // in the special case of a C++ l-value conditional. 7787 if (!(getLangOpts().CPlusPlus 7788 && !commonExpr->isTypeDependent() 7789 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7790 && commonExpr->isGLValue() 7791 && commonExpr->isOrdinaryOrBitFieldObject() 7792 && RHSExpr->isOrdinaryOrBitFieldObject() 7793 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7794 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7795 if (commonRes.isInvalid()) 7796 return ExprError(); 7797 commonExpr = commonRes.get(); 7798 } 7799 7800 // If the common expression is a class or array prvalue, materialize it 7801 // so that we can safely refer to it multiple times. 7802 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7803 commonExpr->getType()->isArrayType())) { 7804 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7805 if (MatExpr.isInvalid()) 7806 return ExprError(); 7807 commonExpr = MatExpr.get(); 7808 } 7809 7810 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7811 commonExpr->getType(), 7812 commonExpr->getValueKind(), 7813 commonExpr->getObjectKind(), 7814 commonExpr); 7815 LHSExpr = CondExpr = opaqueValue; 7816 } 7817 7818 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7819 ExprValueKind VK = VK_RValue; 7820 ExprObjectKind OK = OK_Ordinary; 7821 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7822 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7823 VK, OK, QuestionLoc); 7824 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7825 RHS.isInvalid()) 7826 return ExprError(); 7827 7828 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7829 RHS.get()); 7830 7831 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7832 7833 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7834 Context); 7835 7836 if (!commonExpr) 7837 return new (Context) 7838 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7839 RHS.get(), result, VK, OK); 7840 7841 return new (Context) BinaryConditionalOperator( 7842 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7843 ColonLoc, result, VK, OK); 7844 } 7845 7846 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7847 // being closely modeled after the C99 spec:-). The odd characteristic of this 7848 // routine is it effectively iqnores the qualifiers on the top level pointee. 7849 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7850 // FIXME: add a couple examples in this comment. 7851 static Sema::AssignConvertType 7852 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7853 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7854 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7855 7856 // get the "pointed to" type (ignoring qualifiers at the top level) 7857 const Type *lhptee, *rhptee; 7858 Qualifiers lhq, rhq; 7859 std::tie(lhptee, lhq) = 7860 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7861 std::tie(rhptee, rhq) = 7862 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7863 7864 Sema::AssignConvertType ConvTy = Sema::Compatible; 7865 7866 // C99 6.5.16.1p1: This following citation is common to constraints 7867 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7868 // qualifiers of the type *pointed to* by the right; 7869 7870 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7871 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7872 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7873 // Ignore lifetime for further calculation. 7874 lhq.removeObjCLifetime(); 7875 rhq.removeObjCLifetime(); 7876 } 7877 7878 if (!lhq.compatiblyIncludes(rhq)) { 7879 // Treat address-space mismatches as fatal. 7880 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7881 return Sema::IncompatiblePointerDiscardsQualifiers; 7882 7883 // It's okay to add or remove GC or lifetime qualifiers when converting to 7884 // and from void*. 7885 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7886 .compatiblyIncludes( 7887 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7888 && (lhptee->isVoidType() || rhptee->isVoidType())) 7889 ; // keep old 7890 7891 // Treat lifetime mismatches as fatal. 7892 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7893 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7894 7895 // For GCC/MS compatibility, other qualifier mismatches are treated 7896 // as still compatible in C. 7897 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7898 } 7899 7900 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7901 // incomplete type and the other is a pointer to a qualified or unqualified 7902 // version of void... 7903 if (lhptee->isVoidType()) { 7904 if (rhptee->isIncompleteOrObjectType()) 7905 return ConvTy; 7906 7907 // As an extension, we allow cast to/from void* to function pointer. 7908 assert(rhptee->isFunctionType()); 7909 return Sema::FunctionVoidPointer; 7910 } 7911 7912 if (rhptee->isVoidType()) { 7913 if (lhptee->isIncompleteOrObjectType()) 7914 return ConvTy; 7915 7916 // As an extension, we allow cast to/from void* to function pointer. 7917 assert(lhptee->isFunctionType()); 7918 return Sema::FunctionVoidPointer; 7919 } 7920 7921 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7922 // unqualified versions of compatible types, ... 7923 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7924 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7925 // Check if the pointee types are compatible ignoring the sign. 7926 // We explicitly check for char so that we catch "char" vs 7927 // "unsigned char" on systems where "char" is unsigned. 7928 if (lhptee->isCharType()) 7929 ltrans = S.Context.UnsignedCharTy; 7930 else if (lhptee->hasSignedIntegerRepresentation()) 7931 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7932 7933 if (rhptee->isCharType()) 7934 rtrans = S.Context.UnsignedCharTy; 7935 else if (rhptee->hasSignedIntegerRepresentation()) 7936 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7937 7938 if (ltrans == rtrans) { 7939 // Types are compatible ignoring the sign. Qualifier incompatibility 7940 // takes priority over sign incompatibility because the sign 7941 // warning can be disabled. 7942 if (ConvTy != Sema::Compatible) 7943 return ConvTy; 7944 7945 return Sema::IncompatiblePointerSign; 7946 } 7947 7948 // If we are a multi-level pointer, it's possible that our issue is simply 7949 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7950 // the eventual target type is the same and the pointers have the same 7951 // level of indirection, this must be the issue. 7952 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7953 do { 7954 std::tie(lhptee, lhq) = 7955 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 7956 std::tie(rhptee, rhq) = 7957 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 7958 7959 // Inconsistent address spaces at this point is invalid, even if the 7960 // address spaces would be compatible. 7961 // FIXME: This doesn't catch address space mismatches for pointers of 7962 // different nesting levels, like: 7963 // __local int *** a; 7964 // int ** b = a; 7965 // It's not clear how to actually determine when such pointers are 7966 // invalidly incompatible. 7967 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 7968 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 7969 7970 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7971 7972 if (lhptee == rhptee) 7973 return Sema::IncompatibleNestedPointerQualifiers; 7974 } 7975 7976 // General pointer incompatibility takes priority over qualifiers. 7977 return Sema::IncompatiblePointer; 7978 } 7979 if (!S.getLangOpts().CPlusPlus && 7980 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7981 return Sema::IncompatiblePointer; 7982 return ConvTy; 7983 } 7984 7985 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7986 /// block pointer types are compatible or whether a block and normal pointer 7987 /// are compatible. It is more restrict than comparing two function pointer 7988 // types. 7989 static Sema::AssignConvertType 7990 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7991 QualType RHSType) { 7992 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7993 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7994 7995 QualType lhptee, rhptee; 7996 7997 // get the "pointed to" type (ignoring qualifiers at the top level) 7998 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7999 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8000 8001 // In C++, the types have to match exactly. 8002 if (S.getLangOpts().CPlusPlus) 8003 return Sema::IncompatibleBlockPointer; 8004 8005 Sema::AssignConvertType ConvTy = Sema::Compatible; 8006 8007 // For blocks we enforce that qualifiers are identical. 8008 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8009 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8010 if (S.getLangOpts().OpenCL) { 8011 LQuals.removeAddressSpace(); 8012 RQuals.removeAddressSpace(); 8013 } 8014 if (LQuals != RQuals) 8015 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8016 8017 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8018 // assignment. 8019 // The current behavior is similar to C++ lambdas. A block might be 8020 // assigned to a variable iff its return type and parameters are compatible 8021 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8022 // an assignment. Presumably it should behave in way that a function pointer 8023 // assignment does in C, so for each parameter and return type: 8024 // * CVR and address space of LHS should be a superset of CVR and address 8025 // space of RHS. 8026 // * unqualified types should be compatible. 8027 if (S.getLangOpts().OpenCL) { 8028 if (!S.Context.typesAreBlockPointerCompatible( 8029 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8030 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8031 return Sema::IncompatibleBlockPointer; 8032 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8033 return Sema::IncompatibleBlockPointer; 8034 8035 return ConvTy; 8036 } 8037 8038 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8039 /// for assignment compatibility. 8040 static Sema::AssignConvertType 8041 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8042 QualType RHSType) { 8043 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8044 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8045 8046 if (LHSType->isObjCBuiltinType()) { 8047 // Class is not compatible with ObjC object pointers. 8048 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8049 !RHSType->isObjCQualifiedClassType()) 8050 return Sema::IncompatiblePointer; 8051 return Sema::Compatible; 8052 } 8053 if (RHSType->isObjCBuiltinType()) { 8054 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8055 !LHSType->isObjCQualifiedClassType()) 8056 return Sema::IncompatiblePointer; 8057 return Sema::Compatible; 8058 } 8059 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 8060 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 8061 8062 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8063 // make an exception for id<P> 8064 !LHSType->isObjCQualifiedIdType()) 8065 return Sema::CompatiblePointerDiscardsQualifiers; 8066 8067 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8068 return Sema::Compatible; 8069 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8070 return Sema::IncompatibleObjCQualifiedId; 8071 return Sema::IncompatiblePointer; 8072 } 8073 8074 Sema::AssignConvertType 8075 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8076 QualType LHSType, QualType RHSType) { 8077 // Fake up an opaque expression. We don't actually care about what 8078 // cast operations are required, so if CheckAssignmentConstraints 8079 // adds casts to this they'll be wasted, but fortunately that doesn't 8080 // usually happen on valid code. 8081 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8082 ExprResult RHSPtr = &RHSExpr; 8083 CastKind K; 8084 8085 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8086 } 8087 8088 /// This helper function returns true if QT is a vector type that has element 8089 /// type ElementType. 8090 static bool isVector(QualType QT, QualType ElementType) { 8091 if (const VectorType *VT = QT->getAs<VectorType>()) 8092 return VT->getElementType() == ElementType; 8093 return false; 8094 } 8095 8096 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8097 /// has code to accommodate several GCC extensions when type checking 8098 /// pointers. Here are some objectionable examples that GCC considers warnings: 8099 /// 8100 /// int a, *pint; 8101 /// short *pshort; 8102 /// struct foo *pfoo; 8103 /// 8104 /// pint = pshort; // warning: assignment from incompatible pointer type 8105 /// a = pint; // warning: assignment makes integer from pointer without a cast 8106 /// pint = a; // warning: assignment makes pointer from integer without a cast 8107 /// pint = pfoo; // warning: assignment from incompatible pointer type 8108 /// 8109 /// As a result, the code for dealing with pointers is more complex than the 8110 /// C99 spec dictates. 8111 /// 8112 /// Sets 'Kind' for any result kind except Incompatible. 8113 Sema::AssignConvertType 8114 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8115 CastKind &Kind, bool ConvertRHS) { 8116 QualType RHSType = RHS.get()->getType(); 8117 QualType OrigLHSType = LHSType; 8118 8119 // Get canonical types. We're not formatting these types, just comparing 8120 // them. 8121 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8122 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8123 8124 // Common case: no conversion required. 8125 if (LHSType == RHSType) { 8126 Kind = CK_NoOp; 8127 return Compatible; 8128 } 8129 8130 // If we have an atomic type, try a non-atomic assignment, then just add an 8131 // atomic qualification step. 8132 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8133 Sema::AssignConvertType result = 8134 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8135 if (result != Compatible) 8136 return result; 8137 if (Kind != CK_NoOp && ConvertRHS) 8138 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8139 Kind = CK_NonAtomicToAtomic; 8140 return Compatible; 8141 } 8142 8143 // If the left-hand side is a reference type, then we are in a 8144 // (rare!) case where we've allowed the use of references in C, 8145 // e.g., as a parameter type in a built-in function. In this case, 8146 // just make sure that the type referenced is compatible with the 8147 // right-hand side type. The caller is responsible for adjusting 8148 // LHSType so that the resulting expression does not have reference 8149 // type. 8150 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8151 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8152 Kind = CK_LValueBitCast; 8153 return Compatible; 8154 } 8155 return Incompatible; 8156 } 8157 8158 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8159 // to the same ExtVector type. 8160 if (LHSType->isExtVectorType()) { 8161 if (RHSType->isExtVectorType()) 8162 return Incompatible; 8163 if (RHSType->isArithmeticType()) { 8164 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8165 if (ConvertRHS) 8166 RHS = prepareVectorSplat(LHSType, RHS.get()); 8167 Kind = CK_VectorSplat; 8168 return Compatible; 8169 } 8170 } 8171 8172 // Conversions to or from vector type. 8173 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8174 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8175 // Allow assignments of an AltiVec vector type to an equivalent GCC 8176 // vector type and vice versa 8177 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8178 Kind = CK_BitCast; 8179 return Compatible; 8180 } 8181 8182 // If we are allowing lax vector conversions, and LHS and RHS are both 8183 // vectors, the total size only needs to be the same. This is a bitcast; 8184 // no bits are changed but the result type is different. 8185 if (isLaxVectorConversion(RHSType, LHSType)) { 8186 Kind = CK_BitCast; 8187 return IncompatibleVectors; 8188 } 8189 } 8190 8191 // When the RHS comes from another lax conversion (e.g. binops between 8192 // scalars and vectors) the result is canonicalized as a vector. When the 8193 // LHS is also a vector, the lax is allowed by the condition above. Handle 8194 // the case where LHS is a scalar. 8195 if (LHSType->isScalarType()) { 8196 const VectorType *VecType = RHSType->getAs<VectorType>(); 8197 if (VecType && VecType->getNumElements() == 1 && 8198 isLaxVectorConversion(RHSType, LHSType)) { 8199 ExprResult *VecExpr = &RHS; 8200 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8201 Kind = CK_BitCast; 8202 return Compatible; 8203 } 8204 } 8205 8206 return Incompatible; 8207 } 8208 8209 // Diagnose attempts to convert between __float128 and long double where 8210 // such conversions currently can't be handled. 8211 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8212 return Incompatible; 8213 8214 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8215 // discards the imaginary part. 8216 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8217 !LHSType->getAs<ComplexType>()) 8218 return Incompatible; 8219 8220 // Arithmetic conversions. 8221 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8222 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8223 if (ConvertRHS) 8224 Kind = PrepareScalarCast(RHS, LHSType); 8225 return Compatible; 8226 } 8227 8228 // Conversions to normal pointers. 8229 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8230 // U* -> T* 8231 if (isa<PointerType>(RHSType)) { 8232 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8233 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8234 if (AddrSpaceL != AddrSpaceR) 8235 Kind = CK_AddressSpaceConversion; 8236 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8237 Kind = CK_NoOp; 8238 else 8239 Kind = CK_BitCast; 8240 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8241 } 8242 8243 // int -> T* 8244 if (RHSType->isIntegerType()) { 8245 Kind = CK_IntegralToPointer; // FIXME: null? 8246 return IntToPointer; 8247 } 8248 8249 // C pointers are not compatible with ObjC object pointers, 8250 // with two exceptions: 8251 if (isa<ObjCObjectPointerType>(RHSType)) { 8252 // - conversions to void* 8253 if (LHSPointer->getPointeeType()->isVoidType()) { 8254 Kind = CK_BitCast; 8255 return Compatible; 8256 } 8257 8258 // - conversions from 'Class' to the redefinition type 8259 if (RHSType->isObjCClassType() && 8260 Context.hasSameType(LHSType, 8261 Context.getObjCClassRedefinitionType())) { 8262 Kind = CK_BitCast; 8263 return Compatible; 8264 } 8265 8266 Kind = CK_BitCast; 8267 return IncompatiblePointer; 8268 } 8269 8270 // U^ -> void* 8271 if (RHSType->getAs<BlockPointerType>()) { 8272 if (LHSPointer->getPointeeType()->isVoidType()) { 8273 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8274 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8275 ->getPointeeType() 8276 .getAddressSpace(); 8277 Kind = 8278 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8279 return Compatible; 8280 } 8281 } 8282 8283 return Incompatible; 8284 } 8285 8286 // Conversions to block pointers. 8287 if (isa<BlockPointerType>(LHSType)) { 8288 // U^ -> T^ 8289 if (RHSType->isBlockPointerType()) { 8290 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8291 ->getPointeeType() 8292 .getAddressSpace(); 8293 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8294 ->getPointeeType() 8295 .getAddressSpace(); 8296 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8297 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8298 } 8299 8300 // int or null -> T^ 8301 if (RHSType->isIntegerType()) { 8302 Kind = CK_IntegralToPointer; // FIXME: null 8303 return IntToBlockPointer; 8304 } 8305 8306 // id -> T^ 8307 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8308 Kind = CK_AnyPointerToBlockPointerCast; 8309 return Compatible; 8310 } 8311 8312 // void* -> T^ 8313 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8314 if (RHSPT->getPointeeType()->isVoidType()) { 8315 Kind = CK_AnyPointerToBlockPointerCast; 8316 return Compatible; 8317 } 8318 8319 return Incompatible; 8320 } 8321 8322 // Conversions to Objective-C pointers. 8323 if (isa<ObjCObjectPointerType>(LHSType)) { 8324 // A* -> B* 8325 if (RHSType->isObjCObjectPointerType()) { 8326 Kind = CK_BitCast; 8327 Sema::AssignConvertType result = 8328 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8329 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8330 result == Compatible && 8331 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8332 result = IncompatibleObjCWeakRef; 8333 return result; 8334 } 8335 8336 // int or null -> A* 8337 if (RHSType->isIntegerType()) { 8338 Kind = CK_IntegralToPointer; // FIXME: null 8339 return IntToPointer; 8340 } 8341 8342 // In general, C pointers are not compatible with ObjC object pointers, 8343 // with two exceptions: 8344 if (isa<PointerType>(RHSType)) { 8345 Kind = CK_CPointerToObjCPointerCast; 8346 8347 // - conversions from 'void*' 8348 if (RHSType->isVoidPointerType()) { 8349 return Compatible; 8350 } 8351 8352 // - conversions to 'Class' from its redefinition type 8353 if (LHSType->isObjCClassType() && 8354 Context.hasSameType(RHSType, 8355 Context.getObjCClassRedefinitionType())) { 8356 return Compatible; 8357 } 8358 8359 return IncompatiblePointer; 8360 } 8361 8362 // Only under strict condition T^ is compatible with an Objective-C pointer. 8363 if (RHSType->isBlockPointerType() && 8364 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8365 if (ConvertRHS) 8366 maybeExtendBlockObject(RHS); 8367 Kind = CK_BlockPointerToObjCPointerCast; 8368 return Compatible; 8369 } 8370 8371 return Incompatible; 8372 } 8373 8374 // Conversions from pointers that are not covered by the above. 8375 if (isa<PointerType>(RHSType)) { 8376 // T* -> _Bool 8377 if (LHSType == Context.BoolTy) { 8378 Kind = CK_PointerToBoolean; 8379 return Compatible; 8380 } 8381 8382 // T* -> int 8383 if (LHSType->isIntegerType()) { 8384 Kind = CK_PointerToIntegral; 8385 return PointerToInt; 8386 } 8387 8388 return Incompatible; 8389 } 8390 8391 // Conversions from Objective-C pointers that are not covered by the above. 8392 if (isa<ObjCObjectPointerType>(RHSType)) { 8393 // T* -> _Bool 8394 if (LHSType == Context.BoolTy) { 8395 Kind = CK_PointerToBoolean; 8396 return Compatible; 8397 } 8398 8399 // T* -> int 8400 if (LHSType->isIntegerType()) { 8401 Kind = CK_PointerToIntegral; 8402 return PointerToInt; 8403 } 8404 8405 return Incompatible; 8406 } 8407 8408 // struct A -> struct B 8409 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8410 if (Context.typesAreCompatible(LHSType, RHSType)) { 8411 Kind = CK_NoOp; 8412 return Compatible; 8413 } 8414 } 8415 8416 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8417 Kind = CK_IntToOCLSampler; 8418 return Compatible; 8419 } 8420 8421 return Incompatible; 8422 } 8423 8424 /// Constructs a transparent union from an expression that is 8425 /// used to initialize the transparent union. 8426 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8427 ExprResult &EResult, QualType UnionType, 8428 FieldDecl *Field) { 8429 // Build an initializer list that designates the appropriate member 8430 // of the transparent union. 8431 Expr *E = EResult.get(); 8432 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8433 E, SourceLocation()); 8434 Initializer->setType(UnionType); 8435 Initializer->setInitializedFieldInUnion(Field); 8436 8437 // Build a compound literal constructing a value of the transparent 8438 // union type from this initializer list. 8439 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8440 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8441 VK_RValue, Initializer, false); 8442 } 8443 8444 Sema::AssignConvertType 8445 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8446 ExprResult &RHS) { 8447 QualType RHSType = RHS.get()->getType(); 8448 8449 // If the ArgType is a Union type, we want to handle a potential 8450 // transparent_union GCC extension. 8451 const RecordType *UT = ArgType->getAsUnionType(); 8452 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8453 return Incompatible; 8454 8455 // The field to initialize within the transparent union. 8456 RecordDecl *UD = UT->getDecl(); 8457 FieldDecl *InitField = nullptr; 8458 // It's compatible if the expression matches any of the fields. 8459 for (auto *it : UD->fields()) { 8460 if (it->getType()->isPointerType()) { 8461 // If the transparent union contains a pointer type, we allow: 8462 // 1) void pointer 8463 // 2) null pointer constant 8464 if (RHSType->isPointerType()) 8465 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8466 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8467 InitField = it; 8468 break; 8469 } 8470 8471 if (RHS.get()->isNullPointerConstant(Context, 8472 Expr::NPC_ValueDependentIsNull)) { 8473 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8474 CK_NullToPointer); 8475 InitField = it; 8476 break; 8477 } 8478 } 8479 8480 CastKind Kind; 8481 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8482 == Compatible) { 8483 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8484 InitField = it; 8485 break; 8486 } 8487 } 8488 8489 if (!InitField) 8490 return Incompatible; 8491 8492 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8493 return Compatible; 8494 } 8495 8496 Sema::AssignConvertType 8497 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8498 bool Diagnose, 8499 bool DiagnoseCFAudited, 8500 bool ConvertRHS) { 8501 // We need to be able to tell the caller whether we diagnosed a problem, if 8502 // they ask us to issue diagnostics. 8503 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8504 8505 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8506 // we can't avoid *all* modifications at the moment, so we need some somewhere 8507 // to put the updated value. 8508 ExprResult LocalRHS = CallerRHS; 8509 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8510 8511 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8512 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8513 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8514 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8515 Diag(RHS.get()->getExprLoc(), 8516 diag::warn_noderef_to_dereferenceable_pointer) 8517 << RHS.get()->getSourceRange(); 8518 } 8519 } 8520 } 8521 8522 if (getLangOpts().CPlusPlus) { 8523 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8524 // C++ 5.17p3: If the left operand is not of class type, the 8525 // expression is implicitly converted (C++ 4) to the 8526 // cv-unqualified type of the left operand. 8527 QualType RHSType = RHS.get()->getType(); 8528 if (Diagnose) { 8529 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8530 AA_Assigning); 8531 } else { 8532 ImplicitConversionSequence ICS = 8533 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8534 /*SuppressUserConversions=*/false, 8535 /*AllowExplicit=*/false, 8536 /*InOverloadResolution=*/false, 8537 /*CStyle=*/false, 8538 /*AllowObjCWritebackConversion=*/false); 8539 if (ICS.isFailure()) 8540 return Incompatible; 8541 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8542 ICS, AA_Assigning); 8543 } 8544 if (RHS.isInvalid()) 8545 return Incompatible; 8546 Sema::AssignConvertType result = Compatible; 8547 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8548 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8549 result = IncompatibleObjCWeakRef; 8550 return result; 8551 } 8552 8553 // FIXME: Currently, we fall through and treat C++ classes like C 8554 // structures. 8555 // FIXME: We also fall through for atomics; not sure what should 8556 // happen there, though. 8557 } else if (RHS.get()->getType() == Context.OverloadTy) { 8558 // As a set of extensions to C, we support overloading on functions. These 8559 // functions need to be resolved here. 8560 DeclAccessPair DAP; 8561 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8562 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8563 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8564 else 8565 return Incompatible; 8566 } 8567 8568 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8569 // a null pointer constant. 8570 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8571 LHSType->isBlockPointerType()) && 8572 RHS.get()->isNullPointerConstant(Context, 8573 Expr::NPC_ValueDependentIsNull)) { 8574 if (Diagnose || ConvertRHS) { 8575 CastKind Kind; 8576 CXXCastPath Path; 8577 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8578 /*IgnoreBaseAccess=*/false, Diagnose); 8579 if (ConvertRHS) 8580 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8581 } 8582 return Compatible; 8583 } 8584 8585 // OpenCL queue_t type assignment. 8586 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8587 Context, Expr::NPC_ValueDependentIsNull)) { 8588 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8589 return Compatible; 8590 } 8591 8592 // This check seems unnatural, however it is necessary to ensure the proper 8593 // conversion of functions/arrays. If the conversion were done for all 8594 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8595 // expressions that suppress this implicit conversion (&, sizeof). 8596 // 8597 // Suppress this for references: C++ 8.5.3p5. 8598 if (!LHSType->isReferenceType()) { 8599 // FIXME: We potentially allocate here even if ConvertRHS is false. 8600 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8601 if (RHS.isInvalid()) 8602 return Incompatible; 8603 } 8604 CastKind Kind; 8605 Sema::AssignConvertType result = 8606 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8607 8608 // C99 6.5.16.1p2: The value of the right operand is converted to the 8609 // type of the assignment expression. 8610 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8611 // so that we can use references in built-in functions even in C. 8612 // The getNonReferenceType() call makes sure that the resulting expression 8613 // does not have reference type. 8614 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8615 QualType Ty = LHSType.getNonLValueExprType(Context); 8616 Expr *E = RHS.get(); 8617 8618 // Check for various Objective-C errors. If we are not reporting 8619 // diagnostics and just checking for errors, e.g., during overload 8620 // resolution, return Incompatible to indicate the failure. 8621 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8622 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8623 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8624 if (!Diagnose) 8625 return Incompatible; 8626 } 8627 if (getLangOpts().ObjC && 8628 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8629 E->getType(), E, Diagnose) || 8630 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8631 if (!Diagnose) 8632 return Incompatible; 8633 // Replace the expression with a corrected version and continue so we 8634 // can find further errors. 8635 RHS = E; 8636 return Compatible; 8637 } 8638 8639 if (ConvertRHS) 8640 RHS = ImpCastExprToType(E, Ty, Kind); 8641 } 8642 8643 return result; 8644 } 8645 8646 namespace { 8647 /// The original operand to an operator, prior to the application of the usual 8648 /// arithmetic conversions and converting the arguments of a builtin operator 8649 /// candidate. 8650 struct OriginalOperand { 8651 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8652 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8653 Op = MTE->GetTemporaryExpr(); 8654 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8655 Op = BTE->getSubExpr(); 8656 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8657 Orig = ICE->getSubExprAsWritten(); 8658 Conversion = ICE->getConversionFunction(); 8659 } 8660 } 8661 8662 QualType getType() const { return Orig->getType(); } 8663 8664 Expr *Orig; 8665 NamedDecl *Conversion; 8666 }; 8667 } 8668 8669 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8670 ExprResult &RHS) { 8671 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8672 8673 Diag(Loc, diag::err_typecheck_invalid_operands) 8674 << OrigLHS.getType() << OrigRHS.getType() 8675 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8676 8677 // If a user-defined conversion was applied to either of the operands prior 8678 // to applying the built-in operator rules, tell the user about it. 8679 if (OrigLHS.Conversion) { 8680 Diag(OrigLHS.Conversion->getLocation(), 8681 diag::note_typecheck_invalid_operands_converted) 8682 << 0 << LHS.get()->getType(); 8683 } 8684 if (OrigRHS.Conversion) { 8685 Diag(OrigRHS.Conversion->getLocation(), 8686 diag::note_typecheck_invalid_operands_converted) 8687 << 1 << RHS.get()->getType(); 8688 } 8689 8690 return QualType(); 8691 } 8692 8693 // Diagnose cases where a scalar was implicitly converted to a vector and 8694 // diagnose the underlying types. Otherwise, diagnose the error 8695 // as invalid vector logical operands for non-C++ cases. 8696 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8697 ExprResult &RHS) { 8698 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8699 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8700 8701 bool LHSNatVec = LHSType->isVectorType(); 8702 bool RHSNatVec = RHSType->isVectorType(); 8703 8704 if (!(LHSNatVec && RHSNatVec)) { 8705 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8706 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8707 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8708 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8709 << Vector->getSourceRange(); 8710 return QualType(); 8711 } 8712 8713 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8714 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8715 << RHS.get()->getSourceRange(); 8716 8717 return QualType(); 8718 } 8719 8720 /// Try to convert a value of non-vector type to a vector type by converting 8721 /// the type to the element type of the vector and then performing a splat. 8722 /// If the language is OpenCL, we only use conversions that promote scalar 8723 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8724 /// for float->int. 8725 /// 8726 /// OpenCL V2.0 6.2.6.p2: 8727 /// An error shall occur if any scalar operand type has greater rank 8728 /// than the type of the vector element. 8729 /// 8730 /// \param scalar - if non-null, actually perform the conversions 8731 /// \return true if the operation fails (but without diagnosing the failure) 8732 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8733 QualType scalarTy, 8734 QualType vectorEltTy, 8735 QualType vectorTy, 8736 unsigned &DiagID) { 8737 // The conversion to apply to the scalar before splatting it, 8738 // if necessary. 8739 CastKind scalarCast = CK_NoOp; 8740 8741 if (vectorEltTy->isIntegralType(S.Context)) { 8742 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8743 (scalarTy->isIntegerType() && 8744 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8745 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8746 return true; 8747 } 8748 if (!scalarTy->isIntegralType(S.Context)) 8749 return true; 8750 scalarCast = CK_IntegralCast; 8751 } else if (vectorEltTy->isRealFloatingType()) { 8752 if (scalarTy->isRealFloatingType()) { 8753 if (S.getLangOpts().OpenCL && 8754 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8755 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8756 return true; 8757 } 8758 scalarCast = CK_FloatingCast; 8759 } 8760 else if (scalarTy->isIntegralType(S.Context)) 8761 scalarCast = CK_IntegralToFloating; 8762 else 8763 return true; 8764 } else { 8765 return true; 8766 } 8767 8768 // Adjust scalar if desired. 8769 if (scalar) { 8770 if (scalarCast != CK_NoOp) 8771 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8772 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8773 } 8774 return false; 8775 } 8776 8777 /// Convert vector E to a vector with the same number of elements but different 8778 /// element type. 8779 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8780 const auto *VecTy = E->getType()->getAs<VectorType>(); 8781 assert(VecTy && "Expression E must be a vector"); 8782 QualType NewVecTy = S.Context.getVectorType(ElementType, 8783 VecTy->getNumElements(), 8784 VecTy->getVectorKind()); 8785 8786 // Look through the implicit cast. Return the subexpression if its type is 8787 // NewVecTy. 8788 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8789 if (ICE->getSubExpr()->getType() == NewVecTy) 8790 return ICE->getSubExpr(); 8791 8792 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8793 return S.ImpCastExprToType(E, NewVecTy, Cast); 8794 } 8795 8796 /// Test if a (constant) integer Int can be casted to another integer type 8797 /// IntTy without losing precision. 8798 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8799 QualType OtherIntTy) { 8800 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8801 8802 // Reject cases where the value of the Int is unknown as that would 8803 // possibly cause truncation, but accept cases where the scalar can be 8804 // demoted without loss of precision. 8805 Expr::EvalResult EVResult; 8806 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8807 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8808 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8809 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8810 8811 if (CstInt) { 8812 // If the scalar is constant and is of a higher order and has more active 8813 // bits that the vector element type, reject it. 8814 llvm::APSInt Result = EVResult.Val.getInt(); 8815 unsigned NumBits = IntSigned 8816 ? (Result.isNegative() ? Result.getMinSignedBits() 8817 : Result.getActiveBits()) 8818 : Result.getActiveBits(); 8819 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8820 return true; 8821 8822 // If the signedness of the scalar type and the vector element type 8823 // differs and the number of bits is greater than that of the vector 8824 // element reject it. 8825 return (IntSigned != OtherIntSigned && 8826 NumBits > S.Context.getIntWidth(OtherIntTy)); 8827 } 8828 8829 // Reject cases where the value of the scalar is not constant and it's 8830 // order is greater than that of the vector element type. 8831 return (Order < 0); 8832 } 8833 8834 /// Test if a (constant) integer Int can be casted to floating point type 8835 /// FloatTy without losing precision. 8836 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8837 QualType FloatTy) { 8838 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8839 8840 // Determine if the integer constant can be expressed as a floating point 8841 // number of the appropriate type. 8842 Expr::EvalResult EVResult; 8843 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8844 8845 uint64_t Bits = 0; 8846 if (CstInt) { 8847 // Reject constants that would be truncated if they were converted to 8848 // the floating point type. Test by simple to/from conversion. 8849 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8850 // could be avoided if there was a convertFromAPInt method 8851 // which could signal back if implicit truncation occurred. 8852 llvm::APSInt Result = EVResult.Val.getInt(); 8853 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8854 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8855 llvm::APFloat::rmTowardZero); 8856 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8857 !IntTy->hasSignedIntegerRepresentation()); 8858 bool Ignored = false; 8859 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8860 &Ignored); 8861 if (Result != ConvertBack) 8862 return true; 8863 } else { 8864 // Reject types that cannot be fully encoded into the mantissa of 8865 // the float. 8866 Bits = S.Context.getTypeSize(IntTy); 8867 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8868 S.Context.getFloatTypeSemantics(FloatTy)); 8869 if (Bits > FloatPrec) 8870 return true; 8871 } 8872 8873 return false; 8874 } 8875 8876 /// Attempt to convert and splat Scalar into a vector whose types matches 8877 /// Vector following GCC conversion rules. The rule is that implicit 8878 /// conversion can occur when Scalar can be casted to match Vector's element 8879 /// type without causing truncation of Scalar. 8880 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8881 ExprResult *Vector) { 8882 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8883 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8884 const VectorType *VT = VectorTy->getAs<VectorType>(); 8885 8886 assert(!isa<ExtVectorType>(VT) && 8887 "ExtVectorTypes should not be handled here!"); 8888 8889 QualType VectorEltTy = VT->getElementType(); 8890 8891 // Reject cases where the vector element type or the scalar element type are 8892 // not integral or floating point types. 8893 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8894 return true; 8895 8896 // The conversion to apply to the scalar before splatting it, 8897 // if necessary. 8898 CastKind ScalarCast = CK_NoOp; 8899 8900 // Accept cases where the vector elements are integers and the scalar is 8901 // an integer. 8902 // FIXME: Notionally if the scalar was a floating point value with a precise 8903 // integral representation, we could cast it to an appropriate integer 8904 // type and then perform the rest of the checks here. GCC will perform 8905 // this conversion in some cases as determined by the input language. 8906 // We should accept it on a language independent basis. 8907 if (VectorEltTy->isIntegralType(S.Context) && 8908 ScalarTy->isIntegralType(S.Context) && 8909 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8910 8911 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8912 return true; 8913 8914 ScalarCast = CK_IntegralCast; 8915 } else if (VectorEltTy->isRealFloatingType()) { 8916 if (ScalarTy->isRealFloatingType()) { 8917 8918 // Reject cases where the scalar type is not a constant and has a higher 8919 // Order than the vector element type. 8920 llvm::APFloat Result(0.0); 8921 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8922 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8923 if (!CstScalar && Order < 0) 8924 return true; 8925 8926 // If the scalar cannot be safely casted to the vector element type, 8927 // reject it. 8928 if (CstScalar) { 8929 bool Truncated = false; 8930 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8931 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8932 if (Truncated) 8933 return true; 8934 } 8935 8936 ScalarCast = CK_FloatingCast; 8937 } else if (ScalarTy->isIntegralType(S.Context)) { 8938 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8939 return true; 8940 8941 ScalarCast = CK_IntegralToFloating; 8942 } else 8943 return true; 8944 } 8945 8946 // Adjust scalar if desired. 8947 if (Scalar) { 8948 if (ScalarCast != CK_NoOp) 8949 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8950 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8951 } 8952 return false; 8953 } 8954 8955 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8956 SourceLocation Loc, bool IsCompAssign, 8957 bool AllowBothBool, 8958 bool AllowBoolConversions) { 8959 if (!IsCompAssign) { 8960 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8961 if (LHS.isInvalid()) 8962 return QualType(); 8963 } 8964 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8965 if (RHS.isInvalid()) 8966 return QualType(); 8967 8968 // For conversion purposes, we ignore any qualifiers. 8969 // For example, "const float" and "float" are equivalent. 8970 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8971 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8972 8973 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8974 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8975 assert(LHSVecType || RHSVecType); 8976 8977 // AltiVec-style "vector bool op vector bool" combinations are allowed 8978 // for some operators but not others. 8979 if (!AllowBothBool && 8980 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8981 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8982 return InvalidOperands(Loc, LHS, RHS); 8983 8984 // If the vector types are identical, return. 8985 if (Context.hasSameType(LHSType, RHSType)) 8986 return LHSType; 8987 8988 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8989 if (LHSVecType && RHSVecType && 8990 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8991 if (isa<ExtVectorType>(LHSVecType)) { 8992 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8993 return LHSType; 8994 } 8995 8996 if (!IsCompAssign) 8997 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8998 return RHSType; 8999 } 9000 9001 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9002 // can be mixed, with the result being the non-bool type. The non-bool 9003 // operand must have integer element type. 9004 if (AllowBoolConversions && LHSVecType && RHSVecType && 9005 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9006 (Context.getTypeSize(LHSVecType->getElementType()) == 9007 Context.getTypeSize(RHSVecType->getElementType()))) { 9008 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9009 LHSVecType->getElementType()->isIntegerType() && 9010 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9011 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9012 return LHSType; 9013 } 9014 if (!IsCompAssign && 9015 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9016 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9017 RHSVecType->getElementType()->isIntegerType()) { 9018 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9019 return RHSType; 9020 } 9021 } 9022 9023 // If there's a vector type and a scalar, try to convert the scalar to 9024 // the vector element type and splat. 9025 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9026 if (!RHSVecType) { 9027 if (isa<ExtVectorType>(LHSVecType)) { 9028 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9029 LHSVecType->getElementType(), LHSType, 9030 DiagID)) 9031 return LHSType; 9032 } else { 9033 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9034 return LHSType; 9035 } 9036 } 9037 if (!LHSVecType) { 9038 if (isa<ExtVectorType>(RHSVecType)) { 9039 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9040 LHSType, RHSVecType->getElementType(), 9041 RHSType, DiagID)) 9042 return RHSType; 9043 } else { 9044 if (LHS.get()->getValueKind() == VK_LValue || 9045 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9046 return RHSType; 9047 } 9048 } 9049 9050 // FIXME: The code below also handles conversion between vectors and 9051 // non-scalars, we should break this down into fine grained specific checks 9052 // and emit proper diagnostics. 9053 QualType VecType = LHSVecType ? LHSType : RHSType; 9054 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9055 QualType OtherType = LHSVecType ? RHSType : LHSType; 9056 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9057 if (isLaxVectorConversion(OtherType, VecType)) { 9058 // If we're allowing lax vector conversions, only the total (data) size 9059 // needs to be the same. For non compound assignment, if one of the types is 9060 // scalar, the result is always the vector type. 9061 if (!IsCompAssign) { 9062 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9063 return VecType; 9064 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9065 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9066 // type. Note that this is already done by non-compound assignments in 9067 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9068 // <1 x T> -> T. The result is also a vector type. 9069 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9070 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9071 ExprResult *RHSExpr = &RHS; 9072 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9073 return VecType; 9074 } 9075 } 9076 9077 // Okay, the expression is invalid. 9078 9079 // If there's a non-vector, non-real operand, diagnose that. 9080 if ((!RHSVecType && !RHSType->isRealType()) || 9081 (!LHSVecType && !LHSType->isRealType())) { 9082 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9083 << LHSType << RHSType 9084 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9085 return QualType(); 9086 } 9087 9088 // OpenCL V1.1 6.2.6.p1: 9089 // If the operands are of more than one vector type, then an error shall 9090 // occur. Implicit conversions between vector types are not permitted, per 9091 // section 6.2.1. 9092 if (getLangOpts().OpenCL && 9093 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9094 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9095 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9096 << RHSType; 9097 return QualType(); 9098 } 9099 9100 9101 // If there is a vector type that is not a ExtVector and a scalar, we reach 9102 // this point if scalar could not be converted to the vector's element type 9103 // without truncation. 9104 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9105 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9106 QualType Scalar = LHSVecType ? RHSType : LHSType; 9107 QualType Vector = LHSVecType ? LHSType : RHSType; 9108 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9109 Diag(Loc, 9110 diag::err_typecheck_vector_not_convertable_implict_truncation) 9111 << ScalarOrVector << Scalar << Vector; 9112 9113 return QualType(); 9114 } 9115 9116 // Otherwise, use the generic diagnostic. 9117 Diag(Loc, DiagID) 9118 << LHSType << RHSType 9119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9120 return QualType(); 9121 } 9122 9123 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9124 // expression. These are mainly cases where the null pointer is used as an 9125 // integer instead of a pointer. 9126 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9127 SourceLocation Loc, bool IsCompare) { 9128 // The canonical way to check for a GNU null is with isNullPointerConstant, 9129 // but we use a bit of a hack here for speed; this is a relatively 9130 // hot path, and isNullPointerConstant is slow. 9131 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9132 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9133 9134 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9135 9136 // Avoid analyzing cases where the result will either be invalid (and 9137 // diagnosed as such) or entirely valid and not something to warn about. 9138 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9139 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9140 return; 9141 9142 // Comparison operations would not make sense with a null pointer no matter 9143 // what the other expression is. 9144 if (!IsCompare) { 9145 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9146 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9147 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9148 return; 9149 } 9150 9151 // The rest of the operations only make sense with a null pointer 9152 // if the other expression is a pointer. 9153 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9154 NonNullType->canDecayToPointerType()) 9155 return; 9156 9157 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9158 << LHSNull /* LHS is NULL */ << NonNullType 9159 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9160 } 9161 9162 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9163 SourceLocation Loc) { 9164 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9165 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9166 if (!LUE || !RUE) 9167 return; 9168 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9169 RUE->getKind() != UETT_SizeOf) 9170 return; 9171 9172 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9173 QualType LHSTy = LHSArg->getType(); 9174 QualType RHSTy; 9175 9176 if (RUE->isArgumentType()) 9177 RHSTy = RUE->getArgumentType(); 9178 else 9179 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9180 9181 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9182 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9183 return; 9184 9185 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9186 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9187 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9188 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9189 << LHSArgDecl; 9190 } 9191 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9192 QualType ArrayElemTy = ArrayTy->getElementType(); 9193 if (ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9194 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9195 return; 9196 S.Diag(Loc, diag::warn_division_sizeof_array) 9197 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9198 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9199 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9200 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9201 << LHSArgDecl; 9202 } 9203 9204 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9205 } 9206 } 9207 9208 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9209 ExprResult &RHS, 9210 SourceLocation Loc, bool IsDiv) { 9211 // Check for division/remainder by zero. 9212 Expr::EvalResult RHSValue; 9213 if (!RHS.get()->isValueDependent() && 9214 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9215 RHSValue.Val.getInt() == 0) 9216 S.DiagRuntimeBehavior(Loc, RHS.get(), 9217 S.PDiag(diag::warn_remainder_division_by_zero) 9218 << IsDiv << RHS.get()->getSourceRange()); 9219 } 9220 9221 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9222 SourceLocation Loc, 9223 bool IsCompAssign, bool IsDiv) { 9224 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9225 9226 if (LHS.get()->getType()->isVectorType() || 9227 RHS.get()->getType()->isVectorType()) 9228 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9229 /*AllowBothBool*/getLangOpts().AltiVec, 9230 /*AllowBoolConversions*/false); 9231 9232 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9233 if (LHS.isInvalid() || RHS.isInvalid()) 9234 return QualType(); 9235 9236 9237 if (compType.isNull() || !compType->isArithmeticType()) 9238 return InvalidOperands(Loc, LHS, RHS); 9239 if (IsDiv) { 9240 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9241 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9242 } 9243 return compType; 9244 } 9245 9246 QualType Sema::CheckRemainderOperands( 9247 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9248 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9249 9250 if (LHS.get()->getType()->isVectorType() || 9251 RHS.get()->getType()->isVectorType()) { 9252 if (LHS.get()->getType()->hasIntegerRepresentation() && 9253 RHS.get()->getType()->hasIntegerRepresentation()) 9254 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9255 /*AllowBothBool*/getLangOpts().AltiVec, 9256 /*AllowBoolConversions*/false); 9257 return InvalidOperands(Loc, LHS, RHS); 9258 } 9259 9260 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9261 if (LHS.isInvalid() || RHS.isInvalid()) 9262 return QualType(); 9263 9264 if (compType.isNull() || !compType->isIntegerType()) 9265 return InvalidOperands(Loc, LHS, RHS); 9266 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9267 return compType; 9268 } 9269 9270 /// Diagnose invalid arithmetic on two void pointers. 9271 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9272 Expr *LHSExpr, Expr *RHSExpr) { 9273 S.Diag(Loc, S.getLangOpts().CPlusPlus 9274 ? diag::err_typecheck_pointer_arith_void_type 9275 : diag::ext_gnu_void_ptr) 9276 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9277 << RHSExpr->getSourceRange(); 9278 } 9279 9280 /// Diagnose invalid arithmetic on a void pointer. 9281 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9282 Expr *Pointer) { 9283 S.Diag(Loc, S.getLangOpts().CPlusPlus 9284 ? diag::err_typecheck_pointer_arith_void_type 9285 : diag::ext_gnu_void_ptr) 9286 << 0 /* one pointer */ << Pointer->getSourceRange(); 9287 } 9288 9289 /// Diagnose invalid arithmetic on a null pointer. 9290 /// 9291 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9292 /// idiom, which we recognize as a GNU extension. 9293 /// 9294 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9295 Expr *Pointer, bool IsGNUIdiom) { 9296 if (IsGNUIdiom) 9297 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9298 << Pointer->getSourceRange(); 9299 else 9300 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9301 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9302 } 9303 9304 /// Diagnose invalid arithmetic on two function pointers. 9305 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9306 Expr *LHS, Expr *RHS) { 9307 assert(LHS->getType()->isAnyPointerType()); 9308 assert(RHS->getType()->isAnyPointerType()); 9309 S.Diag(Loc, S.getLangOpts().CPlusPlus 9310 ? diag::err_typecheck_pointer_arith_function_type 9311 : diag::ext_gnu_ptr_func_arith) 9312 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9313 // We only show the second type if it differs from the first. 9314 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9315 RHS->getType()) 9316 << RHS->getType()->getPointeeType() 9317 << LHS->getSourceRange() << RHS->getSourceRange(); 9318 } 9319 9320 /// Diagnose invalid arithmetic on a function pointer. 9321 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9322 Expr *Pointer) { 9323 assert(Pointer->getType()->isAnyPointerType()); 9324 S.Diag(Loc, S.getLangOpts().CPlusPlus 9325 ? diag::err_typecheck_pointer_arith_function_type 9326 : diag::ext_gnu_ptr_func_arith) 9327 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9328 << 0 /* one pointer, so only one type */ 9329 << Pointer->getSourceRange(); 9330 } 9331 9332 /// Emit error if Operand is incomplete pointer type 9333 /// 9334 /// \returns True if pointer has incomplete type 9335 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9336 Expr *Operand) { 9337 QualType ResType = Operand->getType(); 9338 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9339 ResType = ResAtomicType->getValueType(); 9340 9341 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9342 QualType PointeeTy = ResType->getPointeeType(); 9343 return S.RequireCompleteType(Loc, PointeeTy, 9344 diag::err_typecheck_arithmetic_incomplete_type, 9345 PointeeTy, Operand->getSourceRange()); 9346 } 9347 9348 /// Check the validity of an arithmetic pointer operand. 9349 /// 9350 /// If the operand has pointer type, this code will check for pointer types 9351 /// which are invalid in arithmetic operations. These will be diagnosed 9352 /// appropriately, including whether or not the use is supported as an 9353 /// extension. 9354 /// 9355 /// \returns True when the operand is valid to use (even if as an extension). 9356 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9357 Expr *Operand) { 9358 QualType ResType = Operand->getType(); 9359 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9360 ResType = ResAtomicType->getValueType(); 9361 9362 if (!ResType->isAnyPointerType()) return true; 9363 9364 QualType PointeeTy = ResType->getPointeeType(); 9365 if (PointeeTy->isVoidType()) { 9366 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9367 return !S.getLangOpts().CPlusPlus; 9368 } 9369 if (PointeeTy->isFunctionType()) { 9370 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9371 return !S.getLangOpts().CPlusPlus; 9372 } 9373 9374 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9375 9376 return true; 9377 } 9378 9379 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9380 /// operands. 9381 /// 9382 /// This routine will diagnose any invalid arithmetic on pointer operands much 9383 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9384 /// for emitting a single diagnostic even for operations where both LHS and RHS 9385 /// are (potentially problematic) pointers. 9386 /// 9387 /// \returns True when the operand is valid to use (even if as an extension). 9388 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9389 Expr *LHSExpr, Expr *RHSExpr) { 9390 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9391 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9392 if (!isLHSPointer && !isRHSPointer) return true; 9393 9394 QualType LHSPointeeTy, RHSPointeeTy; 9395 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9396 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9397 9398 // if both are pointers check if operation is valid wrt address spaces 9399 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9400 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9401 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9402 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9403 S.Diag(Loc, 9404 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9405 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9406 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9407 return false; 9408 } 9409 } 9410 9411 // Check for arithmetic on pointers to incomplete types. 9412 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9413 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9414 if (isLHSVoidPtr || isRHSVoidPtr) { 9415 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9416 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9417 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9418 9419 return !S.getLangOpts().CPlusPlus; 9420 } 9421 9422 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9423 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9424 if (isLHSFuncPtr || isRHSFuncPtr) { 9425 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9426 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9427 RHSExpr); 9428 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9429 9430 return !S.getLangOpts().CPlusPlus; 9431 } 9432 9433 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9434 return false; 9435 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9436 return false; 9437 9438 return true; 9439 } 9440 9441 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9442 /// literal. 9443 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9444 Expr *LHSExpr, Expr *RHSExpr) { 9445 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9446 Expr* IndexExpr = RHSExpr; 9447 if (!StrExpr) { 9448 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9449 IndexExpr = LHSExpr; 9450 } 9451 9452 bool IsStringPlusInt = StrExpr && 9453 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9454 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9455 return; 9456 9457 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9458 Self.Diag(OpLoc, diag::warn_string_plus_int) 9459 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9460 9461 // Only print a fixit for "str" + int, not for int + "str". 9462 if (IndexExpr == RHSExpr) { 9463 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9464 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9465 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9466 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9467 << FixItHint::CreateInsertion(EndLoc, "]"); 9468 } else 9469 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9470 } 9471 9472 /// Emit a warning when adding a char literal to a string. 9473 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9474 Expr *LHSExpr, Expr *RHSExpr) { 9475 const Expr *StringRefExpr = LHSExpr; 9476 const CharacterLiteral *CharExpr = 9477 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9478 9479 if (!CharExpr) { 9480 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9481 StringRefExpr = RHSExpr; 9482 } 9483 9484 if (!CharExpr || !StringRefExpr) 9485 return; 9486 9487 const QualType StringType = StringRefExpr->getType(); 9488 9489 // Return if not a PointerType. 9490 if (!StringType->isAnyPointerType()) 9491 return; 9492 9493 // Return if not a CharacterType. 9494 if (!StringType->getPointeeType()->isAnyCharacterType()) 9495 return; 9496 9497 ASTContext &Ctx = Self.getASTContext(); 9498 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9499 9500 const QualType CharType = CharExpr->getType(); 9501 if (!CharType->isAnyCharacterType() && 9502 CharType->isIntegerType() && 9503 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9504 Self.Diag(OpLoc, diag::warn_string_plus_char) 9505 << DiagRange << Ctx.CharTy; 9506 } else { 9507 Self.Diag(OpLoc, diag::warn_string_plus_char) 9508 << DiagRange << CharExpr->getType(); 9509 } 9510 9511 // Only print a fixit for str + char, not for char + str. 9512 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9513 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9514 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9515 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9516 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9517 << FixItHint::CreateInsertion(EndLoc, "]"); 9518 } else { 9519 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9520 } 9521 } 9522 9523 /// Emit error when two pointers are incompatible. 9524 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9525 Expr *LHSExpr, Expr *RHSExpr) { 9526 assert(LHSExpr->getType()->isAnyPointerType()); 9527 assert(RHSExpr->getType()->isAnyPointerType()); 9528 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9529 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9530 << RHSExpr->getSourceRange(); 9531 } 9532 9533 // C99 6.5.6 9534 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9535 SourceLocation Loc, BinaryOperatorKind Opc, 9536 QualType* CompLHSTy) { 9537 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9538 9539 if (LHS.get()->getType()->isVectorType() || 9540 RHS.get()->getType()->isVectorType()) { 9541 QualType compType = CheckVectorOperands( 9542 LHS, RHS, Loc, CompLHSTy, 9543 /*AllowBothBool*/getLangOpts().AltiVec, 9544 /*AllowBoolConversions*/getLangOpts().ZVector); 9545 if (CompLHSTy) *CompLHSTy = compType; 9546 return compType; 9547 } 9548 9549 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9550 if (LHS.isInvalid() || RHS.isInvalid()) 9551 return QualType(); 9552 9553 // Diagnose "string literal" '+' int and string '+' "char literal". 9554 if (Opc == BO_Add) { 9555 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9556 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9557 } 9558 9559 // handle the common case first (both operands are arithmetic). 9560 if (!compType.isNull() && compType->isArithmeticType()) { 9561 if (CompLHSTy) *CompLHSTy = compType; 9562 return compType; 9563 } 9564 9565 // Type-checking. Ultimately the pointer's going to be in PExp; 9566 // note that we bias towards the LHS being the pointer. 9567 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9568 9569 bool isObjCPointer; 9570 if (PExp->getType()->isPointerType()) { 9571 isObjCPointer = false; 9572 } else if (PExp->getType()->isObjCObjectPointerType()) { 9573 isObjCPointer = true; 9574 } else { 9575 std::swap(PExp, IExp); 9576 if (PExp->getType()->isPointerType()) { 9577 isObjCPointer = false; 9578 } else if (PExp->getType()->isObjCObjectPointerType()) { 9579 isObjCPointer = true; 9580 } else { 9581 return InvalidOperands(Loc, LHS, RHS); 9582 } 9583 } 9584 assert(PExp->getType()->isAnyPointerType()); 9585 9586 if (!IExp->getType()->isIntegerType()) 9587 return InvalidOperands(Loc, LHS, RHS); 9588 9589 // Adding to a null pointer results in undefined behavior. 9590 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9591 Context, Expr::NPC_ValueDependentIsNotNull)) { 9592 // In C++ adding zero to a null pointer is defined. 9593 Expr::EvalResult KnownVal; 9594 if (!getLangOpts().CPlusPlus || 9595 (!IExp->isValueDependent() && 9596 (!IExp->EvaluateAsInt(KnownVal, Context) || 9597 KnownVal.Val.getInt() != 0))) { 9598 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9599 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9600 Context, BO_Add, PExp, IExp); 9601 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9602 } 9603 } 9604 9605 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9606 return QualType(); 9607 9608 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9609 return QualType(); 9610 9611 // Check array bounds for pointer arithemtic 9612 CheckArrayAccess(PExp, IExp); 9613 9614 if (CompLHSTy) { 9615 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9616 if (LHSTy.isNull()) { 9617 LHSTy = LHS.get()->getType(); 9618 if (LHSTy->isPromotableIntegerType()) 9619 LHSTy = Context.getPromotedIntegerType(LHSTy); 9620 } 9621 *CompLHSTy = LHSTy; 9622 } 9623 9624 return PExp->getType(); 9625 } 9626 9627 // C99 6.5.6 9628 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9629 SourceLocation Loc, 9630 QualType* CompLHSTy) { 9631 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9632 9633 if (LHS.get()->getType()->isVectorType() || 9634 RHS.get()->getType()->isVectorType()) { 9635 QualType compType = CheckVectorOperands( 9636 LHS, RHS, Loc, CompLHSTy, 9637 /*AllowBothBool*/getLangOpts().AltiVec, 9638 /*AllowBoolConversions*/getLangOpts().ZVector); 9639 if (CompLHSTy) *CompLHSTy = compType; 9640 return compType; 9641 } 9642 9643 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9644 if (LHS.isInvalid() || RHS.isInvalid()) 9645 return QualType(); 9646 9647 // Enforce type constraints: C99 6.5.6p3. 9648 9649 // Handle the common case first (both operands are arithmetic). 9650 if (!compType.isNull() && compType->isArithmeticType()) { 9651 if (CompLHSTy) *CompLHSTy = compType; 9652 return compType; 9653 } 9654 9655 // Either ptr - int or ptr - ptr. 9656 if (LHS.get()->getType()->isAnyPointerType()) { 9657 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9658 9659 // Diagnose bad cases where we step over interface counts. 9660 if (LHS.get()->getType()->isObjCObjectPointerType() && 9661 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9662 return QualType(); 9663 9664 // The result type of a pointer-int computation is the pointer type. 9665 if (RHS.get()->getType()->isIntegerType()) { 9666 // Subtracting from a null pointer should produce a warning. 9667 // The last argument to the diagnose call says this doesn't match the 9668 // GNU int-to-pointer idiom. 9669 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9670 Expr::NPC_ValueDependentIsNotNull)) { 9671 // In C++ adding zero to a null pointer is defined. 9672 Expr::EvalResult KnownVal; 9673 if (!getLangOpts().CPlusPlus || 9674 (!RHS.get()->isValueDependent() && 9675 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9676 KnownVal.Val.getInt() != 0))) { 9677 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9678 } 9679 } 9680 9681 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9682 return QualType(); 9683 9684 // Check array bounds for pointer arithemtic 9685 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9686 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9687 9688 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9689 return LHS.get()->getType(); 9690 } 9691 9692 // Handle pointer-pointer subtractions. 9693 if (const PointerType *RHSPTy 9694 = RHS.get()->getType()->getAs<PointerType>()) { 9695 QualType rpointee = RHSPTy->getPointeeType(); 9696 9697 if (getLangOpts().CPlusPlus) { 9698 // Pointee types must be the same: C++ [expr.add] 9699 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9700 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9701 } 9702 } else { 9703 // Pointee types must be compatible C99 6.5.6p3 9704 if (!Context.typesAreCompatible( 9705 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9706 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9707 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9708 return QualType(); 9709 } 9710 } 9711 9712 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9713 LHS.get(), RHS.get())) 9714 return QualType(); 9715 9716 // FIXME: Add warnings for nullptr - ptr. 9717 9718 // The pointee type may have zero size. As an extension, a structure or 9719 // union may have zero size or an array may have zero length. In this 9720 // case subtraction does not make sense. 9721 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9722 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9723 if (ElementSize.isZero()) { 9724 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9725 << rpointee.getUnqualifiedType() 9726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9727 } 9728 } 9729 9730 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9731 return Context.getPointerDiffType(); 9732 } 9733 } 9734 9735 return InvalidOperands(Loc, LHS, RHS); 9736 } 9737 9738 static bool isScopedEnumerationType(QualType T) { 9739 if (const EnumType *ET = T->getAs<EnumType>()) 9740 return ET->getDecl()->isScoped(); 9741 return false; 9742 } 9743 9744 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9745 SourceLocation Loc, BinaryOperatorKind Opc, 9746 QualType LHSType) { 9747 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9748 // so skip remaining warnings as we don't want to modify values within Sema. 9749 if (S.getLangOpts().OpenCL) 9750 return; 9751 9752 // Check right/shifter operand 9753 Expr::EvalResult RHSResult; 9754 if (RHS.get()->isValueDependent() || 9755 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9756 return; 9757 llvm::APSInt Right = RHSResult.Val.getInt(); 9758 9759 if (Right.isNegative()) { 9760 S.DiagRuntimeBehavior(Loc, RHS.get(), 9761 S.PDiag(diag::warn_shift_negative) 9762 << RHS.get()->getSourceRange()); 9763 return; 9764 } 9765 llvm::APInt LeftBits(Right.getBitWidth(), 9766 S.Context.getTypeSize(LHS.get()->getType())); 9767 if (Right.uge(LeftBits)) { 9768 S.DiagRuntimeBehavior(Loc, RHS.get(), 9769 S.PDiag(diag::warn_shift_gt_typewidth) 9770 << RHS.get()->getSourceRange()); 9771 return; 9772 } 9773 if (Opc != BO_Shl) 9774 return; 9775 9776 // When left shifting an ICE which is signed, we can check for overflow which 9777 // according to C++ standards prior to C++2a has undefined behavior 9778 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9779 // more than the maximum value representable in the result type, so never 9780 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9781 // expression is still probably a bug.) 9782 Expr::EvalResult LHSResult; 9783 if (LHS.get()->isValueDependent() || 9784 LHSType->hasUnsignedIntegerRepresentation() || 9785 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9786 return; 9787 llvm::APSInt Left = LHSResult.Val.getInt(); 9788 9789 // If LHS does not have a signed type and non-negative value 9790 // then, the behavior is undefined before C++2a. Warn about it. 9791 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9792 !S.getLangOpts().CPlusPlus2a) { 9793 S.DiagRuntimeBehavior(Loc, LHS.get(), 9794 S.PDiag(diag::warn_shift_lhs_negative) 9795 << LHS.get()->getSourceRange()); 9796 return; 9797 } 9798 9799 llvm::APInt ResultBits = 9800 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9801 if (LeftBits.uge(ResultBits)) 9802 return; 9803 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9804 Result = Result.shl(Right); 9805 9806 // Print the bit representation of the signed integer as an unsigned 9807 // hexadecimal number. 9808 SmallString<40> HexResult; 9809 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9810 9811 // If we are only missing a sign bit, this is less likely to result in actual 9812 // bugs -- if the result is cast back to an unsigned type, it will have the 9813 // expected value. Thus we place this behind a different warning that can be 9814 // turned off separately if needed. 9815 if (LeftBits == ResultBits - 1) { 9816 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9817 << HexResult << LHSType 9818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9819 return; 9820 } 9821 9822 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9823 << HexResult.str() << Result.getMinSignedBits() << LHSType 9824 << Left.getBitWidth() << LHS.get()->getSourceRange() 9825 << RHS.get()->getSourceRange(); 9826 } 9827 9828 /// Return the resulting type when a vector is shifted 9829 /// by a scalar or vector shift amount. 9830 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9831 SourceLocation Loc, bool IsCompAssign) { 9832 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9833 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9834 !LHS.get()->getType()->isVectorType()) { 9835 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9836 << RHS.get()->getType() << LHS.get()->getType() 9837 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9838 return QualType(); 9839 } 9840 9841 if (!IsCompAssign) { 9842 LHS = S.UsualUnaryConversions(LHS.get()); 9843 if (LHS.isInvalid()) return QualType(); 9844 } 9845 9846 RHS = S.UsualUnaryConversions(RHS.get()); 9847 if (RHS.isInvalid()) return QualType(); 9848 9849 QualType LHSType = LHS.get()->getType(); 9850 // Note that LHS might be a scalar because the routine calls not only in 9851 // OpenCL case. 9852 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9853 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9854 9855 // Note that RHS might not be a vector. 9856 QualType RHSType = RHS.get()->getType(); 9857 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9858 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9859 9860 // The operands need to be integers. 9861 if (!LHSEleType->isIntegerType()) { 9862 S.Diag(Loc, diag::err_typecheck_expect_int) 9863 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9864 return QualType(); 9865 } 9866 9867 if (!RHSEleType->isIntegerType()) { 9868 S.Diag(Loc, diag::err_typecheck_expect_int) 9869 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9870 return QualType(); 9871 } 9872 9873 if (!LHSVecTy) { 9874 assert(RHSVecTy); 9875 if (IsCompAssign) 9876 return RHSType; 9877 if (LHSEleType != RHSEleType) { 9878 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9879 LHSEleType = RHSEleType; 9880 } 9881 QualType VecTy = 9882 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9883 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9884 LHSType = VecTy; 9885 } else if (RHSVecTy) { 9886 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9887 // are applied component-wise. So if RHS is a vector, then ensure 9888 // that the number of elements is the same as LHS... 9889 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9890 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9891 << LHS.get()->getType() << RHS.get()->getType() 9892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9893 return QualType(); 9894 } 9895 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9896 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9897 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9898 if (LHSBT != RHSBT && 9899 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9900 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9901 << LHS.get()->getType() << RHS.get()->getType() 9902 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9903 } 9904 } 9905 } else { 9906 // ...else expand RHS to match the number of elements in LHS. 9907 QualType VecTy = 9908 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9909 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9910 } 9911 9912 return LHSType; 9913 } 9914 9915 // C99 6.5.7 9916 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9917 SourceLocation Loc, BinaryOperatorKind Opc, 9918 bool IsCompAssign) { 9919 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9920 9921 // Vector shifts promote their scalar inputs to vector type. 9922 if (LHS.get()->getType()->isVectorType() || 9923 RHS.get()->getType()->isVectorType()) { 9924 if (LangOpts.ZVector) { 9925 // The shift operators for the z vector extensions work basically 9926 // like general shifts, except that neither the LHS nor the RHS is 9927 // allowed to be a "vector bool". 9928 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9929 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9930 return InvalidOperands(Loc, LHS, RHS); 9931 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9932 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9933 return InvalidOperands(Loc, LHS, RHS); 9934 } 9935 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9936 } 9937 9938 // Shifts don't perform usual arithmetic conversions, they just do integer 9939 // promotions on each operand. C99 6.5.7p3 9940 9941 // For the LHS, do usual unary conversions, but then reset them away 9942 // if this is a compound assignment. 9943 ExprResult OldLHS = LHS; 9944 LHS = UsualUnaryConversions(LHS.get()); 9945 if (LHS.isInvalid()) 9946 return QualType(); 9947 QualType LHSType = LHS.get()->getType(); 9948 if (IsCompAssign) LHS = OldLHS; 9949 9950 // The RHS is simpler. 9951 RHS = UsualUnaryConversions(RHS.get()); 9952 if (RHS.isInvalid()) 9953 return QualType(); 9954 QualType RHSType = RHS.get()->getType(); 9955 9956 // C99 6.5.7p2: Each of the operands shall have integer type. 9957 if (!LHSType->hasIntegerRepresentation() || 9958 !RHSType->hasIntegerRepresentation()) 9959 return InvalidOperands(Loc, LHS, RHS); 9960 9961 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9962 // hasIntegerRepresentation() above instead of this. 9963 if (isScopedEnumerationType(LHSType) || 9964 isScopedEnumerationType(RHSType)) { 9965 return InvalidOperands(Loc, LHS, RHS); 9966 } 9967 // Sanity-check shift operands 9968 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9969 9970 // "The type of the result is that of the promoted left operand." 9971 return LHSType; 9972 } 9973 9974 /// If two different enums are compared, raise a warning. 9975 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9976 Expr *RHS) { 9977 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9978 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9979 9980 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9981 if (!LHSEnumType) 9982 return; 9983 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9984 if (!RHSEnumType) 9985 return; 9986 9987 // Ignore anonymous enums. 9988 if (!LHSEnumType->getDecl()->getIdentifier() && 9989 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9990 return; 9991 if (!RHSEnumType->getDecl()->getIdentifier() && 9992 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9993 return; 9994 9995 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9996 return; 9997 9998 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9999 << LHSStrippedType << RHSStrippedType 10000 << LHS->getSourceRange() << RHS->getSourceRange(); 10001 } 10002 10003 /// Diagnose bad pointer comparisons. 10004 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10005 ExprResult &LHS, ExprResult &RHS, 10006 bool IsError) { 10007 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10008 : diag::ext_typecheck_comparison_of_distinct_pointers) 10009 << LHS.get()->getType() << RHS.get()->getType() 10010 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10011 } 10012 10013 /// Returns false if the pointers are converted to a composite type, 10014 /// true otherwise. 10015 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10016 ExprResult &LHS, ExprResult &RHS) { 10017 // C++ [expr.rel]p2: 10018 // [...] Pointer conversions (4.10) and qualification 10019 // conversions (4.4) are performed on pointer operands (or on 10020 // a pointer operand and a null pointer constant) to bring 10021 // them to their composite pointer type. [...] 10022 // 10023 // C++ [expr.eq]p1 uses the same notion for (in)equality 10024 // comparisons of pointers. 10025 10026 QualType LHSType = LHS.get()->getType(); 10027 QualType RHSType = RHS.get()->getType(); 10028 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10029 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10030 10031 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10032 if (T.isNull()) { 10033 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 10034 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 10035 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10036 else 10037 S.InvalidOperands(Loc, LHS, RHS); 10038 return true; 10039 } 10040 10041 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10042 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10043 return false; 10044 } 10045 10046 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10047 ExprResult &LHS, 10048 ExprResult &RHS, 10049 bool IsError) { 10050 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10051 : diag::ext_typecheck_comparison_of_fptr_to_void) 10052 << LHS.get()->getType() << RHS.get()->getType() 10053 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10054 } 10055 10056 static bool isObjCObjectLiteral(ExprResult &E) { 10057 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10058 case Stmt::ObjCArrayLiteralClass: 10059 case Stmt::ObjCDictionaryLiteralClass: 10060 case Stmt::ObjCStringLiteralClass: 10061 case Stmt::ObjCBoxedExprClass: 10062 return true; 10063 default: 10064 // Note that ObjCBoolLiteral is NOT an object literal! 10065 return false; 10066 } 10067 } 10068 10069 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10070 const ObjCObjectPointerType *Type = 10071 LHS->getType()->getAs<ObjCObjectPointerType>(); 10072 10073 // If this is not actually an Objective-C object, bail out. 10074 if (!Type) 10075 return false; 10076 10077 // Get the LHS object's interface type. 10078 QualType InterfaceType = Type->getPointeeType(); 10079 10080 // If the RHS isn't an Objective-C object, bail out. 10081 if (!RHS->getType()->isObjCObjectPointerType()) 10082 return false; 10083 10084 // Try to find the -isEqual: method. 10085 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10086 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10087 InterfaceType, 10088 /*IsInstance=*/true); 10089 if (!Method) { 10090 if (Type->isObjCIdType()) { 10091 // For 'id', just check the global pool. 10092 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10093 /*receiverId=*/true); 10094 } else { 10095 // Check protocols. 10096 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10097 /*IsInstance=*/true); 10098 } 10099 } 10100 10101 if (!Method) 10102 return false; 10103 10104 QualType T = Method->parameters()[0]->getType(); 10105 if (!T->isObjCObjectPointerType()) 10106 return false; 10107 10108 QualType R = Method->getReturnType(); 10109 if (!R->isScalarType()) 10110 return false; 10111 10112 return true; 10113 } 10114 10115 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10116 FromE = FromE->IgnoreParenImpCasts(); 10117 switch (FromE->getStmtClass()) { 10118 default: 10119 break; 10120 case Stmt::ObjCStringLiteralClass: 10121 // "string literal" 10122 return LK_String; 10123 case Stmt::ObjCArrayLiteralClass: 10124 // "array literal" 10125 return LK_Array; 10126 case Stmt::ObjCDictionaryLiteralClass: 10127 // "dictionary literal" 10128 return LK_Dictionary; 10129 case Stmt::BlockExprClass: 10130 return LK_Block; 10131 case Stmt::ObjCBoxedExprClass: { 10132 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10133 switch (Inner->getStmtClass()) { 10134 case Stmt::IntegerLiteralClass: 10135 case Stmt::FloatingLiteralClass: 10136 case Stmt::CharacterLiteralClass: 10137 case Stmt::ObjCBoolLiteralExprClass: 10138 case Stmt::CXXBoolLiteralExprClass: 10139 // "numeric literal" 10140 return LK_Numeric; 10141 case Stmt::ImplicitCastExprClass: { 10142 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10143 // Boolean literals can be represented by implicit casts. 10144 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10145 return LK_Numeric; 10146 break; 10147 } 10148 default: 10149 break; 10150 } 10151 return LK_Boxed; 10152 } 10153 } 10154 return LK_None; 10155 } 10156 10157 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10158 ExprResult &LHS, ExprResult &RHS, 10159 BinaryOperator::Opcode Opc){ 10160 Expr *Literal; 10161 Expr *Other; 10162 if (isObjCObjectLiteral(LHS)) { 10163 Literal = LHS.get(); 10164 Other = RHS.get(); 10165 } else { 10166 Literal = RHS.get(); 10167 Other = LHS.get(); 10168 } 10169 10170 // Don't warn on comparisons against nil. 10171 Other = Other->IgnoreParenCasts(); 10172 if (Other->isNullPointerConstant(S.getASTContext(), 10173 Expr::NPC_ValueDependentIsNotNull)) 10174 return; 10175 10176 // This should be kept in sync with warn_objc_literal_comparison. 10177 // LK_String should always be after the other literals, since it has its own 10178 // warning flag. 10179 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10180 assert(LiteralKind != Sema::LK_Block); 10181 if (LiteralKind == Sema::LK_None) { 10182 llvm_unreachable("Unknown Objective-C object literal kind"); 10183 } 10184 10185 if (LiteralKind == Sema::LK_String) 10186 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10187 << Literal->getSourceRange(); 10188 else 10189 S.Diag(Loc, diag::warn_objc_literal_comparison) 10190 << LiteralKind << Literal->getSourceRange(); 10191 10192 if (BinaryOperator::isEqualityOp(Opc) && 10193 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10194 SourceLocation Start = LHS.get()->getBeginLoc(); 10195 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10196 CharSourceRange OpRange = 10197 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10198 10199 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10200 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10201 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10202 << FixItHint::CreateInsertion(End, "]"); 10203 } 10204 } 10205 10206 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10207 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10208 ExprResult &RHS, SourceLocation Loc, 10209 BinaryOperatorKind Opc) { 10210 // Check that left hand side is !something. 10211 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10212 if (!UO || UO->getOpcode() != UO_LNot) return; 10213 10214 // Only check if the right hand side is non-bool arithmetic type. 10215 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10216 10217 // Make sure that the something in !something is not bool. 10218 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10219 if (SubExpr->isKnownToHaveBooleanValue()) return; 10220 10221 // Emit warning. 10222 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10223 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10224 << Loc << IsBitwiseOp; 10225 10226 // First note suggest !(x < y) 10227 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10228 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10229 FirstClose = S.getLocForEndOfToken(FirstClose); 10230 if (FirstClose.isInvalid()) 10231 FirstOpen = SourceLocation(); 10232 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10233 << IsBitwiseOp 10234 << FixItHint::CreateInsertion(FirstOpen, "(") 10235 << FixItHint::CreateInsertion(FirstClose, ")"); 10236 10237 // Second note suggests (!x) < y 10238 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10239 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10240 SecondClose = S.getLocForEndOfToken(SecondClose); 10241 if (SecondClose.isInvalid()) 10242 SecondOpen = SourceLocation(); 10243 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10244 << FixItHint::CreateInsertion(SecondOpen, "(") 10245 << FixItHint::CreateInsertion(SecondClose, ")"); 10246 } 10247 10248 // Get the decl for a simple expression: a reference to a variable, 10249 // an implicit C++ field reference, or an implicit ObjC ivar reference. 10250 static ValueDecl *getCompareDecl(Expr *E) { 10251 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 10252 return DR->getDecl(); 10253 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 10254 if (Ivar->isFreeIvar()) 10255 return Ivar->getDecl(); 10256 } 10257 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10258 if (Mem->isImplicitAccess()) 10259 return Mem->getMemberDecl(); 10260 } 10261 return nullptr; 10262 } 10263 10264 /// Diagnose some forms of syntactically-obvious tautological comparison. 10265 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10266 Expr *LHS, Expr *RHS, 10267 BinaryOperatorKind Opc) { 10268 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10269 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10270 10271 QualType LHSType = LHS->getType(); 10272 QualType RHSType = RHS->getType(); 10273 if (LHSType->hasFloatingRepresentation() || 10274 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10275 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10276 S.inTemplateInstantiation()) 10277 return; 10278 10279 // Comparisons between two array types are ill-formed for operator<=>, so 10280 // we shouldn't emit any additional warnings about it. 10281 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10282 return; 10283 10284 // For non-floating point types, check for self-comparisons of the form 10285 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10286 // often indicate logic errors in the program. 10287 // 10288 // NOTE: Don't warn about comparison expressions resulting from macro 10289 // expansion. Also don't warn about comparisons which are only self 10290 // comparisons within a template instantiation. The warnings should catch 10291 // obvious cases in the definition of the template anyways. The idea is to 10292 // warn when the typed comparison operator will always evaluate to the same 10293 // result. 10294 ValueDecl *DL = getCompareDecl(LHSStripped); 10295 ValueDecl *DR = getCompareDecl(RHSStripped); 10296 10297 // Used for indexing into %select in warn_comparison_always 10298 enum { 10299 AlwaysConstant, 10300 AlwaysTrue, 10301 AlwaysFalse, 10302 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10303 }; 10304 if (DL && DR && declaresSameEntity(DL, DR)) { 10305 unsigned Result; 10306 switch (Opc) { 10307 case BO_EQ: case BO_LE: case BO_GE: 10308 Result = AlwaysTrue; 10309 break; 10310 case BO_NE: case BO_LT: case BO_GT: 10311 Result = AlwaysFalse; 10312 break; 10313 case BO_Cmp: 10314 Result = AlwaysEqual; 10315 break; 10316 default: 10317 Result = AlwaysConstant; 10318 break; 10319 } 10320 S.DiagRuntimeBehavior(Loc, nullptr, 10321 S.PDiag(diag::warn_comparison_always) 10322 << 0 /*self-comparison*/ 10323 << Result); 10324 } else if (DL && DR && 10325 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10326 !DL->isWeak() && !DR->isWeak()) { 10327 // What is it always going to evaluate to? 10328 unsigned Result; 10329 switch(Opc) { 10330 case BO_EQ: // e.g. array1 == array2 10331 Result = AlwaysFalse; 10332 break; 10333 case BO_NE: // e.g. array1 != array2 10334 Result = AlwaysTrue; 10335 break; 10336 default: // e.g. array1 <= array2 10337 // The best we can say is 'a constant' 10338 Result = AlwaysConstant; 10339 break; 10340 } 10341 S.DiagRuntimeBehavior(Loc, nullptr, 10342 S.PDiag(diag::warn_comparison_always) 10343 << 1 /*array comparison*/ 10344 << Result); 10345 } 10346 10347 if (isa<CastExpr>(LHSStripped)) 10348 LHSStripped = LHSStripped->IgnoreParenCasts(); 10349 if (isa<CastExpr>(RHSStripped)) 10350 RHSStripped = RHSStripped->IgnoreParenCasts(); 10351 10352 // Warn about comparisons against a string constant (unless the other 10353 // operand is null); the user probably wants strcmp. 10354 Expr *LiteralString = nullptr; 10355 Expr *LiteralStringStripped = nullptr; 10356 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10357 !RHSStripped->isNullPointerConstant(S.Context, 10358 Expr::NPC_ValueDependentIsNull)) { 10359 LiteralString = LHS; 10360 LiteralStringStripped = LHSStripped; 10361 } else if ((isa<StringLiteral>(RHSStripped) || 10362 isa<ObjCEncodeExpr>(RHSStripped)) && 10363 !LHSStripped->isNullPointerConstant(S.Context, 10364 Expr::NPC_ValueDependentIsNull)) { 10365 LiteralString = RHS; 10366 LiteralStringStripped = RHSStripped; 10367 } 10368 10369 if (LiteralString) { 10370 S.DiagRuntimeBehavior(Loc, nullptr, 10371 S.PDiag(diag::warn_stringcompare) 10372 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10373 << LiteralString->getSourceRange()); 10374 } 10375 } 10376 10377 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10378 switch (CK) { 10379 default: { 10380 #ifndef NDEBUG 10381 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10382 << "\n"; 10383 #endif 10384 llvm_unreachable("unhandled cast kind"); 10385 } 10386 case CK_UserDefinedConversion: 10387 return ICK_Identity; 10388 case CK_LValueToRValue: 10389 return ICK_Lvalue_To_Rvalue; 10390 case CK_ArrayToPointerDecay: 10391 return ICK_Array_To_Pointer; 10392 case CK_FunctionToPointerDecay: 10393 return ICK_Function_To_Pointer; 10394 case CK_IntegralCast: 10395 return ICK_Integral_Conversion; 10396 case CK_FloatingCast: 10397 return ICK_Floating_Conversion; 10398 case CK_IntegralToFloating: 10399 case CK_FloatingToIntegral: 10400 return ICK_Floating_Integral; 10401 case CK_IntegralComplexCast: 10402 case CK_FloatingComplexCast: 10403 case CK_FloatingComplexToIntegralComplex: 10404 case CK_IntegralComplexToFloatingComplex: 10405 return ICK_Complex_Conversion; 10406 case CK_FloatingComplexToReal: 10407 case CK_FloatingRealToComplex: 10408 case CK_IntegralComplexToReal: 10409 case CK_IntegralRealToComplex: 10410 return ICK_Complex_Real; 10411 } 10412 } 10413 10414 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10415 QualType FromType, 10416 SourceLocation Loc) { 10417 // Check for a narrowing implicit conversion. 10418 StandardConversionSequence SCS; 10419 SCS.setAsIdentityConversion(); 10420 SCS.setToType(0, FromType); 10421 SCS.setToType(1, ToType); 10422 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10423 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10424 10425 APValue PreNarrowingValue; 10426 QualType PreNarrowingType; 10427 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10428 PreNarrowingType, 10429 /*IgnoreFloatToIntegralConversion*/ true)) { 10430 case NK_Dependent_Narrowing: 10431 // Implicit conversion to a narrower type, but the expression is 10432 // value-dependent so we can't tell whether it's actually narrowing. 10433 case NK_Not_Narrowing: 10434 return false; 10435 10436 case NK_Constant_Narrowing: 10437 // Implicit conversion to a narrower type, and the value is not a constant 10438 // expression. 10439 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10440 << /*Constant*/ 1 10441 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10442 return true; 10443 10444 case NK_Variable_Narrowing: 10445 // Implicit conversion to a narrower type, and the value is not a constant 10446 // expression. 10447 case NK_Type_Narrowing: 10448 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10449 << /*Constant*/ 0 << FromType << ToType; 10450 // TODO: It's not a constant expression, but what if the user intended it 10451 // to be? Can we produce notes to help them figure out why it isn't? 10452 return true; 10453 } 10454 llvm_unreachable("unhandled case in switch"); 10455 } 10456 10457 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10458 ExprResult &LHS, 10459 ExprResult &RHS, 10460 SourceLocation Loc) { 10461 using CCT = ComparisonCategoryType; 10462 10463 QualType LHSType = LHS.get()->getType(); 10464 QualType RHSType = RHS.get()->getType(); 10465 // Dig out the original argument type and expression before implicit casts 10466 // were applied. These are the types/expressions we need to check the 10467 // [expr.spaceship] requirements against. 10468 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10469 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10470 QualType LHSStrippedType = LHSStripped.get()->getType(); 10471 QualType RHSStrippedType = RHSStripped.get()->getType(); 10472 10473 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10474 // other is not, the program is ill-formed. 10475 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10476 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10477 return QualType(); 10478 } 10479 10480 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10481 RHSStrippedType->isEnumeralType(); 10482 if (NumEnumArgs == 1) { 10483 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10484 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10485 if (OtherTy->hasFloatingRepresentation()) { 10486 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10487 return QualType(); 10488 } 10489 } 10490 if (NumEnumArgs == 2) { 10491 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10492 // type E, the operator yields the result of converting the operands 10493 // to the underlying type of E and applying <=> to the converted operands. 10494 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10495 S.InvalidOperands(Loc, LHS, RHS); 10496 return QualType(); 10497 } 10498 QualType IntType = 10499 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10500 assert(IntType->isArithmeticType()); 10501 10502 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10503 // promote the boolean type, and all other promotable integer types, to 10504 // avoid this. 10505 if (IntType->isPromotableIntegerType()) 10506 IntType = S.Context.getPromotedIntegerType(IntType); 10507 10508 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10509 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10510 LHSType = RHSType = IntType; 10511 } 10512 10513 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10514 // usual arithmetic conversions are applied to the operands. 10515 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10516 if (LHS.isInvalid() || RHS.isInvalid()) 10517 return QualType(); 10518 if (Type.isNull()) 10519 return S.InvalidOperands(Loc, LHS, RHS); 10520 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10521 10522 bool HasNarrowing = checkThreeWayNarrowingConversion( 10523 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10524 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10525 RHS.get()->getBeginLoc()); 10526 if (HasNarrowing) 10527 return QualType(); 10528 10529 assert(!Type.isNull() && "composite type for <=> has not been set"); 10530 10531 auto TypeKind = [&]() { 10532 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10533 if (CT->getElementType()->hasFloatingRepresentation()) 10534 return CCT::WeakEquality; 10535 return CCT::StrongEquality; 10536 } 10537 if (Type->isIntegralOrEnumerationType()) 10538 return CCT::StrongOrdering; 10539 if (Type->hasFloatingRepresentation()) 10540 return CCT::PartialOrdering; 10541 llvm_unreachable("other types are unimplemented"); 10542 }(); 10543 10544 return S.CheckComparisonCategoryType(TypeKind, Loc); 10545 } 10546 10547 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10548 ExprResult &RHS, 10549 SourceLocation Loc, 10550 BinaryOperatorKind Opc) { 10551 if (Opc == BO_Cmp) 10552 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10553 10554 // C99 6.5.8p3 / C99 6.5.9p4 10555 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10556 if (LHS.isInvalid() || RHS.isInvalid()) 10557 return QualType(); 10558 if (Type.isNull()) 10559 return S.InvalidOperands(Loc, LHS, RHS); 10560 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10561 10562 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10563 10564 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10565 return S.InvalidOperands(Loc, LHS, RHS); 10566 10567 // Check for comparisons of floating point operands using != and ==. 10568 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10569 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10570 10571 // The result of comparisons is 'bool' in C++, 'int' in C. 10572 return S.Context.getLogicalOperationType(); 10573 } 10574 10575 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10576 if (!NullE.get()->getType()->isAnyPointerType()) 10577 return; 10578 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10579 if (!E.get()->getType()->isAnyPointerType() && 10580 E.get()->isNullPointerConstant(Context, 10581 Expr::NPC_ValueDependentIsNotNull) == 10582 Expr::NPCK_ZeroExpression) { 10583 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10584 if (CL->getValue() == 0) 10585 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10586 << NullValue 10587 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10588 NullValue ? "NULL" : "(void *)0"); 10589 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10590 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10591 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10592 if (T == Context.CharTy) 10593 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10594 << NullValue 10595 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10596 NullValue ? "NULL" : "(void *)0"); 10597 } 10598 } 10599 } 10600 10601 // C99 6.5.8, C++ [expr.rel] 10602 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10603 SourceLocation Loc, 10604 BinaryOperatorKind Opc) { 10605 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10606 bool IsThreeWay = Opc == BO_Cmp; 10607 auto IsAnyPointerType = [](ExprResult E) { 10608 QualType Ty = E.get()->getType(); 10609 return Ty->isPointerType() || Ty->isMemberPointerType(); 10610 }; 10611 10612 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10613 // type, array-to-pointer, ..., conversions are performed on both operands to 10614 // bring them to their composite type. 10615 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10616 // any type-related checks. 10617 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10618 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10619 if (LHS.isInvalid()) 10620 return QualType(); 10621 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10622 if (RHS.isInvalid()) 10623 return QualType(); 10624 } else { 10625 LHS = DefaultLvalueConversion(LHS.get()); 10626 if (LHS.isInvalid()) 10627 return QualType(); 10628 RHS = DefaultLvalueConversion(RHS.get()); 10629 if (RHS.isInvalid()) 10630 return QualType(); 10631 } 10632 10633 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10634 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10635 CheckPtrComparisonWithNullChar(LHS, RHS); 10636 CheckPtrComparisonWithNullChar(RHS, LHS); 10637 } 10638 10639 // Handle vector comparisons separately. 10640 if (LHS.get()->getType()->isVectorType() || 10641 RHS.get()->getType()->isVectorType()) 10642 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10643 10644 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10645 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10646 10647 QualType LHSType = LHS.get()->getType(); 10648 QualType RHSType = RHS.get()->getType(); 10649 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10650 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10651 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10652 10653 const Expr::NullPointerConstantKind LHSNullKind = 10654 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10655 const Expr::NullPointerConstantKind RHSNullKind = 10656 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10657 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10658 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10659 10660 auto computeResultTy = [&]() { 10661 if (Opc != BO_Cmp) 10662 return Context.getLogicalOperationType(); 10663 assert(getLangOpts().CPlusPlus); 10664 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10665 10666 QualType CompositeTy = LHS.get()->getType(); 10667 assert(!CompositeTy->isReferenceType()); 10668 10669 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10670 return CheckComparisonCategoryType(Kind, Loc); 10671 }; 10672 10673 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10674 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10675 // result is of type std::strong_equality 10676 if (CompositeTy->isFunctionPointerType() || 10677 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10678 // FIXME: consider making the function pointer case produce 10679 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10680 // and direction polls 10681 return buildResultTy(ComparisonCategoryType::StrongEquality); 10682 10683 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10684 // pointer type, p <=> q is of type std::strong_ordering. 10685 if (CompositeTy->isPointerType()) { 10686 // P0946R0: Comparisons between a null pointer constant and an object 10687 // pointer result in std::strong_equality 10688 if (LHSIsNull != RHSIsNull) 10689 return buildResultTy(ComparisonCategoryType::StrongEquality); 10690 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10691 } 10692 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10693 // TODO: Extend support for operator<=> to ObjC types. 10694 return InvalidOperands(Loc, LHS, RHS); 10695 }; 10696 10697 10698 if (!IsRelational && LHSIsNull != RHSIsNull) { 10699 bool IsEquality = Opc == BO_EQ; 10700 if (RHSIsNull) 10701 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10702 RHS.get()->getSourceRange()); 10703 else 10704 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10705 LHS.get()->getSourceRange()); 10706 } 10707 10708 if ((LHSType->isIntegerType() && !LHSIsNull) || 10709 (RHSType->isIntegerType() && !RHSIsNull)) { 10710 // Skip normal pointer conversion checks in this case; we have better 10711 // diagnostics for this below. 10712 } else if (getLangOpts().CPlusPlus) { 10713 // Equality comparison of a function pointer to a void pointer is invalid, 10714 // but we allow it as an extension. 10715 // FIXME: If we really want to allow this, should it be part of composite 10716 // pointer type computation so it works in conditionals too? 10717 if (!IsRelational && 10718 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10719 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10720 // This is a gcc extension compatibility comparison. 10721 // In a SFINAE context, we treat this as a hard error to maintain 10722 // conformance with the C++ standard. 10723 diagnoseFunctionPointerToVoidComparison( 10724 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10725 10726 if (isSFINAEContext()) 10727 return QualType(); 10728 10729 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10730 return computeResultTy(); 10731 } 10732 10733 // C++ [expr.eq]p2: 10734 // If at least one operand is a pointer [...] bring them to their 10735 // composite pointer type. 10736 // C++ [expr.spaceship]p6 10737 // If at least one of the operands is of pointer type, [...] bring them 10738 // to their composite pointer type. 10739 // C++ [expr.rel]p2: 10740 // If both operands are pointers, [...] bring them to their composite 10741 // pointer type. 10742 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10743 (IsRelational ? 2 : 1) && 10744 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10745 RHSType->isObjCObjectPointerType()))) { 10746 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10747 return QualType(); 10748 return computeResultTy(); 10749 } 10750 } else if (LHSType->isPointerType() && 10751 RHSType->isPointerType()) { // C99 6.5.8p2 10752 // All of the following pointer-related warnings are GCC extensions, except 10753 // when handling null pointer constants. 10754 QualType LCanPointeeTy = 10755 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10756 QualType RCanPointeeTy = 10757 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10758 10759 // C99 6.5.9p2 and C99 6.5.8p2 10760 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10761 RCanPointeeTy.getUnqualifiedType())) { 10762 // Valid unless a relational comparison of function pointers 10763 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10764 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10765 << LHSType << RHSType << LHS.get()->getSourceRange() 10766 << RHS.get()->getSourceRange(); 10767 } 10768 } else if (!IsRelational && 10769 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10770 // Valid unless comparison between non-null pointer and function pointer 10771 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10772 && !LHSIsNull && !RHSIsNull) 10773 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10774 /*isError*/false); 10775 } else { 10776 // Invalid 10777 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10778 } 10779 if (LCanPointeeTy != RCanPointeeTy) { 10780 // Treat NULL constant as a special case in OpenCL. 10781 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10782 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10783 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10784 Diag(Loc, 10785 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10786 << LHSType << RHSType << 0 /* comparison */ 10787 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10788 } 10789 } 10790 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10791 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10792 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10793 : CK_BitCast; 10794 if (LHSIsNull && !RHSIsNull) 10795 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10796 else 10797 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10798 } 10799 return computeResultTy(); 10800 } 10801 10802 if (getLangOpts().CPlusPlus) { 10803 // C++ [expr.eq]p4: 10804 // Two operands of type std::nullptr_t or one operand of type 10805 // std::nullptr_t and the other a null pointer constant compare equal. 10806 if (!IsRelational && LHSIsNull && RHSIsNull) { 10807 if (LHSType->isNullPtrType()) { 10808 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10809 return computeResultTy(); 10810 } 10811 if (RHSType->isNullPtrType()) { 10812 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10813 return computeResultTy(); 10814 } 10815 } 10816 10817 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10818 // These aren't covered by the composite pointer type rules. 10819 if (!IsRelational && RHSType->isNullPtrType() && 10820 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10821 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10822 return computeResultTy(); 10823 } 10824 if (!IsRelational && LHSType->isNullPtrType() && 10825 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10826 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10827 return computeResultTy(); 10828 } 10829 10830 if (IsRelational && 10831 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10832 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10833 // HACK: Relational comparison of nullptr_t against a pointer type is 10834 // invalid per DR583, but we allow it within std::less<> and friends, 10835 // since otherwise common uses of it break. 10836 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10837 // friends to have std::nullptr_t overload candidates. 10838 DeclContext *DC = CurContext; 10839 if (isa<FunctionDecl>(DC)) 10840 DC = DC->getParent(); 10841 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10842 if (CTSD->isInStdNamespace() && 10843 llvm::StringSwitch<bool>(CTSD->getName()) 10844 .Cases("less", "less_equal", "greater", "greater_equal", true) 10845 .Default(false)) { 10846 if (RHSType->isNullPtrType()) 10847 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10848 else 10849 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10850 return computeResultTy(); 10851 } 10852 } 10853 } 10854 10855 // C++ [expr.eq]p2: 10856 // If at least one operand is a pointer to member, [...] bring them to 10857 // their composite pointer type. 10858 if (!IsRelational && 10859 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10860 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10861 return QualType(); 10862 else 10863 return computeResultTy(); 10864 } 10865 } 10866 10867 // Handle block pointer types. 10868 if (!IsRelational && LHSType->isBlockPointerType() && 10869 RHSType->isBlockPointerType()) { 10870 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10871 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10872 10873 if (!LHSIsNull && !RHSIsNull && 10874 !Context.typesAreCompatible(lpointee, rpointee)) { 10875 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10876 << LHSType << RHSType << LHS.get()->getSourceRange() 10877 << RHS.get()->getSourceRange(); 10878 } 10879 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10880 return computeResultTy(); 10881 } 10882 10883 // Allow block pointers to be compared with null pointer constants. 10884 if (!IsRelational 10885 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10886 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10887 if (!LHSIsNull && !RHSIsNull) { 10888 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10889 ->getPointeeType()->isVoidType()) 10890 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10891 ->getPointeeType()->isVoidType()))) 10892 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10893 << LHSType << RHSType << LHS.get()->getSourceRange() 10894 << RHS.get()->getSourceRange(); 10895 } 10896 if (LHSIsNull && !RHSIsNull) 10897 LHS = ImpCastExprToType(LHS.get(), RHSType, 10898 RHSType->isPointerType() ? CK_BitCast 10899 : CK_AnyPointerToBlockPointerCast); 10900 else 10901 RHS = ImpCastExprToType(RHS.get(), LHSType, 10902 LHSType->isPointerType() ? CK_BitCast 10903 : CK_AnyPointerToBlockPointerCast); 10904 return computeResultTy(); 10905 } 10906 10907 if (LHSType->isObjCObjectPointerType() || 10908 RHSType->isObjCObjectPointerType()) { 10909 const PointerType *LPT = LHSType->getAs<PointerType>(); 10910 const PointerType *RPT = RHSType->getAs<PointerType>(); 10911 if (LPT || RPT) { 10912 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10913 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10914 10915 if (!LPtrToVoid && !RPtrToVoid && 10916 !Context.typesAreCompatible(LHSType, RHSType)) { 10917 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10918 /*isError*/false); 10919 } 10920 if (LHSIsNull && !RHSIsNull) { 10921 Expr *E = LHS.get(); 10922 if (getLangOpts().ObjCAutoRefCount) 10923 CheckObjCConversion(SourceRange(), RHSType, E, 10924 CCK_ImplicitConversion); 10925 LHS = ImpCastExprToType(E, RHSType, 10926 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10927 } 10928 else { 10929 Expr *E = RHS.get(); 10930 if (getLangOpts().ObjCAutoRefCount) 10931 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10932 /*Diagnose=*/true, 10933 /*DiagnoseCFAudited=*/false, Opc); 10934 RHS = ImpCastExprToType(E, LHSType, 10935 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10936 } 10937 return computeResultTy(); 10938 } 10939 if (LHSType->isObjCObjectPointerType() && 10940 RHSType->isObjCObjectPointerType()) { 10941 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10942 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10943 /*isError*/false); 10944 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10945 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10946 10947 if (LHSIsNull && !RHSIsNull) 10948 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10949 else 10950 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10951 return computeResultTy(); 10952 } 10953 10954 if (!IsRelational && LHSType->isBlockPointerType() && 10955 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10956 LHS = ImpCastExprToType(LHS.get(), RHSType, 10957 CK_BlockPointerToObjCPointerCast); 10958 return computeResultTy(); 10959 } else if (!IsRelational && 10960 LHSType->isBlockCompatibleObjCPointerType(Context) && 10961 RHSType->isBlockPointerType()) { 10962 RHS = ImpCastExprToType(RHS.get(), LHSType, 10963 CK_BlockPointerToObjCPointerCast); 10964 return computeResultTy(); 10965 } 10966 } 10967 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10968 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10969 unsigned DiagID = 0; 10970 bool isError = false; 10971 if (LangOpts.DebuggerSupport) { 10972 // Under a debugger, allow the comparison of pointers to integers, 10973 // since users tend to want to compare addresses. 10974 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10975 (RHSIsNull && RHSType->isIntegerType())) { 10976 if (IsRelational) { 10977 isError = getLangOpts().CPlusPlus; 10978 DiagID = 10979 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10980 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10981 } 10982 } else if (getLangOpts().CPlusPlus) { 10983 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10984 isError = true; 10985 } else if (IsRelational) 10986 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10987 else 10988 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10989 10990 if (DiagID) { 10991 Diag(Loc, DiagID) 10992 << LHSType << RHSType << LHS.get()->getSourceRange() 10993 << RHS.get()->getSourceRange(); 10994 if (isError) 10995 return QualType(); 10996 } 10997 10998 if (LHSType->isIntegerType()) 10999 LHS = ImpCastExprToType(LHS.get(), RHSType, 11000 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11001 else 11002 RHS = ImpCastExprToType(RHS.get(), LHSType, 11003 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11004 return computeResultTy(); 11005 } 11006 11007 // Handle block pointers. 11008 if (!IsRelational && RHSIsNull 11009 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11010 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11011 return computeResultTy(); 11012 } 11013 if (!IsRelational && LHSIsNull 11014 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11015 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11016 return computeResultTy(); 11017 } 11018 11019 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11020 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11021 return computeResultTy(); 11022 } 11023 11024 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11025 return computeResultTy(); 11026 } 11027 11028 if (LHSIsNull && RHSType->isQueueT()) { 11029 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11030 return computeResultTy(); 11031 } 11032 11033 if (LHSType->isQueueT() && RHSIsNull) { 11034 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11035 return computeResultTy(); 11036 } 11037 } 11038 11039 return InvalidOperands(Loc, LHS, RHS); 11040 } 11041 11042 // Return a signed ext_vector_type that is of identical size and number of 11043 // elements. For floating point vectors, return an integer type of identical 11044 // size and number of elements. In the non ext_vector_type case, search from 11045 // the largest type to the smallest type to avoid cases where long long == long, 11046 // where long gets picked over long long. 11047 QualType Sema::GetSignedVectorType(QualType V) { 11048 const VectorType *VTy = V->getAs<VectorType>(); 11049 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11050 11051 if (isa<ExtVectorType>(VTy)) { 11052 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11053 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11054 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11055 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11056 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11057 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11058 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11059 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11060 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11061 "Unhandled vector element size in vector compare"); 11062 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11063 } 11064 11065 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11066 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11067 VectorType::GenericVector); 11068 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11069 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11070 VectorType::GenericVector); 11071 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11072 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11073 VectorType::GenericVector); 11074 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11075 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11076 VectorType::GenericVector); 11077 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11078 "Unhandled vector element size in vector compare"); 11079 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11080 VectorType::GenericVector); 11081 } 11082 11083 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11084 /// operates on extended vector types. Instead of producing an IntTy result, 11085 /// like a scalar comparison, a vector comparison produces a vector of integer 11086 /// types. 11087 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11088 SourceLocation Loc, 11089 BinaryOperatorKind Opc) { 11090 // Check to make sure we're operating on vectors of the same type and width, 11091 // Allowing one side to be a scalar of element type. 11092 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11093 /*AllowBothBool*/true, 11094 /*AllowBoolConversions*/getLangOpts().ZVector); 11095 if (vType.isNull()) 11096 return vType; 11097 11098 QualType LHSType = LHS.get()->getType(); 11099 11100 // If AltiVec, the comparison results in a numeric type, i.e. 11101 // bool for C++, int for C 11102 if (getLangOpts().AltiVec && 11103 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11104 return Context.getLogicalOperationType(); 11105 11106 // For non-floating point types, check for self-comparisons of the form 11107 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11108 // often indicate logic errors in the program. 11109 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11110 11111 // Check for comparisons of floating point operands using != and ==. 11112 if (BinaryOperator::isEqualityOp(Opc) && 11113 LHSType->hasFloatingRepresentation()) { 11114 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11115 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11116 } 11117 11118 // Return a signed type for the vector. 11119 return GetSignedVectorType(vType); 11120 } 11121 11122 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11123 const ExprResult &XorRHS, 11124 const SourceLocation Loc) { 11125 // Do not diagnose macros. 11126 if (Loc.isMacroID()) 11127 return; 11128 11129 bool Negative = false; 11130 bool ExplicitPlus = false; 11131 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11132 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11133 11134 if (!LHSInt) 11135 return; 11136 if (!RHSInt) { 11137 // Check negative literals. 11138 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11139 UnaryOperatorKind Opc = UO->getOpcode(); 11140 if (Opc != UO_Minus && Opc != UO_Plus) 11141 return; 11142 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11143 if (!RHSInt) 11144 return; 11145 Negative = (Opc == UO_Minus); 11146 ExplicitPlus = !Negative; 11147 } else { 11148 return; 11149 } 11150 } 11151 11152 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11153 llvm::APInt RightSideValue = RHSInt->getValue(); 11154 if (LeftSideValue != 2 && LeftSideValue != 10) 11155 return; 11156 11157 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11158 return; 11159 11160 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11161 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11162 llvm::StringRef ExprStr = 11163 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11164 11165 CharSourceRange XorRange = 11166 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11167 llvm::StringRef XorStr = 11168 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11169 // Do not diagnose if xor keyword/macro is used. 11170 if (XorStr == "xor") 11171 return; 11172 11173 std::string LHSStr = Lexer::getSourceText( 11174 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11175 S.getSourceManager(), S.getLangOpts()); 11176 std::string RHSStr = Lexer::getSourceText( 11177 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11178 S.getSourceManager(), S.getLangOpts()); 11179 11180 if (Negative) { 11181 RightSideValue = -RightSideValue; 11182 RHSStr = "-" + RHSStr; 11183 } else if (ExplicitPlus) { 11184 RHSStr = "+" + RHSStr; 11185 } 11186 11187 StringRef LHSStrRef = LHSStr; 11188 StringRef RHSStrRef = RHSStr; 11189 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11190 // literals. 11191 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11192 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11193 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11194 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11195 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11196 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11197 LHSStrRef.find('\'') != StringRef::npos || 11198 RHSStrRef.find('\'') != StringRef::npos) 11199 return; 11200 11201 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11202 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11203 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11204 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11205 std::string SuggestedExpr = "1 << " + RHSStr; 11206 bool Overflow = false; 11207 llvm::APInt One = (LeftSideValue - 1); 11208 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11209 if (Overflow) { 11210 if (RightSideIntValue < 64) 11211 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11212 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11213 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11214 else if (RightSideIntValue == 64) 11215 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11216 else 11217 return; 11218 } else { 11219 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11220 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11221 << PowValue.toString(10, true) 11222 << FixItHint::CreateReplacement( 11223 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11224 } 11225 11226 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11227 } else if (LeftSideValue == 10) { 11228 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11229 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11230 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11231 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11232 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11233 } 11234 } 11235 11236 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11237 SourceLocation Loc) { 11238 // Ensure that either both operands are of the same vector type, or 11239 // one operand is of a vector type and the other is of its element type. 11240 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11241 /*AllowBothBool*/true, 11242 /*AllowBoolConversions*/false); 11243 if (vType.isNull()) 11244 return InvalidOperands(Loc, LHS, RHS); 11245 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11246 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11247 return InvalidOperands(Loc, LHS, RHS); 11248 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11249 // usage of the logical operators && and || with vectors in C. This 11250 // check could be notionally dropped. 11251 if (!getLangOpts().CPlusPlus && 11252 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11253 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11254 11255 return GetSignedVectorType(LHS.get()->getType()); 11256 } 11257 11258 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11259 SourceLocation Loc, 11260 BinaryOperatorKind Opc) { 11261 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11262 11263 bool IsCompAssign = 11264 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11265 11266 if (LHS.get()->getType()->isVectorType() || 11267 RHS.get()->getType()->isVectorType()) { 11268 if (LHS.get()->getType()->hasIntegerRepresentation() && 11269 RHS.get()->getType()->hasIntegerRepresentation()) 11270 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11271 /*AllowBothBool*/true, 11272 /*AllowBoolConversions*/getLangOpts().ZVector); 11273 return InvalidOperands(Loc, LHS, RHS); 11274 } 11275 11276 if (Opc == BO_And) 11277 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11278 11279 ExprResult LHSResult = LHS, RHSResult = RHS; 11280 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11281 IsCompAssign); 11282 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11283 return QualType(); 11284 LHS = LHSResult.get(); 11285 RHS = RHSResult.get(); 11286 11287 if (Opc == BO_Xor) 11288 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11289 11290 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11291 return compType; 11292 return InvalidOperands(Loc, LHS, RHS); 11293 } 11294 11295 // C99 6.5.[13,14] 11296 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11297 SourceLocation Loc, 11298 BinaryOperatorKind Opc) { 11299 // Check vector operands differently. 11300 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11301 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11302 11303 // Diagnose cases where the user write a logical and/or but probably meant a 11304 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11305 // is a constant. 11306 if (LHS.get()->getType()->isIntegerType() && 11307 !LHS.get()->getType()->isBooleanType() && 11308 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11309 // Don't warn in macros or template instantiations. 11310 !Loc.isMacroID() && !inTemplateInstantiation()) { 11311 // If the RHS can be constant folded, and if it constant folds to something 11312 // that isn't 0 or 1 (which indicate a potential logical operation that 11313 // happened to fold to true/false) then warn. 11314 // Parens on the RHS are ignored. 11315 Expr::EvalResult EVResult; 11316 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11317 llvm::APSInt Result = EVResult.Val.getInt(); 11318 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11319 !RHS.get()->getExprLoc().isMacroID()) || 11320 (Result != 0 && Result != 1)) { 11321 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11322 << RHS.get()->getSourceRange() 11323 << (Opc == BO_LAnd ? "&&" : "||"); 11324 // Suggest replacing the logical operator with the bitwise version 11325 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11326 << (Opc == BO_LAnd ? "&" : "|") 11327 << FixItHint::CreateReplacement(SourceRange( 11328 Loc, getLocForEndOfToken(Loc)), 11329 Opc == BO_LAnd ? "&" : "|"); 11330 if (Opc == BO_LAnd) 11331 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11332 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11333 << FixItHint::CreateRemoval( 11334 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11335 RHS.get()->getEndLoc())); 11336 } 11337 } 11338 } 11339 11340 if (!Context.getLangOpts().CPlusPlus) { 11341 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11342 // not operate on the built-in scalar and vector float types. 11343 if (Context.getLangOpts().OpenCL && 11344 Context.getLangOpts().OpenCLVersion < 120) { 11345 if (LHS.get()->getType()->isFloatingType() || 11346 RHS.get()->getType()->isFloatingType()) 11347 return InvalidOperands(Loc, LHS, RHS); 11348 } 11349 11350 LHS = UsualUnaryConversions(LHS.get()); 11351 if (LHS.isInvalid()) 11352 return QualType(); 11353 11354 RHS = UsualUnaryConversions(RHS.get()); 11355 if (RHS.isInvalid()) 11356 return QualType(); 11357 11358 if (!LHS.get()->getType()->isScalarType() || 11359 !RHS.get()->getType()->isScalarType()) 11360 return InvalidOperands(Loc, LHS, RHS); 11361 11362 return Context.IntTy; 11363 } 11364 11365 // The following is safe because we only use this method for 11366 // non-overloadable operands. 11367 11368 // C++ [expr.log.and]p1 11369 // C++ [expr.log.or]p1 11370 // The operands are both contextually converted to type bool. 11371 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11372 if (LHSRes.isInvalid()) 11373 return InvalidOperands(Loc, LHS, RHS); 11374 LHS = LHSRes; 11375 11376 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11377 if (RHSRes.isInvalid()) 11378 return InvalidOperands(Loc, LHS, RHS); 11379 RHS = RHSRes; 11380 11381 // C++ [expr.log.and]p2 11382 // C++ [expr.log.or]p2 11383 // The result is a bool. 11384 return Context.BoolTy; 11385 } 11386 11387 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11388 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11389 if (!ME) return false; 11390 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11391 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11392 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11393 if (!Base) return false; 11394 return Base->getMethodDecl() != nullptr; 11395 } 11396 11397 /// Is the given expression (which must be 'const') a reference to a 11398 /// variable which was originally non-const, but which has become 11399 /// 'const' due to being captured within a block? 11400 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11401 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11402 assert(E->isLValue() && E->getType().isConstQualified()); 11403 E = E->IgnoreParens(); 11404 11405 // Must be a reference to a declaration from an enclosing scope. 11406 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11407 if (!DRE) return NCCK_None; 11408 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11409 11410 // The declaration must be a variable which is not declared 'const'. 11411 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11412 if (!var) return NCCK_None; 11413 if (var->getType().isConstQualified()) return NCCK_None; 11414 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11415 11416 // Decide whether the first capture was for a block or a lambda. 11417 DeclContext *DC = S.CurContext, *Prev = nullptr; 11418 // Decide whether the first capture was for a block or a lambda. 11419 while (DC) { 11420 // For init-capture, it is possible that the variable belongs to the 11421 // template pattern of the current context. 11422 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11423 if (var->isInitCapture() && 11424 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11425 break; 11426 if (DC == var->getDeclContext()) 11427 break; 11428 Prev = DC; 11429 DC = DC->getParent(); 11430 } 11431 // Unless we have an init-capture, we've gone one step too far. 11432 if (!var->isInitCapture()) 11433 DC = Prev; 11434 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11435 } 11436 11437 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11438 Ty = Ty.getNonReferenceType(); 11439 if (IsDereference && Ty->isPointerType()) 11440 Ty = Ty->getPointeeType(); 11441 return !Ty.isConstQualified(); 11442 } 11443 11444 // Update err_typecheck_assign_const and note_typecheck_assign_const 11445 // when this enum is changed. 11446 enum { 11447 ConstFunction, 11448 ConstVariable, 11449 ConstMember, 11450 ConstMethod, 11451 NestedConstMember, 11452 ConstUnknown, // Keep as last element 11453 }; 11454 11455 /// Emit the "read-only variable not assignable" error and print notes to give 11456 /// more information about why the variable is not assignable, such as pointing 11457 /// to the declaration of a const variable, showing that a method is const, or 11458 /// that the function is returning a const reference. 11459 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11460 SourceLocation Loc) { 11461 SourceRange ExprRange = E->getSourceRange(); 11462 11463 // Only emit one error on the first const found. All other consts will emit 11464 // a note to the error. 11465 bool DiagnosticEmitted = false; 11466 11467 // Track if the current expression is the result of a dereference, and if the 11468 // next checked expression is the result of a dereference. 11469 bool IsDereference = false; 11470 bool NextIsDereference = false; 11471 11472 // Loop to process MemberExpr chains. 11473 while (true) { 11474 IsDereference = NextIsDereference; 11475 11476 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11477 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11478 NextIsDereference = ME->isArrow(); 11479 const ValueDecl *VD = ME->getMemberDecl(); 11480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11481 // Mutable fields can be modified even if the class is const. 11482 if (Field->isMutable()) { 11483 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11484 break; 11485 } 11486 11487 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11488 if (!DiagnosticEmitted) { 11489 S.Diag(Loc, diag::err_typecheck_assign_const) 11490 << ExprRange << ConstMember << false /*static*/ << Field 11491 << Field->getType(); 11492 DiagnosticEmitted = true; 11493 } 11494 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11495 << ConstMember << false /*static*/ << Field << Field->getType() 11496 << Field->getSourceRange(); 11497 } 11498 E = ME->getBase(); 11499 continue; 11500 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11501 if (VDecl->getType().isConstQualified()) { 11502 if (!DiagnosticEmitted) { 11503 S.Diag(Loc, diag::err_typecheck_assign_const) 11504 << ExprRange << ConstMember << true /*static*/ << VDecl 11505 << VDecl->getType(); 11506 DiagnosticEmitted = true; 11507 } 11508 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11509 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11510 << VDecl->getSourceRange(); 11511 } 11512 // Static fields do not inherit constness from parents. 11513 break; 11514 } 11515 break; // End MemberExpr 11516 } else if (const ArraySubscriptExpr *ASE = 11517 dyn_cast<ArraySubscriptExpr>(E)) { 11518 E = ASE->getBase()->IgnoreParenImpCasts(); 11519 continue; 11520 } else if (const ExtVectorElementExpr *EVE = 11521 dyn_cast<ExtVectorElementExpr>(E)) { 11522 E = EVE->getBase()->IgnoreParenImpCasts(); 11523 continue; 11524 } 11525 break; 11526 } 11527 11528 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11529 // Function calls 11530 const FunctionDecl *FD = CE->getDirectCallee(); 11531 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11532 if (!DiagnosticEmitted) { 11533 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11534 << ConstFunction << FD; 11535 DiagnosticEmitted = true; 11536 } 11537 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11538 diag::note_typecheck_assign_const) 11539 << ConstFunction << FD << FD->getReturnType() 11540 << FD->getReturnTypeSourceRange(); 11541 } 11542 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11543 // Point to variable declaration. 11544 if (const ValueDecl *VD = DRE->getDecl()) { 11545 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11546 if (!DiagnosticEmitted) { 11547 S.Diag(Loc, diag::err_typecheck_assign_const) 11548 << ExprRange << ConstVariable << VD << VD->getType(); 11549 DiagnosticEmitted = true; 11550 } 11551 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11552 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11553 } 11554 } 11555 } else if (isa<CXXThisExpr>(E)) { 11556 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11557 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11558 if (MD->isConst()) { 11559 if (!DiagnosticEmitted) { 11560 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11561 << ConstMethod << MD; 11562 DiagnosticEmitted = true; 11563 } 11564 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11565 << ConstMethod << MD << MD->getSourceRange(); 11566 } 11567 } 11568 } 11569 } 11570 11571 if (DiagnosticEmitted) 11572 return; 11573 11574 // Can't determine a more specific message, so display the generic error. 11575 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11576 } 11577 11578 enum OriginalExprKind { 11579 OEK_Variable, 11580 OEK_Member, 11581 OEK_LValue 11582 }; 11583 11584 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11585 const RecordType *Ty, 11586 SourceLocation Loc, SourceRange Range, 11587 OriginalExprKind OEK, 11588 bool &DiagnosticEmitted) { 11589 std::vector<const RecordType *> RecordTypeList; 11590 RecordTypeList.push_back(Ty); 11591 unsigned NextToCheckIndex = 0; 11592 // We walk the record hierarchy breadth-first to ensure that we print 11593 // diagnostics in field nesting order. 11594 while (RecordTypeList.size() > NextToCheckIndex) { 11595 bool IsNested = NextToCheckIndex > 0; 11596 for (const FieldDecl *Field : 11597 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11598 // First, check every field for constness. 11599 QualType FieldTy = Field->getType(); 11600 if (FieldTy.isConstQualified()) { 11601 if (!DiagnosticEmitted) { 11602 S.Diag(Loc, diag::err_typecheck_assign_const) 11603 << Range << NestedConstMember << OEK << VD 11604 << IsNested << Field; 11605 DiagnosticEmitted = true; 11606 } 11607 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11608 << NestedConstMember << IsNested << Field 11609 << FieldTy << Field->getSourceRange(); 11610 } 11611 11612 // Then we append it to the list to check next in order. 11613 FieldTy = FieldTy.getCanonicalType(); 11614 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11615 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11616 RecordTypeList.push_back(FieldRecTy); 11617 } 11618 } 11619 ++NextToCheckIndex; 11620 } 11621 } 11622 11623 /// Emit an error for the case where a record we are trying to assign to has a 11624 /// const-qualified field somewhere in its hierarchy. 11625 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11626 SourceLocation Loc) { 11627 QualType Ty = E->getType(); 11628 assert(Ty->isRecordType() && "lvalue was not record?"); 11629 SourceRange Range = E->getSourceRange(); 11630 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11631 bool DiagEmitted = false; 11632 11633 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11634 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11635 Range, OEK_Member, DiagEmitted); 11636 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11637 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11638 Range, OEK_Variable, DiagEmitted); 11639 else 11640 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11641 Range, OEK_LValue, DiagEmitted); 11642 if (!DiagEmitted) 11643 DiagnoseConstAssignment(S, E, Loc); 11644 } 11645 11646 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11647 /// emit an error and return true. If so, return false. 11648 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11649 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11650 11651 S.CheckShadowingDeclModification(E, Loc); 11652 11653 SourceLocation OrigLoc = Loc; 11654 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11655 &Loc); 11656 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11657 IsLV = Expr::MLV_InvalidMessageExpression; 11658 if (IsLV == Expr::MLV_Valid) 11659 return false; 11660 11661 unsigned DiagID = 0; 11662 bool NeedType = false; 11663 switch (IsLV) { // C99 6.5.16p2 11664 case Expr::MLV_ConstQualified: 11665 // Use a specialized diagnostic when we're assigning to an object 11666 // from an enclosing function or block. 11667 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11668 if (NCCK == NCCK_Block) 11669 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11670 else 11671 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11672 break; 11673 } 11674 11675 // In ARC, use some specialized diagnostics for occasions where we 11676 // infer 'const'. These are always pseudo-strong variables. 11677 if (S.getLangOpts().ObjCAutoRefCount) { 11678 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11679 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11680 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11681 11682 // Use the normal diagnostic if it's pseudo-__strong but the 11683 // user actually wrote 'const'. 11684 if (var->isARCPseudoStrong() && 11685 (!var->getTypeSourceInfo() || 11686 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11687 // There are three pseudo-strong cases: 11688 // - self 11689 ObjCMethodDecl *method = S.getCurMethodDecl(); 11690 if (method && var == method->getSelfDecl()) { 11691 DiagID = method->isClassMethod() 11692 ? diag::err_typecheck_arc_assign_self_class_method 11693 : diag::err_typecheck_arc_assign_self; 11694 11695 // - Objective-C externally_retained attribute. 11696 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11697 isa<ParmVarDecl>(var)) { 11698 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11699 11700 // - fast enumeration variables 11701 } else { 11702 DiagID = diag::err_typecheck_arr_assign_enumeration; 11703 } 11704 11705 SourceRange Assign; 11706 if (Loc != OrigLoc) 11707 Assign = SourceRange(OrigLoc, OrigLoc); 11708 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11709 // We need to preserve the AST regardless, so migration tool 11710 // can do its job. 11711 return false; 11712 } 11713 } 11714 } 11715 11716 // If none of the special cases above are triggered, then this is a 11717 // simple const assignment. 11718 if (DiagID == 0) { 11719 DiagnoseConstAssignment(S, E, Loc); 11720 return true; 11721 } 11722 11723 break; 11724 case Expr::MLV_ConstAddrSpace: 11725 DiagnoseConstAssignment(S, E, Loc); 11726 return true; 11727 case Expr::MLV_ConstQualifiedField: 11728 DiagnoseRecursiveConstFields(S, E, Loc); 11729 return true; 11730 case Expr::MLV_ArrayType: 11731 case Expr::MLV_ArrayTemporary: 11732 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11733 NeedType = true; 11734 break; 11735 case Expr::MLV_NotObjectType: 11736 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11737 NeedType = true; 11738 break; 11739 case Expr::MLV_LValueCast: 11740 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11741 break; 11742 case Expr::MLV_Valid: 11743 llvm_unreachable("did not take early return for MLV_Valid"); 11744 case Expr::MLV_InvalidExpression: 11745 case Expr::MLV_MemberFunction: 11746 case Expr::MLV_ClassTemporary: 11747 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11748 break; 11749 case Expr::MLV_IncompleteType: 11750 case Expr::MLV_IncompleteVoidType: 11751 return S.RequireCompleteType(Loc, E->getType(), 11752 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11753 case Expr::MLV_DuplicateVectorComponents: 11754 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11755 break; 11756 case Expr::MLV_NoSetterProperty: 11757 llvm_unreachable("readonly properties should be processed differently"); 11758 case Expr::MLV_InvalidMessageExpression: 11759 DiagID = diag::err_readonly_message_assignment; 11760 break; 11761 case Expr::MLV_SubObjCPropertySetting: 11762 DiagID = diag::err_no_subobject_property_setting; 11763 break; 11764 } 11765 11766 SourceRange Assign; 11767 if (Loc != OrigLoc) 11768 Assign = SourceRange(OrigLoc, OrigLoc); 11769 if (NeedType) 11770 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11771 else 11772 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11773 return true; 11774 } 11775 11776 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11777 SourceLocation Loc, 11778 Sema &Sema) { 11779 if (Sema.inTemplateInstantiation()) 11780 return; 11781 if (Sema.isUnevaluatedContext()) 11782 return; 11783 if (Loc.isInvalid() || Loc.isMacroID()) 11784 return; 11785 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11786 return; 11787 11788 // C / C++ fields 11789 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11790 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11791 if (ML && MR) { 11792 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11793 return; 11794 const ValueDecl *LHSDecl = 11795 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11796 const ValueDecl *RHSDecl = 11797 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11798 if (LHSDecl != RHSDecl) 11799 return; 11800 if (LHSDecl->getType().isVolatileQualified()) 11801 return; 11802 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11803 if (RefTy->getPointeeType().isVolatileQualified()) 11804 return; 11805 11806 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11807 } 11808 11809 // Objective-C instance variables 11810 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11811 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11812 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11813 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11814 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11815 if (RL && RR && RL->getDecl() == RR->getDecl()) 11816 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11817 } 11818 } 11819 11820 // C99 6.5.16.1 11821 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11822 SourceLocation Loc, 11823 QualType CompoundType) { 11824 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11825 11826 // Verify that LHS is a modifiable lvalue, and emit error if not. 11827 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11828 return QualType(); 11829 11830 QualType LHSType = LHSExpr->getType(); 11831 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11832 CompoundType; 11833 // OpenCL v1.2 s6.1.1.1 p2: 11834 // The half data type can only be used to declare a pointer to a buffer that 11835 // contains half values 11836 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11837 LHSType->isHalfType()) { 11838 Diag(Loc, diag::err_opencl_half_load_store) << 1 11839 << LHSType.getUnqualifiedType(); 11840 return QualType(); 11841 } 11842 11843 AssignConvertType ConvTy; 11844 if (CompoundType.isNull()) { 11845 Expr *RHSCheck = RHS.get(); 11846 11847 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11848 11849 QualType LHSTy(LHSType); 11850 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11851 if (RHS.isInvalid()) 11852 return QualType(); 11853 // Special case of NSObject attributes on c-style pointer types. 11854 if (ConvTy == IncompatiblePointer && 11855 ((Context.isObjCNSObjectType(LHSType) && 11856 RHSType->isObjCObjectPointerType()) || 11857 (Context.isObjCNSObjectType(RHSType) && 11858 LHSType->isObjCObjectPointerType()))) 11859 ConvTy = Compatible; 11860 11861 if (ConvTy == Compatible && 11862 LHSType->isObjCObjectType()) 11863 Diag(Loc, diag::err_objc_object_assignment) 11864 << LHSType; 11865 11866 // If the RHS is a unary plus or minus, check to see if they = and + are 11867 // right next to each other. If so, the user may have typo'd "x =+ 4" 11868 // instead of "x += 4". 11869 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11870 RHSCheck = ICE->getSubExpr(); 11871 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11872 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11873 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11874 // Only if the two operators are exactly adjacent. 11875 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11876 // And there is a space or other character before the subexpr of the 11877 // unary +/-. We don't want to warn on "x=-1". 11878 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11879 UO->getSubExpr()->getBeginLoc().isFileID()) { 11880 Diag(Loc, diag::warn_not_compound_assign) 11881 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11882 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11883 } 11884 } 11885 11886 if (ConvTy == Compatible) { 11887 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11888 // Warn about retain cycles where a block captures the LHS, but 11889 // not if the LHS is a simple variable into which the block is 11890 // being stored...unless that variable can be captured by reference! 11891 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11892 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11893 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11894 checkRetainCycles(LHSExpr, RHS.get()); 11895 } 11896 11897 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11898 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11899 // It is safe to assign a weak reference into a strong variable. 11900 // Although this code can still have problems: 11901 // id x = self.weakProp; 11902 // id y = self.weakProp; 11903 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11904 // paths through the function. This should be revisited if 11905 // -Wrepeated-use-of-weak is made flow-sensitive. 11906 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11907 // variable, which will be valid for the current autorelease scope. 11908 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11909 RHS.get()->getBeginLoc())) 11910 getCurFunction()->markSafeWeakUse(RHS.get()); 11911 11912 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11913 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11914 } 11915 } 11916 } else { 11917 // Compound assignment "x += y" 11918 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11919 } 11920 11921 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11922 RHS.get(), AA_Assigning)) 11923 return QualType(); 11924 11925 CheckForNullPointerDereference(*this, LHSExpr); 11926 11927 // C99 6.5.16p3: The type of an assignment expression is the type of the 11928 // left operand unless the left operand has qualified type, in which case 11929 // it is the unqualified version of the type of the left operand. 11930 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11931 // is converted to the type of the assignment expression (above). 11932 // C++ 5.17p1: the type of the assignment expression is that of its left 11933 // operand. 11934 return (getLangOpts().CPlusPlus 11935 ? LHSType : LHSType.getUnqualifiedType()); 11936 } 11937 11938 // Only ignore explicit casts to void. 11939 static bool IgnoreCommaOperand(const Expr *E) { 11940 E = E->IgnoreParens(); 11941 11942 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11943 if (CE->getCastKind() == CK_ToVoid) { 11944 return true; 11945 } 11946 11947 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11948 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11949 CE->getSubExpr()->getType()->isDependentType()) { 11950 return true; 11951 } 11952 } 11953 11954 return false; 11955 } 11956 11957 // Look for instances where it is likely the comma operator is confused with 11958 // another operator. There is a whitelist of acceptable expressions for the 11959 // left hand side of the comma operator, otherwise emit a warning. 11960 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11961 // No warnings in macros 11962 if (Loc.isMacroID()) 11963 return; 11964 11965 // Don't warn in template instantiations. 11966 if (inTemplateInstantiation()) 11967 return; 11968 11969 // Scope isn't fine-grained enough to whitelist the specific cases, so 11970 // instead, skip more than needed, then call back into here with the 11971 // CommaVisitor in SemaStmt.cpp. 11972 // The whitelisted locations are the initialization and increment portions 11973 // of a for loop. The additional checks are on the condition of 11974 // if statements, do/while loops, and for loops. 11975 // Differences in scope flags for C89 mode requires the extra logic. 11976 const unsigned ForIncrementFlags = 11977 getLangOpts().C99 || getLangOpts().CPlusPlus 11978 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11979 : Scope::ContinueScope | Scope::BreakScope; 11980 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11981 const unsigned ScopeFlags = getCurScope()->getFlags(); 11982 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11983 (ScopeFlags & ForInitFlags) == ForInitFlags) 11984 return; 11985 11986 // If there are multiple comma operators used together, get the RHS of the 11987 // of the comma operator as the LHS. 11988 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11989 if (BO->getOpcode() != BO_Comma) 11990 break; 11991 LHS = BO->getRHS(); 11992 } 11993 11994 // Only allow some expressions on LHS to not warn. 11995 if (IgnoreCommaOperand(LHS)) 11996 return; 11997 11998 Diag(Loc, diag::warn_comma_operator); 11999 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12000 << LHS->getSourceRange() 12001 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12002 LangOpts.CPlusPlus ? "static_cast<void>(" 12003 : "(void)(") 12004 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12005 ")"); 12006 } 12007 12008 // C99 6.5.17 12009 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12010 SourceLocation Loc) { 12011 LHS = S.CheckPlaceholderExpr(LHS.get()); 12012 RHS = S.CheckPlaceholderExpr(RHS.get()); 12013 if (LHS.isInvalid() || RHS.isInvalid()) 12014 return QualType(); 12015 12016 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12017 // operands, but not unary promotions. 12018 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12019 12020 // So we treat the LHS as a ignored value, and in C++ we allow the 12021 // containing site to determine what should be done with the RHS. 12022 LHS = S.IgnoredValueConversions(LHS.get()); 12023 if (LHS.isInvalid()) 12024 return QualType(); 12025 12026 S.DiagnoseUnusedExprResult(LHS.get()); 12027 12028 if (!S.getLangOpts().CPlusPlus) { 12029 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12030 if (RHS.isInvalid()) 12031 return QualType(); 12032 if (!RHS.get()->getType()->isVoidType()) 12033 S.RequireCompleteType(Loc, RHS.get()->getType(), 12034 diag::err_incomplete_type); 12035 } 12036 12037 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12038 S.DiagnoseCommaOperator(LHS.get(), Loc); 12039 12040 return RHS.get()->getType(); 12041 } 12042 12043 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12044 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12045 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12046 ExprValueKind &VK, 12047 ExprObjectKind &OK, 12048 SourceLocation OpLoc, 12049 bool IsInc, bool IsPrefix) { 12050 if (Op->isTypeDependent()) 12051 return S.Context.DependentTy; 12052 12053 QualType ResType = Op->getType(); 12054 // Atomic types can be used for increment / decrement where the non-atomic 12055 // versions can, so ignore the _Atomic() specifier for the purpose of 12056 // checking. 12057 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12058 ResType = ResAtomicType->getValueType(); 12059 12060 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12061 12062 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12063 // Decrement of bool is not allowed. 12064 if (!IsInc) { 12065 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12066 return QualType(); 12067 } 12068 // Increment of bool sets it to true, but is deprecated. 12069 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12070 : diag::warn_increment_bool) 12071 << Op->getSourceRange(); 12072 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12073 // Error on enum increments and decrements in C++ mode 12074 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12075 return QualType(); 12076 } else if (ResType->isRealType()) { 12077 // OK! 12078 } else if (ResType->isPointerType()) { 12079 // C99 6.5.2.4p2, 6.5.6p2 12080 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12081 return QualType(); 12082 } else if (ResType->isObjCObjectPointerType()) { 12083 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12084 // Otherwise, we just need a complete type. 12085 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12086 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12087 return QualType(); 12088 } else if (ResType->isAnyComplexType()) { 12089 // C99 does not support ++/-- on complex types, we allow as an extension. 12090 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12091 << ResType << Op->getSourceRange(); 12092 } else if (ResType->isPlaceholderType()) { 12093 ExprResult PR = S.CheckPlaceholderExpr(Op); 12094 if (PR.isInvalid()) return QualType(); 12095 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12096 IsInc, IsPrefix); 12097 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12098 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12099 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12100 (ResType->getAs<VectorType>()->getVectorKind() != 12101 VectorType::AltiVecBool)) { 12102 // The z vector extensions allow ++ and -- for non-bool vectors. 12103 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12104 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 12105 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12106 } else { 12107 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12108 << ResType << int(IsInc) << Op->getSourceRange(); 12109 return QualType(); 12110 } 12111 // At this point, we know we have a real, complex or pointer type. 12112 // Now make sure the operand is a modifiable lvalue. 12113 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12114 return QualType(); 12115 // In C++, a prefix increment is the same type as the operand. Otherwise 12116 // (in C or with postfix), the increment is the unqualified type of the 12117 // operand. 12118 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12119 VK = VK_LValue; 12120 OK = Op->getObjectKind(); 12121 return ResType; 12122 } else { 12123 VK = VK_RValue; 12124 return ResType.getUnqualifiedType(); 12125 } 12126 } 12127 12128 12129 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12130 /// This routine allows us to typecheck complex/recursive expressions 12131 /// where the declaration is needed for type checking. We only need to 12132 /// handle cases when the expression references a function designator 12133 /// or is an lvalue. Here are some examples: 12134 /// - &(x) => x 12135 /// - &*****f => f for f a function designator. 12136 /// - &s.xx => s 12137 /// - &s.zz[1].yy -> s, if zz is an array 12138 /// - *(x + 1) -> x, if x is an array 12139 /// - &"123"[2] -> 0 12140 /// - & __real__ x -> x 12141 static ValueDecl *getPrimaryDecl(Expr *E) { 12142 switch (E->getStmtClass()) { 12143 case Stmt::DeclRefExprClass: 12144 return cast<DeclRefExpr>(E)->getDecl(); 12145 case Stmt::MemberExprClass: 12146 // If this is an arrow operator, the address is an offset from 12147 // the base's value, so the object the base refers to is 12148 // irrelevant. 12149 if (cast<MemberExpr>(E)->isArrow()) 12150 return nullptr; 12151 // Otherwise, the expression refers to a part of the base 12152 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12153 case Stmt::ArraySubscriptExprClass: { 12154 // FIXME: This code shouldn't be necessary! We should catch the implicit 12155 // promotion of register arrays earlier. 12156 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12157 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12158 if (ICE->getSubExpr()->getType()->isArrayType()) 12159 return getPrimaryDecl(ICE->getSubExpr()); 12160 } 12161 return nullptr; 12162 } 12163 case Stmt::UnaryOperatorClass: { 12164 UnaryOperator *UO = cast<UnaryOperator>(E); 12165 12166 switch(UO->getOpcode()) { 12167 case UO_Real: 12168 case UO_Imag: 12169 case UO_Extension: 12170 return getPrimaryDecl(UO->getSubExpr()); 12171 default: 12172 return nullptr; 12173 } 12174 } 12175 case Stmt::ParenExprClass: 12176 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12177 case Stmt::ImplicitCastExprClass: 12178 // If the result of an implicit cast is an l-value, we care about 12179 // the sub-expression; otherwise, the result here doesn't matter. 12180 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12181 default: 12182 return nullptr; 12183 } 12184 } 12185 12186 namespace { 12187 enum { 12188 AO_Bit_Field = 0, 12189 AO_Vector_Element = 1, 12190 AO_Property_Expansion = 2, 12191 AO_Register_Variable = 3, 12192 AO_No_Error = 4 12193 }; 12194 } 12195 /// Diagnose invalid operand for address of operations. 12196 /// 12197 /// \param Type The type of operand which cannot have its address taken. 12198 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12199 Expr *E, unsigned Type) { 12200 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12201 } 12202 12203 /// CheckAddressOfOperand - The operand of & must be either a function 12204 /// designator or an lvalue designating an object. If it is an lvalue, the 12205 /// object cannot be declared with storage class register or be a bit field. 12206 /// Note: The usual conversions are *not* applied to the operand of the & 12207 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12208 /// In C++, the operand might be an overloaded function name, in which case 12209 /// we allow the '&' but retain the overloaded-function type. 12210 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12211 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12212 if (PTy->getKind() == BuiltinType::Overload) { 12213 Expr *E = OrigOp.get()->IgnoreParens(); 12214 if (!isa<OverloadExpr>(E)) { 12215 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12216 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12217 << OrigOp.get()->getSourceRange(); 12218 return QualType(); 12219 } 12220 12221 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12222 if (isa<UnresolvedMemberExpr>(Ovl)) 12223 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12224 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12225 << OrigOp.get()->getSourceRange(); 12226 return QualType(); 12227 } 12228 12229 return Context.OverloadTy; 12230 } 12231 12232 if (PTy->getKind() == BuiltinType::UnknownAny) 12233 return Context.UnknownAnyTy; 12234 12235 if (PTy->getKind() == BuiltinType::BoundMember) { 12236 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12237 << OrigOp.get()->getSourceRange(); 12238 return QualType(); 12239 } 12240 12241 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12242 if (OrigOp.isInvalid()) return QualType(); 12243 } 12244 12245 if (OrigOp.get()->isTypeDependent()) 12246 return Context.DependentTy; 12247 12248 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12249 12250 // Make sure to ignore parentheses in subsequent checks 12251 Expr *op = OrigOp.get()->IgnoreParens(); 12252 12253 // In OpenCL captures for blocks called as lambda functions 12254 // are located in the private address space. Blocks used in 12255 // enqueue_kernel can be located in a different address space 12256 // depending on a vendor implementation. Thus preventing 12257 // taking an address of the capture to avoid invalid AS casts. 12258 if (LangOpts.OpenCL) { 12259 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12260 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12261 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12262 return QualType(); 12263 } 12264 } 12265 12266 if (getLangOpts().C99) { 12267 // Implement C99-only parts of addressof rules. 12268 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12269 if (uOp->getOpcode() == UO_Deref) 12270 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12271 // (assuming the deref expression is valid). 12272 return uOp->getSubExpr()->getType(); 12273 } 12274 // Technically, there should be a check for array subscript 12275 // expressions here, but the result of one is always an lvalue anyway. 12276 } 12277 ValueDecl *dcl = getPrimaryDecl(op); 12278 12279 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12280 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12281 op->getBeginLoc())) 12282 return QualType(); 12283 12284 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12285 unsigned AddressOfError = AO_No_Error; 12286 12287 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12288 bool sfinae = (bool)isSFINAEContext(); 12289 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12290 : diag::ext_typecheck_addrof_temporary) 12291 << op->getType() << op->getSourceRange(); 12292 if (sfinae) 12293 return QualType(); 12294 // Materialize the temporary as an lvalue so that we can take its address. 12295 OrigOp = op = 12296 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12297 } else if (isa<ObjCSelectorExpr>(op)) { 12298 return Context.getPointerType(op->getType()); 12299 } else if (lval == Expr::LV_MemberFunction) { 12300 // If it's an instance method, make a member pointer. 12301 // The expression must have exactly the form &A::foo. 12302 12303 // If the underlying expression isn't a decl ref, give up. 12304 if (!isa<DeclRefExpr>(op)) { 12305 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12306 << OrigOp.get()->getSourceRange(); 12307 return QualType(); 12308 } 12309 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12310 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12311 12312 // The id-expression was parenthesized. 12313 if (OrigOp.get() != DRE) { 12314 Diag(OpLoc, diag::err_parens_pointer_member_function) 12315 << OrigOp.get()->getSourceRange(); 12316 12317 // The method was named without a qualifier. 12318 } else if (!DRE->getQualifier()) { 12319 if (MD->getParent()->getName().empty()) 12320 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12321 << op->getSourceRange(); 12322 else { 12323 SmallString<32> Str; 12324 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12325 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12326 << op->getSourceRange() 12327 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12328 } 12329 } 12330 12331 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12332 if (isa<CXXDestructorDecl>(MD)) 12333 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12334 12335 QualType MPTy = Context.getMemberPointerType( 12336 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12337 // Under the MS ABI, lock down the inheritance model now. 12338 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12339 (void)isCompleteType(OpLoc, MPTy); 12340 return MPTy; 12341 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12342 // C99 6.5.3.2p1 12343 // The operand must be either an l-value or a function designator 12344 if (!op->getType()->isFunctionType()) { 12345 // Use a special diagnostic for loads from property references. 12346 if (isa<PseudoObjectExpr>(op)) { 12347 AddressOfError = AO_Property_Expansion; 12348 } else { 12349 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12350 << op->getType() << op->getSourceRange(); 12351 return QualType(); 12352 } 12353 } 12354 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12355 // The operand cannot be a bit-field 12356 AddressOfError = AO_Bit_Field; 12357 } else if (op->getObjectKind() == OK_VectorComponent) { 12358 // The operand cannot be an element of a vector 12359 AddressOfError = AO_Vector_Element; 12360 } else if (dcl) { // C99 6.5.3.2p1 12361 // We have an lvalue with a decl. Make sure the decl is not declared 12362 // with the register storage-class specifier. 12363 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12364 // in C++ it is not error to take address of a register 12365 // variable (c++03 7.1.1P3) 12366 if (vd->getStorageClass() == SC_Register && 12367 !getLangOpts().CPlusPlus) { 12368 AddressOfError = AO_Register_Variable; 12369 } 12370 } else if (isa<MSPropertyDecl>(dcl)) { 12371 AddressOfError = AO_Property_Expansion; 12372 } else if (isa<FunctionTemplateDecl>(dcl)) { 12373 return Context.OverloadTy; 12374 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12375 // Okay: we can take the address of a field. 12376 // Could be a pointer to member, though, if there is an explicit 12377 // scope qualifier for the class. 12378 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12379 DeclContext *Ctx = dcl->getDeclContext(); 12380 if (Ctx && Ctx->isRecord()) { 12381 if (dcl->getType()->isReferenceType()) { 12382 Diag(OpLoc, 12383 diag::err_cannot_form_pointer_to_member_of_reference_type) 12384 << dcl->getDeclName() << dcl->getType(); 12385 return QualType(); 12386 } 12387 12388 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12389 Ctx = Ctx->getParent(); 12390 12391 QualType MPTy = Context.getMemberPointerType( 12392 op->getType(), 12393 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12394 // Under the MS ABI, lock down the inheritance model now. 12395 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12396 (void)isCompleteType(OpLoc, MPTy); 12397 return MPTy; 12398 } 12399 } 12400 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12401 !isa<BindingDecl>(dcl)) 12402 llvm_unreachable("Unknown/unexpected decl type"); 12403 } 12404 12405 if (AddressOfError != AO_No_Error) { 12406 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12407 return QualType(); 12408 } 12409 12410 if (lval == Expr::LV_IncompleteVoidType) { 12411 // Taking the address of a void variable is technically illegal, but we 12412 // allow it in cases which are otherwise valid. 12413 // Example: "extern void x; void* y = &x;". 12414 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12415 } 12416 12417 // If the operand has type "type", the result has type "pointer to type". 12418 if (op->getType()->isObjCObjectType()) 12419 return Context.getObjCObjectPointerType(op->getType()); 12420 12421 CheckAddressOfPackedMember(op); 12422 12423 return Context.getPointerType(op->getType()); 12424 } 12425 12426 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12427 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12428 if (!DRE) 12429 return; 12430 const Decl *D = DRE->getDecl(); 12431 if (!D) 12432 return; 12433 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12434 if (!Param) 12435 return; 12436 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12437 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12438 return; 12439 if (FunctionScopeInfo *FD = S.getCurFunction()) 12440 if (!FD->ModifiedNonNullParams.count(Param)) 12441 FD->ModifiedNonNullParams.insert(Param); 12442 } 12443 12444 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12445 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12446 SourceLocation OpLoc) { 12447 if (Op->isTypeDependent()) 12448 return S.Context.DependentTy; 12449 12450 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12451 if (ConvResult.isInvalid()) 12452 return QualType(); 12453 Op = ConvResult.get(); 12454 QualType OpTy = Op->getType(); 12455 QualType Result; 12456 12457 if (isa<CXXReinterpretCastExpr>(Op)) { 12458 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12459 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12460 Op->getSourceRange()); 12461 } 12462 12463 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12464 { 12465 Result = PT->getPointeeType(); 12466 } 12467 else if (const ObjCObjectPointerType *OPT = 12468 OpTy->getAs<ObjCObjectPointerType>()) 12469 Result = OPT->getPointeeType(); 12470 else { 12471 ExprResult PR = S.CheckPlaceholderExpr(Op); 12472 if (PR.isInvalid()) return QualType(); 12473 if (PR.get() != Op) 12474 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12475 } 12476 12477 if (Result.isNull()) { 12478 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12479 << OpTy << Op->getSourceRange(); 12480 return QualType(); 12481 } 12482 12483 // Note that per both C89 and C99, indirection is always legal, even if Result 12484 // is an incomplete type or void. It would be possible to warn about 12485 // dereferencing a void pointer, but it's completely well-defined, and such a 12486 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12487 // for pointers to 'void' but is fine for any other pointer type: 12488 // 12489 // C++ [expr.unary.op]p1: 12490 // [...] the expression to which [the unary * operator] is applied shall 12491 // be a pointer to an object type, or a pointer to a function type 12492 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12493 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12494 << OpTy << Op->getSourceRange(); 12495 12496 // Dereferences are usually l-values... 12497 VK = VK_LValue; 12498 12499 // ...except that certain expressions are never l-values in C. 12500 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12501 VK = VK_RValue; 12502 12503 return Result; 12504 } 12505 12506 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12507 BinaryOperatorKind Opc; 12508 switch (Kind) { 12509 default: llvm_unreachable("Unknown binop!"); 12510 case tok::periodstar: Opc = BO_PtrMemD; break; 12511 case tok::arrowstar: Opc = BO_PtrMemI; break; 12512 case tok::star: Opc = BO_Mul; break; 12513 case tok::slash: Opc = BO_Div; break; 12514 case tok::percent: Opc = BO_Rem; break; 12515 case tok::plus: Opc = BO_Add; break; 12516 case tok::minus: Opc = BO_Sub; break; 12517 case tok::lessless: Opc = BO_Shl; break; 12518 case tok::greatergreater: Opc = BO_Shr; break; 12519 case tok::lessequal: Opc = BO_LE; break; 12520 case tok::less: Opc = BO_LT; break; 12521 case tok::greaterequal: Opc = BO_GE; break; 12522 case tok::greater: Opc = BO_GT; break; 12523 case tok::exclaimequal: Opc = BO_NE; break; 12524 case tok::equalequal: Opc = BO_EQ; break; 12525 case tok::spaceship: Opc = BO_Cmp; break; 12526 case tok::amp: Opc = BO_And; break; 12527 case tok::caret: Opc = BO_Xor; break; 12528 case tok::pipe: Opc = BO_Or; break; 12529 case tok::ampamp: Opc = BO_LAnd; break; 12530 case tok::pipepipe: Opc = BO_LOr; break; 12531 case tok::equal: Opc = BO_Assign; break; 12532 case tok::starequal: Opc = BO_MulAssign; break; 12533 case tok::slashequal: Opc = BO_DivAssign; break; 12534 case tok::percentequal: Opc = BO_RemAssign; break; 12535 case tok::plusequal: Opc = BO_AddAssign; break; 12536 case tok::minusequal: Opc = BO_SubAssign; break; 12537 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12538 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12539 case tok::ampequal: Opc = BO_AndAssign; break; 12540 case tok::caretequal: Opc = BO_XorAssign; break; 12541 case tok::pipeequal: Opc = BO_OrAssign; break; 12542 case tok::comma: Opc = BO_Comma; break; 12543 } 12544 return Opc; 12545 } 12546 12547 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12548 tok::TokenKind Kind) { 12549 UnaryOperatorKind Opc; 12550 switch (Kind) { 12551 default: llvm_unreachable("Unknown unary op!"); 12552 case tok::plusplus: Opc = UO_PreInc; break; 12553 case tok::minusminus: Opc = UO_PreDec; break; 12554 case tok::amp: Opc = UO_AddrOf; break; 12555 case tok::star: Opc = UO_Deref; break; 12556 case tok::plus: Opc = UO_Plus; break; 12557 case tok::minus: Opc = UO_Minus; break; 12558 case tok::tilde: Opc = UO_Not; break; 12559 case tok::exclaim: Opc = UO_LNot; break; 12560 case tok::kw___real: Opc = UO_Real; break; 12561 case tok::kw___imag: Opc = UO_Imag; break; 12562 case tok::kw___extension__: Opc = UO_Extension; break; 12563 } 12564 return Opc; 12565 } 12566 12567 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12568 /// This warning suppressed in the event of macro expansions. 12569 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12570 SourceLocation OpLoc, bool IsBuiltin) { 12571 if (S.inTemplateInstantiation()) 12572 return; 12573 if (S.isUnevaluatedContext()) 12574 return; 12575 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12576 return; 12577 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12578 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12579 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12580 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12581 if (!LHSDeclRef || !RHSDeclRef || 12582 LHSDeclRef->getLocation().isMacroID() || 12583 RHSDeclRef->getLocation().isMacroID()) 12584 return; 12585 const ValueDecl *LHSDecl = 12586 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12587 const ValueDecl *RHSDecl = 12588 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12589 if (LHSDecl != RHSDecl) 12590 return; 12591 if (LHSDecl->getType().isVolatileQualified()) 12592 return; 12593 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12594 if (RefTy->getPointeeType().isVolatileQualified()) 12595 return; 12596 12597 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12598 : diag::warn_self_assignment_overloaded) 12599 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12600 << RHSExpr->getSourceRange(); 12601 } 12602 12603 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12604 /// is usually indicative of introspection within the Objective-C pointer. 12605 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12606 SourceLocation OpLoc) { 12607 if (!S.getLangOpts().ObjC) 12608 return; 12609 12610 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12611 const Expr *LHS = L.get(); 12612 const Expr *RHS = R.get(); 12613 12614 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12615 ObjCPointerExpr = LHS; 12616 OtherExpr = RHS; 12617 } 12618 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12619 ObjCPointerExpr = RHS; 12620 OtherExpr = LHS; 12621 } 12622 12623 // This warning is deliberately made very specific to reduce false 12624 // positives with logic that uses '&' for hashing. This logic mainly 12625 // looks for code trying to introspect into tagged pointers, which 12626 // code should generally never do. 12627 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12628 unsigned Diag = diag::warn_objc_pointer_masking; 12629 // Determine if we are introspecting the result of performSelectorXXX. 12630 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12631 // Special case messages to -performSelector and friends, which 12632 // can return non-pointer values boxed in a pointer value. 12633 // Some clients may wish to silence warnings in this subcase. 12634 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12635 Selector S = ME->getSelector(); 12636 StringRef SelArg0 = S.getNameForSlot(0); 12637 if (SelArg0.startswith("performSelector")) 12638 Diag = diag::warn_objc_pointer_masking_performSelector; 12639 } 12640 12641 S.Diag(OpLoc, Diag) 12642 << ObjCPointerExpr->getSourceRange(); 12643 } 12644 } 12645 12646 static NamedDecl *getDeclFromExpr(Expr *E) { 12647 if (!E) 12648 return nullptr; 12649 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12650 return DRE->getDecl(); 12651 if (auto *ME = dyn_cast<MemberExpr>(E)) 12652 return ME->getMemberDecl(); 12653 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12654 return IRE->getDecl(); 12655 return nullptr; 12656 } 12657 12658 // This helper function promotes a binary operator's operands (which are of a 12659 // half vector type) to a vector of floats and then truncates the result to 12660 // a vector of either half or short. 12661 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12662 BinaryOperatorKind Opc, QualType ResultTy, 12663 ExprValueKind VK, ExprObjectKind OK, 12664 bool IsCompAssign, SourceLocation OpLoc, 12665 FPOptions FPFeatures) { 12666 auto &Context = S.getASTContext(); 12667 assert((isVector(ResultTy, Context.HalfTy) || 12668 isVector(ResultTy, Context.ShortTy)) && 12669 "Result must be a vector of half or short"); 12670 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12671 isVector(RHS.get()->getType(), Context.HalfTy) && 12672 "both operands expected to be a half vector"); 12673 12674 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12675 QualType BinOpResTy = RHS.get()->getType(); 12676 12677 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12678 // change BinOpResTy to a vector of ints. 12679 if (isVector(ResultTy, Context.ShortTy)) 12680 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12681 12682 if (IsCompAssign) 12683 return new (Context) CompoundAssignOperator( 12684 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12685 OpLoc, FPFeatures); 12686 12687 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12688 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12689 VK, OK, OpLoc, FPFeatures); 12690 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12691 } 12692 12693 static std::pair<ExprResult, ExprResult> 12694 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12695 Expr *RHSExpr) { 12696 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12697 if (!S.getLangOpts().CPlusPlus) { 12698 // C cannot handle TypoExpr nodes on either side of a binop because it 12699 // doesn't handle dependent types properly, so make sure any TypoExprs have 12700 // been dealt with before checking the operands. 12701 LHS = S.CorrectDelayedTyposInExpr(LHS); 12702 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12703 if (Opc != BO_Assign) 12704 return ExprResult(E); 12705 // Avoid correcting the RHS to the same Expr as the LHS. 12706 Decl *D = getDeclFromExpr(E); 12707 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12708 }); 12709 } 12710 return std::make_pair(LHS, RHS); 12711 } 12712 12713 /// Returns true if conversion between vectors of halfs and vectors of floats 12714 /// is needed. 12715 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12716 QualType SrcType) { 12717 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12718 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12719 isVector(SrcType, Ctx.HalfTy); 12720 } 12721 12722 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12723 /// operator @p Opc at location @c TokLoc. This routine only supports 12724 /// built-in operations; ActOnBinOp handles overloaded operators. 12725 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12726 BinaryOperatorKind Opc, 12727 Expr *LHSExpr, Expr *RHSExpr) { 12728 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12729 // The syntax only allows initializer lists on the RHS of assignment, 12730 // so we don't need to worry about accepting invalid code for 12731 // non-assignment operators. 12732 // C++11 5.17p9: 12733 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12734 // of x = {} is x = T(). 12735 InitializationKind Kind = InitializationKind::CreateDirectList( 12736 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12737 InitializedEntity Entity = 12738 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12739 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12740 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12741 if (Init.isInvalid()) 12742 return Init; 12743 RHSExpr = Init.get(); 12744 } 12745 12746 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12747 QualType ResultTy; // Result type of the binary operator. 12748 // The following two variables are used for compound assignment operators 12749 QualType CompLHSTy; // Type of LHS after promotions for computation 12750 QualType CompResultTy; // Type of computation result 12751 ExprValueKind VK = VK_RValue; 12752 ExprObjectKind OK = OK_Ordinary; 12753 bool ConvertHalfVec = false; 12754 12755 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12756 if (!LHS.isUsable() || !RHS.isUsable()) 12757 return ExprError(); 12758 12759 if (getLangOpts().OpenCL) { 12760 QualType LHSTy = LHSExpr->getType(); 12761 QualType RHSTy = RHSExpr->getType(); 12762 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12763 // the ATOMIC_VAR_INIT macro. 12764 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12765 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12766 if (BO_Assign == Opc) 12767 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12768 else 12769 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12770 return ExprError(); 12771 } 12772 12773 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12774 // only with a builtin functions and therefore should be disallowed here. 12775 if (LHSTy->isImageType() || RHSTy->isImageType() || 12776 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12777 LHSTy->isPipeType() || RHSTy->isPipeType() || 12778 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12779 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12780 return ExprError(); 12781 } 12782 } 12783 12784 // Diagnose operations on the unsupported types for OpenMP device compilation. 12785 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12786 if (Opc != BO_Assign && Opc != BO_Comma) { 12787 checkOpenMPDeviceExpr(LHSExpr); 12788 checkOpenMPDeviceExpr(RHSExpr); 12789 } 12790 } 12791 12792 switch (Opc) { 12793 case BO_Assign: 12794 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12795 if (getLangOpts().CPlusPlus && 12796 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12797 VK = LHS.get()->getValueKind(); 12798 OK = LHS.get()->getObjectKind(); 12799 } 12800 if (!ResultTy.isNull()) { 12801 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12802 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12803 12804 // Avoid copying a block to the heap if the block is assigned to a local 12805 // auto variable that is declared in the same scope as the block. This 12806 // optimization is unsafe if the local variable is declared in an outer 12807 // scope. For example: 12808 // 12809 // BlockTy b; 12810 // { 12811 // b = ^{...}; 12812 // } 12813 // // It is unsafe to invoke the block here if it wasn't copied to the 12814 // // heap. 12815 // b(); 12816 12817 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12818 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12819 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12820 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12821 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12822 12823 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12824 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12825 NTCUC_Assignment, NTCUK_Copy); 12826 } 12827 RecordModifiableNonNullParam(*this, LHS.get()); 12828 break; 12829 case BO_PtrMemD: 12830 case BO_PtrMemI: 12831 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12832 Opc == BO_PtrMemI); 12833 break; 12834 case BO_Mul: 12835 case BO_Div: 12836 ConvertHalfVec = true; 12837 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12838 Opc == BO_Div); 12839 break; 12840 case BO_Rem: 12841 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12842 break; 12843 case BO_Add: 12844 ConvertHalfVec = true; 12845 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12846 break; 12847 case BO_Sub: 12848 ConvertHalfVec = true; 12849 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12850 break; 12851 case BO_Shl: 12852 case BO_Shr: 12853 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12854 break; 12855 case BO_LE: 12856 case BO_LT: 12857 case BO_GE: 12858 case BO_GT: 12859 ConvertHalfVec = true; 12860 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12861 break; 12862 case BO_EQ: 12863 case BO_NE: 12864 ConvertHalfVec = true; 12865 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12866 break; 12867 case BO_Cmp: 12868 ConvertHalfVec = true; 12869 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12870 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12871 break; 12872 case BO_And: 12873 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12874 LLVM_FALLTHROUGH; 12875 case BO_Xor: 12876 case BO_Or: 12877 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12878 break; 12879 case BO_LAnd: 12880 case BO_LOr: 12881 ConvertHalfVec = true; 12882 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12883 break; 12884 case BO_MulAssign: 12885 case BO_DivAssign: 12886 ConvertHalfVec = true; 12887 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12888 Opc == BO_DivAssign); 12889 CompLHSTy = CompResultTy; 12890 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12891 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12892 break; 12893 case BO_RemAssign: 12894 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12895 CompLHSTy = CompResultTy; 12896 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12897 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12898 break; 12899 case BO_AddAssign: 12900 ConvertHalfVec = true; 12901 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12904 break; 12905 case BO_SubAssign: 12906 ConvertHalfVec = true; 12907 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12908 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12909 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12910 break; 12911 case BO_ShlAssign: 12912 case BO_ShrAssign: 12913 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12914 CompLHSTy = CompResultTy; 12915 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12916 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12917 break; 12918 case BO_AndAssign: 12919 case BO_OrAssign: // fallthrough 12920 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12921 LLVM_FALLTHROUGH; 12922 case BO_XorAssign: 12923 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12924 CompLHSTy = CompResultTy; 12925 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12926 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12927 break; 12928 case BO_Comma: 12929 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12930 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12931 VK = RHS.get()->getValueKind(); 12932 OK = RHS.get()->getObjectKind(); 12933 } 12934 break; 12935 } 12936 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12937 return ExprError(); 12938 12939 // Some of the binary operations require promoting operands of half vector to 12940 // float vectors and truncating the result back to half vector. For now, we do 12941 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12942 // arm64). 12943 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12944 isVector(LHS.get()->getType(), Context.HalfTy) && 12945 "both sides are half vectors or neither sides are"); 12946 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12947 LHS.get()->getType()); 12948 12949 // Check for array bounds violations for both sides of the BinaryOperator 12950 CheckArrayAccess(LHS.get()); 12951 CheckArrayAccess(RHS.get()); 12952 12953 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12954 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12955 &Context.Idents.get("object_setClass"), 12956 SourceLocation(), LookupOrdinaryName); 12957 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12958 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12959 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12960 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12961 "object_setClass(") 12962 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12963 ",") 12964 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12965 } 12966 else 12967 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12968 } 12969 else if (const ObjCIvarRefExpr *OIRE = 12970 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12971 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12972 12973 // Opc is not a compound assignment if CompResultTy is null. 12974 if (CompResultTy.isNull()) { 12975 if (ConvertHalfVec) 12976 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12977 OpLoc, FPFeatures); 12978 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12979 OK, OpLoc, FPFeatures); 12980 } 12981 12982 // Handle compound assignments. 12983 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12984 OK_ObjCProperty) { 12985 VK = VK_LValue; 12986 OK = LHS.get()->getObjectKind(); 12987 } 12988 12989 if (ConvertHalfVec) 12990 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12991 OpLoc, FPFeatures); 12992 12993 return new (Context) CompoundAssignOperator( 12994 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12995 OpLoc, FPFeatures); 12996 } 12997 12998 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12999 /// operators are mixed in a way that suggests that the programmer forgot that 13000 /// comparison operators have higher precedence. The most typical example of 13001 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13002 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13003 SourceLocation OpLoc, Expr *LHSExpr, 13004 Expr *RHSExpr) { 13005 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13006 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13007 13008 // Check that one of the sides is a comparison operator and the other isn't. 13009 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13010 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13011 if (isLeftComp == isRightComp) 13012 return; 13013 13014 // Bitwise operations are sometimes used as eager logical ops. 13015 // Don't diagnose this. 13016 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13017 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13018 if (isLeftBitwise || isRightBitwise) 13019 return; 13020 13021 SourceRange DiagRange = isLeftComp 13022 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13023 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13024 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13025 SourceRange ParensRange = 13026 isLeftComp 13027 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13028 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13029 13030 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13031 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13032 SuggestParentheses(Self, OpLoc, 13033 Self.PDiag(diag::note_precedence_silence) << OpStr, 13034 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13035 SuggestParentheses(Self, OpLoc, 13036 Self.PDiag(diag::note_precedence_bitwise_first) 13037 << BinaryOperator::getOpcodeStr(Opc), 13038 ParensRange); 13039 } 13040 13041 /// It accepts a '&&' expr that is inside a '||' one. 13042 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13043 /// in parentheses. 13044 static void 13045 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13046 BinaryOperator *Bop) { 13047 assert(Bop->getOpcode() == BO_LAnd); 13048 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13049 << Bop->getSourceRange() << OpLoc; 13050 SuggestParentheses(Self, Bop->getOperatorLoc(), 13051 Self.PDiag(diag::note_precedence_silence) 13052 << Bop->getOpcodeStr(), 13053 Bop->getSourceRange()); 13054 } 13055 13056 /// Returns true if the given expression can be evaluated as a constant 13057 /// 'true'. 13058 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13059 bool Res; 13060 return !E->isValueDependent() && 13061 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13062 } 13063 13064 /// Returns true if the given expression can be evaluated as a constant 13065 /// 'false'. 13066 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13067 bool Res; 13068 return !E->isValueDependent() && 13069 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13070 } 13071 13072 /// Look for '&&' in the left hand of a '||' expr. 13073 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13074 Expr *LHSExpr, Expr *RHSExpr) { 13075 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13076 if (Bop->getOpcode() == BO_LAnd) { 13077 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13078 if (EvaluatesAsFalse(S, RHSExpr)) 13079 return; 13080 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13081 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13082 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13083 } else if (Bop->getOpcode() == BO_LOr) { 13084 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13085 // If it's "a || b && 1 || c" we didn't warn earlier for 13086 // "a || b && 1", but warn now. 13087 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13088 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13089 } 13090 } 13091 } 13092 } 13093 13094 /// Look for '&&' in the right hand of a '||' expr. 13095 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13096 Expr *LHSExpr, Expr *RHSExpr) { 13097 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13098 if (Bop->getOpcode() == BO_LAnd) { 13099 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13100 if (EvaluatesAsFalse(S, LHSExpr)) 13101 return; 13102 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13103 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13104 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13105 } 13106 } 13107 } 13108 13109 /// Look for bitwise op in the left or right hand of a bitwise op with 13110 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13111 /// the '&' expression in parentheses. 13112 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13113 SourceLocation OpLoc, Expr *SubExpr) { 13114 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13115 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13116 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13117 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13118 << Bop->getSourceRange() << OpLoc; 13119 SuggestParentheses(S, Bop->getOperatorLoc(), 13120 S.PDiag(diag::note_precedence_silence) 13121 << Bop->getOpcodeStr(), 13122 Bop->getSourceRange()); 13123 } 13124 } 13125 } 13126 13127 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13128 Expr *SubExpr, StringRef Shift) { 13129 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13130 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13131 StringRef Op = Bop->getOpcodeStr(); 13132 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13133 << Bop->getSourceRange() << OpLoc << Shift << Op; 13134 SuggestParentheses(S, Bop->getOperatorLoc(), 13135 S.PDiag(diag::note_precedence_silence) << Op, 13136 Bop->getSourceRange()); 13137 } 13138 } 13139 } 13140 13141 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13142 Expr *LHSExpr, Expr *RHSExpr) { 13143 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13144 if (!OCE) 13145 return; 13146 13147 FunctionDecl *FD = OCE->getDirectCallee(); 13148 if (!FD || !FD->isOverloadedOperator()) 13149 return; 13150 13151 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13152 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13153 return; 13154 13155 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13156 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13157 << (Kind == OO_LessLess); 13158 SuggestParentheses(S, OCE->getOperatorLoc(), 13159 S.PDiag(diag::note_precedence_silence) 13160 << (Kind == OO_LessLess ? "<<" : ">>"), 13161 OCE->getSourceRange()); 13162 SuggestParentheses( 13163 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13164 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13165 } 13166 13167 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13168 /// precedence. 13169 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13170 SourceLocation OpLoc, Expr *LHSExpr, 13171 Expr *RHSExpr){ 13172 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13173 if (BinaryOperator::isBitwiseOp(Opc)) 13174 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13175 13176 // Diagnose "arg1 & arg2 | arg3" 13177 if ((Opc == BO_Or || Opc == BO_Xor) && 13178 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13179 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13180 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13181 } 13182 13183 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13184 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13185 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13186 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13187 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13188 } 13189 13190 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13191 || Opc == BO_Shr) { 13192 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13193 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13194 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13195 } 13196 13197 // Warn on overloaded shift operators and comparisons, such as: 13198 // cout << 5 == 4; 13199 if (BinaryOperator::isComparisonOp(Opc)) 13200 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13201 } 13202 13203 // Binary Operators. 'Tok' is the token for the operator. 13204 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13205 tok::TokenKind Kind, 13206 Expr *LHSExpr, Expr *RHSExpr) { 13207 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13208 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13209 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13210 13211 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13212 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13213 13214 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13215 } 13216 13217 /// Build an overloaded binary operator expression in the given scope. 13218 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13219 BinaryOperatorKind Opc, 13220 Expr *LHS, Expr *RHS) { 13221 switch (Opc) { 13222 case BO_Assign: 13223 case BO_DivAssign: 13224 case BO_RemAssign: 13225 case BO_SubAssign: 13226 case BO_AndAssign: 13227 case BO_OrAssign: 13228 case BO_XorAssign: 13229 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13230 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13231 break; 13232 default: 13233 break; 13234 } 13235 13236 // Find all of the overloaded operators visible from this 13237 // point. We perform both an operator-name lookup from the local 13238 // scope and an argument-dependent lookup based on the types of 13239 // the arguments. 13240 UnresolvedSet<16> Functions; 13241 OverloadedOperatorKind OverOp 13242 = BinaryOperator::getOverloadedOperator(Opc); 13243 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13244 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13245 RHS->getType(), Functions); 13246 13247 // Build the (potentially-overloaded, potentially-dependent) 13248 // binary operation. 13249 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13250 } 13251 13252 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13253 BinaryOperatorKind Opc, 13254 Expr *LHSExpr, Expr *RHSExpr) { 13255 ExprResult LHS, RHS; 13256 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13257 if (!LHS.isUsable() || !RHS.isUsable()) 13258 return ExprError(); 13259 LHSExpr = LHS.get(); 13260 RHSExpr = RHS.get(); 13261 13262 // We want to end up calling one of checkPseudoObjectAssignment 13263 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13264 // both expressions are overloadable or either is type-dependent), 13265 // or CreateBuiltinBinOp (in any other case). We also want to get 13266 // any placeholder types out of the way. 13267 13268 // Handle pseudo-objects in the LHS. 13269 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13270 // Assignments with a pseudo-object l-value need special analysis. 13271 if (pty->getKind() == BuiltinType::PseudoObject && 13272 BinaryOperator::isAssignmentOp(Opc)) 13273 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13274 13275 // Don't resolve overloads if the other type is overloadable. 13276 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13277 // We can't actually test that if we still have a placeholder, 13278 // though. Fortunately, none of the exceptions we see in that 13279 // code below are valid when the LHS is an overload set. Note 13280 // that an overload set can be dependently-typed, but it never 13281 // instantiates to having an overloadable type. 13282 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13283 if (resolvedRHS.isInvalid()) return ExprError(); 13284 RHSExpr = resolvedRHS.get(); 13285 13286 if (RHSExpr->isTypeDependent() || 13287 RHSExpr->getType()->isOverloadableType()) 13288 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13289 } 13290 13291 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13292 // template, diagnose the missing 'template' keyword instead of diagnosing 13293 // an invalid use of a bound member function. 13294 // 13295 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13296 // to C++1z [over.over]/1.4, but we already checked for that case above. 13297 if (Opc == BO_LT && inTemplateInstantiation() && 13298 (pty->getKind() == BuiltinType::BoundMember || 13299 pty->getKind() == BuiltinType::Overload)) { 13300 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13301 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13302 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13303 return isa<FunctionTemplateDecl>(ND); 13304 })) { 13305 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13306 : OE->getNameLoc(), 13307 diag::err_template_kw_missing) 13308 << OE->getName().getAsString() << ""; 13309 return ExprError(); 13310 } 13311 } 13312 13313 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13314 if (LHS.isInvalid()) return ExprError(); 13315 LHSExpr = LHS.get(); 13316 } 13317 13318 // Handle pseudo-objects in the RHS. 13319 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13320 // An overload in the RHS can potentially be resolved by the type 13321 // being assigned to. 13322 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13323 if (getLangOpts().CPlusPlus && 13324 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13325 LHSExpr->getType()->isOverloadableType())) 13326 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13327 13328 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13329 } 13330 13331 // Don't resolve overloads if the other type is overloadable. 13332 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13333 LHSExpr->getType()->isOverloadableType()) 13334 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13335 13336 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13337 if (!resolvedRHS.isUsable()) return ExprError(); 13338 RHSExpr = resolvedRHS.get(); 13339 } 13340 13341 if (getLangOpts().CPlusPlus) { 13342 // If either expression is type-dependent, always build an 13343 // overloaded op. 13344 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13345 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13346 13347 // Otherwise, build an overloaded op if either expression has an 13348 // overloadable type. 13349 if (LHSExpr->getType()->isOverloadableType() || 13350 RHSExpr->getType()->isOverloadableType()) 13351 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13352 } 13353 13354 // Build a built-in binary operation. 13355 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13356 } 13357 13358 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13359 if (T.isNull() || T->isDependentType()) 13360 return false; 13361 13362 if (!T->isPromotableIntegerType()) 13363 return true; 13364 13365 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13366 } 13367 13368 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13369 UnaryOperatorKind Opc, 13370 Expr *InputExpr) { 13371 ExprResult Input = InputExpr; 13372 ExprValueKind VK = VK_RValue; 13373 ExprObjectKind OK = OK_Ordinary; 13374 QualType resultType; 13375 bool CanOverflow = false; 13376 13377 bool ConvertHalfVec = false; 13378 if (getLangOpts().OpenCL) { 13379 QualType Ty = InputExpr->getType(); 13380 // The only legal unary operation for atomics is '&'. 13381 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13382 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13383 // only with a builtin functions and therefore should be disallowed here. 13384 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13385 || Ty->isBlockPointerType())) { 13386 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13387 << InputExpr->getType() 13388 << Input.get()->getSourceRange()); 13389 } 13390 } 13391 // Diagnose operations on the unsupported types for OpenMP device compilation. 13392 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13393 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13394 UnaryOperator::isArithmeticOp(Opc)) 13395 checkOpenMPDeviceExpr(InputExpr); 13396 } 13397 13398 switch (Opc) { 13399 case UO_PreInc: 13400 case UO_PreDec: 13401 case UO_PostInc: 13402 case UO_PostDec: 13403 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13404 OpLoc, 13405 Opc == UO_PreInc || 13406 Opc == UO_PostInc, 13407 Opc == UO_PreInc || 13408 Opc == UO_PreDec); 13409 CanOverflow = isOverflowingIntegerType(Context, resultType); 13410 break; 13411 case UO_AddrOf: 13412 resultType = CheckAddressOfOperand(Input, OpLoc); 13413 CheckAddressOfNoDeref(InputExpr); 13414 RecordModifiableNonNullParam(*this, InputExpr); 13415 break; 13416 case UO_Deref: { 13417 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13418 if (Input.isInvalid()) return ExprError(); 13419 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13420 break; 13421 } 13422 case UO_Plus: 13423 case UO_Minus: 13424 CanOverflow = Opc == UO_Minus && 13425 isOverflowingIntegerType(Context, Input.get()->getType()); 13426 Input = UsualUnaryConversions(Input.get()); 13427 if (Input.isInvalid()) return ExprError(); 13428 // Unary plus and minus require promoting an operand of half vector to a 13429 // float vector and truncating the result back to a half vector. For now, we 13430 // do this only when HalfArgsAndReturns is set (that is, when the target is 13431 // arm or arm64). 13432 ConvertHalfVec = 13433 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13434 13435 // If the operand is a half vector, promote it to a float vector. 13436 if (ConvertHalfVec) 13437 Input = convertVector(Input.get(), Context.FloatTy, *this); 13438 resultType = Input.get()->getType(); 13439 if (resultType->isDependentType()) 13440 break; 13441 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13442 break; 13443 else if (resultType->isVectorType() && 13444 // The z vector extensions don't allow + or - with bool vectors. 13445 (!Context.getLangOpts().ZVector || 13446 resultType->getAs<VectorType>()->getVectorKind() != 13447 VectorType::AltiVecBool)) 13448 break; 13449 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13450 Opc == UO_Plus && 13451 resultType->isPointerType()) 13452 break; 13453 13454 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13455 << resultType << Input.get()->getSourceRange()); 13456 13457 case UO_Not: // bitwise complement 13458 Input = UsualUnaryConversions(Input.get()); 13459 if (Input.isInvalid()) 13460 return ExprError(); 13461 resultType = Input.get()->getType(); 13462 13463 if (resultType->isDependentType()) 13464 break; 13465 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13466 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13467 // C99 does not support '~' for complex conjugation. 13468 Diag(OpLoc, diag::ext_integer_complement_complex) 13469 << resultType << Input.get()->getSourceRange(); 13470 else if (resultType->hasIntegerRepresentation()) 13471 break; 13472 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13473 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13474 // on vector float types. 13475 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13476 if (!T->isIntegerType()) 13477 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13478 << resultType << Input.get()->getSourceRange()); 13479 } else { 13480 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13481 << resultType << Input.get()->getSourceRange()); 13482 } 13483 break; 13484 13485 case UO_LNot: // logical negation 13486 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13487 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13488 if (Input.isInvalid()) return ExprError(); 13489 resultType = Input.get()->getType(); 13490 13491 // Though we still have to promote half FP to float... 13492 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13493 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13494 resultType = Context.FloatTy; 13495 } 13496 13497 if (resultType->isDependentType()) 13498 break; 13499 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13500 // C99 6.5.3.3p1: ok, fallthrough; 13501 if (Context.getLangOpts().CPlusPlus) { 13502 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13503 // operand contextually converted to bool. 13504 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13505 ScalarTypeToBooleanCastKind(resultType)); 13506 } else if (Context.getLangOpts().OpenCL && 13507 Context.getLangOpts().OpenCLVersion < 120) { 13508 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13509 // operate on scalar float types. 13510 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13511 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13512 << resultType << Input.get()->getSourceRange()); 13513 } 13514 } else if (resultType->isExtVectorType()) { 13515 if (Context.getLangOpts().OpenCL && 13516 Context.getLangOpts().OpenCLVersion < 120 && 13517 !Context.getLangOpts().OpenCLCPlusPlus) { 13518 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13519 // operate on vector float types. 13520 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13521 if (!T->isIntegerType()) 13522 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13523 << resultType << Input.get()->getSourceRange()); 13524 } 13525 // Vector logical not returns the signed variant of the operand type. 13526 resultType = GetSignedVectorType(resultType); 13527 break; 13528 } else { 13529 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13530 // type in C++. We should allow that here too. 13531 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13532 << resultType << Input.get()->getSourceRange()); 13533 } 13534 13535 // LNot always has type int. C99 6.5.3.3p5. 13536 // In C++, it's bool. C++ 5.3.1p8 13537 resultType = Context.getLogicalOperationType(); 13538 break; 13539 case UO_Real: 13540 case UO_Imag: 13541 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13542 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13543 // complex l-values to ordinary l-values and all other values to r-values. 13544 if (Input.isInvalid()) return ExprError(); 13545 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13546 if (Input.get()->getValueKind() != VK_RValue && 13547 Input.get()->getObjectKind() == OK_Ordinary) 13548 VK = Input.get()->getValueKind(); 13549 } else if (!getLangOpts().CPlusPlus) { 13550 // In C, a volatile scalar is read by __imag. In C++, it is not. 13551 Input = DefaultLvalueConversion(Input.get()); 13552 } 13553 break; 13554 case UO_Extension: 13555 resultType = Input.get()->getType(); 13556 VK = Input.get()->getValueKind(); 13557 OK = Input.get()->getObjectKind(); 13558 break; 13559 case UO_Coawait: 13560 // It's unnecessary to represent the pass-through operator co_await in the 13561 // AST; just return the input expression instead. 13562 assert(!Input.get()->getType()->isDependentType() && 13563 "the co_await expression must be non-dependant before " 13564 "building operator co_await"); 13565 return Input; 13566 } 13567 if (resultType.isNull() || Input.isInvalid()) 13568 return ExprError(); 13569 13570 // Check for array bounds violations in the operand of the UnaryOperator, 13571 // except for the '*' and '&' operators that have to be handled specially 13572 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13573 // that are explicitly defined as valid by the standard). 13574 if (Opc != UO_AddrOf && Opc != UO_Deref) 13575 CheckArrayAccess(Input.get()); 13576 13577 auto *UO = new (Context) 13578 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13579 13580 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13581 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13582 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13583 13584 // Convert the result back to a half vector. 13585 if (ConvertHalfVec) 13586 return convertVector(UO, Context.HalfTy, *this); 13587 return UO; 13588 } 13589 13590 /// Determine whether the given expression is a qualified member 13591 /// access expression, of a form that could be turned into a pointer to member 13592 /// with the address-of operator. 13593 bool Sema::isQualifiedMemberAccess(Expr *E) { 13594 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13595 if (!DRE->getQualifier()) 13596 return false; 13597 13598 ValueDecl *VD = DRE->getDecl(); 13599 if (!VD->isCXXClassMember()) 13600 return false; 13601 13602 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13603 return true; 13604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13605 return Method->isInstance(); 13606 13607 return false; 13608 } 13609 13610 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13611 if (!ULE->getQualifier()) 13612 return false; 13613 13614 for (NamedDecl *D : ULE->decls()) { 13615 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13616 if (Method->isInstance()) 13617 return true; 13618 } else { 13619 // Overload set does not contain methods. 13620 break; 13621 } 13622 } 13623 13624 return false; 13625 } 13626 13627 return false; 13628 } 13629 13630 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13631 UnaryOperatorKind Opc, Expr *Input) { 13632 // First things first: handle placeholders so that the 13633 // overloaded-operator check considers the right type. 13634 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13635 // Increment and decrement of pseudo-object references. 13636 if (pty->getKind() == BuiltinType::PseudoObject && 13637 UnaryOperator::isIncrementDecrementOp(Opc)) 13638 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13639 13640 // extension is always a builtin operator. 13641 if (Opc == UO_Extension) 13642 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13643 13644 // & gets special logic for several kinds of placeholder. 13645 // The builtin code knows what to do. 13646 if (Opc == UO_AddrOf && 13647 (pty->getKind() == BuiltinType::Overload || 13648 pty->getKind() == BuiltinType::UnknownAny || 13649 pty->getKind() == BuiltinType::BoundMember)) 13650 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13651 13652 // Anything else needs to be handled now. 13653 ExprResult Result = CheckPlaceholderExpr(Input); 13654 if (Result.isInvalid()) return ExprError(); 13655 Input = Result.get(); 13656 } 13657 13658 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13659 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13660 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13661 // Find all of the overloaded operators visible from this 13662 // point. We perform both an operator-name lookup from the local 13663 // scope and an argument-dependent lookup based on the types of 13664 // the arguments. 13665 UnresolvedSet<16> Functions; 13666 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13667 if (S && OverOp != OO_None) 13668 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13669 Functions); 13670 13671 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13672 } 13673 13674 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13675 } 13676 13677 // Unary Operators. 'Tok' is the token for the operator. 13678 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13679 tok::TokenKind Op, Expr *Input) { 13680 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13681 } 13682 13683 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13684 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13685 LabelDecl *TheDecl) { 13686 TheDecl->markUsed(Context); 13687 // Create the AST node. The address of a label always has type 'void*'. 13688 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13689 Context.getPointerType(Context.VoidTy)); 13690 } 13691 13692 void Sema::ActOnStartStmtExpr() { 13693 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13694 } 13695 13696 void Sema::ActOnStmtExprError() { 13697 // Note that function is also called by TreeTransform when leaving a 13698 // StmtExpr scope without rebuilding anything. 13699 13700 DiscardCleanupsInEvaluationContext(); 13701 PopExpressionEvaluationContext(); 13702 } 13703 13704 ExprResult 13705 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13706 SourceLocation RPLoc) { // "({..})" 13707 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13708 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13709 13710 if (hasAnyUnrecoverableErrorsInThisFunction()) 13711 DiscardCleanupsInEvaluationContext(); 13712 assert(!Cleanup.exprNeedsCleanups() && 13713 "cleanups within StmtExpr not correctly bound!"); 13714 PopExpressionEvaluationContext(); 13715 13716 // FIXME: there are a variety of strange constraints to enforce here, for 13717 // example, it is not possible to goto into a stmt expression apparently. 13718 // More semantic analysis is needed. 13719 13720 // If there are sub-stmts in the compound stmt, take the type of the last one 13721 // as the type of the stmtexpr. 13722 QualType Ty = Context.VoidTy; 13723 bool StmtExprMayBindToTemp = false; 13724 if (!Compound->body_empty()) { 13725 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13726 if (const auto *LastStmt = 13727 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13728 if (const Expr *Value = LastStmt->getExprStmt()) { 13729 StmtExprMayBindToTemp = true; 13730 Ty = Value->getType(); 13731 } 13732 } 13733 } 13734 13735 // FIXME: Check that expression type is complete/non-abstract; statement 13736 // expressions are not lvalues. 13737 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13738 if (StmtExprMayBindToTemp) 13739 return MaybeBindToTemporary(ResStmtExpr); 13740 return ResStmtExpr; 13741 } 13742 13743 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13744 if (ER.isInvalid()) 13745 return ExprError(); 13746 13747 // Do function/array conversion on the last expression, but not 13748 // lvalue-to-rvalue. However, initialize an unqualified type. 13749 ER = DefaultFunctionArrayConversion(ER.get()); 13750 if (ER.isInvalid()) 13751 return ExprError(); 13752 Expr *E = ER.get(); 13753 13754 if (E->isTypeDependent()) 13755 return E; 13756 13757 // In ARC, if the final expression ends in a consume, splice 13758 // the consume out and bind it later. In the alternate case 13759 // (when dealing with a retainable type), the result 13760 // initialization will create a produce. In both cases the 13761 // result will be +1, and we'll need to balance that out with 13762 // a bind. 13763 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13764 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13765 return Cast->getSubExpr(); 13766 13767 // FIXME: Provide a better location for the initialization. 13768 return PerformCopyInitialization( 13769 InitializedEntity::InitializeStmtExprResult( 13770 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13771 SourceLocation(), E); 13772 } 13773 13774 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13775 TypeSourceInfo *TInfo, 13776 ArrayRef<OffsetOfComponent> Components, 13777 SourceLocation RParenLoc) { 13778 QualType ArgTy = TInfo->getType(); 13779 bool Dependent = ArgTy->isDependentType(); 13780 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13781 13782 // We must have at least one component that refers to the type, and the first 13783 // one is known to be a field designator. Verify that the ArgTy represents 13784 // a struct/union/class. 13785 if (!Dependent && !ArgTy->isRecordType()) 13786 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13787 << ArgTy << TypeRange); 13788 13789 // Type must be complete per C99 7.17p3 because a declaring a variable 13790 // with an incomplete type would be ill-formed. 13791 if (!Dependent 13792 && RequireCompleteType(BuiltinLoc, ArgTy, 13793 diag::err_offsetof_incomplete_type, TypeRange)) 13794 return ExprError(); 13795 13796 bool DidWarnAboutNonPOD = false; 13797 QualType CurrentType = ArgTy; 13798 SmallVector<OffsetOfNode, 4> Comps; 13799 SmallVector<Expr*, 4> Exprs; 13800 for (const OffsetOfComponent &OC : Components) { 13801 if (OC.isBrackets) { 13802 // Offset of an array sub-field. TODO: Should we allow vector elements? 13803 if (!CurrentType->isDependentType()) { 13804 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13805 if(!AT) 13806 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13807 << CurrentType); 13808 CurrentType = AT->getElementType(); 13809 } else 13810 CurrentType = Context.DependentTy; 13811 13812 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13813 if (IdxRval.isInvalid()) 13814 return ExprError(); 13815 Expr *Idx = IdxRval.get(); 13816 13817 // The expression must be an integral expression. 13818 // FIXME: An integral constant expression? 13819 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13820 !Idx->getType()->isIntegerType()) 13821 return ExprError( 13822 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13823 << Idx->getSourceRange()); 13824 13825 // Record this array index. 13826 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13827 Exprs.push_back(Idx); 13828 continue; 13829 } 13830 13831 // Offset of a field. 13832 if (CurrentType->isDependentType()) { 13833 // We have the offset of a field, but we can't look into the dependent 13834 // type. Just record the identifier of the field. 13835 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13836 CurrentType = Context.DependentTy; 13837 continue; 13838 } 13839 13840 // We need to have a complete type to look into. 13841 if (RequireCompleteType(OC.LocStart, CurrentType, 13842 diag::err_offsetof_incomplete_type)) 13843 return ExprError(); 13844 13845 // Look for the designated field. 13846 const RecordType *RC = CurrentType->getAs<RecordType>(); 13847 if (!RC) 13848 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13849 << CurrentType); 13850 RecordDecl *RD = RC->getDecl(); 13851 13852 // C++ [lib.support.types]p5: 13853 // The macro offsetof accepts a restricted set of type arguments in this 13854 // International Standard. type shall be a POD structure or a POD union 13855 // (clause 9). 13856 // C++11 [support.types]p4: 13857 // If type is not a standard-layout class (Clause 9), the results are 13858 // undefined. 13859 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13860 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13861 unsigned DiagID = 13862 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13863 : diag::ext_offsetof_non_pod_type; 13864 13865 if (!IsSafe && !DidWarnAboutNonPOD && 13866 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13867 PDiag(DiagID) 13868 << SourceRange(Components[0].LocStart, OC.LocEnd) 13869 << CurrentType)) 13870 DidWarnAboutNonPOD = true; 13871 } 13872 13873 // Look for the field. 13874 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13875 LookupQualifiedName(R, RD); 13876 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13877 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13878 if (!MemberDecl) { 13879 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13880 MemberDecl = IndirectMemberDecl->getAnonField(); 13881 } 13882 13883 if (!MemberDecl) 13884 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13885 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13886 OC.LocEnd)); 13887 13888 // C99 7.17p3: 13889 // (If the specified member is a bit-field, the behavior is undefined.) 13890 // 13891 // We diagnose this as an error. 13892 if (MemberDecl->isBitField()) { 13893 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13894 << MemberDecl->getDeclName() 13895 << SourceRange(BuiltinLoc, RParenLoc); 13896 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13897 return ExprError(); 13898 } 13899 13900 RecordDecl *Parent = MemberDecl->getParent(); 13901 if (IndirectMemberDecl) 13902 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13903 13904 // If the member was found in a base class, introduce OffsetOfNodes for 13905 // the base class indirections. 13906 CXXBasePaths Paths; 13907 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13908 Paths)) { 13909 if (Paths.getDetectedVirtual()) { 13910 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13911 << MemberDecl->getDeclName() 13912 << SourceRange(BuiltinLoc, RParenLoc); 13913 return ExprError(); 13914 } 13915 13916 CXXBasePath &Path = Paths.front(); 13917 for (const CXXBasePathElement &B : Path) 13918 Comps.push_back(OffsetOfNode(B.Base)); 13919 } 13920 13921 if (IndirectMemberDecl) { 13922 for (auto *FI : IndirectMemberDecl->chain()) { 13923 assert(isa<FieldDecl>(FI)); 13924 Comps.push_back(OffsetOfNode(OC.LocStart, 13925 cast<FieldDecl>(FI), OC.LocEnd)); 13926 } 13927 } else 13928 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13929 13930 CurrentType = MemberDecl->getType().getNonReferenceType(); 13931 } 13932 13933 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13934 Comps, Exprs, RParenLoc); 13935 } 13936 13937 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13938 SourceLocation BuiltinLoc, 13939 SourceLocation TypeLoc, 13940 ParsedType ParsedArgTy, 13941 ArrayRef<OffsetOfComponent> Components, 13942 SourceLocation RParenLoc) { 13943 13944 TypeSourceInfo *ArgTInfo; 13945 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13946 if (ArgTy.isNull()) 13947 return ExprError(); 13948 13949 if (!ArgTInfo) 13950 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13951 13952 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13953 } 13954 13955 13956 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13957 Expr *CondExpr, 13958 Expr *LHSExpr, Expr *RHSExpr, 13959 SourceLocation RPLoc) { 13960 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13961 13962 ExprValueKind VK = VK_RValue; 13963 ExprObjectKind OK = OK_Ordinary; 13964 QualType resType; 13965 bool ValueDependent = false; 13966 bool CondIsTrue = false; 13967 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13968 resType = Context.DependentTy; 13969 ValueDependent = true; 13970 } else { 13971 // The conditional expression is required to be a constant expression. 13972 llvm::APSInt condEval(32); 13973 ExprResult CondICE 13974 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13975 diag::err_typecheck_choose_expr_requires_constant, false); 13976 if (CondICE.isInvalid()) 13977 return ExprError(); 13978 CondExpr = CondICE.get(); 13979 CondIsTrue = condEval.getZExtValue(); 13980 13981 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13982 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13983 13984 resType = ActiveExpr->getType(); 13985 ValueDependent = ActiveExpr->isValueDependent(); 13986 VK = ActiveExpr->getValueKind(); 13987 OK = ActiveExpr->getObjectKind(); 13988 } 13989 13990 return new (Context) 13991 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13992 CondIsTrue, resType->isDependentType(), ValueDependent); 13993 } 13994 13995 //===----------------------------------------------------------------------===// 13996 // Clang Extensions. 13997 //===----------------------------------------------------------------------===// 13998 13999 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14000 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14001 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14002 14003 if (LangOpts.CPlusPlus) { 14004 Decl *ManglingContextDecl; 14005 if (MangleNumberingContext *MCtx = 14006 getCurrentMangleNumberContext(Block->getDeclContext(), 14007 ManglingContextDecl)) { 14008 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14009 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14010 } 14011 } 14012 14013 PushBlockScope(CurScope, Block); 14014 CurContext->addDecl(Block); 14015 if (CurScope) 14016 PushDeclContext(CurScope, Block); 14017 else 14018 CurContext = Block; 14019 14020 getCurBlock()->HasImplicitReturnType = true; 14021 14022 // Enter a new evaluation context to insulate the block from any 14023 // cleanups from the enclosing full-expression. 14024 PushExpressionEvaluationContext( 14025 ExpressionEvaluationContext::PotentiallyEvaluated); 14026 } 14027 14028 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14029 Scope *CurScope) { 14030 assert(ParamInfo.getIdentifier() == nullptr && 14031 "block-id should have no identifier!"); 14032 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14033 BlockScopeInfo *CurBlock = getCurBlock(); 14034 14035 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14036 QualType T = Sig->getType(); 14037 14038 // FIXME: We should allow unexpanded parameter packs here, but that would, 14039 // in turn, make the block expression contain unexpanded parameter packs. 14040 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14041 // Drop the parameters. 14042 FunctionProtoType::ExtProtoInfo EPI; 14043 EPI.HasTrailingReturn = false; 14044 EPI.TypeQuals.addConst(); 14045 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14046 Sig = Context.getTrivialTypeSourceInfo(T); 14047 } 14048 14049 // GetTypeForDeclarator always produces a function type for a block 14050 // literal signature. Furthermore, it is always a FunctionProtoType 14051 // unless the function was written with a typedef. 14052 assert(T->isFunctionType() && 14053 "GetTypeForDeclarator made a non-function block signature"); 14054 14055 // Look for an explicit signature in that function type. 14056 FunctionProtoTypeLoc ExplicitSignature; 14057 14058 if ((ExplicitSignature = Sig->getTypeLoc() 14059 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14060 14061 // Check whether that explicit signature was synthesized by 14062 // GetTypeForDeclarator. If so, don't save that as part of the 14063 // written signature. 14064 if (ExplicitSignature.getLocalRangeBegin() == 14065 ExplicitSignature.getLocalRangeEnd()) { 14066 // This would be much cheaper if we stored TypeLocs instead of 14067 // TypeSourceInfos. 14068 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14069 unsigned Size = Result.getFullDataSize(); 14070 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14071 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14072 14073 ExplicitSignature = FunctionProtoTypeLoc(); 14074 } 14075 } 14076 14077 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14078 CurBlock->FunctionType = T; 14079 14080 const FunctionType *Fn = T->getAs<FunctionType>(); 14081 QualType RetTy = Fn->getReturnType(); 14082 bool isVariadic = 14083 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14084 14085 CurBlock->TheDecl->setIsVariadic(isVariadic); 14086 14087 // Context.DependentTy is used as a placeholder for a missing block 14088 // return type. TODO: what should we do with declarators like: 14089 // ^ * { ... } 14090 // If the answer is "apply template argument deduction".... 14091 if (RetTy != Context.DependentTy) { 14092 CurBlock->ReturnType = RetTy; 14093 CurBlock->TheDecl->setBlockMissingReturnType(false); 14094 CurBlock->HasImplicitReturnType = false; 14095 } 14096 14097 // Push block parameters from the declarator if we had them. 14098 SmallVector<ParmVarDecl*, 8> Params; 14099 if (ExplicitSignature) { 14100 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14101 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14102 if (Param->getIdentifier() == nullptr && 14103 !Param->isImplicit() && 14104 !Param->isInvalidDecl() && 14105 !getLangOpts().CPlusPlus) 14106 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14107 Params.push_back(Param); 14108 } 14109 14110 // Fake up parameter variables if we have a typedef, like 14111 // ^ fntype { ... } 14112 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14113 for (const auto &I : Fn->param_types()) { 14114 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14115 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14116 Params.push_back(Param); 14117 } 14118 } 14119 14120 // Set the parameters on the block decl. 14121 if (!Params.empty()) { 14122 CurBlock->TheDecl->setParams(Params); 14123 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14124 /*CheckParameterNames=*/false); 14125 } 14126 14127 // Finally we can process decl attributes. 14128 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14129 14130 // Put the parameter variables in scope. 14131 for (auto AI : CurBlock->TheDecl->parameters()) { 14132 AI->setOwningFunction(CurBlock->TheDecl); 14133 14134 // If this has an identifier, add it to the scope stack. 14135 if (AI->getIdentifier()) { 14136 CheckShadow(CurBlock->TheScope, AI); 14137 14138 PushOnScopeChains(AI, CurBlock->TheScope); 14139 } 14140 } 14141 } 14142 14143 /// ActOnBlockError - If there is an error parsing a block, this callback 14144 /// is invoked to pop the information about the block from the action impl. 14145 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14146 // Leave the expression-evaluation context. 14147 DiscardCleanupsInEvaluationContext(); 14148 PopExpressionEvaluationContext(); 14149 14150 // Pop off CurBlock, handle nested blocks. 14151 PopDeclContext(); 14152 PopFunctionScopeInfo(); 14153 } 14154 14155 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14156 /// literal was successfully completed. ^(int x){...} 14157 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14158 Stmt *Body, Scope *CurScope) { 14159 // If blocks are disabled, emit an error. 14160 if (!LangOpts.Blocks) 14161 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14162 14163 // Leave the expression-evaluation context. 14164 if (hasAnyUnrecoverableErrorsInThisFunction()) 14165 DiscardCleanupsInEvaluationContext(); 14166 assert(!Cleanup.exprNeedsCleanups() && 14167 "cleanups within block not correctly bound!"); 14168 PopExpressionEvaluationContext(); 14169 14170 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14171 BlockDecl *BD = BSI->TheDecl; 14172 14173 if (BSI->HasImplicitReturnType) 14174 deduceClosureReturnType(*BSI); 14175 14176 QualType RetTy = Context.VoidTy; 14177 if (!BSI->ReturnType.isNull()) 14178 RetTy = BSI->ReturnType; 14179 14180 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14181 QualType BlockTy; 14182 14183 // If the user wrote a function type in some form, try to use that. 14184 if (!BSI->FunctionType.isNull()) { 14185 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 14186 14187 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14188 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14189 14190 // Turn protoless block types into nullary block types. 14191 if (isa<FunctionNoProtoType>(FTy)) { 14192 FunctionProtoType::ExtProtoInfo EPI; 14193 EPI.ExtInfo = Ext; 14194 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14195 14196 // Otherwise, if we don't need to change anything about the function type, 14197 // preserve its sugar structure. 14198 } else if (FTy->getReturnType() == RetTy && 14199 (!NoReturn || FTy->getNoReturnAttr())) { 14200 BlockTy = BSI->FunctionType; 14201 14202 // Otherwise, make the minimal modifications to the function type. 14203 } else { 14204 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14205 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14206 EPI.TypeQuals = Qualifiers(); 14207 EPI.ExtInfo = Ext; 14208 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14209 } 14210 14211 // If we don't have a function type, just build one from nothing. 14212 } else { 14213 FunctionProtoType::ExtProtoInfo EPI; 14214 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14215 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14216 } 14217 14218 DiagnoseUnusedParameters(BD->parameters()); 14219 BlockTy = Context.getBlockPointerType(BlockTy); 14220 14221 // If needed, diagnose invalid gotos and switches in the block. 14222 if (getCurFunction()->NeedsScopeChecking() && 14223 !PP.isCodeCompletionEnabled()) 14224 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14225 14226 BD->setBody(cast<CompoundStmt>(Body)); 14227 14228 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14229 DiagnoseUnguardedAvailabilityViolations(BD); 14230 14231 // Try to apply the named return value optimization. We have to check again 14232 // if we can do this, though, because blocks keep return statements around 14233 // to deduce an implicit return type. 14234 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14235 !BD->isDependentContext()) 14236 computeNRVO(Body, BSI); 14237 14238 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14239 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14240 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14241 NTCUK_Destruct|NTCUK_Copy); 14242 14243 PopDeclContext(); 14244 14245 // Pop the block scope now but keep it alive to the end of this function. 14246 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14247 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14248 14249 // Set the captured variables on the block. 14250 SmallVector<BlockDecl::Capture, 4> Captures; 14251 for (Capture &Cap : BSI->Captures) { 14252 if (Cap.isInvalid() || Cap.isThisCapture()) 14253 continue; 14254 14255 VarDecl *Var = Cap.getVariable(); 14256 Expr *CopyExpr = nullptr; 14257 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14258 if (const RecordType *Record = 14259 Cap.getCaptureType()->getAs<RecordType>()) { 14260 // The capture logic needs the destructor, so make sure we mark it. 14261 // Usually this is unnecessary because most local variables have 14262 // their destructors marked at declaration time, but parameters are 14263 // an exception because it's technically only the call site that 14264 // actually requires the destructor. 14265 if (isa<ParmVarDecl>(Var)) 14266 FinalizeVarWithDestructor(Var, Record); 14267 14268 // Enter a separate potentially-evaluated context while building block 14269 // initializers to isolate their cleanups from those of the block 14270 // itself. 14271 // FIXME: Is this appropriate even when the block itself occurs in an 14272 // unevaluated operand? 14273 EnterExpressionEvaluationContext EvalContext( 14274 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14275 14276 SourceLocation Loc = Cap.getLocation(); 14277 14278 ExprResult Result = BuildDeclarationNameExpr( 14279 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14280 14281 // According to the blocks spec, the capture of a variable from 14282 // the stack requires a const copy constructor. This is not true 14283 // of the copy/move done to move a __block variable to the heap. 14284 if (!Result.isInvalid() && 14285 !Result.get()->getType().isConstQualified()) { 14286 Result = ImpCastExprToType(Result.get(), 14287 Result.get()->getType().withConst(), 14288 CK_NoOp, VK_LValue); 14289 } 14290 14291 if (!Result.isInvalid()) { 14292 Result = PerformCopyInitialization( 14293 InitializedEntity::InitializeBlock(Var->getLocation(), 14294 Cap.getCaptureType(), false), 14295 Loc, Result.get()); 14296 } 14297 14298 // Build a full-expression copy expression if initialization 14299 // succeeded and used a non-trivial constructor. Recover from 14300 // errors by pretending that the copy isn't necessary. 14301 if (!Result.isInvalid() && 14302 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14303 ->isTrivial()) { 14304 Result = MaybeCreateExprWithCleanups(Result); 14305 CopyExpr = Result.get(); 14306 } 14307 } 14308 } 14309 14310 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14311 CopyExpr); 14312 Captures.push_back(NewCap); 14313 } 14314 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14315 14316 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14317 14318 // If the block isn't obviously global, i.e. it captures anything at 14319 // all, then we need to do a few things in the surrounding context: 14320 if (Result->getBlockDecl()->hasCaptures()) { 14321 // First, this expression has a new cleanup object. 14322 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14323 Cleanup.setExprNeedsCleanups(true); 14324 14325 // It also gets a branch-protected scope if any of the captured 14326 // variables needs destruction. 14327 for (const auto &CI : Result->getBlockDecl()->captures()) { 14328 const VarDecl *var = CI.getVariable(); 14329 if (var->getType().isDestructedType() != QualType::DK_none) { 14330 setFunctionHasBranchProtectedScope(); 14331 break; 14332 } 14333 } 14334 } 14335 14336 if (getCurFunction()) 14337 getCurFunction()->addBlock(BD); 14338 14339 return Result; 14340 } 14341 14342 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14343 SourceLocation RPLoc) { 14344 TypeSourceInfo *TInfo; 14345 GetTypeFromParser(Ty, &TInfo); 14346 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14347 } 14348 14349 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14350 Expr *E, TypeSourceInfo *TInfo, 14351 SourceLocation RPLoc) { 14352 Expr *OrigExpr = E; 14353 bool IsMS = false; 14354 14355 // CUDA device code does not support varargs. 14356 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14357 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14358 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14359 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14360 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14361 } 14362 } 14363 14364 // NVPTX does not support va_arg expression. 14365 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14366 Context.getTargetInfo().getTriple().isNVPTX()) 14367 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14368 14369 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14370 // as Microsoft ABI on an actual Microsoft platform, where 14371 // __builtin_ms_va_list and __builtin_va_list are the same.) 14372 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14373 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14374 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14375 if (Context.hasSameType(MSVaListType, E->getType())) { 14376 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14377 return ExprError(); 14378 IsMS = true; 14379 } 14380 } 14381 14382 // Get the va_list type 14383 QualType VaListType = Context.getBuiltinVaListType(); 14384 if (!IsMS) { 14385 if (VaListType->isArrayType()) { 14386 // Deal with implicit array decay; for example, on x86-64, 14387 // va_list is an array, but it's supposed to decay to 14388 // a pointer for va_arg. 14389 VaListType = Context.getArrayDecayedType(VaListType); 14390 // Make sure the input expression also decays appropriately. 14391 ExprResult Result = UsualUnaryConversions(E); 14392 if (Result.isInvalid()) 14393 return ExprError(); 14394 E = Result.get(); 14395 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14396 // If va_list is a record type and we are compiling in C++ mode, 14397 // check the argument using reference binding. 14398 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14399 Context, Context.getLValueReferenceType(VaListType), false); 14400 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14401 if (Init.isInvalid()) 14402 return ExprError(); 14403 E = Init.getAs<Expr>(); 14404 } else { 14405 // Otherwise, the va_list argument must be an l-value because 14406 // it is modified by va_arg. 14407 if (!E->isTypeDependent() && 14408 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14409 return ExprError(); 14410 } 14411 } 14412 14413 if (!IsMS && !E->isTypeDependent() && 14414 !Context.hasSameType(VaListType, E->getType())) 14415 return ExprError( 14416 Diag(E->getBeginLoc(), 14417 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14418 << OrigExpr->getType() << E->getSourceRange()); 14419 14420 if (!TInfo->getType()->isDependentType()) { 14421 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14422 diag::err_second_parameter_to_va_arg_incomplete, 14423 TInfo->getTypeLoc())) 14424 return ExprError(); 14425 14426 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14427 TInfo->getType(), 14428 diag::err_second_parameter_to_va_arg_abstract, 14429 TInfo->getTypeLoc())) 14430 return ExprError(); 14431 14432 if (!TInfo->getType().isPODType(Context)) { 14433 Diag(TInfo->getTypeLoc().getBeginLoc(), 14434 TInfo->getType()->isObjCLifetimeType() 14435 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14436 : diag::warn_second_parameter_to_va_arg_not_pod) 14437 << TInfo->getType() 14438 << TInfo->getTypeLoc().getSourceRange(); 14439 } 14440 14441 // Check for va_arg where arguments of the given type will be promoted 14442 // (i.e. this va_arg is guaranteed to have undefined behavior). 14443 QualType PromoteType; 14444 if (TInfo->getType()->isPromotableIntegerType()) { 14445 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14446 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14447 PromoteType = QualType(); 14448 } 14449 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14450 PromoteType = Context.DoubleTy; 14451 if (!PromoteType.isNull()) 14452 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14453 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14454 << TInfo->getType() 14455 << PromoteType 14456 << TInfo->getTypeLoc().getSourceRange()); 14457 } 14458 14459 QualType T = TInfo->getType().getNonLValueExprType(Context); 14460 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14461 } 14462 14463 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14464 // The type of __null will be int or long, depending on the size of 14465 // pointers on the target. 14466 QualType Ty; 14467 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14468 if (pw == Context.getTargetInfo().getIntWidth()) 14469 Ty = Context.IntTy; 14470 else if (pw == Context.getTargetInfo().getLongWidth()) 14471 Ty = Context.LongTy; 14472 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14473 Ty = Context.LongLongTy; 14474 else { 14475 llvm_unreachable("I don't know size of pointer!"); 14476 } 14477 14478 return new (Context) GNUNullExpr(Ty, TokenLoc); 14479 } 14480 14481 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14482 SourceLocation BuiltinLoc, 14483 SourceLocation RPLoc) { 14484 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14485 } 14486 14487 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14488 SourceLocation BuiltinLoc, 14489 SourceLocation RPLoc, 14490 DeclContext *ParentContext) { 14491 return new (Context) 14492 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14493 } 14494 14495 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14496 bool Diagnose) { 14497 if (!getLangOpts().ObjC) 14498 return false; 14499 14500 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14501 if (!PT) 14502 return false; 14503 14504 if (!PT->isObjCIdType()) { 14505 // Check if the destination is the 'NSString' interface. 14506 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14507 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14508 return false; 14509 } 14510 14511 // Ignore any parens, implicit casts (should only be 14512 // array-to-pointer decays), and not-so-opaque values. The last is 14513 // important for making this trigger for property assignments. 14514 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14515 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14516 if (OV->getSourceExpr()) 14517 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14518 14519 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14520 if (!SL || !SL->isAscii()) 14521 return false; 14522 if (Diagnose) { 14523 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14524 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14525 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14526 } 14527 return true; 14528 } 14529 14530 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14531 const Expr *SrcExpr) { 14532 if (!DstType->isFunctionPointerType() || 14533 !SrcExpr->getType()->isFunctionType()) 14534 return false; 14535 14536 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14537 if (!DRE) 14538 return false; 14539 14540 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14541 if (!FD) 14542 return false; 14543 14544 return !S.checkAddressOfFunctionIsAvailable(FD, 14545 /*Complain=*/true, 14546 SrcExpr->getBeginLoc()); 14547 } 14548 14549 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14550 SourceLocation Loc, 14551 QualType DstType, QualType SrcType, 14552 Expr *SrcExpr, AssignmentAction Action, 14553 bool *Complained) { 14554 if (Complained) 14555 *Complained = false; 14556 14557 // Decode the result (notice that AST's are still created for extensions). 14558 bool CheckInferredResultType = false; 14559 bool isInvalid = false; 14560 unsigned DiagKind = 0; 14561 FixItHint Hint; 14562 ConversionFixItGenerator ConvHints; 14563 bool MayHaveConvFixit = false; 14564 bool MayHaveFunctionDiff = false; 14565 const ObjCInterfaceDecl *IFace = nullptr; 14566 const ObjCProtocolDecl *PDecl = nullptr; 14567 14568 switch (ConvTy) { 14569 case Compatible: 14570 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14571 return false; 14572 14573 case PointerToInt: 14574 DiagKind = diag::ext_typecheck_convert_pointer_int; 14575 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14576 MayHaveConvFixit = true; 14577 break; 14578 case IntToPointer: 14579 DiagKind = diag::ext_typecheck_convert_int_pointer; 14580 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14581 MayHaveConvFixit = true; 14582 break; 14583 case IncompatiblePointer: 14584 if (Action == AA_Passing_CFAudited) 14585 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14586 else if (SrcType->isFunctionPointerType() && 14587 DstType->isFunctionPointerType()) 14588 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14589 else 14590 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14591 14592 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14593 SrcType->isObjCObjectPointerType(); 14594 if (Hint.isNull() && !CheckInferredResultType) { 14595 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14596 } 14597 else if (CheckInferredResultType) { 14598 SrcType = SrcType.getUnqualifiedType(); 14599 DstType = DstType.getUnqualifiedType(); 14600 } 14601 MayHaveConvFixit = true; 14602 break; 14603 case IncompatiblePointerSign: 14604 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14605 break; 14606 case FunctionVoidPointer: 14607 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14608 break; 14609 case IncompatiblePointerDiscardsQualifiers: { 14610 // Perform array-to-pointer decay if necessary. 14611 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14612 14613 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14614 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14615 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14616 DiagKind = diag::err_typecheck_incompatible_address_space; 14617 break; 14618 14619 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14620 DiagKind = diag::err_typecheck_incompatible_ownership; 14621 break; 14622 } 14623 14624 llvm_unreachable("unknown error case for discarding qualifiers!"); 14625 // fallthrough 14626 } 14627 case CompatiblePointerDiscardsQualifiers: 14628 // If the qualifiers lost were because we were applying the 14629 // (deprecated) C++ conversion from a string literal to a char* 14630 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14631 // Ideally, this check would be performed in 14632 // checkPointerTypesForAssignment. However, that would require a 14633 // bit of refactoring (so that the second argument is an 14634 // expression, rather than a type), which should be done as part 14635 // of a larger effort to fix checkPointerTypesForAssignment for 14636 // C++ semantics. 14637 if (getLangOpts().CPlusPlus && 14638 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14639 return false; 14640 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14641 break; 14642 case IncompatibleNestedPointerQualifiers: 14643 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14644 break; 14645 case IncompatibleNestedPointerAddressSpaceMismatch: 14646 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14647 break; 14648 case IntToBlockPointer: 14649 DiagKind = diag::err_int_to_block_pointer; 14650 break; 14651 case IncompatibleBlockPointer: 14652 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14653 break; 14654 case IncompatibleObjCQualifiedId: { 14655 if (SrcType->isObjCQualifiedIdType()) { 14656 const ObjCObjectPointerType *srcOPT = 14657 SrcType->getAs<ObjCObjectPointerType>(); 14658 for (auto *srcProto : srcOPT->quals()) { 14659 PDecl = srcProto; 14660 break; 14661 } 14662 if (const ObjCInterfaceType *IFaceT = 14663 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14664 IFace = IFaceT->getDecl(); 14665 } 14666 else if (DstType->isObjCQualifiedIdType()) { 14667 const ObjCObjectPointerType *dstOPT = 14668 DstType->getAs<ObjCObjectPointerType>(); 14669 for (auto *dstProto : dstOPT->quals()) { 14670 PDecl = dstProto; 14671 break; 14672 } 14673 if (const ObjCInterfaceType *IFaceT = 14674 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14675 IFace = IFaceT->getDecl(); 14676 } 14677 DiagKind = diag::warn_incompatible_qualified_id; 14678 break; 14679 } 14680 case IncompatibleVectors: 14681 DiagKind = diag::warn_incompatible_vectors; 14682 break; 14683 case IncompatibleObjCWeakRef: 14684 DiagKind = diag::err_arc_weak_unavailable_assign; 14685 break; 14686 case Incompatible: 14687 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14688 if (Complained) 14689 *Complained = true; 14690 return true; 14691 } 14692 14693 DiagKind = diag::err_typecheck_convert_incompatible; 14694 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14695 MayHaveConvFixit = true; 14696 isInvalid = true; 14697 MayHaveFunctionDiff = true; 14698 break; 14699 } 14700 14701 QualType FirstType, SecondType; 14702 switch (Action) { 14703 case AA_Assigning: 14704 case AA_Initializing: 14705 // The destination type comes first. 14706 FirstType = DstType; 14707 SecondType = SrcType; 14708 break; 14709 14710 case AA_Returning: 14711 case AA_Passing: 14712 case AA_Passing_CFAudited: 14713 case AA_Converting: 14714 case AA_Sending: 14715 case AA_Casting: 14716 // The source type comes first. 14717 FirstType = SrcType; 14718 SecondType = DstType; 14719 break; 14720 } 14721 14722 PartialDiagnostic FDiag = PDiag(DiagKind); 14723 if (Action == AA_Passing_CFAudited) 14724 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14725 else 14726 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14727 14728 // If we can fix the conversion, suggest the FixIts. 14729 assert(ConvHints.isNull() || Hint.isNull()); 14730 if (!ConvHints.isNull()) { 14731 for (FixItHint &H : ConvHints.Hints) 14732 FDiag << H; 14733 } else { 14734 FDiag << Hint; 14735 } 14736 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14737 14738 if (MayHaveFunctionDiff) 14739 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14740 14741 Diag(Loc, FDiag); 14742 if (DiagKind == diag::warn_incompatible_qualified_id && 14743 PDecl && IFace && !IFace->hasDefinition()) 14744 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14745 << IFace << PDecl; 14746 14747 if (SecondType == Context.OverloadTy) 14748 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14749 FirstType, /*TakingAddress=*/true); 14750 14751 if (CheckInferredResultType) 14752 EmitRelatedResultTypeNote(SrcExpr); 14753 14754 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14755 EmitRelatedResultTypeNoteForReturn(DstType); 14756 14757 if (Complained) 14758 *Complained = true; 14759 return isInvalid; 14760 } 14761 14762 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14763 llvm::APSInt *Result) { 14764 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14765 public: 14766 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14767 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14768 } 14769 } Diagnoser; 14770 14771 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14772 } 14773 14774 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14775 llvm::APSInt *Result, 14776 unsigned DiagID, 14777 bool AllowFold) { 14778 class IDDiagnoser : public VerifyICEDiagnoser { 14779 unsigned DiagID; 14780 14781 public: 14782 IDDiagnoser(unsigned DiagID) 14783 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14784 14785 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14786 S.Diag(Loc, DiagID) << SR; 14787 } 14788 } Diagnoser(DiagID); 14789 14790 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14791 } 14792 14793 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14794 SourceRange SR) { 14795 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14796 } 14797 14798 ExprResult 14799 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14800 VerifyICEDiagnoser &Diagnoser, 14801 bool AllowFold) { 14802 SourceLocation DiagLoc = E->getBeginLoc(); 14803 14804 if (getLangOpts().CPlusPlus11) { 14805 // C++11 [expr.const]p5: 14806 // If an expression of literal class type is used in a context where an 14807 // integral constant expression is required, then that class type shall 14808 // have a single non-explicit conversion function to an integral or 14809 // unscoped enumeration type 14810 ExprResult Converted; 14811 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14812 public: 14813 CXX11ConvertDiagnoser(bool Silent) 14814 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14815 Silent, true) {} 14816 14817 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14818 QualType T) override { 14819 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14820 } 14821 14822 SemaDiagnosticBuilder diagnoseIncomplete( 14823 Sema &S, SourceLocation Loc, QualType T) override { 14824 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14825 } 14826 14827 SemaDiagnosticBuilder diagnoseExplicitConv( 14828 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14829 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14830 } 14831 14832 SemaDiagnosticBuilder noteExplicitConv( 14833 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14834 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14835 << ConvTy->isEnumeralType() << ConvTy; 14836 } 14837 14838 SemaDiagnosticBuilder diagnoseAmbiguous( 14839 Sema &S, SourceLocation Loc, QualType T) override { 14840 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14841 } 14842 14843 SemaDiagnosticBuilder noteAmbiguous( 14844 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14845 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14846 << ConvTy->isEnumeralType() << ConvTy; 14847 } 14848 14849 SemaDiagnosticBuilder diagnoseConversion( 14850 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14851 llvm_unreachable("conversion functions are permitted"); 14852 } 14853 } ConvertDiagnoser(Diagnoser.Suppress); 14854 14855 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14856 ConvertDiagnoser); 14857 if (Converted.isInvalid()) 14858 return Converted; 14859 E = Converted.get(); 14860 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14861 return ExprError(); 14862 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14863 // An ICE must be of integral or unscoped enumeration type. 14864 if (!Diagnoser.Suppress) 14865 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14866 return ExprError(); 14867 } 14868 14869 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14870 // in the non-ICE case. 14871 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14872 if (Result) 14873 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14874 if (!isa<ConstantExpr>(E)) 14875 E = ConstantExpr::Create(Context, E); 14876 return E; 14877 } 14878 14879 Expr::EvalResult EvalResult; 14880 SmallVector<PartialDiagnosticAt, 8> Notes; 14881 EvalResult.Diag = &Notes; 14882 14883 // Try to evaluate the expression, and produce diagnostics explaining why it's 14884 // not a constant expression as a side-effect. 14885 bool Folded = 14886 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14887 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14888 14889 if (!isa<ConstantExpr>(E)) 14890 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14891 14892 // In C++11, we can rely on diagnostics being produced for any expression 14893 // which is not a constant expression. If no diagnostics were produced, then 14894 // this is a constant expression. 14895 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14896 if (Result) 14897 *Result = EvalResult.Val.getInt(); 14898 return E; 14899 } 14900 14901 // If our only note is the usual "invalid subexpression" note, just point 14902 // the caret at its location rather than producing an essentially 14903 // redundant note. 14904 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14905 diag::note_invalid_subexpr_in_const_expr) { 14906 DiagLoc = Notes[0].first; 14907 Notes.clear(); 14908 } 14909 14910 if (!Folded || !AllowFold) { 14911 if (!Diagnoser.Suppress) { 14912 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14913 for (const PartialDiagnosticAt &Note : Notes) 14914 Diag(Note.first, Note.second); 14915 } 14916 14917 return ExprError(); 14918 } 14919 14920 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14921 for (const PartialDiagnosticAt &Note : Notes) 14922 Diag(Note.first, Note.second); 14923 14924 if (Result) 14925 *Result = EvalResult.Val.getInt(); 14926 return E; 14927 } 14928 14929 namespace { 14930 // Handle the case where we conclude a expression which we speculatively 14931 // considered to be unevaluated is actually evaluated. 14932 class TransformToPE : public TreeTransform<TransformToPE> { 14933 typedef TreeTransform<TransformToPE> BaseTransform; 14934 14935 public: 14936 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14937 14938 // Make sure we redo semantic analysis 14939 bool AlwaysRebuild() { return true; } 14940 bool ReplacingOriginal() { return true; } 14941 14942 // We need to special-case DeclRefExprs referring to FieldDecls which 14943 // are not part of a member pointer formation; normal TreeTransforming 14944 // doesn't catch this case because of the way we represent them in the AST. 14945 // FIXME: This is a bit ugly; is it really the best way to handle this 14946 // case? 14947 // 14948 // Error on DeclRefExprs referring to FieldDecls. 14949 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14950 if (isa<FieldDecl>(E->getDecl()) && 14951 !SemaRef.isUnevaluatedContext()) 14952 return SemaRef.Diag(E->getLocation(), 14953 diag::err_invalid_non_static_member_use) 14954 << E->getDecl() << E->getSourceRange(); 14955 14956 return BaseTransform::TransformDeclRefExpr(E); 14957 } 14958 14959 // Exception: filter out member pointer formation 14960 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14961 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14962 return E; 14963 14964 return BaseTransform::TransformUnaryOperator(E); 14965 } 14966 14967 // The body of a lambda-expression is in a separate expression evaluation 14968 // context so never needs to be transformed. 14969 // FIXME: Ideally we wouldn't transform the closure type either, and would 14970 // just recreate the capture expressions and lambda expression. 14971 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 14972 return SkipLambdaBody(E, Body); 14973 } 14974 }; 14975 } 14976 14977 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14978 assert(isUnevaluatedContext() && 14979 "Should only transform unevaluated expressions"); 14980 ExprEvalContexts.back().Context = 14981 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14982 if (isUnevaluatedContext()) 14983 return E; 14984 return TransformToPE(*this).TransformExpr(E); 14985 } 14986 14987 void 14988 Sema::PushExpressionEvaluationContext( 14989 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14990 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14991 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14992 LambdaContextDecl, ExprContext); 14993 Cleanup.reset(); 14994 if (!MaybeODRUseExprs.empty()) 14995 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14996 } 14997 14998 void 14999 Sema::PushExpressionEvaluationContext( 15000 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15001 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15002 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15003 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15004 } 15005 15006 namespace { 15007 15008 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15009 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15010 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15011 if (E->getOpcode() == UO_Deref) 15012 return CheckPossibleDeref(S, E->getSubExpr()); 15013 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15014 return CheckPossibleDeref(S, E->getBase()); 15015 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15016 return CheckPossibleDeref(S, E->getBase()); 15017 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15018 QualType Inner; 15019 QualType Ty = E->getType(); 15020 if (const auto *Ptr = Ty->getAs<PointerType>()) 15021 Inner = Ptr->getPointeeType(); 15022 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15023 Inner = Arr->getElementType(); 15024 else 15025 return nullptr; 15026 15027 if (Inner->hasAttr(attr::NoDeref)) 15028 return E; 15029 } 15030 return nullptr; 15031 } 15032 15033 } // namespace 15034 15035 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15036 for (const Expr *E : Rec.PossibleDerefs) { 15037 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15038 if (DeclRef) { 15039 const ValueDecl *Decl = DeclRef->getDecl(); 15040 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15041 << Decl->getName() << E->getSourceRange(); 15042 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15043 } else { 15044 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15045 << E->getSourceRange(); 15046 } 15047 } 15048 Rec.PossibleDerefs.clear(); 15049 } 15050 15051 void Sema::PopExpressionEvaluationContext() { 15052 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15053 unsigned NumTypos = Rec.NumTypos; 15054 15055 if (!Rec.Lambdas.empty()) { 15056 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15057 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15058 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15059 unsigned D; 15060 if (Rec.isUnevaluated()) { 15061 // C++11 [expr.prim.lambda]p2: 15062 // A lambda-expression shall not appear in an unevaluated operand 15063 // (Clause 5). 15064 D = diag::err_lambda_unevaluated_operand; 15065 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15066 // C++1y [expr.const]p2: 15067 // A conditional-expression e is a core constant expression unless the 15068 // evaluation of e, following the rules of the abstract machine, would 15069 // evaluate [...] a lambda-expression. 15070 D = diag::err_lambda_in_constant_expression; 15071 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15072 // C++17 [expr.prim.lamda]p2: 15073 // A lambda-expression shall not appear [...] in a template-argument. 15074 D = diag::err_lambda_in_invalid_context; 15075 } else 15076 llvm_unreachable("Couldn't infer lambda error message."); 15077 15078 for (const auto *L : Rec.Lambdas) 15079 Diag(L->getBeginLoc(), D); 15080 } 15081 } 15082 15083 WarnOnPendingNoDerefs(Rec); 15084 15085 // When are coming out of an unevaluated context, clear out any 15086 // temporaries that we may have created as part of the evaluation of 15087 // the expression in that context: they aren't relevant because they 15088 // will never be constructed. 15089 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15090 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15091 ExprCleanupObjects.end()); 15092 Cleanup = Rec.ParentCleanup; 15093 CleanupVarDeclMarking(); 15094 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15095 // Otherwise, merge the contexts together. 15096 } else { 15097 Cleanup.mergeFrom(Rec.ParentCleanup); 15098 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15099 Rec.SavedMaybeODRUseExprs.end()); 15100 } 15101 15102 // Pop the current expression evaluation context off the stack. 15103 ExprEvalContexts.pop_back(); 15104 15105 // The global expression evaluation context record is never popped. 15106 ExprEvalContexts.back().NumTypos += NumTypos; 15107 } 15108 15109 void Sema::DiscardCleanupsInEvaluationContext() { 15110 ExprCleanupObjects.erase( 15111 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15112 ExprCleanupObjects.end()); 15113 Cleanup.reset(); 15114 MaybeODRUseExprs.clear(); 15115 } 15116 15117 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15118 ExprResult Result = CheckPlaceholderExpr(E); 15119 if (Result.isInvalid()) 15120 return ExprError(); 15121 E = Result.get(); 15122 if (!E->getType()->isVariablyModifiedType()) 15123 return E; 15124 return TransformToPotentiallyEvaluated(E); 15125 } 15126 15127 /// Are we in a context that is potentially constant evaluated per C++20 15128 /// [expr.const]p12? 15129 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15130 /// C++2a [expr.const]p12: 15131 // An expression or conversion is potentially constant evaluated if it is 15132 switch (SemaRef.ExprEvalContexts.back().Context) { 15133 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15134 // -- a manifestly constant-evaluated expression, 15135 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15136 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15137 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15138 // -- a potentially-evaluated expression, 15139 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15140 // -- an immediate subexpression of a braced-init-list, 15141 15142 // -- [FIXME] an expression of the form & cast-expression that occurs 15143 // within a templated entity 15144 // -- a subexpression of one of the above that is not a subexpression of 15145 // a nested unevaluated operand. 15146 return true; 15147 15148 case Sema::ExpressionEvaluationContext::Unevaluated: 15149 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15150 // Expressions in this context are never evaluated. 15151 return false; 15152 } 15153 llvm_unreachable("Invalid context"); 15154 } 15155 15156 /// Return true if this function has a calling convention that requires mangling 15157 /// in the size of the parameter pack. 15158 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15159 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15160 // we don't need parameter type sizes. 15161 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15162 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15163 TT.getArch() != llvm::Triple::x86_64)) 15164 return false; 15165 15166 // If this is C++ and this isn't an extern "C" function, parameters do not 15167 // need to be complete. In this case, C++ mangling will apply, which doesn't 15168 // use the size of the parameters. 15169 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15170 return false; 15171 15172 // Stdcall, fastcall, and vectorcall need this special treatment. 15173 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15174 switch (CC) { 15175 case CC_X86StdCall: 15176 case CC_X86FastCall: 15177 case CC_X86VectorCall: 15178 return true; 15179 default: 15180 break; 15181 } 15182 return false; 15183 } 15184 15185 /// Require that all of the parameter types of function be complete. Normally, 15186 /// parameter types are only required to be complete when a function is called 15187 /// or defined, but to mangle functions with certain calling conventions, the 15188 /// mangler needs to know the size of the parameter list. In this situation, 15189 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15190 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15191 /// result in a linker error. Clang doesn't implement this behavior, and instead 15192 /// attempts to error at compile time. 15193 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15194 SourceLocation Loc) { 15195 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15196 FunctionDecl *FD; 15197 ParmVarDecl *Param; 15198 15199 public: 15200 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15201 : FD(FD), Param(Param) {} 15202 15203 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15204 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15205 StringRef CCName; 15206 switch (CC) { 15207 case CC_X86StdCall: 15208 CCName = "stdcall"; 15209 break; 15210 case CC_X86FastCall: 15211 CCName = "fastcall"; 15212 break; 15213 case CC_X86VectorCall: 15214 CCName = "vectorcall"; 15215 break; 15216 default: 15217 llvm_unreachable("CC does not need mangling"); 15218 } 15219 15220 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15221 << Param->getDeclName() << FD->getDeclName() << CCName; 15222 } 15223 }; 15224 15225 for (ParmVarDecl *Param : FD->parameters()) { 15226 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15227 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15228 } 15229 } 15230 15231 namespace { 15232 enum class OdrUseContext { 15233 /// Declarations in this context are not odr-used. 15234 None, 15235 /// Declarations in this context are formally odr-used, but this is a 15236 /// dependent context. 15237 Dependent, 15238 /// Declarations in this context are odr-used but not actually used (yet). 15239 FormallyOdrUsed, 15240 /// Declarations in this context are used. 15241 Used 15242 }; 15243 } 15244 15245 /// Are we within a context in which references to resolved functions or to 15246 /// variables result in odr-use? 15247 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15248 OdrUseContext Result; 15249 15250 switch (SemaRef.ExprEvalContexts.back().Context) { 15251 case Sema::ExpressionEvaluationContext::Unevaluated: 15252 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15253 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15254 return OdrUseContext::None; 15255 15256 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15257 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15258 Result = OdrUseContext::Used; 15259 break; 15260 15261 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15262 Result = OdrUseContext::FormallyOdrUsed; 15263 break; 15264 15265 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15266 // A default argument formally results in odr-use, but doesn't actually 15267 // result in a use in any real sense until it itself is used. 15268 Result = OdrUseContext::FormallyOdrUsed; 15269 break; 15270 } 15271 15272 if (SemaRef.CurContext->isDependentContext()) 15273 return OdrUseContext::Dependent; 15274 15275 return Result; 15276 } 15277 15278 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15279 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 15280 return Func->isConstexpr() && 15281 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 15282 } 15283 15284 /// Mark a function referenced, and check whether it is odr-used 15285 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15286 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15287 bool MightBeOdrUse) { 15288 assert(Func && "No function?"); 15289 15290 Func->setReferenced(); 15291 15292 // Recursive functions aren't really used until they're used from some other 15293 // context. 15294 bool IsRecursiveCall = CurContext == Func; 15295 15296 // C++11 [basic.def.odr]p3: 15297 // A function whose name appears as a potentially-evaluated expression is 15298 // odr-used if it is the unique lookup result or the selected member of a 15299 // set of overloaded functions [...]. 15300 // 15301 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15302 // can just check that here. 15303 OdrUseContext OdrUse = 15304 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15305 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15306 OdrUse = OdrUseContext::FormallyOdrUsed; 15307 15308 // Trivial default constructors and destructors are never actually used. 15309 // FIXME: What about other special members? 15310 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15311 OdrUse == OdrUseContext::Used) { 15312 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15313 if (Constructor->isDefaultConstructor()) 15314 OdrUse = OdrUseContext::FormallyOdrUsed; 15315 if (isa<CXXDestructorDecl>(Func)) 15316 OdrUse = OdrUseContext::FormallyOdrUsed; 15317 } 15318 15319 // C++20 [expr.const]p12: 15320 // A function [...] is needed for constant evaluation if it is [...] a 15321 // constexpr function that is named by an expression that is potentially 15322 // constant evaluated 15323 bool NeededForConstantEvaluation = 15324 isPotentiallyConstantEvaluatedContext(*this) && 15325 isImplicitlyDefinableConstexprFunction(Func); 15326 15327 // Determine whether we require a function definition to exist, per 15328 // C++11 [temp.inst]p3: 15329 // Unless a function template specialization has been explicitly 15330 // instantiated or explicitly specialized, the function template 15331 // specialization is implicitly instantiated when the specialization is 15332 // referenced in a context that requires a function definition to exist. 15333 // C++20 [temp.inst]p7: 15334 // The existence of a definition of a [...] function is considered to 15335 // affect the semantics of the program if the [...] function is needed for 15336 // constant evaluation by an expression 15337 // C++20 [basic.def.odr]p10: 15338 // Every program shall contain exactly one definition of every non-inline 15339 // function or variable that is odr-used in that program outside of a 15340 // discarded statement 15341 // C++20 [special]p1: 15342 // The implementation will implicitly define [defaulted special members] 15343 // if they are odr-used or needed for constant evaluation. 15344 // 15345 // Note that we skip the implicit instantiation of templates that are only 15346 // used in unused default arguments or by recursive calls to themselves. 15347 // This is formally non-conforming, but seems reasonable in practice. 15348 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15349 NeededForConstantEvaluation); 15350 15351 // C++14 [temp.expl.spec]p6: 15352 // If a template [...] is explicitly specialized then that specialization 15353 // shall be declared before the first use of that specialization that would 15354 // cause an implicit instantiation to take place, in every translation unit 15355 // in which such a use occurs 15356 if (NeedDefinition && 15357 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15358 Func->getMemberSpecializationInfo())) 15359 checkSpecializationVisibility(Loc, Func); 15360 15361 // C++14 [except.spec]p17: 15362 // An exception-specification is considered to be needed when: 15363 // - the function is odr-used or, if it appears in an unevaluated operand, 15364 // would be odr-used if the expression were potentially-evaluated; 15365 // 15366 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15367 // function is a pure virtual function we're calling, and in that case the 15368 // function was selected by overload resolution and we need to resolve its 15369 // exception specification for a different reason. 15370 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15371 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15372 ResolveExceptionSpec(Loc, FPT); 15373 15374 if (getLangOpts().CUDA) 15375 CheckCUDACall(Loc, Func); 15376 15377 // If we need a definition, try to create one. 15378 if (NeedDefinition && !Func->getBody()) { 15379 runWithSufficientStackSpace(Loc, [&] { 15380 if (CXXConstructorDecl *Constructor = 15381 dyn_cast<CXXConstructorDecl>(Func)) { 15382 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15383 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15384 if (Constructor->isDefaultConstructor()) { 15385 if (Constructor->isTrivial() && 15386 !Constructor->hasAttr<DLLExportAttr>()) 15387 return; 15388 DefineImplicitDefaultConstructor(Loc, Constructor); 15389 } else if (Constructor->isCopyConstructor()) { 15390 DefineImplicitCopyConstructor(Loc, Constructor); 15391 } else if (Constructor->isMoveConstructor()) { 15392 DefineImplicitMoveConstructor(Loc, Constructor); 15393 } 15394 } else if (Constructor->getInheritedConstructor()) { 15395 DefineInheritingConstructor(Loc, Constructor); 15396 } 15397 } else if (CXXDestructorDecl *Destructor = 15398 dyn_cast<CXXDestructorDecl>(Func)) { 15399 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15400 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15401 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15402 return; 15403 DefineImplicitDestructor(Loc, Destructor); 15404 } 15405 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15406 MarkVTableUsed(Loc, Destructor->getParent()); 15407 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15408 if (MethodDecl->isOverloadedOperator() && 15409 MethodDecl->getOverloadedOperator() == OO_Equal) { 15410 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15411 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15412 if (MethodDecl->isCopyAssignmentOperator()) 15413 DefineImplicitCopyAssignment(Loc, MethodDecl); 15414 else if (MethodDecl->isMoveAssignmentOperator()) 15415 DefineImplicitMoveAssignment(Loc, MethodDecl); 15416 } 15417 } else if (isa<CXXConversionDecl>(MethodDecl) && 15418 MethodDecl->getParent()->isLambda()) { 15419 CXXConversionDecl *Conversion = 15420 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15421 if (Conversion->isLambdaToBlockPointerConversion()) 15422 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15423 else 15424 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15425 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15426 MarkVTableUsed(Loc, MethodDecl->getParent()); 15427 } 15428 15429 // Implicit instantiation of function templates and member functions of 15430 // class templates. 15431 if (Func->isImplicitlyInstantiable()) { 15432 TemplateSpecializationKind TSK = 15433 Func->getTemplateSpecializationKindForInstantiation(); 15434 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15435 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15436 if (FirstInstantiation) { 15437 PointOfInstantiation = Loc; 15438 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15439 } else if (TSK != TSK_ImplicitInstantiation) { 15440 // Use the point of use as the point of instantiation, instead of the 15441 // point of explicit instantiation (which we track as the actual point 15442 // of instantiation). This gives better backtraces in diagnostics. 15443 PointOfInstantiation = Loc; 15444 } 15445 15446 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15447 Func->isConstexpr()) { 15448 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15449 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15450 CodeSynthesisContexts.size()) 15451 PendingLocalImplicitInstantiations.push_back( 15452 std::make_pair(Func, PointOfInstantiation)); 15453 else if (Func->isConstexpr()) 15454 // Do not defer instantiations of constexpr functions, to avoid the 15455 // expression evaluator needing to call back into Sema if it sees a 15456 // call to such a function. 15457 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15458 else { 15459 Func->setInstantiationIsPending(true); 15460 PendingInstantiations.push_back( 15461 std::make_pair(Func, PointOfInstantiation)); 15462 // Notify the consumer that a function was implicitly instantiated. 15463 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15464 } 15465 } 15466 } else { 15467 // Walk redefinitions, as some of them may be instantiable. 15468 for (auto i : Func->redecls()) { 15469 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15470 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15471 } 15472 } 15473 }); 15474 } 15475 15476 // If this is the first "real" use, act on that. 15477 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15478 // Keep track of used but undefined functions. 15479 if (!Func->isDefined()) { 15480 if (mightHaveNonExternalLinkage(Func)) 15481 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15482 else if (Func->getMostRecentDecl()->isInlined() && 15483 !LangOpts.GNUInline && 15484 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15485 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15486 else if (isExternalWithNoLinkageType(Func)) 15487 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15488 } 15489 15490 // Some x86 Windows calling conventions mangle the size of the parameter 15491 // pack into the name. Computing the size of the parameters requires the 15492 // parameter types to be complete. Check that now. 15493 if (funcHasParameterSizeMangling(*this, Func)) 15494 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15495 15496 Func->markUsed(Context); 15497 } 15498 15499 if (LangOpts.OpenMP) { 15500 if (LangOpts.OpenMPIsDevice) 15501 checkOpenMPDeviceFunction(Loc, Func); 15502 else 15503 checkOpenMPHostFunction(Loc, Func); 15504 } 15505 } 15506 15507 /// Directly mark a variable odr-used. Given a choice, prefer to use 15508 /// MarkVariableReferenced since it does additional checks and then 15509 /// calls MarkVarDeclODRUsed. 15510 /// If the variable must be captured: 15511 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15512 /// - else capture it in the DeclContext that maps to the 15513 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15514 static void 15515 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15516 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15517 // Keep track of used but undefined variables. 15518 // FIXME: We shouldn't suppress this warning for static data members. 15519 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15520 (!Var->isExternallyVisible() || Var->isInline() || 15521 SemaRef.isExternalWithNoLinkageType(Var)) && 15522 !(Var->isStaticDataMember() && Var->hasInit())) { 15523 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15524 if (old.isInvalid()) 15525 old = Loc; 15526 } 15527 QualType CaptureType, DeclRefType; 15528 if (SemaRef.LangOpts.OpenMP) 15529 SemaRef.tryCaptureOpenMPLambdas(Var); 15530 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15531 /*EllipsisLoc*/ SourceLocation(), 15532 /*BuildAndDiagnose*/ true, 15533 CaptureType, DeclRefType, 15534 FunctionScopeIndexToStopAt); 15535 15536 Var->markUsed(SemaRef.Context); 15537 } 15538 15539 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15540 SourceLocation Loc, 15541 unsigned CapturingScopeIndex) { 15542 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15543 } 15544 15545 static void 15546 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15547 ValueDecl *var, DeclContext *DC) { 15548 DeclContext *VarDC = var->getDeclContext(); 15549 15550 // If the parameter still belongs to the translation unit, then 15551 // we're actually just using one parameter in the declaration of 15552 // the next. 15553 if (isa<ParmVarDecl>(var) && 15554 isa<TranslationUnitDecl>(VarDC)) 15555 return; 15556 15557 // For C code, don't diagnose about capture if we're not actually in code 15558 // right now; it's impossible to write a non-constant expression outside of 15559 // function context, so we'll get other (more useful) diagnostics later. 15560 // 15561 // For C++, things get a bit more nasty... it would be nice to suppress this 15562 // diagnostic for certain cases like using a local variable in an array bound 15563 // for a member of a local class, but the correct predicate is not obvious. 15564 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15565 return; 15566 15567 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15568 unsigned ContextKind = 3; // unknown 15569 if (isa<CXXMethodDecl>(VarDC) && 15570 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15571 ContextKind = 2; 15572 } else if (isa<FunctionDecl>(VarDC)) { 15573 ContextKind = 0; 15574 } else if (isa<BlockDecl>(VarDC)) { 15575 ContextKind = 1; 15576 } 15577 15578 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15579 << var << ValueKind << ContextKind << VarDC; 15580 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15581 << var; 15582 15583 // FIXME: Add additional diagnostic info about class etc. which prevents 15584 // capture. 15585 } 15586 15587 15588 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15589 bool &SubCapturesAreNested, 15590 QualType &CaptureType, 15591 QualType &DeclRefType) { 15592 // Check whether we've already captured it. 15593 if (CSI->CaptureMap.count(Var)) { 15594 // If we found a capture, any subcaptures are nested. 15595 SubCapturesAreNested = true; 15596 15597 // Retrieve the capture type for this variable. 15598 CaptureType = CSI->getCapture(Var).getCaptureType(); 15599 15600 // Compute the type of an expression that refers to this variable. 15601 DeclRefType = CaptureType.getNonReferenceType(); 15602 15603 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15604 // are mutable in the sense that user can change their value - they are 15605 // private instances of the captured declarations. 15606 const Capture &Cap = CSI->getCapture(Var); 15607 if (Cap.isCopyCapture() && 15608 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15609 !(isa<CapturedRegionScopeInfo>(CSI) && 15610 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15611 DeclRefType.addConst(); 15612 return true; 15613 } 15614 return false; 15615 } 15616 15617 // Only block literals, captured statements, and lambda expressions can 15618 // capture; other scopes don't work. 15619 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15620 SourceLocation Loc, 15621 const bool Diagnose, Sema &S) { 15622 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15623 return getLambdaAwareParentOfDeclContext(DC); 15624 else if (Var->hasLocalStorage()) { 15625 if (Diagnose) 15626 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15627 } 15628 return nullptr; 15629 } 15630 15631 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15632 // certain types of variables (unnamed, variably modified types etc.) 15633 // so check for eligibility. 15634 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15635 SourceLocation Loc, 15636 const bool Diagnose, Sema &S) { 15637 15638 bool IsBlock = isa<BlockScopeInfo>(CSI); 15639 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15640 15641 // Lambdas are not allowed to capture unnamed variables 15642 // (e.g. anonymous unions). 15643 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15644 // assuming that's the intent. 15645 if (IsLambda && !Var->getDeclName()) { 15646 if (Diagnose) { 15647 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15648 S.Diag(Var->getLocation(), diag::note_declared_at); 15649 } 15650 return false; 15651 } 15652 15653 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15654 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15655 if (Diagnose) { 15656 S.Diag(Loc, diag::err_ref_vm_type); 15657 S.Diag(Var->getLocation(), diag::note_previous_decl) 15658 << Var->getDeclName(); 15659 } 15660 return false; 15661 } 15662 // Prohibit structs with flexible array members too. 15663 // We cannot capture what is in the tail end of the struct. 15664 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15665 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15666 if (Diagnose) { 15667 if (IsBlock) 15668 S.Diag(Loc, diag::err_ref_flexarray_type); 15669 else 15670 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15671 << Var->getDeclName(); 15672 S.Diag(Var->getLocation(), diag::note_previous_decl) 15673 << Var->getDeclName(); 15674 } 15675 return false; 15676 } 15677 } 15678 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15679 // Lambdas and captured statements are not allowed to capture __block 15680 // variables; they don't support the expected semantics. 15681 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15682 if (Diagnose) { 15683 S.Diag(Loc, diag::err_capture_block_variable) 15684 << Var->getDeclName() << !IsLambda; 15685 S.Diag(Var->getLocation(), diag::note_previous_decl) 15686 << Var->getDeclName(); 15687 } 15688 return false; 15689 } 15690 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15691 if (S.getLangOpts().OpenCL && IsBlock && 15692 Var->getType()->isBlockPointerType()) { 15693 if (Diagnose) 15694 S.Diag(Loc, diag::err_opencl_block_ref_block); 15695 return false; 15696 } 15697 15698 return true; 15699 } 15700 15701 // Returns true if the capture by block was successful. 15702 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15703 SourceLocation Loc, 15704 const bool BuildAndDiagnose, 15705 QualType &CaptureType, 15706 QualType &DeclRefType, 15707 const bool Nested, 15708 Sema &S, bool Invalid) { 15709 bool ByRef = false; 15710 15711 // Blocks are not allowed to capture arrays, excepting OpenCL. 15712 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15713 // (decayed to pointers). 15714 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15715 if (BuildAndDiagnose) { 15716 S.Diag(Loc, diag::err_ref_array_type); 15717 S.Diag(Var->getLocation(), diag::note_previous_decl) 15718 << Var->getDeclName(); 15719 Invalid = true; 15720 } else { 15721 return false; 15722 } 15723 } 15724 15725 // Forbid the block-capture of autoreleasing variables. 15726 if (!Invalid && 15727 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15728 if (BuildAndDiagnose) { 15729 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15730 << /*block*/ 0; 15731 S.Diag(Var->getLocation(), diag::note_previous_decl) 15732 << Var->getDeclName(); 15733 Invalid = true; 15734 } else { 15735 return false; 15736 } 15737 } 15738 15739 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15740 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15741 QualType PointeeTy = PT->getPointeeType(); 15742 15743 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15744 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15745 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15746 if (BuildAndDiagnose) { 15747 SourceLocation VarLoc = Var->getLocation(); 15748 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15749 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15750 } 15751 } 15752 } 15753 15754 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15755 if (HasBlocksAttr || CaptureType->isReferenceType() || 15756 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15757 // Block capture by reference does not change the capture or 15758 // declaration reference types. 15759 ByRef = true; 15760 } else { 15761 // Block capture by copy introduces 'const'. 15762 CaptureType = CaptureType.getNonReferenceType().withConst(); 15763 DeclRefType = CaptureType; 15764 } 15765 15766 // Actually capture the variable. 15767 if (BuildAndDiagnose) 15768 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15769 CaptureType, Invalid); 15770 15771 return !Invalid; 15772 } 15773 15774 15775 /// Capture the given variable in the captured region. 15776 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15777 VarDecl *Var, 15778 SourceLocation Loc, 15779 const bool BuildAndDiagnose, 15780 QualType &CaptureType, 15781 QualType &DeclRefType, 15782 const bool RefersToCapturedVariable, 15783 Sema &S, bool Invalid) { 15784 // By default, capture variables by reference. 15785 bool ByRef = true; 15786 // Using an LValue reference type is consistent with Lambdas (see below). 15787 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15788 if (S.isOpenMPCapturedDecl(Var)) { 15789 bool HasConst = DeclRefType.isConstQualified(); 15790 DeclRefType = DeclRefType.getUnqualifiedType(); 15791 // Don't lose diagnostics about assignments to const. 15792 if (HasConst) 15793 DeclRefType.addConst(); 15794 } 15795 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15796 RSI->OpenMPCaptureLevel); 15797 } 15798 15799 if (ByRef) 15800 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15801 else 15802 CaptureType = DeclRefType; 15803 15804 // Actually capture the variable. 15805 if (BuildAndDiagnose) 15806 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15807 Loc, SourceLocation(), CaptureType, Invalid); 15808 15809 return !Invalid; 15810 } 15811 15812 /// Capture the given variable in the lambda. 15813 static bool captureInLambda(LambdaScopeInfo *LSI, 15814 VarDecl *Var, 15815 SourceLocation Loc, 15816 const bool BuildAndDiagnose, 15817 QualType &CaptureType, 15818 QualType &DeclRefType, 15819 const bool RefersToCapturedVariable, 15820 const Sema::TryCaptureKind Kind, 15821 SourceLocation EllipsisLoc, 15822 const bool IsTopScope, 15823 Sema &S, bool Invalid) { 15824 // Determine whether we are capturing by reference or by value. 15825 bool ByRef = false; 15826 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15827 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15828 } else { 15829 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15830 } 15831 15832 // Compute the type of the field that will capture this variable. 15833 if (ByRef) { 15834 // C++11 [expr.prim.lambda]p15: 15835 // An entity is captured by reference if it is implicitly or 15836 // explicitly captured but not captured by copy. It is 15837 // unspecified whether additional unnamed non-static data 15838 // members are declared in the closure type for entities 15839 // captured by reference. 15840 // 15841 // FIXME: It is not clear whether we want to build an lvalue reference 15842 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15843 // to do the former, while EDG does the latter. Core issue 1249 will 15844 // clarify, but for now we follow GCC because it's a more permissive and 15845 // easily defensible position. 15846 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15847 } else { 15848 // C++11 [expr.prim.lambda]p14: 15849 // For each entity captured by copy, an unnamed non-static 15850 // data member is declared in the closure type. The 15851 // declaration order of these members is unspecified. The type 15852 // of such a data member is the type of the corresponding 15853 // captured entity if the entity is not a reference to an 15854 // object, or the referenced type otherwise. [Note: If the 15855 // captured entity is a reference to a function, the 15856 // corresponding data member is also a reference to a 15857 // function. - end note ] 15858 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15859 if (!RefType->getPointeeType()->isFunctionType()) 15860 CaptureType = RefType->getPointeeType(); 15861 } 15862 15863 // Forbid the lambda copy-capture of autoreleasing variables. 15864 if (!Invalid && 15865 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15866 if (BuildAndDiagnose) { 15867 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15868 S.Diag(Var->getLocation(), diag::note_previous_decl) 15869 << Var->getDeclName(); 15870 Invalid = true; 15871 } else { 15872 return false; 15873 } 15874 } 15875 15876 // Make sure that by-copy captures are of a complete and non-abstract type. 15877 if (!Invalid && BuildAndDiagnose) { 15878 if (!CaptureType->isDependentType() && 15879 S.RequireCompleteType(Loc, CaptureType, 15880 diag::err_capture_of_incomplete_type, 15881 Var->getDeclName())) 15882 Invalid = true; 15883 else if (S.RequireNonAbstractType(Loc, CaptureType, 15884 diag::err_capture_of_abstract_type)) 15885 Invalid = true; 15886 } 15887 } 15888 15889 // Compute the type of a reference to this captured variable. 15890 if (ByRef) 15891 DeclRefType = CaptureType.getNonReferenceType(); 15892 else { 15893 // C++ [expr.prim.lambda]p5: 15894 // The closure type for a lambda-expression has a public inline 15895 // function call operator [...]. This function call operator is 15896 // declared const (9.3.1) if and only if the lambda-expression's 15897 // parameter-declaration-clause is not followed by mutable. 15898 DeclRefType = CaptureType.getNonReferenceType(); 15899 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15900 DeclRefType.addConst(); 15901 } 15902 15903 // Add the capture. 15904 if (BuildAndDiagnose) 15905 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 15906 Loc, EllipsisLoc, CaptureType, Invalid); 15907 15908 return !Invalid; 15909 } 15910 15911 bool Sema::tryCaptureVariable( 15912 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15913 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15914 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15915 // An init-capture is notionally from the context surrounding its 15916 // declaration, but its parent DC is the lambda class. 15917 DeclContext *VarDC = Var->getDeclContext(); 15918 if (Var->isInitCapture()) 15919 VarDC = VarDC->getParent(); 15920 15921 DeclContext *DC = CurContext; 15922 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15923 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15924 // We need to sync up the Declaration Context with the 15925 // FunctionScopeIndexToStopAt 15926 if (FunctionScopeIndexToStopAt) { 15927 unsigned FSIndex = FunctionScopes.size() - 1; 15928 while (FSIndex != MaxFunctionScopesIndex) { 15929 DC = getLambdaAwareParentOfDeclContext(DC); 15930 --FSIndex; 15931 } 15932 } 15933 15934 15935 // If the variable is declared in the current context, there is no need to 15936 // capture it. 15937 if (VarDC == DC) return true; 15938 15939 // Capture global variables if it is required to use private copy of this 15940 // variable. 15941 bool IsGlobal = !Var->hasLocalStorage(); 15942 if (IsGlobal && 15943 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 15944 MaxFunctionScopesIndex))) 15945 return true; 15946 Var = Var->getCanonicalDecl(); 15947 15948 // Walk up the stack to determine whether we can capture the variable, 15949 // performing the "simple" checks that don't depend on type. We stop when 15950 // we've either hit the declared scope of the variable or find an existing 15951 // capture of that variable. We start from the innermost capturing-entity 15952 // (the DC) and ensure that all intervening capturing-entities 15953 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15954 // declcontext can either capture the variable or have already captured 15955 // the variable. 15956 CaptureType = Var->getType(); 15957 DeclRefType = CaptureType.getNonReferenceType(); 15958 bool Nested = false; 15959 bool Explicit = (Kind != TryCapture_Implicit); 15960 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15961 do { 15962 // Only block literals, captured statements, and lambda expressions can 15963 // capture; other scopes don't work. 15964 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15965 ExprLoc, 15966 BuildAndDiagnose, 15967 *this); 15968 // We need to check for the parent *first* because, if we *have* 15969 // private-captured a global variable, we need to recursively capture it in 15970 // intermediate blocks, lambdas, etc. 15971 if (!ParentDC) { 15972 if (IsGlobal) { 15973 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15974 break; 15975 } 15976 return true; 15977 } 15978 15979 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15980 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15981 15982 15983 // Check whether we've already captured it. 15984 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15985 DeclRefType)) { 15986 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15987 break; 15988 } 15989 // If we are instantiating a generic lambda call operator body, 15990 // we do not want to capture new variables. What was captured 15991 // during either a lambdas transformation or initial parsing 15992 // should be used. 15993 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15994 if (BuildAndDiagnose) { 15995 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15996 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15997 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15998 Diag(Var->getLocation(), diag::note_previous_decl) 15999 << Var->getDeclName(); 16000 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16001 } else 16002 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16003 } 16004 return true; 16005 } 16006 16007 // Try to capture variable-length arrays types. 16008 if (Var->getType()->isVariablyModifiedType()) { 16009 // We're going to walk down into the type and look for VLA 16010 // expressions. 16011 QualType QTy = Var->getType(); 16012 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16013 QTy = PVD->getOriginalType(); 16014 captureVariablyModifiedType(Context, QTy, CSI); 16015 } 16016 16017 if (getLangOpts().OpenMP) { 16018 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16019 // OpenMP private variables should not be captured in outer scope, so 16020 // just break here. Similarly, global variables that are captured in a 16021 // target region should not be captured outside the scope of the region. 16022 if (RSI->CapRegionKind == CR_OpenMP) { 16023 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16024 auto IsTargetCap = !IsOpenMPPrivateDecl && 16025 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16026 // When we detect target captures we are looking from inside the 16027 // target region, therefore we need to propagate the capture from the 16028 // enclosing region. Therefore, the capture is not initially nested. 16029 if (IsTargetCap) 16030 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16031 16032 if (IsTargetCap || IsOpenMPPrivateDecl) { 16033 Nested = !IsTargetCap; 16034 DeclRefType = DeclRefType.getUnqualifiedType(); 16035 CaptureType = Context.getLValueReferenceType(DeclRefType); 16036 break; 16037 } 16038 } 16039 } 16040 } 16041 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16042 // No capture-default, and this is not an explicit capture 16043 // so cannot capture this variable. 16044 if (BuildAndDiagnose) { 16045 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16046 Diag(Var->getLocation(), diag::note_previous_decl) 16047 << Var->getDeclName(); 16048 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16049 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16050 diag::note_lambda_decl); 16051 // FIXME: If we error out because an outer lambda can not implicitly 16052 // capture a variable that an inner lambda explicitly captures, we 16053 // should have the inner lambda do the explicit capture - because 16054 // it makes for cleaner diagnostics later. This would purely be done 16055 // so that the diagnostic does not misleadingly claim that a variable 16056 // can not be captured by a lambda implicitly even though it is captured 16057 // explicitly. Suggestion: 16058 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16059 // at the function head 16060 // - cache the StartingDeclContext - this must be a lambda 16061 // - captureInLambda in the innermost lambda the variable. 16062 } 16063 return true; 16064 } 16065 16066 FunctionScopesIndex--; 16067 DC = ParentDC; 16068 Explicit = false; 16069 } while (!VarDC->Equals(DC)); 16070 16071 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16072 // computing the type of the capture at each step, checking type-specific 16073 // requirements, and adding captures if requested. 16074 // If the variable had already been captured previously, we start capturing 16075 // at the lambda nested within that one. 16076 bool Invalid = false; 16077 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16078 ++I) { 16079 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16080 16081 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16082 // certain types of variables (unnamed, variably modified types etc.) 16083 // so check for eligibility. 16084 if (!Invalid) 16085 Invalid = 16086 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16087 16088 // After encountering an error, if we're actually supposed to capture, keep 16089 // capturing in nested contexts to suppress any follow-on diagnostics. 16090 if (Invalid && !BuildAndDiagnose) 16091 return true; 16092 16093 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16094 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16095 DeclRefType, Nested, *this, Invalid); 16096 Nested = true; 16097 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16098 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16099 CaptureType, DeclRefType, Nested, 16100 *this, Invalid); 16101 Nested = true; 16102 } else { 16103 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16104 Invalid = 16105 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16106 DeclRefType, Nested, Kind, EllipsisLoc, 16107 /*IsTopScope*/ I == N - 1, *this, Invalid); 16108 Nested = true; 16109 } 16110 16111 if (Invalid && !BuildAndDiagnose) 16112 return true; 16113 } 16114 return Invalid; 16115 } 16116 16117 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16118 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16119 QualType CaptureType; 16120 QualType DeclRefType; 16121 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16122 /*BuildAndDiagnose=*/true, CaptureType, 16123 DeclRefType, nullptr); 16124 } 16125 16126 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16127 QualType CaptureType; 16128 QualType DeclRefType; 16129 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16130 /*BuildAndDiagnose=*/false, CaptureType, 16131 DeclRefType, nullptr); 16132 } 16133 16134 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16135 QualType CaptureType; 16136 QualType DeclRefType; 16137 16138 // Determine whether we can capture this variable. 16139 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16140 /*BuildAndDiagnose=*/false, CaptureType, 16141 DeclRefType, nullptr)) 16142 return QualType(); 16143 16144 return DeclRefType; 16145 } 16146 16147 namespace { 16148 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16149 // The produced TemplateArgumentListInfo* points to data stored within this 16150 // object, so should only be used in contexts where the pointer will not be 16151 // used after the CopiedTemplateArgs object is destroyed. 16152 class CopiedTemplateArgs { 16153 bool HasArgs; 16154 TemplateArgumentListInfo TemplateArgStorage; 16155 public: 16156 template<typename RefExpr> 16157 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16158 if (HasArgs) 16159 E->copyTemplateArgumentsInto(TemplateArgStorage); 16160 } 16161 operator TemplateArgumentListInfo*() 16162 #ifdef __has_cpp_attribute 16163 #if __has_cpp_attribute(clang::lifetimebound) 16164 [[clang::lifetimebound]] 16165 #endif 16166 #endif 16167 { 16168 return HasArgs ? &TemplateArgStorage : nullptr; 16169 } 16170 }; 16171 } 16172 16173 /// Walk the set of potential results of an expression and mark them all as 16174 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16175 /// 16176 /// \return A new expression if we found any potential results, ExprEmpty() if 16177 /// not, and ExprError() if we diagnosed an error. 16178 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16179 NonOdrUseReason NOUR) { 16180 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16181 // an object that satisfies the requirements for appearing in a 16182 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16183 // is immediately applied." This function handles the lvalue-to-rvalue 16184 // conversion part. 16185 // 16186 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16187 // transform it into the relevant kind of non-odr-use node and rebuild the 16188 // tree of nodes leading to it. 16189 // 16190 // This is a mini-TreeTransform that only transforms a restricted subset of 16191 // nodes (and only certain operands of them). 16192 16193 // Rebuild a subexpression. 16194 auto Rebuild = [&](Expr *Sub) { 16195 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16196 }; 16197 16198 // Check whether a potential result satisfies the requirements of NOUR. 16199 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16200 // Any entity other than a VarDecl is always odr-used whenever it's named 16201 // in a potentially-evaluated expression. 16202 auto *VD = dyn_cast<VarDecl>(D); 16203 if (!VD) 16204 return true; 16205 16206 // C++2a [basic.def.odr]p4: 16207 // A variable x whose name appears as a potentially-evalauted expression 16208 // e is odr-used by e unless 16209 // -- x is a reference that is usable in constant expressions, or 16210 // -- x is a variable of non-reference type that is usable in constant 16211 // expressions and has no mutable subobjects, and e is an element of 16212 // the set of potential results of an expression of 16213 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16214 // conversion is applied, or 16215 // -- x is a variable of non-reference type, and e is an element of the 16216 // set of potential results of a discarded-value expression to which 16217 // the lvalue-to-rvalue conversion is not applied 16218 // 16219 // We check the first bullet and the "potentially-evaluated" condition in 16220 // BuildDeclRefExpr. We check the type requirements in the second bullet 16221 // in CheckLValueToRValueConversionOperand below. 16222 switch (NOUR) { 16223 case NOUR_None: 16224 case NOUR_Unevaluated: 16225 llvm_unreachable("unexpected non-odr-use-reason"); 16226 16227 case NOUR_Constant: 16228 // Constant references were handled when they were built. 16229 if (VD->getType()->isReferenceType()) 16230 return true; 16231 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16232 if (RD->hasMutableFields()) 16233 return true; 16234 if (!VD->isUsableInConstantExpressions(S.Context)) 16235 return true; 16236 break; 16237 16238 case NOUR_Discarded: 16239 if (VD->getType()->isReferenceType()) 16240 return true; 16241 break; 16242 } 16243 return false; 16244 }; 16245 16246 // Mark that this expression does not constitute an odr-use. 16247 auto MarkNotOdrUsed = [&] { 16248 S.MaybeODRUseExprs.erase(E); 16249 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16250 LSI->markVariableExprAsNonODRUsed(E); 16251 }; 16252 16253 // C++2a [basic.def.odr]p2: 16254 // The set of potential results of an expression e is defined as follows: 16255 switch (E->getStmtClass()) { 16256 // -- If e is an id-expression, ... 16257 case Expr::DeclRefExprClass: { 16258 auto *DRE = cast<DeclRefExpr>(E); 16259 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16260 break; 16261 16262 // Rebuild as a non-odr-use DeclRefExpr. 16263 MarkNotOdrUsed(); 16264 return DeclRefExpr::Create( 16265 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16266 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16267 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16268 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16269 } 16270 16271 case Expr::FunctionParmPackExprClass: { 16272 auto *FPPE = cast<FunctionParmPackExpr>(E); 16273 // If any of the declarations in the pack is odr-used, then the expression 16274 // as a whole constitutes an odr-use. 16275 for (VarDecl *D : *FPPE) 16276 if (IsPotentialResultOdrUsed(D)) 16277 return ExprEmpty(); 16278 16279 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16280 // nothing cares about whether we marked this as an odr-use, but it might 16281 // be useful for non-compiler tools. 16282 MarkNotOdrUsed(); 16283 break; 16284 } 16285 16286 // -- If e is a subscripting operation with an array operand... 16287 case Expr::ArraySubscriptExprClass: { 16288 auto *ASE = cast<ArraySubscriptExpr>(E); 16289 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16290 if (!OldBase->getType()->isArrayType()) 16291 break; 16292 ExprResult Base = Rebuild(OldBase); 16293 if (!Base.isUsable()) 16294 return Base; 16295 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16296 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16297 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16298 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16299 ASE->getRBracketLoc()); 16300 } 16301 16302 case Expr::MemberExprClass: { 16303 auto *ME = cast<MemberExpr>(E); 16304 // -- If e is a class member access expression [...] naming a non-static 16305 // data member... 16306 if (isa<FieldDecl>(ME->getMemberDecl())) { 16307 ExprResult Base = Rebuild(ME->getBase()); 16308 if (!Base.isUsable()) 16309 return Base; 16310 return MemberExpr::Create( 16311 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16312 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16313 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16314 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16315 ME->getObjectKind(), ME->isNonOdrUse()); 16316 } 16317 16318 if (ME->getMemberDecl()->isCXXInstanceMember()) 16319 break; 16320 16321 // -- If e is a class member access expression naming a static data member, 16322 // ... 16323 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16324 break; 16325 16326 // Rebuild as a non-odr-use MemberExpr. 16327 MarkNotOdrUsed(); 16328 return MemberExpr::Create( 16329 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16330 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16331 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16332 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16333 return ExprEmpty(); 16334 } 16335 16336 case Expr::BinaryOperatorClass: { 16337 auto *BO = cast<BinaryOperator>(E); 16338 Expr *LHS = BO->getLHS(); 16339 Expr *RHS = BO->getRHS(); 16340 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16341 if (BO->getOpcode() == BO_PtrMemD) { 16342 ExprResult Sub = Rebuild(LHS); 16343 if (!Sub.isUsable()) 16344 return Sub; 16345 LHS = Sub.get(); 16346 // -- If e is a comma expression, ... 16347 } else if (BO->getOpcode() == BO_Comma) { 16348 ExprResult Sub = Rebuild(RHS); 16349 if (!Sub.isUsable()) 16350 return Sub; 16351 RHS = Sub.get(); 16352 } else { 16353 break; 16354 } 16355 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16356 LHS, RHS); 16357 } 16358 16359 // -- If e has the form (e1)... 16360 case Expr::ParenExprClass: { 16361 auto *PE = cast<ParenExpr>(E); 16362 ExprResult Sub = Rebuild(PE->getSubExpr()); 16363 if (!Sub.isUsable()) 16364 return Sub; 16365 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16366 } 16367 16368 // -- If e is a glvalue conditional expression, ... 16369 // We don't apply this to a binary conditional operator. FIXME: Should we? 16370 case Expr::ConditionalOperatorClass: { 16371 auto *CO = cast<ConditionalOperator>(E); 16372 ExprResult LHS = Rebuild(CO->getLHS()); 16373 if (LHS.isInvalid()) 16374 return ExprError(); 16375 ExprResult RHS = Rebuild(CO->getRHS()); 16376 if (RHS.isInvalid()) 16377 return ExprError(); 16378 if (!LHS.isUsable() && !RHS.isUsable()) 16379 return ExprEmpty(); 16380 if (!LHS.isUsable()) 16381 LHS = CO->getLHS(); 16382 if (!RHS.isUsable()) 16383 RHS = CO->getRHS(); 16384 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16385 CO->getCond(), LHS.get(), RHS.get()); 16386 } 16387 16388 // [Clang extension] 16389 // -- If e has the form __extension__ e1... 16390 case Expr::UnaryOperatorClass: { 16391 auto *UO = cast<UnaryOperator>(E); 16392 if (UO->getOpcode() != UO_Extension) 16393 break; 16394 ExprResult Sub = Rebuild(UO->getSubExpr()); 16395 if (!Sub.isUsable()) 16396 return Sub; 16397 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16398 Sub.get()); 16399 } 16400 16401 // [Clang extension] 16402 // -- If e has the form _Generic(...), the set of potential results is the 16403 // union of the sets of potential results of the associated expressions. 16404 case Expr::GenericSelectionExprClass: { 16405 auto *GSE = cast<GenericSelectionExpr>(E); 16406 16407 SmallVector<Expr *, 4> AssocExprs; 16408 bool AnyChanged = false; 16409 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16410 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16411 if (AssocExpr.isInvalid()) 16412 return ExprError(); 16413 if (AssocExpr.isUsable()) { 16414 AssocExprs.push_back(AssocExpr.get()); 16415 AnyChanged = true; 16416 } else { 16417 AssocExprs.push_back(OrigAssocExpr); 16418 } 16419 } 16420 16421 return AnyChanged ? S.CreateGenericSelectionExpr( 16422 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16423 GSE->getRParenLoc(), GSE->getControllingExpr(), 16424 GSE->getAssocTypeSourceInfos(), AssocExprs) 16425 : ExprEmpty(); 16426 } 16427 16428 // [Clang extension] 16429 // -- If e has the form __builtin_choose_expr(...), the set of potential 16430 // results is the union of the sets of potential results of the 16431 // second and third subexpressions. 16432 case Expr::ChooseExprClass: { 16433 auto *CE = cast<ChooseExpr>(E); 16434 16435 ExprResult LHS = Rebuild(CE->getLHS()); 16436 if (LHS.isInvalid()) 16437 return ExprError(); 16438 16439 ExprResult RHS = Rebuild(CE->getLHS()); 16440 if (RHS.isInvalid()) 16441 return ExprError(); 16442 16443 if (!LHS.get() && !RHS.get()) 16444 return ExprEmpty(); 16445 if (!LHS.isUsable()) 16446 LHS = CE->getLHS(); 16447 if (!RHS.isUsable()) 16448 RHS = CE->getRHS(); 16449 16450 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16451 RHS.get(), CE->getRParenLoc()); 16452 } 16453 16454 // Step through non-syntactic nodes. 16455 case Expr::ConstantExprClass: { 16456 auto *CE = cast<ConstantExpr>(E); 16457 ExprResult Sub = Rebuild(CE->getSubExpr()); 16458 if (!Sub.isUsable()) 16459 return Sub; 16460 return ConstantExpr::Create(S.Context, Sub.get()); 16461 } 16462 16463 // We could mostly rely on the recursive rebuilding to rebuild implicit 16464 // casts, but not at the top level, so rebuild them here. 16465 case Expr::ImplicitCastExprClass: { 16466 auto *ICE = cast<ImplicitCastExpr>(E); 16467 // Only step through the narrow set of cast kinds we expect to encounter. 16468 // Anything else suggests we've left the region in which potential results 16469 // can be found. 16470 switch (ICE->getCastKind()) { 16471 case CK_NoOp: 16472 case CK_DerivedToBase: 16473 case CK_UncheckedDerivedToBase: { 16474 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16475 if (!Sub.isUsable()) 16476 return Sub; 16477 CXXCastPath Path(ICE->path()); 16478 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16479 ICE->getValueKind(), &Path); 16480 } 16481 16482 default: 16483 break; 16484 } 16485 break; 16486 } 16487 16488 default: 16489 break; 16490 } 16491 16492 // Can't traverse through this node. Nothing to do. 16493 return ExprEmpty(); 16494 } 16495 16496 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16497 // Check whether the operand is or contains an object of non-trivial C union 16498 // type. 16499 if (E->getType().isVolatileQualified() && 16500 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16501 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16502 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16503 Sema::NTCUC_LValueToRValueVolatile, 16504 NTCUK_Destruct|NTCUK_Copy); 16505 16506 // C++2a [basic.def.odr]p4: 16507 // [...] an expression of non-volatile-qualified non-class type to which 16508 // the lvalue-to-rvalue conversion is applied [...] 16509 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16510 return E; 16511 16512 ExprResult Result = 16513 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16514 if (Result.isInvalid()) 16515 return ExprError(); 16516 return Result.get() ? Result : E; 16517 } 16518 16519 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16520 Res = CorrectDelayedTyposInExpr(Res); 16521 16522 if (!Res.isUsable()) 16523 return Res; 16524 16525 // If a constant-expression is a reference to a variable where we delay 16526 // deciding whether it is an odr-use, just assume we will apply the 16527 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16528 // (a non-type template argument), we have special handling anyway. 16529 return CheckLValueToRValueConversionOperand(Res.get()); 16530 } 16531 16532 void Sema::CleanupVarDeclMarking() { 16533 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16534 // call. 16535 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16536 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16537 16538 for (Expr *E : LocalMaybeODRUseExprs) { 16539 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16540 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16541 DRE->getLocation(), *this); 16542 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16543 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16544 *this); 16545 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16546 for (VarDecl *VD : *FP) 16547 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16548 } else { 16549 llvm_unreachable("Unexpected expression"); 16550 } 16551 } 16552 16553 assert(MaybeODRUseExprs.empty() && 16554 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16555 } 16556 16557 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16558 VarDecl *Var, Expr *E) { 16559 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16560 isa<FunctionParmPackExpr>(E)) && 16561 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16562 Var->setReferenced(); 16563 16564 if (Var->isInvalidDecl()) 16565 return; 16566 16567 auto *MSI = Var->getMemberSpecializationInfo(); 16568 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16569 : Var->getTemplateSpecializationKind(); 16570 16571 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16572 bool UsableInConstantExpr = 16573 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16574 16575 // C++20 [expr.const]p12: 16576 // A variable [...] is needed for constant evaluation if it is [...] a 16577 // variable whose name appears as a potentially constant evaluated 16578 // expression that is either a contexpr variable or is of non-volatile 16579 // const-qualified integral type or of reference type 16580 bool NeededForConstantEvaluation = 16581 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16582 16583 bool NeedDefinition = 16584 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16585 16586 VarTemplateSpecializationDecl *VarSpec = 16587 dyn_cast<VarTemplateSpecializationDecl>(Var); 16588 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16589 "Can't instantiate a partial template specialization."); 16590 16591 // If this might be a member specialization of a static data member, check 16592 // the specialization is visible. We already did the checks for variable 16593 // template specializations when we created them. 16594 if (NeedDefinition && TSK != TSK_Undeclared && 16595 !isa<VarTemplateSpecializationDecl>(Var)) 16596 SemaRef.checkSpecializationVisibility(Loc, Var); 16597 16598 // Perform implicit instantiation of static data members, static data member 16599 // templates of class templates, and variable template specializations. Delay 16600 // instantiations of variable templates, except for those that could be used 16601 // in a constant expression. 16602 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16603 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16604 // instantiation declaration if a variable is usable in a constant 16605 // expression (among other cases). 16606 bool TryInstantiating = 16607 TSK == TSK_ImplicitInstantiation || 16608 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16609 16610 if (TryInstantiating) { 16611 SourceLocation PointOfInstantiation = 16612 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16613 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16614 if (FirstInstantiation) { 16615 PointOfInstantiation = Loc; 16616 if (MSI) 16617 MSI->setPointOfInstantiation(PointOfInstantiation); 16618 else 16619 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16620 } 16621 16622 bool InstantiationDependent = false; 16623 bool IsNonDependent = 16624 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16625 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16626 : true; 16627 16628 // Do not instantiate specializations that are still type-dependent. 16629 if (IsNonDependent) { 16630 if (UsableInConstantExpr) { 16631 // Do not defer instantiations of variables that could be used in a 16632 // constant expression. 16633 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16634 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16635 }); 16636 } else if (FirstInstantiation || 16637 isa<VarTemplateSpecializationDecl>(Var)) { 16638 // FIXME: For a specialization of a variable template, we don't 16639 // distinguish between "declaration and type implicitly instantiated" 16640 // and "implicit instantiation of definition requested", so we have 16641 // no direct way to avoid enqueueing the pending instantiation 16642 // multiple times. 16643 SemaRef.PendingInstantiations 16644 .push_back(std::make_pair(Var, PointOfInstantiation)); 16645 } 16646 } 16647 } 16648 } 16649 16650 // C++2a [basic.def.odr]p4: 16651 // A variable x whose name appears as a potentially-evaluated expression e 16652 // is odr-used by e unless 16653 // -- x is a reference that is usable in constant expressions 16654 // -- x is a variable of non-reference type that is usable in constant 16655 // expressions and has no mutable subobjects [FIXME], and e is an 16656 // element of the set of potential results of an expression of 16657 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16658 // conversion is applied 16659 // -- x is a variable of non-reference type, and e is an element of the set 16660 // of potential results of a discarded-value expression to which the 16661 // lvalue-to-rvalue conversion is not applied [FIXME] 16662 // 16663 // We check the first part of the second bullet here, and 16664 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16665 // FIXME: To get the third bullet right, we need to delay this even for 16666 // variables that are not usable in constant expressions. 16667 16668 // If we already know this isn't an odr-use, there's nothing more to do. 16669 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16670 if (DRE->isNonOdrUse()) 16671 return; 16672 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16673 if (ME->isNonOdrUse()) 16674 return; 16675 16676 switch (OdrUse) { 16677 case OdrUseContext::None: 16678 assert((!E || isa<FunctionParmPackExpr>(E)) && 16679 "missing non-odr-use marking for unevaluated decl ref"); 16680 break; 16681 16682 case OdrUseContext::FormallyOdrUsed: 16683 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16684 // behavior. 16685 break; 16686 16687 case OdrUseContext::Used: 16688 // If we might later find that this expression isn't actually an odr-use, 16689 // delay the marking. 16690 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16691 SemaRef.MaybeODRUseExprs.insert(E); 16692 else 16693 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16694 break; 16695 16696 case OdrUseContext::Dependent: 16697 // If this is a dependent context, we don't need to mark variables as 16698 // odr-used, but we may still need to track them for lambda capture. 16699 // FIXME: Do we also need to do this inside dependent typeid expressions 16700 // (which are modeled as unevaluated at this point)? 16701 const bool RefersToEnclosingScope = 16702 (SemaRef.CurContext != Var->getDeclContext() && 16703 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16704 if (RefersToEnclosingScope) { 16705 LambdaScopeInfo *const LSI = 16706 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16707 if (LSI && (!LSI->CallOperator || 16708 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16709 // If a variable could potentially be odr-used, defer marking it so 16710 // until we finish analyzing the full expression for any 16711 // lvalue-to-rvalue 16712 // or discarded value conversions that would obviate odr-use. 16713 // Add it to the list of potential captures that will be analyzed 16714 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16715 // unless the variable is a reference that was initialized by a constant 16716 // expression (this will never need to be captured or odr-used). 16717 // 16718 // FIXME: We can simplify this a lot after implementing P0588R1. 16719 assert(E && "Capture variable should be used in an expression."); 16720 if (!Var->getType()->isReferenceType() || 16721 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16722 LSI->addPotentialCapture(E->IgnoreParens()); 16723 } 16724 } 16725 break; 16726 } 16727 } 16728 16729 /// Mark a variable referenced, and check whether it is odr-used 16730 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16731 /// used directly for normal expressions referring to VarDecl. 16732 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16733 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16734 } 16735 16736 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16737 Decl *D, Expr *E, bool MightBeOdrUse) { 16738 if (SemaRef.isInOpenMPDeclareTargetContext()) 16739 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16740 16741 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16742 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16743 return; 16744 } 16745 16746 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16747 16748 // If this is a call to a method via a cast, also mark the method in the 16749 // derived class used in case codegen can devirtualize the call. 16750 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16751 if (!ME) 16752 return; 16753 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16754 if (!MD) 16755 return; 16756 // Only attempt to devirtualize if this is truly a virtual call. 16757 bool IsVirtualCall = MD->isVirtual() && 16758 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16759 if (!IsVirtualCall) 16760 return; 16761 16762 // If it's possible to devirtualize the call, mark the called function 16763 // referenced. 16764 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16765 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16766 if (DM) 16767 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16768 } 16769 16770 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16771 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16772 // TODO: update this with DR# once a defect report is filed. 16773 // C++11 defect. The address of a pure member should not be an ODR use, even 16774 // if it's a qualified reference. 16775 bool OdrUse = true; 16776 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16777 if (Method->isVirtual() && 16778 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16779 OdrUse = false; 16780 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16781 } 16782 16783 /// Perform reference-marking and odr-use handling for a MemberExpr. 16784 void Sema::MarkMemberReferenced(MemberExpr *E) { 16785 // C++11 [basic.def.odr]p2: 16786 // A non-overloaded function whose name appears as a potentially-evaluated 16787 // expression or a member of a set of candidate functions, if selected by 16788 // overload resolution when referred to from a potentially-evaluated 16789 // expression, is odr-used, unless it is a pure virtual function and its 16790 // name is not explicitly qualified. 16791 bool MightBeOdrUse = true; 16792 if (E->performsVirtualDispatch(getLangOpts())) { 16793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16794 if (Method->isPure()) 16795 MightBeOdrUse = false; 16796 } 16797 SourceLocation Loc = 16798 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16799 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16800 } 16801 16802 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16803 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16804 for (VarDecl *VD : *E) 16805 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16806 } 16807 16808 /// Perform marking for a reference to an arbitrary declaration. It 16809 /// marks the declaration referenced, and performs odr-use checking for 16810 /// functions and variables. This method should not be used when building a 16811 /// normal expression which refers to a variable. 16812 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16813 bool MightBeOdrUse) { 16814 if (MightBeOdrUse) { 16815 if (auto *VD = dyn_cast<VarDecl>(D)) { 16816 MarkVariableReferenced(Loc, VD); 16817 return; 16818 } 16819 } 16820 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16821 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16822 return; 16823 } 16824 D->setReferenced(); 16825 } 16826 16827 namespace { 16828 // Mark all of the declarations used by a type as referenced. 16829 // FIXME: Not fully implemented yet! We need to have a better understanding 16830 // of when we're entering a context we should not recurse into. 16831 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16832 // TreeTransforms rebuilding the type in a new context. Rather than 16833 // duplicating the TreeTransform logic, we should consider reusing it here. 16834 // Currently that causes problems when rebuilding LambdaExprs. 16835 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16836 Sema &S; 16837 SourceLocation Loc; 16838 16839 public: 16840 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16841 16842 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16843 16844 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16845 }; 16846 } 16847 16848 bool MarkReferencedDecls::TraverseTemplateArgument( 16849 const TemplateArgument &Arg) { 16850 { 16851 // A non-type template argument is a constant-evaluated context. 16852 EnterExpressionEvaluationContext Evaluated( 16853 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 16854 if (Arg.getKind() == TemplateArgument::Declaration) { 16855 if (Decl *D = Arg.getAsDecl()) 16856 S.MarkAnyDeclReferenced(Loc, D, true); 16857 } else if (Arg.getKind() == TemplateArgument::Expression) { 16858 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 16859 } 16860 } 16861 16862 return Inherited::TraverseTemplateArgument(Arg); 16863 } 16864 16865 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 16866 MarkReferencedDecls Marker(*this, Loc); 16867 Marker.TraverseType(T); 16868 } 16869 16870 namespace { 16871 /// Helper class that marks all of the declarations referenced by 16872 /// potentially-evaluated subexpressions as "referenced". 16873 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 16874 Sema &S; 16875 bool SkipLocalVariables; 16876 16877 public: 16878 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 16879 16880 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 16881 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 16882 16883 void VisitDeclRefExpr(DeclRefExpr *E) { 16884 // If we were asked not to visit local variables, don't. 16885 if (SkipLocalVariables) { 16886 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 16887 if (VD->hasLocalStorage()) 16888 return; 16889 } 16890 16891 S.MarkDeclRefReferenced(E); 16892 } 16893 16894 void VisitMemberExpr(MemberExpr *E) { 16895 S.MarkMemberReferenced(E); 16896 Inherited::VisitMemberExpr(E); 16897 } 16898 16899 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 16900 S.MarkFunctionReferenced( 16901 E->getBeginLoc(), 16902 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 16903 Visit(E->getSubExpr()); 16904 } 16905 16906 void VisitCXXNewExpr(CXXNewExpr *E) { 16907 if (E->getOperatorNew()) 16908 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 16909 if (E->getOperatorDelete()) 16910 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16911 Inherited::VisitCXXNewExpr(E); 16912 } 16913 16914 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16915 if (E->getOperatorDelete()) 16916 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16917 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 16918 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 16919 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 16920 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 16921 } 16922 16923 Inherited::VisitCXXDeleteExpr(E); 16924 } 16925 16926 void VisitCXXConstructExpr(CXXConstructExpr *E) { 16927 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 16928 Inherited::VisitCXXConstructExpr(E); 16929 } 16930 16931 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 16932 Visit(E->getExpr()); 16933 } 16934 }; 16935 } 16936 16937 /// Mark any declarations that appear within this expression or any 16938 /// potentially-evaluated subexpressions as "referenced". 16939 /// 16940 /// \param SkipLocalVariables If true, don't mark local variables as 16941 /// 'referenced'. 16942 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 16943 bool SkipLocalVariables) { 16944 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 16945 } 16946 16947 /// Emit a diagnostic that describes an effect on the run-time behavior 16948 /// of the program being compiled. 16949 /// 16950 /// This routine emits the given diagnostic when the code currently being 16951 /// type-checked is "potentially evaluated", meaning that there is a 16952 /// possibility that the code will actually be executable. Code in sizeof() 16953 /// expressions, code used only during overload resolution, etc., are not 16954 /// potentially evaluated. This routine will suppress such diagnostics or, 16955 /// in the absolutely nutty case of potentially potentially evaluated 16956 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 16957 /// later. 16958 /// 16959 /// This routine should be used for all diagnostics that describe the run-time 16960 /// behavior of a program, such as passing a non-POD value through an ellipsis. 16961 /// Failure to do so will likely result in spurious diagnostics or failures 16962 /// during overload resolution or within sizeof/alignof/typeof/typeid. 16963 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 16964 const PartialDiagnostic &PD) { 16965 switch (ExprEvalContexts.back().Context) { 16966 case ExpressionEvaluationContext::Unevaluated: 16967 case ExpressionEvaluationContext::UnevaluatedList: 16968 case ExpressionEvaluationContext::UnevaluatedAbstract: 16969 case ExpressionEvaluationContext::DiscardedStatement: 16970 // The argument will never be evaluated, so don't complain. 16971 break; 16972 16973 case ExpressionEvaluationContext::ConstantEvaluated: 16974 // Relevant diagnostics should be produced by constant evaluation. 16975 break; 16976 16977 case ExpressionEvaluationContext::PotentiallyEvaluated: 16978 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16979 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 16980 FunctionScopes.back()->PossiblyUnreachableDiags. 16981 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 16982 return true; 16983 } 16984 16985 // The initializer of a constexpr variable or of the first declaration of a 16986 // static data member is not syntactically a constant evaluated constant, 16987 // but nonetheless is always required to be a constant expression, so we 16988 // can skip diagnosing. 16989 // FIXME: Using the mangling context here is a hack. 16990 if (auto *VD = dyn_cast_or_null<VarDecl>( 16991 ExprEvalContexts.back().ManglingContextDecl)) { 16992 if (VD->isConstexpr() || 16993 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 16994 break; 16995 // FIXME: For any other kind of variable, we should build a CFG for its 16996 // initializer and check whether the context in question is reachable. 16997 } 16998 16999 Diag(Loc, PD); 17000 return true; 17001 } 17002 17003 return false; 17004 } 17005 17006 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17007 const PartialDiagnostic &PD) { 17008 return DiagRuntimeBehavior( 17009 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17010 } 17011 17012 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17013 CallExpr *CE, FunctionDecl *FD) { 17014 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17015 return false; 17016 17017 // If we're inside a decltype's expression, don't check for a valid return 17018 // type or construct temporaries until we know whether this is the last call. 17019 if (ExprEvalContexts.back().ExprContext == 17020 ExpressionEvaluationContextRecord::EK_Decltype) { 17021 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17022 return false; 17023 } 17024 17025 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17026 FunctionDecl *FD; 17027 CallExpr *CE; 17028 17029 public: 17030 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17031 : FD(FD), CE(CE) { } 17032 17033 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17034 if (!FD) { 17035 S.Diag(Loc, diag::err_call_incomplete_return) 17036 << T << CE->getSourceRange(); 17037 return; 17038 } 17039 17040 S.Diag(Loc, diag::err_call_function_incomplete_return) 17041 << CE->getSourceRange() << FD->getDeclName() << T; 17042 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17043 << FD->getDeclName(); 17044 } 17045 } Diagnoser(FD, CE); 17046 17047 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17048 return true; 17049 17050 return false; 17051 } 17052 17053 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17054 // will prevent this condition from triggering, which is what we want. 17055 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17056 SourceLocation Loc; 17057 17058 unsigned diagnostic = diag::warn_condition_is_assignment; 17059 bool IsOrAssign = false; 17060 17061 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17062 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17063 return; 17064 17065 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17066 17067 // Greylist some idioms by putting them into a warning subcategory. 17068 if (ObjCMessageExpr *ME 17069 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17070 Selector Sel = ME->getSelector(); 17071 17072 // self = [<foo> init...] 17073 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17074 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17075 17076 // <foo> = [<bar> nextObject] 17077 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17078 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17079 } 17080 17081 Loc = Op->getOperatorLoc(); 17082 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17083 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17084 return; 17085 17086 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17087 Loc = Op->getOperatorLoc(); 17088 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17089 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17090 else { 17091 // Not an assignment. 17092 return; 17093 } 17094 17095 Diag(Loc, diagnostic) << E->getSourceRange(); 17096 17097 SourceLocation Open = E->getBeginLoc(); 17098 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17099 Diag(Loc, diag::note_condition_assign_silence) 17100 << FixItHint::CreateInsertion(Open, "(") 17101 << FixItHint::CreateInsertion(Close, ")"); 17102 17103 if (IsOrAssign) 17104 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17105 << FixItHint::CreateReplacement(Loc, "!="); 17106 else 17107 Diag(Loc, diag::note_condition_assign_to_comparison) 17108 << FixItHint::CreateReplacement(Loc, "=="); 17109 } 17110 17111 /// Redundant parentheses over an equality comparison can indicate 17112 /// that the user intended an assignment used as condition. 17113 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17114 // Don't warn if the parens came from a macro. 17115 SourceLocation parenLoc = ParenE->getBeginLoc(); 17116 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17117 return; 17118 // Don't warn for dependent expressions. 17119 if (ParenE->isTypeDependent()) 17120 return; 17121 17122 Expr *E = ParenE->IgnoreParens(); 17123 17124 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17125 if (opE->getOpcode() == BO_EQ && 17126 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17127 == Expr::MLV_Valid) { 17128 SourceLocation Loc = opE->getOperatorLoc(); 17129 17130 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17131 SourceRange ParenERange = ParenE->getSourceRange(); 17132 Diag(Loc, diag::note_equality_comparison_silence) 17133 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17134 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17135 Diag(Loc, diag::note_equality_comparison_to_assign) 17136 << FixItHint::CreateReplacement(Loc, "="); 17137 } 17138 } 17139 17140 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17141 bool IsConstexpr) { 17142 DiagnoseAssignmentAsCondition(E); 17143 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17144 DiagnoseEqualityWithExtraParens(parenE); 17145 17146 ExprResult result = CheckPlaceholderExpr(E); 17147 if (result.isInvalid()) return ExprError(); 17148 E = result.get(); 17149 17150 if (!E->isTypeDependent()) { 17151 if (getLangOpts().CPlusPlus) 17152 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17153 17154 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17155 if (ERes.isInvalid()) 17156 return ExprError(); 17157 E = ERes.get(); 17158 17159 QualType T = E->getType(); 17160 if (!T->isScalarType()) { // C99 6.8.4.1p1 17161 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17162 << T << E->getSourceRange(); 17163 return ExprError(); 17164 } 17165 CheckBoolLikeConversion(E, Loc); 17166 } 17167 17168 return E; 17169 } 17170 17171 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17172 Expr *SubExpr, ConditionKind CK) { 17173 // Empty conditions are valid in for-statements. 17174 if (!SubExpr) 17175 return ConditionResult(); 17176 17177 ExprResult Cond; 17178 switch (CK) { 17179 case ConditionKind::Boolean: 17180 Cond = CheckBooleanCondition(Loc, SubExpr); 17181 break; 17182 17183 case ConditionKind::ConstexprIf: 17184 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17185 break; 17186 17187 case ConditionKind::Switch: 17188 Cond = CheckSwitchCondition(Loc, SubExpr); 17189 break; 17190 } 17191 if (Cond.isInvalid()) 17192 return ConditionError(); 17193 17194 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17195 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17196 if (!FullExpr.get()) 17197 return ConditionError(); 17198 17199 return ConditionResult(*this, nullptr, FullExpr, 17200 CK == ConditionKind::ConstexprIf); 17201 } 17202 17203 namespace { 17204 /// A visitor for rebuilding a call to an __unknown_any expression 17205 /// to have an appropriate type. 17206 struct RebuildUnknownAnyFunction 17207 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17208 17209 Sema &S; 17210 17211 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17212 17213 ExprResult VisitStmt(Stmt *S) { 17214 llvm_unreachable("unexpected statement!"); 17215 } 17216 17217 ExprResult VisitExpr(Expr *E) { 17218 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17219 << E->getSourceRange(); 17220 return ExprError(); 17221 } 17222 17223 /// Rebuild an expression which simply semantically wraps another 17224 /// expression which it shares the type and value kind of. 17225 template <class T> ExprResult rebuildSugarExpr(T *E) { 17226 ExprResult SubResult = Visit(E->getSubExpr()); 17227 if (SubResult.isInvalid()) return ExprError(); 17228 17229 Expr *SubExpr = SubResult.get(); 17230 E->setSubExpr(SubExpr); 17231 E->setType(SubExpr->getType()); 17232 E->setValueKind(SubExpr->getValueKind()); 17233 assert(E->getObjectKind() == OK_Ordinary); 17234 return E; 17235 } 17236 17237 ExprResult VisitParenExpr(ParenExpr *E) { 17238 return rebuildSugarExpr(E); 17239 } 17240 17241 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17242 return rebuildSugarExpr(E); 17243 } 17244 17245 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17246 ExprResult SubResult = Visit(E->getSubExpr()); 17247 if (SubResult.isInvalid()) return ExprError(); 17248 17249 Expr *SubExpr = SubResult.get(); 17250 E->setSubExpr(SubExpr); 17251 E->setType(S.Context.getPointerType(SubExpr->getType())); 17252 assert(E->getValueKind() == VK_RValue); 17253 assert(E->getObjectKind() == OK_Ordinary); 17254 return E; 17255 } 17256 17257 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17258 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17259 17260 E->setType(VD->getType()); 17261 17262 assert(E->getValueKind() == VK_RValue); 17263 if (S.getLangOpts().CPlusPlus && 17264 !(isa<CXXMethodDecl>(VD) && 17265 cast<CXXMethodDecl>(VD)->isInstance())) 17266 E->setValueKind(VK_LValue); 17267 17268 return E; 17269 } 17270 17271 ExprResult VisitMemberExpr(MemberExpr *E) { 17272 return resolveDecl(E, E->getMemberDecl()); 17273 } 17274 17275 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17276 return resolveDecl(E, E->getDecl()); 17277 } 17278 }; 17279 } 17280 17281 /// Given a function expression of unknown-any type, try to rebuild it 17282 /// to have a function type. 17283 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17284 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17285 if (Result.isInvalid()) return ExprError(); 17286 return S.DefaultFunctionArrayConversion(Result.get()); 17287 } 17288 17289 namespace { 17290 /// A visitor for rebuilding an expression of type __unknown_anytype 17291 /// into one which resolves the type directly on the referring 17292 /// expression. Strict preservation of the original source 17293 /// structure is not a goal. 17294 struct RebuildUnknownAnyExpr 17295 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17296 17297 Sema &S; 17298 17299 /// The current destination type. 17300 QualType DestType; 17301 17302 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17303 : S(S), DestType(CastType) {} 17304 17305 ExprResult VisitStmt(Stmt *S) { 17306 llvm_unreachable("unexpected statement!"); 17307 } 17308 17309 ExprResult VisitExpr(Expr *E) { 17310 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17311 << E->getSourceRange(); 17312 return ExprError(); 17313 } 17314 17315 ExprResult VisitCallExpr(CallExpr *E); 17316 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17317 17318 /// Rebuild an expression which simply semantically wraps another 17319 /// expression which it shares the type and value kind of. 17320 template <class T> ExprResult rebuildSugarExpr(T *E) { 17321 ExprResult SubResult = Visit(E->getSubExpr()); 17322 if (SubResult.isInvalid()) return ExprError(); 17323 Expr *SubExpr = SubResult.get(); 17324 E->setSubExpr(SubExpr); 17325 E->setType(SubExpr->getType()); 17326 E->setValueKind(SubExpr->getValueKind()); 17327 assert(E->getObjectKind() == OK_Ordinary); 17328 return E; 17329 } 17330 17331 ExprResult VisitParenExpr(ParenExpr *E) { 17332 return rebuildSugarExpr(E); 17333 } 17334 17335 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17336 return rebuildSugarExpr(E); 17337 } 17338 17339 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17340 const PointerType *Ptr = DestType->getAs<PointerType>(); 17341 if (!Ptr) { 17342 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17343 << E->getSourceRange(); 17344 return ExprError(); 17345 } 17346 17347 if (isa<CallExpr>(E->getSubExpr())) { 17348 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17349 << E->getSourceRange(); 17350 return ExprError(); 17351 } 17352 17353 assert(E->getValueKind() == VK_RValue); 17354 assert(E->getObjectKind() == OK_Ordinary); 17355 E->setType(DestType); 17356 17357 // Build the sub-expression as if it were an object of the pointee type. 17358 DestType = Ptr->getPointeeType(); 17359 ExprResult SubResult = Visit(E->getSubExpr()); 17360 if (SubResult.isInvalid()) return ExprError(); 17361 E->setSubExpr(SubResult.get()); 17362 return E; 17363 } 17364 17365 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17366 17367 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17368 17369 ExprResult VisitMemberExpr(MemberExpr *E) { 17370 return resolveDecl(E, E->getMemberDecl()); 17371 } 17372 17373 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17374 return resolveDecl(E, E->getDecl()); 17375 } 17376 }; 17377 } 17378 17379 /// Rebuilds a call expression which yielded __unknown_anytype. 17380 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17381 Expr *CalleeExpr = E->getCallee(); 17382 17383 enum FnKind { 17384 FK_MemberFunction, 17385 FK_FunctionPointer, 17386 FK_BlockPointer 17387 }; 17388 17389 FnKind Kind; 17390 QualType CalleeType = CalleeExpr->getType(); 17391 if (CalleeType == S.Context.BoundMemberTy) { 17392 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17393 Kind = FK_MemberFunction; 17394 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17395 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17396 CalleeType = Ptr->getPointeeType(); 17397 Kind = FK_FunctionPointer; 17398 } else { 17399 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17400 Kind = FK_BlockPointer; 17401 } 17402 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17403 17404 // Verify that this is a legal result type of a function. 17405 if (DestType->isArrayType() || DestType->isFunctionType()) { 17406 unsigned diagID = diag::err_func_returning_array_function; 17407 if (Kind == FK_BlockPointer) 17408 diagID = diag::err_block_returning_array_function; 17409 17410 S.Diag(E->getExprLoc(), diagID) 17411 << DestType->isFunctionType() << DestType; 17412 return ExprError(); 17413 } 17414 17415 // Otherwise, go ahead and set DestType as the call's result. 17416 E->setType(DestType.getNonLValueExprType(S.Context)); 17417 E->setValueKind(Expr::getValueKindForType(DestType)); 17418 assert(E->getObjectKind() == OK_Ordinary); 17419 17420 // Rebuild the function type, replacing the result type with DestType. 17421 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17422 if (Proto) { 17423 // __unknown_anytype(...) is a special case used by the debugger when 17424 // it has no idea what a function's signature is. 17425 // 17426 // We want to build this call essentially under the K&R 17427 // unprototyped rules, but making a FunctionNoProtoType in C++ 17428 // would foul up all sorts of assumptions. However, we cannot 17429 // simply pass all arguments as variadic arguments, nor can we 17430 // portably just call the function under a non-variadic type; see 17431 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17432 // However, it turns out that in practice it is generally safe to 17433 // call a function declared as "A foo(B,C,D);" under the prototype 17434 // "A foo(B,C,D,...);". The only known exception is with the 17435 // Windows ABI, where any variadic function is implicitly cdecl 17436 // regardless of its normal CC. Therefore we change the parameter 17437 // types to match the types of the arguments. 17438 // 17439 // This is a hack, but it is far superior to moving the 17440 // corresponding target-specific code from IR-gen to Sema/AST. 17441 17442 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17443 SmallVector<QualType, 8> ArgTypes; 17444 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17445 ArgTypes.reserve(E->getNumArgs()); 17446 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17447 Expr *Arg = E->getArg(i); 17448 QualType ArgType = Arg->getType(); 17449 if (E->isLValue()) { 17450 ArgType = S.Context.getLValueReferenceType(ArgType); 17451 } else if (E->isXValue()) { 17452 ArgType = S.Context.getRValueReferenceType(ArgType); 17453 } 17454 ArgTypes.push_back(ArgType); 17455 } 17456 ParamTypes = ArgTypes; 17457 } 17458 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17459 Proto->getExtProtoInfo()); 17460 } else { 17461 DestType = S.Context.getFunctionNoProtoType(DestType, 17462 FnType->getExtInfo()); 17463 } 17464 17465 // Rebuild the appropriate pointer-to-function type. 17466 switch (Kind) { 17467 case FK_MemberFunction: 17468 // Nothing to do. 17469 break; 17470 17471 case FK_FunctionPointer: 17472 DestType = S.Context.getPointerType(DestType); 17473 break; 17474 17475 case FK_BlockPointer: 17476 DestType = S.Context.getBlockPointerType(DestType); 17477 break; 17478 } 17479 17480 // Finally, we can recurse. 17481 ExprResult CalleeResult = Visit(CalleeExpr); 17482 if (!CalleeResult.isUsable()) return ExprError(); 17483 E->setCallee(CalleeResult.get()); 17484 17485 // Bind a temporary if necessary. 17486 return S.MaybeBindToTemporary(E); 17487 } 17488 17489 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17490 // Verify that this is a legal result type of a call. 17491 if (DestType->isArrayType() || DestType->isFunctionType()) { 17492 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17493 << DestType->isFunctionType() << DestType; 17494 return ExprError(); 17495 } 17496 17497 // Rewrite the method result type if available. 17498 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17499 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17500 Method->setReturnType(DestType); 17501 } 17502 17503 // Change the type of the message. 17504 E->setType(DestType.getNonReferenceType()); 17505 E->setValueKind(Expr::getValueKindForType(DestType)); 17506 17507 return S.MaybeBindToTemporary(E); 17508 } 17509 17510 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17511 // The only case we should ever see here is a function-to-pointer decay. 17512 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17513 assert(E->getValueKind() == VK_RValue); 17514 assert(E->getObjectKind() == OK_Ordinary); 17515 17516 E->setType(DestType); 17517 17518 // Rebuild the sub-expression as the pointee (function) type. 17519 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17520 17521 ExprResult Result = Visit(E->getSubExpr()); 17522 if (!Result.isUsable()) return ExprError(); 17523 17524 E->setSubExpr(Result.get()); 17525 return E; 17526 } else if (E->getCastKind() == CK_LValueToRValue) { 17527 assert(E->getValueKind() == VK_RValue); 17528 assert(E->getObjectKind() == OK_Ordinary); 17529 17530 assert(isa<BlockPointerType>(E->getType())); 17531 17532 E->setType(DestType); 17533 17534 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17535 DestType = S.Context.getLValueReferenceType(DestType); 17536 17537 ExprResult Result = Visit(E->getSubExpr()); 17538 if (!Result.isUsable()) return ExprError(); 17539 17540 E->setSubExpr(Result.get()); 17541 return E; 17542 } else { 17543 llvm_unreachable("Unhandled cast type!"); 17544 } 17545 } 17546 17547 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17548 ExprValueKind ValueKind = VK_LValue; 17549 QualType Type = DestType; 17550 17551 // We know how to make this work for certain kinds of decls: 17552 17553 // - functions 17554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17555 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17556 DestType = Ptr->getPointeeType(); 17557 ExprResult Result = resolveDecl(E, VD); 17558 if (Result.isInvalid()) return ExprError(); 17559 return S.ImpCastExprToType(Result.get(), Type, 17560 CK_FunctionToPointerDecay, VK_RValue); 17561 } 17562 17563 if (!Type->isFunctionType()) { 17564 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17565 << VD << E->getSourceRange(); 17566 return ExprError(); 17567 } 17568 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17569 // We must match the FunctionDecl's type to the hack introduced in 17570 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17571 // type. See the lengthy commentary in that routine. 17572 QualType FDT = FD->getType(); 17573 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17574 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17575 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17576 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17577 SourceLocation Loc = FD->getLocation(); 17578 FunctionDecl *NewFD = FunctionDecl::Create( 17579 S.Context, FD->getDeclContext(), Loc, Loc, 17580 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17581 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17582 /*ConstexprKind*/ CSK_unspecified); 17583 17584 if (FD->getQualifier()) 17585 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17586 17587 SmallVector<ParmVarDecl*, 16> Params; 17588 for (const auto &AI : FT->param_types()) { 17589 ParmVarDecl *Param = 17590 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17591 Param->setScopeInfo(0, Params.size()); 17592 Params.push_back(Param); 17593 } 17594 NewFD->setParams(Params); 17595 DRE->setDecl(NewFD); 17596 VD = DRE->getDecl(); 17597 } 17598 } 17599 17600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17601 if (MD->isInstance()) { 17602 ValueKind = VK_RValue; 17603 Type = S.Context.BoundMemberTy; 17604 } 17605 17606 // Function references aren't l-values in C. 17607 if (!S.getLangOpts().CPlusPlus) 17608 ValueKind = VK_RValue; 17609 17610 // - variables 17611 } else if (isa<VarDecl>(VD)) { 17612 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17613 Type = RefTy->getPointeeType(); 17614 } else if (Type->isFunctionType()) { 17615 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17616 << VD << E->getSourceRange(); 17617 return ExprError(); 17618 } 17619 17620 // - nothing else 17621 } else { 17622 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17623 << VD << E->getSourceRange(); 17624 return ExprError(); 17625 } 17626 17627 // Modifying the declaration like this is friendly to IR-gen but 17628 // also really dangerous. 17629 VD->setType(DestType); 17630 E->setType(Type); 17631 E->setValueKind(ValueKind); 17632 return E; 17633 } 17634 17635 /// Check a cast of an unknown-any type. We intentionally only 17636 /// trigger this for C-style casts. 17637 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17638 Expr *CastExpr, CastKind &CastKind, 17639 ExprValueKind &VK, CXXCastPath &Path) { 17640 // The type we're casting to must be either void or complete. 17641 if (!CastType->isVoidType() && 17642 RequireCompleteType(TypeRange.getBegin(), CastType, 17643 diag::err_typecheck_cast_to_incomplete)) 17644 return ExprError(); 17645 17646 // Rewrite the casted expression from scratch. 17647 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17648 if (!result.isUsable()) return ExprError(); 17649 17650 CastExpr = result.get(); 17651 VK = CastExpr->getValueKind(); 17652 CastKind = CK_NoOp; 17653 17654 return CastExpr; 17655 } 17656 17657 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17658 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17659 } 17660 17661 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17662 Expr *arg, QualType ¶mType) { 17663 // If the syntactic form of the argument is not an explicit cast of 17664 // any sort, just do default argument promotion. 17665 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17666 if (!castArg) { 17667 ExprResult result = DefaultArgumentPromotion(arg); 17668 if (result.isInvalid()) return ExprError(); 17669 paramType = result.get()->getType(); 17670 return result; 17671 } 17672 17673 // Otherwise, use the type that was written in the explicit cast. 17674 assert(!arg->hasPlaceholderType()); 17675 paramType = castArg->getTypeAsWritten(); 17676 17677 // Copy-initialize a parameter of that type. 17678 InitializedEntity entity = 17679 InitializedEntity::InitializeParameter(Context, paramType, 17680 /*consumed*/ false); 17681 return PerformCopyInitialization(entity, callLoc, arg); 17682 } 17683 17684 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17685 Expr *orig = E; 17686 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17687 while (true) { 17688 E = E->IgnoreParenImpCasts(); 17689 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17690 E = call->getCallee(); 17691 diagID = diag::err_uncasted_call_of_unknown_any; 17692 } else { 17693 break; 17694 } 17695 } 17696 17697 SourceLocation loc; 17698 NamedDecl *d; 17699 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17700 loc = ref->getLocation(); 17701 d = ref->getDecl(); 17702 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17703 loc = mem->getMemberLoc(); 17704 d = mem->getMemberDecl(); 17705 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17706 diagID = diag::err_uncasted_call_of_unknown_any; 17707 loc = msg->getSelectorStartLoc(); 17708 d = msg->getMethodDecl(); 17709 if (!d) { 17710 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17711 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17712 << orig->getSourceRange(); 17713 return ExprError(); 17714 } 17715 } else { 17716 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17717 << E->getSourceRange(); 17718 return ExprError(); 17719 } 17720 17721 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17722 17723 // Never recoverable. 17724 return ExprError(); 17725 } 17726 17727 /// Check for operands with placeholder types and complain if found. 17728 /// Returns ExprError() if there was an error and no recovery was possible. 17729 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17730 if (!getLangOpts().CPlusPlus) { 17731 // C cannot handle TypoExpr nodes on either side of a binop because it 17732 // doesn't handle dependent types properly, so make sure any TypoExprs have 17733 // been dealt with before checking the operands. 17734 ExprResult Result = CorrectDelayedTyposInExpr(E); 17735 if (!Result.isUsable()) return ExprError(); 17736 E = Result.get(); 17737 } 17738 17739 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17740 if (!placeholderType) return E; 17741 17742 switch (placeholderType->getKind()) { 17743 17744 // Overloaded expressions. 17745 case BuiltinType::Overload: { 17746 // Try to resolve a single function template specialization. 17747 // This is obligatory. 17748 ExprResult Result = E; 17749 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17750 return Result; 17751 17752 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17753 // leaves Result unchanged on failure. 17754 Result = E; 17755 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17756 return Result; 17757 17758 // If that failed, try to recover with a call. 17759 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17760 /*complain*/ true); 17761 return Result; 17762 } 17763 17764 // Bound member functions. 17765 case BuiltinType::BoundMember: { 17766 ExprResult result = E; 17767 const Expr *BME = E->IgnoreParens(); 17768 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17769 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17770 if (isa<CXXPseudoDestructorExpr>(BME)) { 17771 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17772 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17773 if (ME->getMemberNameInfo().getName().getNameKind() == 17774 DeclarationName::CXXDestructorName) 17775 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17776 } 17777 tryToRecoverWithCall(result, PD, 17778 /*complain*/ true); 17779 return result; 17780 } 17781 17782 // ARC unbridged casts. 17783 case BuiltinType::ARCUnbridgedCast: { 17784 Expr *realCast = stripARCUnbridgedCast(E); 17785 diagnoseARCUnbridgedCast(realCast); 17786 return realCast; 17787 } 17788 17789 // Expressions of unknown type. 17790 case BuiltinType::UnknownAny: 17791 return diagnoseUnknownAnyExpr(*this, E); 17792 17793 // Pseudo-objects. 17794 case BuiltinType::PseudoObject: 17795 return checkPseudoObjectRValue(E); 17796 17797 case BuiltinType::BuiltinFn: { 17798 // Accept __noop without parens by implicitly converting it to a call expr. 17799 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17800 if (DRE) { 17801 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17802 if (FD->getBuiltinID() == Builtin::BI__noop) { 17803 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17804 CK_BuiltinFnToFnPtr) 17805 .get(); 17806 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17807 VK_RValue, SourceLocation()); 17808 } 17809 } 17810 17811 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17812 return ExprError(); 17813 } 17814 17815 // Expressions of unknown type. 17816 case BuiltinType::OMPArraySection: 17817 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17818 return ExprError(); 17819 17820 // Everything else should be impossible. 17821 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17822 case BuiltinType::Id: 17823 #include "clang/Basic/OpenCLImageTypes.def" 17824 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17825 case BuiltinType::Id: 17826 #include "clang/Basic/OpenCLExtensionTypes.def" 17827 #define SVE_TYPE(Name, Id, SingletonId) \ 17828 case BuiltinType::Id: 17829 #include "clang/Basic/AArch64SVEACLETypes.def" 17830 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17831 #define PLACEHOLDER_TYPE(Id, SingletonId) 17832 #include "clang/AST/BuiltinTypes.def" 17833 break; 17834 } 17835 17836 llvm_unreachable("invalid placeholder type!"); 17837 } 17838 17839 bool Sema::CheckCaseExpression(Expr *E) { 17840 if (E->isTypeDependent()) 17841 return true; 17842 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17843 return E->getType()->isIntegralOrEnumerationType(); 17844 return false; 17845 } 17846 17847 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 17848 ExprResult 17849 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 17850 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 17851 "Unknown Objective-C Boolean value!"); 17852 QualType BoolT = Context.ObjCBuiltinBoolTy; 17853 if (!Context.getBOOLDecl()) { 17854 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 17855 Sema::LookupOrdinaryName); 17856 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 17857 NamedDecl *ND = Result.getFoundDecl(); 17858 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 17859 Context.setBOOLDecl(TD); 17860 } 17861 } 17862 if (Context.getBOOLDecl()) 17863 BoolT = Context.getBOOLType(); 17864 return new (Context) 17865 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 17866 } 17867 17868 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 17869 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 17870 SourceLocation RParen) { 17871 17872 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 17873 17874 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 17875 return Spec.getPlatform() == Platform; 17876 }); 17877 17878 VersionTuple Version; 17879 if (Spec != AvailSpecs.end()) 17880 Version = Spec->getVersion(); 17881 17882 // The use of `@available` in the enclosing function should be analyzed to 17883 // warn when it's used inappropriately (i.e. not if(@available)). 17884 if (getCurFunctionOrMethodDecl()) 17885 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 17886 else if (getCurBlock() || getCurLambda()) 17887 getCurFunction()->HasPotentialAvailabilityViolations = true; 17888 17889 return new (Context) 17890 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 17891 } 17892