1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks) { 210 SourceLocation Loc = Locs.front(); 211 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 212 // If there were any diagnostics suppressed by template argument deduction, 213 // emit them now. 214 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 215 if (Pos != SuppressedDiagnostics.end()) { 216 for (const PartialDiagnosticAt &Suppressed : Pos->second) 217 Diag(Suppressed.first, Suppressed.second); 218 219 // Clear out the list of suppressed diagnostics, so that we don't emit 220 // them again for this specialization. However, we don't obsolete this 221 // entry from the table, because we want to avoid ever emitting these 222 // diagnostics again. 223 Pos->second.clear(); 224 } 225 226 // C++ [basic.start.main]p3: 227 // The function 'main' shall not be used within a program. 228 if (cast<FunctionDecl>(D)->isMain()) 229 Diag(Loc, diag::ext_main_used); 230 } 231 232 // See if this is an auto-typed variable whose initializer we are parsing. 233 if (ParsingInitForAutoVars.count(D)) { 234 if (isa<BindingDecl>(D)) { 235 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 236 << D->getDeclName(); 237 } else { 238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 239 << D->getDeclName() << cast<VarDecl>(D)->getType(); 240 } 241 return true; 242 } 243 244 // See if this is a deleted function. 245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 246 if (FD->isDeleted()) { 247 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 248 if (Ctor && Ctor->isInheritingConstructor()) 249 Diag(Loc, diag::err_deleted_inherited_ctor_use) 250 << Ctor->getParent() 251 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 252 else 253 Diag(Loc, diag::err_deleted_function_use); 254 NoteDeletedFunction(FD); 255 return true; 256 } 257 258 // If the function has a deduced return type, and we can't deduce it, 259 // then we can't use it either. 260 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 261 DeduceReturnType(FD, Loc)) 262 return true; 263 264 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 265 return true; 266 } 267 268 auto getReferencedObjCProp = [](const NamedDecl *D) -> 269 const ObjCPropertyDecl * { 270 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 271 return MD->findPropertyDecl(); 272 return nullptr; 273 }; 274 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 275 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 276 return true; 277 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 278 return true; 279 } 280 281 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 282 // Only the variables omp_in and omp_out are allowed in the combiner. 283 // Only the variables omp_priv and omp_orig are allowed in the 284 // initializer-clause. 285 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 286 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 287 isa<VarDecl>(D)) { 288 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 289 << getCurFunction()->HasOMPDeclareReductionCombiner; 290 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 291 return true; 292 } 293 294 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 295 AvoidPartialAvailabilityChecks); 296 297 DiagnoseUnusedOfDecl(*this, D, Loc); 298 299 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 300 301 return false; 302 } 303 304 /// Retrieve the message suffix that should be added to a 305 /// diagnostic complaining about the given function being deleted or 306 /// unavailable. 307 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 308 std::string Message; 309 if (FD->getAvailability(&Message)) 310 return ": " + Message; 311 312 return std::string(); 313 } 314 315 /// DiagnoseSentinelCalls - This routine checks whether a call or 316 /// message-send is to a declaration with the sentinel attribute, and 317 /// if so, it checks that the requirements of the sentinel are 318 /// satisfied. 319 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 320 ArrayRef<Expr *> Args) { 321 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 322 if (!attr) 323 return; 324 325 // The number of formal parameters of the declaration. 326 unsigned numFormalParams; 327 328 // The kind of declaration. This is also an index into a %select in 329 // the diagnostic. 330 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 331 332 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 333 numFormalParams = MD->param_size(); 334 calleeType = CT_Method; 335 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 336 numFormalParams = FD->param_size(); 337 calleeType = CT_Function; 338 } else if (isa<VarDecl>(D)) { 339 QualType type = cast<ValueDecl>(D)->getType(); 340 const FunctionType *fn = nullptr; 341 if (const PointerType *ptr = type->getAs<PointerType>()) { 342 fn = ptr->getPointeeType()->getAs<FunctionType>(); 343 if (!fn) return; 344 calleeType = CT_Function; 345 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 346 fn = ptr->getPointeeType()->castAs<FunctionType>(); 347 calleeType = CT_Block; 348 } else { 349 return; 350 } 351 352 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 353 numFormalParams = proto->getNumParams(); 354 } else { 355 numFormalParams = 0; 356 } 357 } else { 358 return; 359 } 360 361 // "nullPos" is the number of formal parameters at the end which 362 // effectively count as part of the variadic arguments. This is 363 // useful if you would prefer to not have *any* formal parameters, 364 // but the language forces you to have at least one. 365 unsigned nullPos = attr->getNullPos(); 366 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 367 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 368 369 // The number of arguments which should follow the sentinel. 370 unsigned numArgsAfterSentinel = attr->getSentinel(); 371 372 // If there aren't enough arguments for all the formal parameters, 373 // the sentinel, and the args after the sentinel, complain. 374 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 375 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 376 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 377 return; 378 } 379 380 // Otherwise, find the sentinel expression. 381 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 382 if (!sentinelExpr) return; 383 if (sentinelExpr->isValueDependent()) return; 384 if (Context.isSentinelNullExpr(sentinelExpr)) return; 385 386 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 387 // or 'NULL' if those are actually defined in the context. Only use 388 // 'nil' for ObjC methods, where it's much more likely that the 389 // variadic arguments form a list of object pointers. 390 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 391 std::string NullValue; 392 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 393 NullValue = "nil"; 394 else if (getLangOpts().CPlusPlus11) 395 NullValue = "nullptr"; 396 else if (PP.isMacroDefined("NULL")) 397 NullValue = "NULL"; 398 else 399 NullValue = "(void*) 0"; 400 401 if (MissingNilLoc.isInvalid()) 402 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 403 else 404 Diag(MissingNilLoc, diag::warn_missing_sentinel) 405 << int(calleeType) 406 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 407 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 408 } 409 410 SourceRange Sema::getExprRange(Expr *E) const { 411 return E ? E->getSourceRange() : SourceRange(); 412 } 413 414 //===----------------------------------------------------------------------===// 415 // Standard Promotions and Conversions 416 //===----------------------------------------------------------------------===// 417 418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 420 // Handle any placeholder expressions which made it here. 421 if (E->getType()->isPlaceholderType()) { 422 ExprResult result = CheckPlaceholderExpr(E); 423 if (result.isInvalid()) return ExprError(); 424 E = result.get(); 425 } 426 427 QualType Ty = E->getType(); 428 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 429 430 if (Ty->isFunctionType()) { 431 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 432 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 433 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 434 return ExprError(); 435 436 E = ImpCastExprToType(E, Context.getPointerType(Ty), 437 CK_FunctionToPointerDecay).get(); 438 } else if (Ty->isArrayType()) { 439 // In C90 mode, arrays only promote to pointers if the array expression is 440 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 441 // type 'array of type' is converted to an expression that has type 'pointer 442 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 443 // that has type 'array of type' ...". The relevant change is "an lvalue" 444 // (C90) to "an expression" (C99). 445 // 446 // C++ 4.2p1: 447 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 448 // T" can be converted to an rvalue of type "pointer to T". 449 // 450 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 451 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 452 CK_ArrayToPointerDecay).get(); 453 } 454 return E; 455 } 456 457 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 458 // Check to see if we are dereferencing a null pointer. If so, 459 // and if not volatile-qualified, this is undefined behavior that the 460 // optimizer will delete, so warn about it. People sometimes try to use this 461 // to get a deterministic trap and are surprised by clang's behavior. This 462 // only handles the pattern "*null", which is a very syntactic check. 463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 464 if (UO->getOpcode() == UO_Deref && 465 UO->getSubExpr()->IgnoreParenCasts()-> 466 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 467 !UO->getType().isVolatileQualified()) { 468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 469 S.PDiag(diag::warn_indirection_through_null) 470 << UO->getSubExpr()->getSourceRange()); 471 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 472 S.PDiag(diag::note_indirection_through_null)); 473 } 474 } 475 476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 477 SourceLocation AssignLoc, 478 const Expr* RHS) { 479 const ObjCIvarDecl *IV = OIRE->getDecl(); 480 if (!IV) 481 return; 482 483 DeclarationName MemberName = IV->getDeclName(); 484 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 485 if (!Member || !Member->isStr("isa")) 486 return; 487 488 const Expr *Base = OIRE->getBase(); 489 QualType BaseType = Base->getType(); 490 if (OIRE->isArrow()) 491 BaseType = BaseType->getPointeeType(); 492 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 493 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 494 ObjCInterfaceDecl *ClassDeclared = nullptr; 495 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 496 if (!ClassDeclared->getSuperClass() 497 && (*ClassDeclared->ivar_begin()) == IV) { 498 if (RHS) { 499 NamedDecl *ObjectSetClass = 500 S.LookupSingleName(S.TUScope, 501 &S.Context.Idents.get("object_setClass"), 502 SourceLocation(), S.LookupOrdinaryName); 503 if (ObjectSetClass) { 504 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 505 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 506 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 507 "object_setClass(") 508 << FixItHint::CreateReplacement( 509 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 510 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 511 } 512 else 513 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 514 } else { 515 NamedDecl *ObjectGetClass = 516 S.LookupSingleName(S.TUScope, 517 &S.Context.Idents.get("object_getClass"), 518 SourceLocation(), S.LookupOrdinaryName); 519 if (ObjectGetClass) 520 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 521 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 522 "object_getClass(") 523 << FixItHint::CreateReplacement( 524 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 525 else 526 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 527 } 528 S.Diag(IV->getLocation(), diag::note_ivar_decl); 529 } 530 } 531 } 532 533 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 534 // Handle any placeholder expressions which made it here. 535 if (E->getType()->isPlaceholderType()) { 536 ExprResult result = CheckPlaceholderExpr(E); 537 if (result.isInvalid()) return ExprError(); 538 E = result.get(); 539 } 540 541 // C++ [conv.lval]p1: 542 // A glvalue of a non-function, non-array type T can be 543 // converted to a prvalue. 544 if (!E->isGLValue()) return E; 545 546 QualType T = E->getType(); 547 assert(!T.isNull() && "r-value conversion on typeless expression?"); 548 549 // We don't want to throw lvalue-to-rvalue casts on top of 550 // expressions of certain types in C++. 551 if (getLangOpts().CPlusPlus && 552 (E->getType() == Context.OverloadTy || 553 T->isDependentType() || 554 T->isRecordType())) 555 return E; 556 557 // The C standard is actually really unclear on this point, and 558 // DR106 tells us what the result should be but not why. It's 559 // generally best to say that void types just doesn't undergo 560 // lvalue-to-rvalue at all. Note that expressions of unqualified 561 // 'void' type are never l-values, but qualified void can be. 562 if (T->isVoidType()) 563 return E; 564 565 // OpenCL usually rejects direct accesses to values of 'half' type. 566 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 567 T->isHalfType()) { 568 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 569 << 0 << T; 570 return ExprError(); 571 } 572 573 CheckForNullPointerDereference(*this, E); 574 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 575 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 576 &Context.Idents.get("object_getClass"), 577 SourceLocation(), LookupOrdinaryName); 578 if (ObjectGetClass) 579 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 580 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 583 else 584 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 585 } 586 else if (const ObjCIvarRefExpr *OIRE = 587 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 588 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 589 590 // C++ [conv.lval]p1: 591 // [...] If T is a non-class type, the type of the prvalue is the 592 // cv-unqualified version of T. Otherwise, the type of the 593 // rvalue is T. 594 // 595 // C99 6.3.2.1p2: 596 // If the lvalue has qualified type, the value has the unqualified 597 // version of the type of the lvalue; otherwise, the value has the 598 // type of the lvalue. 599 if (T.hasQualifiers()) 600 T = T.getUnqualifiedType(); 601 602 // Under the MS ABI, lock down the inheritance model now. 603 if (T->isMemberPointerType() && 604 Context.getTargetInfo().getCXXABI().isMicrosoft()) 605 (void)isCompleteType(E->getExprLoc(), T); 606 607 UpdateMarkingForLValueToRValue(E); 608 609 // Loading a __weak object implicitly retains the value, so we need a cleanup to 610 // balance that. 611 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 612 Cleanup.setExprNeedsCleanups(true); 613 614 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 615 nullptr, VK_RValue); 616 617 // C11 6.3.2.1p2: 618 // ... if the lvalue has atomic type, the value has the non-atomic version 619 // of the type of the lvalue ... 620 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 621 T = Atomic->getValueType().getUnqualifiedType(); 622 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 623 nullptr, VK_RValue); 624 } 625 626 return Res; 627 } 628 629 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 630 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 631 if (Res.isInvalid()) 632 return ExprError(); 633 Res = DefaultLvalueConversion(Res.get()); 634 if (Res.isInvalid()) 635 return ExprError(); 636 return Res; 637 } 638 639 /// CallExprUnaryConversions - a special case of an unary conversion 640 /// performed on a function designator of a call expression. 641 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 642 QualType Ty = E->getType(); 643 ExprResult Res = E; 644 // Only do implicit cast for a function type, but not for a pointer 645 // to function type. 646 if (Ty->isFunctionType()) { 647 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 648 CK_FunctionToPointerDecay).get(); 649 if (Res.isInvalid()) 650 return ExprError(); 651 } 652 Res = DefaultLvalueConversion(Res.get()); 653 if (Res.isInvalid()) 654 return ExprError(); 655 return Res.get(); 656 } 657 658 /// UsualUnaryConversions - Performs various conversions that are common to most 659 /// operators (C99 6.3). The conversions of array and function types are 660 /// sometimes suppressed. For example, the array->pointer conversion doesn't 661 /// apply if the array is an argument to the sizeof or address (&) operators. 662 /// In these instances, this routine should *not* be called. 663 ExprResult Sema::UsualUnaryConversions(Expr *E) { 664 // First, convert to an r-value. 665 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 666 if (Res.isInvalid()) 667 return ExprError(); 668 E = Res.get(); 669 670 QualType Ty = E->getType(); 671 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 672 673 // Half FP have to be promoted to float unless it is natively supported 674 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 675 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 676 677 // Try to perform integral promotions if the object has a theoretically 678 // promotable type. 679 if (Ty->isIntegralOrUnscopedEnumerationType()) { 680 // C99 6.3.1.1p2: 681 // 682 // The following may be used in an expression wherever an int or 683 // unsigned int may be used: 684 // - an object or expression with an integer type whose integer 685 // conversion rank is less than or equal to the rank of int 686 // and unsigned int. 687 // - A bit-field of type _Bool, int, signed int, or unsigned int. 688 // 689 // If an int can represent all values of the original type, the 690 // value is converted to an int; otherwise, it is converted to an 691 // unsigned int. These are called the integer promotions. All 692 // other types are unchanged by the integer promotions. 693 694 QualType PTy = Context.isPromotableBitField(E); 695 if (!PTy.isNull()) { 696 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 697 return E; 698 } 699 if (Ty->isPromotableIntegerType()) { 700 QualType PT = Context.getPromotedIntegerType(Ty); 701 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 702 return E; 703 } 704 } 705 return E; 706 } 707 708 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 709 /// do not have a prototype. Arguments that have type float or __fp16 710 /// are promoted to double. All other argument types are converted by 711 /// UsualUnaryConversions(). 712 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 713 QualType Ty = E->getType(); 714 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 715 716 ExprResult Res = UsualUnaryConversions(E); 717 if (Res.isInvalid()) 718 return ExprError(); 719 E = Res.get(); 720 721 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 722 // promote to double. 723 // Note that default argument promotion applies only to float (and 724 // half/fp16); it does not apply to _Float16. 725 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 726 if (BTy && (BTy->getKind() == BuiltinType::Half || 727 BTy->getKind() == BuiltinType::Float)) { 728 if (getLangOpts().OpenCL && 729 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 730 if (BTy->getKind() == BuiltinType::Half) { 731 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 732 } 733 } else { 734 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 735 } 736 } 737 738 // C++ performs lvalue-to-rvalue conversion as a default argument 739 // promotion, even on class types, but note: 740 // C++11 [conv.lval]p2: 741 // When an lvalue-to-rvalue conversion occurs in an unevaluated 742 // operand or a subexpression thereof the value contained in the 743 // referenced object is not accessed. Otherwise, if the glvalue 744 // has a class type, the conversion copy-initializes a temporary 745 // of type T from the glvalue and the result of the conversion 746 // is a prvalue for the temporary. 747 // FIXME: add some way to gate this entire thing for correctness in 748 // potentially potentially evaluated contexts. 749 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 750 ExprResult Temp = PerformCopyInitialization( 751 InitializedEntity::InitializeTemporary(E->getType()), 752 E->getExprLoc(), E); 753 if (Temp.isInvalid()) 754 return ExprError(); 755 E = Temp.get(); 756 } 757 758 return E; 759 } 760 761 /// Determine the degree of POD-ness for an expression. 762 /// Incomplete types are considered POD, since this check can be performed 763 /// when we're in an unevaluated context. 764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 765 if (Ty->isIncompleteType()) { 766 // C++11 [expr.call]p7: 767 // After these conversions, if the argument does not have arithmetic, 768 // enumeration, pointer, pointer to member, or class type, the program 769 // is ill-formed. 770 // 771 // Since we've already performed array-to-pointer and function-to-pointer 772 // decay, the only such type in C++ is cv void. This also handles 773 // initializer lists as variadic arguments. 774 if (Ty->isVoidType()) 775 return VAK_Invalid; 776 777 if (Ty->isObjCObjectType()) 778 return VAK_Invalid; 779 return VAK_Valid; 780 } 781 782 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 783 return VAK_Invalid; 784 785 if (Ty.isCXX98PODType(Context)) 786 return VAK_Valid; 787 788 // C++11 [expr.call]p7: 789 // Passing a potentially-evaluated argument of class type (Clause 9) 790 // having a non-trivial copy constructor, a non-trivial move constructor, 791 // or a non-trivial destructor, with no corresponding parameter, 792 // is conditionally-supported with implementation-defined semantics. 793 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 794 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 795 if (!Record->hasNonTrivialCopyConstructor() && 796 !Record->hasNonTrivialMoveConstructor() && 797 !Record->hasNonTrivialDestructor()) 798 return VAK_ValidInCXX11; 799 800 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 801 return VAK_Valid; 802 803 if (Ty->isObjCObjectType()) 804 return VAK_Invalid; 805 806 if (getLangOpts().MSVCCompat) 807 return VAK_MSVCUndefined; 808 809 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 810 // permitted to reject them. We should consider doing so. 811 return VAK_Undefined; 812 } 813 814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 815 // Don't allow one to pass an Objective-C interface to a vararg. 816 const QualType &Ty = E->getType(); 817 VarArgKind VAK = isValidVarArgType(Ty); 818 819 // Complain about passing non-POD types through varargs. 820 switch (VAK) { 821 case VAK_ValidInCXX11: 822 DiagRuntimeBehavior( 823 E->getBeginLoc(), nullptr, 824 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 825 LLVM_FALLTHROUGH; 826 case VAK_Valid: 827 if (Ty->isRecordType()) { 828 // This is unlikely to be what the user intended. If the class has a 829 // 'c_str' member function, the user probably meant to call that. 830 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 831 PDiag(diag::warn_pass_class_arg_to_vararg) 832 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 833 } 834 break; 835 836 case VAK_Undefined: 837 case VAK_MSVCUndefined: 838 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 839 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 840 << getLangOpts().CPlusPlus11 << Ty << CT); 841 break; 842 843 case VAK_Invalid: 844 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 845 Diag(E->getBeginLoc(), 846 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 847 << Ty << CT; 848 else if (Ty->isObjCObjectType()) 849 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 850 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 851 << Ty << CT); 852 else 853 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 854 << isa<InitListExpr>(E) << Ty << CT; 855 break; 856 } 857 } 858 859 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 860 /// will create a trap if the resulting type is not a POD type. 861 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 862 FunctionDecl *FDecl) { 863 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 864 // Strip the unbridged-cast placeholder expression off, if applicable. 865 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 866 (CT == VariadicMethod || 867 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 868 E = stripARCUnbridgedCast(E); 869 870 // Otherwise, do normal placeholder checking. 871 } else { 872 ExprResult ExprRes = CheckPlaceholderExpr(E); 873 if (ExprRes.isInvalid()) 874 return ExprError(); 875 E = ExprRes.get(); 876 } 877 } 878 879 ExprResult ExprRes = DefaultArgumentPromotion(E); 880 if (ExprRes.isInvalid()) 881 return ExprError(); 882 E = ExprRes.get(); 883 884 // Diagnostics regarding non-POD argument types are 885 // emitted along with format string checking in Sema::CheckFunctionCall(). 886 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 887 // Turn this into a trap. 888 CXXScopeSpec SS; 889 SourceLocation TemplateKWLoc; 890 UnqualifiedId Name; 891 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 892 E->getBeginLoc()); 893 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 894 Name, true, false); 895 if (TrapFn.isInvalid()) 896 return ExprError(); 897 898 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 899 None, E->getEndLoc()); 900 if (Call.isInvalid()) 901 return ExprError(); 902 903 ExprResult Comma = 904 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 905 if (Comma.isInvalid()) 906 return ExprError(); 907 return Comma.get(); 908 } 909 910 if (!getLangOpts().CPlusPlus && 911 RequireCompleteType(E->getExprLoc(), E->getType(), 912 diag::err_call_incomplete_argument)) 913 return ExprError(); 914 915 return E; 916 } 917 918 /// Converts an integer to complex float type. Helper function of 919 /// UsualArithmeticConversions() 920 /// 921 /// \return false if the integer expression is an integer type and is 922 /// successfully converted to the complex type. 923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 924 ExprResult &ComplexExpr, 925 QualType IntTy, 926 QualType ComplexTy, 927 bool SkipCast) { 928 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 929 if (SkipCast) return false; 930 if (IntTy->isIntegerType()) { 931 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 932 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 933 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 934 CK_FloatingRealToComplex); 935 } else { 936 assert(IntTy->isComplexIntegerType()); 937 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 938 CK_IntegralComplexToFloatingComplex); 939 } 940 return false; 941 } 942 943 /// Handle arithmetic conversion with complex types. Helper function of 944 /// UsualArithmeticConversions() 945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 946 ExprResult &RHS, QualType LHSType, 947 QualType RHSType, 948 bool IsCompAssign) { 949 // if we have an integer operand, the result is the complex type. 950 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 951 /*skipCast*/false)) 952 return LHSType; 953 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 954 /*skipCast*/IsCompAssign)) 955 return RHSType; 956 957 // This handles complex/complex, complex/float, or float/complex. 958 // When both operands are complex, the shorter operand is converted to the 959 // type of the longer, and that is the type of the result. This corresponds 960 // to what is done when combining two real floating-point operands. 961 // The fun begins when size promotion occur across type domains. 962 // From H&S 6.3.4: When one operand is complex and the other is a real 963 // floating-point type, the less precise type is converted, within it's 964 // real or complex domain, to the precision of the other type. For example, 965 // when combining a "long double" with a "double _Complex", the 966 // "double _Complex" is promoted to "long double _Complex". 967 968 // Compute the rank of the two types, regardless of whether they are complex. 969 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 970 971 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 972 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 973 QualType LHSElementType = 974 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 975 QualType RHSElementType = 976 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 977 978 QualType ResultType = S.Context.getComplexType(LHSElementType); 979 if (Order < 0) { 980 // Promote the precision of the LHS if not an assignment. 981 ResultType = S.Context.getComplexType(RHSElementType); 982 if (!IsCompAssign) { 983 if (LHSComplexType) 984 LHS = 985 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 986 else 987 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 988 } 989 } else if (Order > 0) { 990 // Promote the precision of the RHS. 991 if (RHSComplexType) 992 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 993 else 994 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 995 } 996 return ResultType; 997 } 998 999 /// Handle arithmetic conversion from integer to float. Helper function 1000 /// of UsualArithmeticConversions() 1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1002 ExprResult &IntExpr, 1003 QualType FloatTy, QualType IntTy, 1004 bool ConvertFloat, bool ConvertInt) { 1005 if (IntTy->isIntegerType()) { 1006 if (ConvertInt) 1007 // Convert intExpr to the lhs floating point type. 1008 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1009 CK_IntegralToFloating); 1010 return FloatTy; 1011 } 1012 1013 // Convert both sides to the appropriate complex float. 1014 assert(IntTy->isComplexIntegerType()); 1015 QualType result = S.Context.getComplexType(FloatTy); 1016 1017 // _Complex int -> _Complex float 1018 if (ConvertInt) 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1020 CK_IntegralComplexToFloatingComplex); 1021 1022 // float -> _Complex float 1023 if (ConvertFloat) 1024 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1025 CK_FloatingRealToComplex); 1026 1027 return result; 1028 } 1029 1030 /// Handle arithmethic conversion with floating point types. Helper 1031 /// function of UsualArithmeticConversions() 1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1033 ExprResult &RHS, QualType LHSType, 1034 QualType RHSType, bool IsCompAssign) { 1035 bool LHSFloat = LHSType->isRealFloatingType(); 1036 bool RHSFloat = RHSType->isRealFloatingType(); 1037 1038 // If we have two real floating types, convert the smaller operand 1039 // to the bigger result. 1040 if (LHSFloat && RHSFloat) { 1041 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1042 if (order > 0) { 1043 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1044 return LHSType; 1045 } 1046 1047 assert(order < 0 && "illegal float comparison"); 1048 if (!IsCompAssign) 1049 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1050 return RHSType; 1051 } 1052 1053 if (LHSFloat) { 1054 // Half FP has to be promoted to float unless it is natively supported 1055 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1056 LHSType = S.Context.FloatTy; 1057 1058 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1059 /*convertFloat=*/!IsCompAssign, 1060 /*convertInt=*/ true); 1061 } 1062 assert(RHSFloat); 1063 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1064 /*convertInt=*/ true, 1065 /*convertFloat=*/!IsCompAssign); 1066 } 1067 1068 /// Diagnose attempts to convert between __float128 and long double if 1069 /// there is no support for such conversion. Helper function of 1070 /// UsualArithmeticConversions(). 1071 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1072 QualType RHSType) { 1073 /* No issue converting if at least one of the types is not a floating point 1074 type or the two types have the same rank. 1075 */ 1076 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1077 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1078 return false; 1079 1080 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1081 "The remaining types must be floating point types."); 1082 1083 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1084 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1085 1086 QualType LHSElemType = LHSComplex ? 1087 LHSComplex->getElementType() : LHSType; 1088 QualType RHSElemType = RHSComplex ? 1089 RHSComplex->getElementType() : RHSType; 1090 1091 // No issue if the two types have the same representation 1092 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1093 &S.Context.getFloatTypeSemantics(RHSElemType)) 1094 return false; 1095 1096 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1097 RHSElemType == S.Context.LongDoubleTy); 1098 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1099 RHSElemType == S.Context.Float128Ty); 1100 1101 // We've handled the situation where __float128 and long double have the same 1102 // representation. We allow all conversions for all possible long double types 1103 // except PPC's double double. 1104 return Float128AndLongDouble && 1105 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1106 &llvm::APFloat::PPCDoubleDouble()); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Diagnose attempts to convert between __float128 and long double where 1273 // such conversions currently can't be handled. 1274 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1275 return QualType(); 1276 1277 // Handle complex types first (C99 6.3.1.8p1). 1278 if (LHSType->isComplexType() || RHSType->isComplexType()) 1279 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Now handle "real" floating types (i.e. float, double, long double). 1283 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1284 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Handle GCC complex int extension. 1288 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1289 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1290 IsCompAssign); 1291 1292 // Finally, we have two differing integer types. 1293 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1294 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1295 } 1296 1297 1298 //===----------------------------------------------------------------------===// 1299 // Semantic Analysis for various Expression Types 1300 //===----------------------------------------------------------------------===// 1301 1302 1303 ExprResult 1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1305 SourceLocation DefaultLoc, 1306 SourceLocation RParenLoc, 1307 Expr *ControllingExpr, 1308 ArrayRef<ParsedType> ArgTypes, 1309 ArrayRef<Expr *> ArgExprs) { 1310 unsigned NumAssocs = ArgTypes.size(); 1311 assert(NumAssocs == ArgExprs.size()); 1312 1313 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1314 for (unsigned i = 0; i < NumAssocs; ++i) { 1315 if (ArgTypes[i]) 1316 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1317 else 1318 Types[i] = nullptr; 1319 } 1320 1321 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1322 ControllingExpr, 1323 llvm::makeArrayRef(Types, NumAssocs), 1324 ArgExprs); 1325 delete [] Types; 1326 return ER; 1327 } 1328 1329 ExprResult 1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1331 SourceLocation DefaultLoc, 1332 SourceLocation RParenLoc, 1333 Expr *ControllingExpr, 1334 ArrayRef<TypeSourceInfo *> Types, 1335 ArrayRef<Expr *> Exprs) { 1336 unsigned NumAssocs = Types.size(); 1337 assert(NumAssocs == Exprs.size()); 1338 1339 // Decay and strip qualifiers for the controlling expression type, and handle 1340 // placeholder type replacement. See committee discussion from WG14 DR423. 1341 { 1342 EnterExpressionEvaluationContext Unevaluated( 1343 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1344 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1345 if (R.isInvalid()) 1346 return ExprError(); 1347 ControllingExpr = R.get(); 1348 } 1349 1350 // The controlling expression is an unevaluated operand, so side effects are 1351 // likely unintended. 1352 if (!inTemplateInstantiation() && 1353 ControllingExpr->HasSideEffects(Context, false)) 1354 Diag(ControllingExpr->getExprLoc(), 1355 diag::warn_side_effects_unevaluated_context); 1356 1357 bool TypeErrorFound = false, 1358 IsResultDependent = ControllingExpr->isTypeDependent(), 1359 ContainsUnexpandedParameterPack 1360 = ControllingExpr->containsUnexpandedParameterPack(); 1361 1362 for (unsigned i = 0; i < NumAssocs; ++i) { 1363 if (Exprs[i]->containsUnexpandedParameterPack()) 1364 ContainsUnexpandedParameterPack = true; 1365 1366 if (Types[i]) { 1367 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1368 ContainsUnexpandedParameterPack = true; 1369 1370 if (Types[i]->getType()->isDependentType()) { 1371 IsResultDependent = true; 1372 } else { 1373 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1374 // complete object type other than a variably modified type." 1375 unsigned D = 0; 1376 if (Types[i]->getType()->isIncompleteType()) 1377 D = diag::err_assoc_type_incomplete; 1378 else if (!Types[i]->getType()->isObjectType()) 1379 D = diag::err_assoc_type_nonobject; 1380 else if (Types[i]->getType()->isVariablyModifiedType()) 1381 D = diag::err_assoc_type_variably_modified; 1382 1383 if (D != 0) { 1384 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 1390 // C11 6.5.1.1p2 "No two generic associations in the same generic 1391 // selection shall specify compatible types." 1392 for (unsigned j = i+1; j < NumAssocs; ++j) 1393 if (Types[j] && !Types[j]->getType()->isDependentType() && 1394 Context.typesAreCompatible(Types[i]->getType(), 1395 Types[j]->getType())) { 1396 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1397 diag::err_assoc_compatible_types) 1398 << Types[j]->getTypeLoc().getSourceRange() 1399 << Types[j]->getType() 1400 << Types[i]->getType(); 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1402 diag::note_compat_assoc) 1403 << Types[i]->getTypeLoc().getSourceRange() 1404 << Types[i]->getType(); 1405 TypeErrorFound = true; 1406 } 1407 } 1408 } 1409 } 1410 if (TypeErrorFound) 1411 return ExprError(); 1412 1413 // If we determined that the generic selection is result-dependent, don't 1414 // try to compute the result expression. 1415 if (IsResultDependent) 1416 return new (Context) GenericSelectionExpr( 1417 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1418 ContainsUnexpandedParameterPack); 1419 1420 SmallVector<unsigned, 1> CompatIndices; 1421 unsigned DefaultIndex = -1U; 1422 for (unsigned i = 0; i < NumAssocs; ++i) { 1423 if (!Types[i]) 1424 DefaultIndex = i; 1425 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1426 Types[i]->getType())) 1427 CompatIndices.push_back(i); 1428 } 1429 1430 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1431 // type compatible with at most one of the types named in its generic 1432 // association list." 1433 if (CompatIndices.size() > 1) { 1434 // We strip parens here because the controlling expression is typically 1435 // parenthesized in macro definitions. 1436 ControllingExpr = ControllingExpr->IgnoreParens(); 1437 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1438 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1439 << (unsigned)CompatIndices.size(); 1440 for (unsigned I : CompatIndices) { 1441 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1442 diag::note_compat_assoc) 1443 << Types[I]->getTypeLoc().getSourceRange() 1444 << Types[I]->getType(); 1445 } 1446 return ExprError(); 1447 } 1448 1449 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1450 // its controlling expression shall have type compatible with exactly one of 1451 // the types named in its generic association list." 1452 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1453 // We strip parens here because the controlling expression is typically 1454 // parenthesized in macro definitions. 1455 ControllingExpr = ControllingExpr->IgnoreParens(); 1456 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1457 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1462 // type name that is compatible with the type of the controlling expression, 1463 // then the result expression of the generic selection is the expression 1464 // in that generic association. Otherwise, the result expression of the 1465 // generic selection is the expression in the default generic association." 1466 unsigned ResultIndex = 1467 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1468 1469 return new (Context) GenericSelectionExpr( 1470 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1471 ContainsUnexpandedParameterPack, ResultIndex); 1472 } 1473 1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1475 /// location of the token and the offset of the ud-suffix within it. 1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1477 unsigned Offset) { 1478 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1479 S.getLangOpts()); 1480 } 1481 1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1485 IdentifierInfo *UDSuffix, 1486 SourceLocation UDSuffixLoc, 1487 ArrayRef<Expr*> Args, 1488 SourceLocation LitEndLoc) { 1489 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1490 1491 QualType ArgTy[2]; 1492 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1493 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1494 if (ArgTy[ArgIdx]->isArrayType()) 1495 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1496 } 1497 1498 DeclarationName OpName = 1499 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1500 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1501 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1502 1503 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1504 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1505 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1506 /*AllowStringTemplate*/ false, 1507 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1508 return ExprError(); 1509 1510 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1511 } 1512 1513 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1514 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1515 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1516 /// multiple tokens. However, the common case is that StringToks points to one 1517 /// string. 1518 /// 1519 ExprResult 1520 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1521 assert(!StringToks.empty() && "Must have at least one string!"); 1522 1523 StringLiteralParser Literal(StringToks, PP); 1524 if (Literal.hadError) 1525 return ExprError(); 1526 1527 SmallVector<SourceLocation, 4> StringTokLocs; 1528 for (const Token &Tok : StringToks) 1529 StringTokLocs.push_back(Tok.getLocation()); 1530 1531 QualType CharTy = Context.CharTy; 1532 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1533 if (Literal.isWide()) { 1534 CharTy = Context.getWideCharType(); 1535 Kind = StringLiteral::Wide; 1536 } else if (Literal.isUTF8()) { 1537 if (getLangOpts().Char8) 1538 CharTy = Context.Char8Ty; 1539 Kind = StringLiteral::UTF8; 1540 } else if (Literal.isUTF16()) { 1541 CharTy = Context.Char16Ty; 1542 Kind = StringLiteral::UTF16; 1543 } else if (Literal.isUTF32()) { 1544 CharTy = Context.Char32Ty; 1545 Kind = StringLiteral::UTF32; 1546 } else if (Literal.isPascal()) { 1547 CharTy = Context.UnsignedCharTy; 1548 } 1549 1550 QualType CharTyConst = CharTy; 1551 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1552 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1553 CharTyConst.addConst(); 1554 1555 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1556 1557 // Get an array type for the string, according to C99 6.4.5. This includes 1558 // the nul terminator character as well as the string length for pascal 1559 // strings. 1560 QualType StrTy = Context.getConstantArrayType( 1561 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1562 ArrayType::Normal, 0); 1563 1564 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1565 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1566 Kind, Literal.Pascal, StrTy, 1567 &StringTokLocs[0], 1568 StringTokLocs.size()); 1569 if (Literal.getUDSuffix().empty()) 1570 return Lit; 1571 1572 // We're building a user-defined literal. 1573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1574 SourceLocation UDSuffixLoc = 1575 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1576 Literal.getUDSuffixOffset()); 1577 1578 // Make sure we're allowed user-defined literals here. 1579 if (!UDLScope) 1580 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1581 1582 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1583 // operator "" X (str, len) 1584 QualType SizeType = Context.getSizeType(); 1585 1586 DeclarationName OpName = 1587 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1588 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1589 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1590 1591 QualType ArgTy[] = { 1592 Context.getArrayDecayedType(StrTy), SizeType 1593 }; 1594 1595 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1596 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1597 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1598 /*AllowStringTemplate*/ true, 1599 /*DiagnoseMissing*/ true)) { 1600 1601 case LOLR_Cooked: { 1602 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1603 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1604 StringTokLocs[0]); 1605 Expr *Args[] = { Lit, LenArg }; 1606 1607 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1608 } 1609 1610 case LOLR_StringTemplate: { 1611 TemplateArgumentListInfo ExplicitArgs; 1612 1613 unsigned CharBits = Context.getIntWidth(CharTy); 1614 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1615 llvm::APSInt Value(CharBits, CharIsUnsigned); 1616 1617 TemplateArgument TypeArg(CharTy); 1618 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1619 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1620 1621 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1622 Value = Lit->getCodeUnit(I); 1623 TemplateArgument Arg(Context, Value, CharTy); 1624 TemplateArgumentLocInfo ArgInfo; 1625 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1626 } 1627 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1628 &ExplicitArgs); 1629 } 1630 case LOLR_Raw: 1631 case LOLR_Template: 1632 case LOLR_ErrorNoDiagnostic: 1633 llvm_unreachable("unexpected literal operator lookup result"); 1634 case LOLR_Error: 1635 return ExprError(); 1636 } 1637 llvm_unreachable("unexpected literal operator lookup result"); 1638 } 1639 1640 ExprResult 1641 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1642 SourceLocation Loc, 1643 const CXXScopeSpec *SS) { 1644 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1645 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1646 } 1647 1648 /// BuildDeclRefExpr - Build an expression that references a 1649 /// declaration that does not require a closure capture. 1650 ExprResult 1651 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1652 const DeclarationNameInfo &NameInfo, 1653 const CXXScopeSpec *SS, NamedDecl *FoundD, 1654 const TemplateArgumentListInfo *TemplateArgs) { 1655 bool RefersToCapturedVariable = 1656 isa<VarDecl>(D) && 1657 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1658 1659 DeclRefExpr *E; 1660 if (isa<VarTemplateSpecializationDecl>(D)) { 1661 VarTemplateSpecializationDecl *VarSpec = 1662 cast<VarTemplateSpecializationDecl>(D); 1663 1664 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1665 : NestedNameSpecifierLoc(), 1666 VarSpec->getTemplateKeywordLoc(), D, 1667 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1668 FoundD, TemplateArgs); 1669 } else { 1670 assert(!TemplateArgs && "No template arguments for non-variable" 1671 " template specialization references"); 1672 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1673 : NestedNameSpecifierLoc(), 1674 SourceLocation(), D, RefersToCapturedVariable, 1675 NameInfo, Ty, VK, FoundD); 1676 } 1677 1678 MarkDeclRefReferenced(E); 1679 1680 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1681 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1682 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1683 getCurFunction()->recordUseOfWeak(E); 1684 1685 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1686 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1687 FD = IFD->getAnonField(); 1688 if (FD) { 1689 UnusedPrivateFields.remove(FD); 1690 // Just in case we're building an illegal pointer-to-member. 1691 if (FD->isBitField()) 1692 E->setObjectKind(OK_BitField); 1693 } 1694 1695 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1696 // designates a bit-field. 1697 if (auto *BD = dyn_cast<BindingDecl>(D)) 1698 if (auto *BE = BD->getBinding()) 1699 E->setObjectKind(BE->getObjectKind()); 1700 1701 return E; 1702 } 1703 1704 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1705 /// possibly a list of template arguments. 1706 /// 1707 /// If this produces template arguments, it is permitted to call 1708 /// DecomposeTemplateName. 1709 /// 1710 /// This actually loses a lot of source location information for 1711 /// non-standard name kinds; we should consider preserving that in 1712 /// some way. 1713 void 1714 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1715 TemplateArgumentListInfo &Buffer, 1716 DeclarationNameInfo &NameInfo, 1717 const TemplateArgumentListInfo *&TemplateArgs) { 1718 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1719 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1720 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1721 1722 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1723 Id.TemplateId->NumArgs); 1724 translateTemplateArguments(TemplateArgsPtr, Buffer); 1725 1726 TemplateName TName = Id.TemplateId->Template.get(); 1727 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1728 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1729 TemplateArgs = &Buffer; 1730 } else { 1731 NameInfo = GetNameFromUnqualifiedId(Id); 1732 TemplateArgs = nullptr; 1733 } 1734 } 1735 1736 static void emitEmptyLookupTypoDiagnostic( 1737 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1738 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1739 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1740 DeclContext *Ctx = 1741 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1742 if (!TC) { 1743 // Emit a special diagnostic for failed member lookups. 1744 // FIXME: computing the declaration context might fail here (?) 1745 if (Ctx) 1746 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1747 << SS.getRange(); 1748 else 1749 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1750 return; 1751 } 1752 1753 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1754 bool DroppedSpecifier = 1755 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1756 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1757 ? diag::note_implicit_param_decl 1758 : diag::note_previous_decl; 1759 if (!Ctx) 1760 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1761 SemaRef.PDiag(NoteID)); 1762 else 1763 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1764 << Typo << Ctx << DroppedSpecifier 1765 << SS.getRange(), 1766 SemaRef.PDiag(NoteID)); 1767 } 1768 1769 /// Diagnose an empty lookup. 1770 /// 1771 /// \return false if new lookup candidates were found 1772 bool 1773 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1774 std::unique_ptr<CorrectionCandidateCallback> CCC, 1775 TemplateArgumentListInfo *ExplicitTemplateArgs, 1776 ArrayRef<Expr *> Args, TypoExpr **Out) { 1777 DeclarationName Name = R.getLookupName(); 1778 1779 unsigned diagnostic = diag::err_undeclared_var_use; 1780 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1781 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1782 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1783 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1784 diagnostic = diag::err_undeclared_use; 1785 diagnostic_suggest = diag::err_undeclared_use_suggest; 1786 } 1787 1788 // If the original lookup was an unqualified lookup, fake an 1789 // unqualified lookup. This is useful when (for example) the 1790 // original lookup would not have found something because it was a 1791 // dependent name. 1792 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1793 while (DC) { 1794 if (isa<CXXRecordDecl>(DC)) { 1795 LookupQualifiedName(R, DC); 1796 1797 if (!R.empty()) { 1798 // Don't give errors about ambiguities in this lookup. 1799 R.suppressDiagnostics(); 1800 1801 // During a default argument instantiation the CurContext points 1802 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1803 // function parameter list, hence add an explicit check. 1804 bool isDefaultArgument = 1805 !CodeSynthesisContexts.empty() && 1806 CodeSynthesisContexts.back().Kind == 1807 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1808 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1809 bool isInstance = CurMethod && 1810 CurMethod->isInstance() && 1811 DC == CurMethod->getParent() && !isDefaultArgument; 1812 1813 // Give a code modification hint to insert 'this->'. 1814 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1815 // Actually quite difficult! 1816 if (getLangOpts().MSVCCompat) 1817 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1818 if (isInstance) { 1819 Diag(R.getNameLoc(), diagnostic) << Name 1820 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1821 CheckCXXThisCapture(R.getNameLoc()); 1822 } else { 1823 Diag(R.getNameLoc(), diagnostic) << Name; 1824 } 1825 1826 // Do we really want to note all of these? 1827 for (NamedDecl *D : R) 1828 Diag(D->getLocation(), diag::note_dependent_var_use); 1829 1830 // Return true if we are inside a default argument instantiation 1831 // and the found name refers to an instance member function, otherwise 1832 // the function calling DiagnoseEmptyLookup will try to create an 1833 // implicit member call and this is wrong for default argument. 1834 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1835 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1836 return true; 1837 } 1838 1839 // Tell the callee to try to recover. 1840 return false; 1841 } 1842 1843 R.clear(); 1844 } 1845 1846 // In Microsoft mode, if we are performing lookup from within a friend 1847 // function definition declared at class scope then we must set 1848 // DC to the lexical parent to be able to search into the parent 1849 // class. 1850 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1851 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1852 DC->getLexicalParent()->isRecord()) 1853 DC = DC->getLexicalParent(); 1854 else 1855 DC = DC->getParent(); 1856 } 1857 1858 // We didn't find anything, so try to correct for a typo. 1859 TypoCorrection Corrected; 1860 if (S && Out) { 1861 SourceLocation TypoLoc = R.getNameLoc(); 1862 assert(!ExplicitTemplateArgs && 1863 "Diagnosing an empty lookup with explicit template args!"); 1864 *Out = CorrectTypoDelayed( 1865 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1866 [=](const TypoCorrection &TC) { 1867 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1868 diagnostic, diagnostic_suggest); 1869 }, 1870 nullptr, CTK_ErrorRecovery); 1871 if (*Out) 1872 return true; 1873 } else if (S && (Corrected = 1874 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1875 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1876 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1877 bool DroppedSpecifier = 1878 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1879 R.setLookupName(Corrected.getCorrection()); 1880 1881 bool AcceptableWithRecovery = false; 1882 bool AcceptableWithoutRecovery = false; 1883 NamedDecl *ND = Corrected.getFoundDecl(); 1884 if (ND) { 1885 if (Corrected.isOverloaded()) { 1886 OverloadCandidateSet OCS(R.getNameLoc(), 1887 OverloadCandidateSet::CSK_Normal); 1888 OverloadCandidateSet::iterator Best; 1889 for (NamedDecl *CD : Corrected) { 1890 if (FunctionTemplateDecl *FTD = 1891 dyn_cast<FunctionTemplateDecl>(CD)) 1892 AddTemplateOverloadCandidate( 1893 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1894 Args, OCS); 1895 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1896 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1897 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1898 Args, OCS); 1899 } 1900 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1901 case OR_Success: 1902 ND = Best->FoundDecl; 1903 Corrected.setCorrectionDecl(ND); 1904 break; 1905 default: 1906 // FIXME: Arbitrarily pick the first declaration for the note. 1907 Corrected.setCorrectionDecl(ND); 1908 break; 1909 } 1910 } 1911 R.addDecl(ND); 1912 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1913 CXXRecordDecl *Record = nullptr; 1914 if (Corrected.getCorrectionSpecifier()) { 1915 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1916 Record = Ty->getAsCXXRecordDecl(); 1917 } 1918 if (!Record) 1919 Record = cast<CXXRecordDecl>( 1920 ND->getDeclContext()->getRedeclContext()); 1921 R.setNamingClass(Record); 1922 } 1923 1924 auto *UnderlyingND = ND->getUnderlyingDecl(); 1925 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1926 isa<FunctionTemplateDecl>(UnderlyingND); 1927 // FIXME: If we ended up with a typo for a type name or 1928 // Objective-C class name, we're in trouble because the parser 1929 // is in the wrong place to recover. Suggest the typo 1930 // correction, but don't make it a fix-it since we're not going 1931 // to recover well anyway. 1932 AcceptableWithoutRecovery = 1933 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1934 } else { 1935 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1936 // because we aren't able to recover. 1937 AcceptableWithoutRecovery = true; 1938 } 1939 1940 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1941 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1942 ? diag::note_implicit_param_decl 1943 : diag::note_previous_decl; 1944 if (SS.isEmpty()) 1945 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 else 1948 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1949 << Name << computeDeclContext(SS, false) 1950 << DroppedSpecifier << SS.getRange(), 1951 PDiag(NoteID), AcceptableWithRecovery); 1952 1953 // Tell the callee whether to try to recover. 1954 return !AcceptableWithRecovery; 1955 } 1956 } 1957 R.clear(); 1958 1959 // Emit a special diagnostic for failed member lookups. 1960 // FIXME: computing the declaration context might fail here (?) 1961 if (!SS.isEmpty()) { 1962 Diag(R.getNameLoc(), diag::err_no_member) 1963 << Name << computeDeclContext(SS, false) 1964 << SS.getRange(); 1965 return true; 1966 } 1967 1968 // Give up, we can't recover. 1969 Diag(R.getNameLoc(), diagnostic) << Name; 1970 return true; 1971 } 1972 1973 /// In Microsoft mode, if we are inside a template class whose parent class has 1974 /// dependent base classes, and we can't resolve an unqualified identifier, then 1975 /// assume the identifier is a member of a dependent base class. We can only 1976 /// recover successfully in static methods, instance methods, and other contexts 1977 /// where 'this' is available. This doesn't precisely match MSVC's 1978 /// instantiation model, but it's close enough. 1979 static Expr * 1980 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1981 DeclarationNameInfo &NameInfo, 1982 SourceLocation TemplateKWLoc, 1983 const TemplateArgumentListInfo *TemplateArgs) { 1984 // Only try to recover from lookup into dependent bases in static methods or 1985 // contexts where 'this' is available. 1986 QualType ThisType = S.getCurrentThisType(); 1987 const CXXRecordDecl *RD = nullptr; 1988 if (!ThisType.isNull()) 1989 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1990 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1991 RD = MD->getParent(); 1992 if (!RD || !RD->hasAnyDependentBases()) 1993 return nullptr; 1994 1995 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1996 // is available, suggest inserting 'this->' as a fixit. 1997 SourceLocation Loc = NameInfo.getLoc(); 1998 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1999 DB << NameInfo.getName() << RD; 2000 2001 if (!ThisType.isNull()) { 2002 DB << FixItHint::CreateInsertion(Loc, "this->"); 2003 return CXXDependentScopeMemberExpr::Create( 2004 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2005 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2006 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2007 } 2008 2009 // Synthesize a fake NNS that points to the derived class. This will 2010 // perform name lookup during template instantiation. 2011 CXXScopeSpec SS; 2012 auto *NNS = 2013 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2014 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2015 return DependentScopeDeclRefExpr::Create( 2016 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2017 TemplateArgs); 2018 } 2019 2020 ExprResult 2021 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2022 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2023 bool HasTrailingLParen, bool IsAddressOfOperand, 2024 std::unique_ptr<CorrectionCandidateCallback> CCC, 2025 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2026 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2027 "cannot be direct & operand and have a trailing lparen"); 2028 if (SS.isInvalid()) 2029 return ExprError(); 2030 2031 TemplateArgumentListInfo TemplateArgsBuffer; 2032 2033 // Decompose the UnqualifiedId into the following data. 2034 DeclarationNameInfo NameInfo; 2035 const TemplateArgumentListInfo *TemplateArgs; 2036 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2037 2038 DeclarationName Name = NameInfo.getName(); 2039 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2040 SourceLocation NameLoc = NameInfo.getLoc(); 2041 2042 if (II && II->isEditorPlaceholder()) { 2043 // FIXME: When typed placeholders are supported we can create a typed 2044 // placeholder expression node. 2045 return ExprError(); 2046 } 2047 2048 // C++ [temp.dep.expr]p3: 2049 // An id-expression is type-dependent if it contains: 2050 // -- an identifier that was declared with a dependent type, 2051 // (note: handled after lookup) 2052 // -- a template-id that is dependent, 2053 // (note: handled in BuildTemplateIdExpr) 2054 // -- a conversion-function-id that specifies a dependent type, 2055 // -- a nested-name-specifier that contains a class-name that 2056 // names a dependent type. 2057 // Determine whether this is a member of an unknown specialization; 2058 // we need to handle these differently. 2059 bool DependentID = false; 2060 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2061 Name.getCXXNameType()->isDependentType()) { 2062 DependentID = true; 2063 } else if (SS.isSet()) { 2064 if (DeclContext *DC = computeDeclContext(SS, false)) { 2065 if (RequireCompleteDeclContext(SS, DC)) 2066 return ExprError(); 2067 } else { 2068 DependentID = true; 2069 } 2070 } 2071 2072 if (DependentID) 2073 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2074 IsAddressOfOperand, TemplateArgs); 2075 2076 // Perform the required lookup. 2077 LookupResult R(*this, NameInfo, 2078 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2079 ? LookupObjCImplicitSelfParam 2080 : LookupOrdinaryName); 2081 if (TemplateKWLoc.isValid() || TemplateArgs) { 2082 // Lookup the template name again to correctly establish the context in 2083 // which it was found. This is really unfortunate as we already did the 2084 // lookup to determine that it was a template name in the first place. If 2085 // this becomes a performance hit, we can work harder to preserve those 2086 // results until we get here but it's likely not worth it. 2087 bool MemberOfUnknownSpecialization; 2088 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2089 MemberOfUnknownSpecialization, TemplateKWLoc)) 2090 return ExprError(); 2091 2092 if (MemberOfUnknownSpecialization || 2093 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2094 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2095 IsAddressOfOperand, TemplateArgs); 2096 } else { 2097 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2098 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2099 2100 // If the result might be in a dependent base class, this is a dependent 2101 // id-expression. 2102 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2103 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2104 IsAddressOfOperand, TemplateArgs); 2105 2106 // If this reference is in an Objective-C method, then we need to do 2107 // some special Objective-C lookup, too. 2108 if (IvarLookupFollowUp) { 2109 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2110 if (E.isInvalid()) 2111 return ExprError(); 2112 2113 if (Expr *Ex = E.getAs<Expr>()) 2114 return Ex; 2115 } 2116 } 2117 2118 if (R.isAmbiguous()) 2119 return ExprError(); 2120 2121 // This could be an implicitly declared function reference (legal in C90, 2122 // extension in C99, forbidden in C++). 2123 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2124 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2125 if (D) R.addDecl(D); 2126 } 2127 2128 // Determine whether this name might be a candidate for 2129 // argument-dependent lookup. 2130 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2131 2132 if (R.empty() && !ADL) { 2133 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2134 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2135 TemplateKWLoc, TemplateArgs)) 2136 return E; 2137 } 2138 2139 // Don't diagnose an empty lookup for inline assembly. 2140 if (IsInlineAsmIdentifier) 2141 return ExprError(); 2142 2143 // If this name wasn't predeclared and if this is not a function 2144 // call, diagnose the problem. 2145 TypoExpr *TE = nullptr; 2146 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2147 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2148 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2149 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2150 "Typo correction callback misconfigured"); 2151 if (CCC) { 2152 // Make sure the callback knows what the typo being diagnosed is. 2153 CCC->setTypoName(II); 2154 if (SS.isValid()) 2155 CCC->setTypoNNS(SS.getScopeRep()); 2156 } 2157 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2158 // a template name, but we happen to have always already looked up the name 2159 // before we get here if it must be a template name. 2160 if (DiagnoseEmptyLookup(S, SS, R, 2161 CCC ? std::move(CCC) : std::move(DefaultValidator), 2162 nullptr, None, &TE)) { 2163 if (TE && KeywordReplacement) { 2164 auto &State = getTypoExprState(TE); 2165 auto BestTC = State.Consumer->getNextCorrection(); 2166 if (BestTC.isKeyword()) { 2167 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2168 if (State.DiagHandler) 2169 State.DiagHandler(BestTC); 2170 KeywordReplacement->startToken(); 2171 KeywordReplacement->setKind(II->getTokenID()); 2172 KeywordReplacement->setIdentifierInfo(II); 2173 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2174 // Clean up the state associated with the TypoExpr, since it has 2175 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2176 clearDelayedTypo(TE); 2177 // Signal that a correction to a keyword was performed by returning a 2178 // valid-but-null ExprResult. 2179 return (Expr*)nullptr; 2180 } 2181 State.Consumer->resetCorrectionStream(); 2182 } 2183 return TE ? TE : ExprError(); 2184 } 2185 2186 assert(!R.empty() && 2187 "DiagnoseEmptyLookup returned false but added no results"); 2188 2189 // If we found an Objective-C instance variable, let 2190 // LookupInObjCMethod build the appropriate expression to 2191 // reference the ivar. 2192 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2193 R.clear(); 2194 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2195 // In a hopelessly buggy code, Objective-C instance variable 2196 // lookup fails and no expression will be built to reference it. 2197 if (!E.isInvalid() && !E.get()) 2198 return ExprError(); 2199 return E; 2200 } 2201 } 2202 2203 // This is guaranteed from this point on. 2204 assert(!R.empty() || ADL); 2205 2206 // Check whether this might be a C++ implicit instance member access. 2207 // C++ [class.mfct.non-static]p3: 2208 // When an id-expression that is not part of a class member access 2209 // syntax and not used to form a pointer to member is used in the 2210 // body of a non-static member function of class X, if name lookup 2211 // resolves the name in the id-expression to a non-static non-type 2212 // member of some class C, the id-expression is transformed into a 2213 // class member access expression using (*this) as the 2214 // postfix-expression to the left of the . operator. 2215 // 2216 // But we don't actually need to do this for '&' operands if R 2217 // resolved to a function or overloaded function set, because the 2218 // expression is ill-formed if it actually works out to be a 2219 // non-static member function: 2220 // 2221 // C++ [expr.ref]p4: 2222 // Otherwise, if E1.E2 refers to a non-static member function. . . 2223 // [t]he expression can be used only as the left-hand operand of a 2224 // member function call. 2225 // 2226 // There are other safeguards against such uses, but it's important 2227 // to get this right here so that we don't end up making a 2228 // spuriously dependent expression if we're inside a dependent 2229 // instance method. 2230 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2231 bool MightBeImplicitMember; 2232 if (!IsAddressOfOperand) 2233 MightBeImplicitMember = true; 2234 else if (!SS.isEmpty()) 2235 MightBeImplicitMember = false; 2236 else if (R.isOverloadedResult()) 2237 MightBeImplicitMember = false; 2238 else if (R.isUnresolvableResult()) 2239 MightBeImplicitMember = true; 2240 else 2241 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2242 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2243 isa<MSPropertyDecl>(R.getFoundDecl()); 2244 2245 if (MightBeImplicitMember) 2246 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2247 R, TemplateArgs, S); 2248 } 2249 2250 if (TemplateArgs || TemplateKWLoc.isValid()) { 2251 2252 // In C++1y, if this is a variable template id, then check it 2253 // in BuildTemplateIdExpr(). 2254 // The single lookup result must be a variable template declaration. 2255 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2256 Id.TemplateId->Kind == TNK_Var_template) { 2257 assert(R.getAsSingle<VarTemplateDecl>() && 2258 "There should only be one declaration found."); 2259 } 2260 2261 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2262 } 2263 2264 return BuildDeclarationNameExpr(SS, R, ADL); 2265 } 2266 2267 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2268 /// declaration name, generally during template instantiation. 2269 /// There's a large number of things which don't need to be done along 2270 /// this path. 2271 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2272 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2273 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2274 DeclContext *DC = computeDeclContext(SS, false); 2275 if (!DC) 2276 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2277 NameInfo, /*TemplateArgs=*/nullptr); 2278 2279 if (RequireCompleteDeclContext(SS, DC)) 2280 return ExprError(); 2281 2282 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2283 LookupQualifiedName(R, DC); 2284 2285 if (R.isAmbiguous()) 2286 return ExprError(); 2287 2288 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2289 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2290 NameInfo, /*TemplateArgs=*/nullptr); 2291 2292 if (R.empty()) { 2293 Diag(NameInfo.getLoc(), diag::err_no_member) 2294 << NameInfo.getName() << DC << SS.getRange(); 2295 return ExprError(); 2296 } 2297 2298 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2299 // Diagnose a missing typename if this resolved unambiguously to a type in 2300 // a dependent context. If we can recover with a type, downgrade this to 2301 // a warning in Microsoft compatibility mode. 2302 unsigned DiagID = diag::err_typename_missing; 2303 if (RecoveryTSI && getLangOpts().MSVCCompat) 2304 DiagID = diag::ext_typename_missing; 2305 SourceLocation Loc = SS.getBeginLoc(); 2306 auto D = Diag(Loc, DiagID); 2307 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2308 << SourceRange(Loc, NameInfo.getEndLoc()); 2309 2310 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2311 // context. 2312 if (!RecoveryTSI) 2313 return ExprError(); 2314 2315 // Only issue the fixit if we're prepared to recover. 2316 D << FixItHint::CreateInsertion(Loc, "typename "); 2317 2318 // Recover by pretending this was an elaborated type. 2319 QualType Ty = Context.getTypeDeclType(TD); 2320 TypeLocBuilder TLB; 2321 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2322 2323 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2324 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2325 QTL.setElaboratedKeywordLoc(SourceLocation()); 2326 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2327 2328 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2329 2330 return ExprEmpty(); 2331 } 2332 2333 // Defend against this resolving to an implicit member access. We usually 2334 // won't get here if this might be a legitimate a class member (we end up in 2335 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2336 // a pointer-to-member or in an unevaluated context in C++11. 2337 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2338 return BuildPossibleImplicitMemberExpr(SS, 2339 /*TemplateKWLoc=*/SourceLocation(), 2340 R, /*TemplateArgs=*/nullptr, S); 2341 2342 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2343 } 2344 2345 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2346 /// detected that we're currently inside an ObjC method. Perform some 2347 /// additional lookup. 2348 /// 2349 /// Ideally, most of this would be done by lookup, but there's 2350 /// actually quite a lot of extra work involved. 2351 /// 2352 /// Returns a null sentinel to indicate trivial success. 2353 ExprResult 2354 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2355 IdentifierInfo *II, bool AllowBuiltinCreation) { 2356 SourceLocation Loc = Lookup.getNameLoc(); 2357 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2358 2359 // Check for error condition which is already reported. 2360 if (!CurMethod) 2361 return ExprError(); 2362 2363 // There are two cases to handle here. 1) scoped lookup could have failed, 2364 // in which case we should look for an ivar. 2) scoped lookup could have 2365 // found a decl, but that decl is outside the current instance method (i.e. 2366 // a global variable). In these two cases, we do a lookup for an ivar with 2367 // this name, if the lookup sucedes, we replace it our current decl. 2368 2369 // If we're in a class method, we don't normally want to look for 2370 // ivars. But if we don't find anything else, and there's an 2371 // ivar, that's an error. 2372 bool IsClassMethod = CurMethod->isClassMethod(); 2373 2374 bool LookForIvars; 2375 if (Lookup.empty()) 2376 LookForIvars = true; 2377 else if (IsClassMethod) 2378 LookForIvars = false; 2379 else 2380 LookForIvars = (Lookup.isSingleResult() && 2381 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2382 ObjCInterfaceDecl *IFace = nullptr; 2383 if (LookForIvars) { 2384 IFace = CurMethod->getClassInterface(); 2385 ObjCInterfaceDecl *ClassDeclared; 2386 ObjCIvarDecl *IV = nullptr; 2387 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2388 // Diagnose using an ivar in a class method. 2389 if (IsClassMethod) 2390 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2391 << IV->getDeclName()); 2392 2393 // If we're referencing an invalid decl, just return this as a silent 2394 // error node. The error diagnostic was already emitted on the decl. 2395 if (IV->isInvalidDecl()) 2396 return ExprError(); 2397 2398 // Check if referencing a field with __attribute__((deprecated)). 2399 if (DiagnoseUseOfDecl(IV, Loc)) 2400 return ExprError(); 2401 2402 // Diagnose the use of an ivar outside of the declaring class. 2403 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2404 !declaresSameEntity(ClassDeclared, IFace) && 2405 !getLangOpts().DebuggerSupport) 2406 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2407 2408 // FIXME: This should use a new expr for a direct reference, don't 2409 // turn this into Self->ivar, just return a BareIVarExpr or something. 2410 IdentifierInfo &II = Context.Idents.get("self"); 2411 UnqualifiedId SelfName; 2412 SelfName.setIdentifier(&II, SourceLocation()); 2413 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2414 CXXScopeSpec SelfScopeSpec; 2415 SourceLocation TemplateKWLoc; 2416 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2417 SelfName, false, false); 2418 if (SelfExpr.isInvalid()) 2419 return ExprError(); 2420 2421 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2422 if (SelfExpr.isInvalid()) 2423 return ExprError(); 2424 2425 MarkAnyDeclReferenced(Loc, IV, true); 2426 2427 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2428 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2429 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2430 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2431 2432 ObjCIvarRefExpr *Result = new (Context) 2433 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2434 IV->getLocation(), SelfExpr.get(), true, true); 2435 2436 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2437 if (!isUnevaluatedContext() && 2438 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2439 getCurFunction()->recordUseOfWeak(Result); 2440 } 2441 if (getLangOpts().ObjCAutoRefCount) { 2442 if (CurContext->isClosure()) 2443 Diag(Loc, diag::warn_implicitly_retains_self) 2444 << FixItHint::CreateInsertion(Loc, "self->"); 2445 } 2446 2447 return Result; 2448 } 2449 } else if (CurMethod->isInstanceMethod()) { 2450 // We should warn if a local variable hides an ivar. 2451 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2452 ObjCInterfaceDecl *ClassDeclared; 2453 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2454 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2455 declaresSameEntity(IFace, ClassDeclared)) 2456 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2457 } 2458 } 2459 } else if (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2461 // If accessing a stand-alone ivar in a class method, this is an error. 2462 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2463 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2464 << IV->getDeclName()); 2465 } 2466 2467 if (Lookup.empty() && II && AllowBuiltinCreation) { 2468 // FIXME. Consolidate this with similar code in LookupName. 2469 if (unsigned BuiltinID = II->getBuiltinID()) { 2470 if (!(getLangOpts().CPlusPlus && 2471 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2472 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2473 S, Lookup.isForRedeclaration(), 2474 Lookup.getNameLoc()); 2475 if (D) Lookup.addDecl(D); 2476 } 2477 } 2478 } 2479 // Sentinel value saying that we didn't do anything special. 2480 return ExprResult((Expr *)nullptr); 2481 } 2482 2483 /// Cast a base object to a member's actual type. 2484 /// 2485 /// Logically this happens in three phases: 2486 /// 2487 /// * First we cast from the base type to the naming class. 2488 /// The naming class is the class into which we were looking 2489 /// when we found the member; it's the qualifier type if a 2490 /// qualifier was provided, and otherwise it's the base type. 2491 /// 2492 /// * Next we cast from the naming class to the declaring class. 2493 /// If the member we found was brought into a class's scope by 2494 /// a using declaration, this is that class; otherwise it's 2495 /// the class declaring the member. 2496 /// 2497 /// * Finally we cast from the declaring class to the "true" 2498 /// declaring class of the member. This conversion does not 2499 /// obey access control. 2500 ExprResult 2501 Sema::PerformObjectMemberConversion(Expr *From, 2502 NestedNameSpecifier *Qualifier, 2503 NamedDecl *FoundDecl, 2504 NamedDecl *Member) { 2505 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2506 if (!RD) 2507 return From; 2508 2509 QualType DestRecordType; 2510 QualType DestType; 2511 QualType FromRecordType; 2512 QualType FromType = From->getType(); 2513 bool PointerConversions = false; 2514 if (isa<FieldDecl>(Member)) { 2515 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2516 2517 if (FromType->getAs<PointerType>()) { 2518 DestType = Context.getPointerType(DestRecordType); 2519 FromRecordType = FromType->getPointeeType(); 2520 PointerConversions = true; 2521 } else { 2522 DestType = DestRecordType; 2523 FromRecordType = FromType; 2524 } 2525 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2526 if (Method->isStatic()) 2527 return From; 2528 2529 DestType = Method->getThisType(Context); 2530 DestRecordType = DestType->getPointeeType(); 2531 2532 if (FromType->getAs<PointerType>()) { 2533 FromRecordType = FromType->getPointeeType(); 2534 PointerConversions = true; 2535 } else { 2536 FromRecordType = FromType; 2537 DestType = DestRecordType; 2538 } 2539 } else { 2540 // No conversion necessary. 2541 return From; 2542 } 2543 2544 if (DestType->isDependentType() || FromType->isDependentType()) 2545 return From; 2546 2547 // If the unqualified types are the same, no conversion is necessary. 2548 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2549 return From; 2550 2551 SourceRange FromRange = From->getSourceRange(); 2552 SourceLocation FromLoc = FromRange.getBegin(); 2553 2554 ExprValueKind VK = From->getValueKind(); 2555 2556 // C++ [class.member.lookup]p8: 2557 // [...] Ambiguities can often be resolved by qualifying a name with its 2558 // class name. 2559 // 2560 // If the member was a qualified name and the qualified referred to a 2561 // specific base subobject type, we'll cast to that intermediate type 2562 // first and then to the object in which the member is declared. That allows 2563 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2564 // 2565 // class Base { public: int x; }; 2566 // class Derived1 : public Base { }; 2567 // class Derived2 : public Base { }; 2568 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2569 // 2570 // void VeryDerived::f() { 2571 // x = 17; // error: ambiguous base subobjects 2572 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2573 // } 2574 if (Qualifier && Qualifier->getAsType()) { 2575 QualType QType = QualType(Qualifier->getAsType(), 0); 2576 assert(QType->isRecordType() && "lookup done with non-record type"); 2577 2578 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2579 2580 // In C++98, the qualifier type doesn't actually have to be a base 2581 // type of the object type, in which case we just ignore it. 2582 // Otherwise build the appropriate casts. 2583 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2584 CXXCastPath BasePath; 2585 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2586 FromLoc, FromRange, &BasePath)) 2587 return ExprError(); 2588 2589 if (PointerConversions) 2590 QType = Context.getPointerType(QType); 2591 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2592 VK, &BasePath).get(); 2593 2594 FromType = QType; 2595 FromRecordType = QRecordType; 2596 2597 // If the qualifier type was the same as the destination type, 2598 // we're done. 2599 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2600 return From; 2601 } 2602 } 2603 2604 bool IgnoreAccess = false; 2605 2606 // If we actually found the member through a using declaration, cast 2607 // down to the using declaration's type. 2608 // 2609 // Pointer equality is fine here because only one declaration of a 2610 // class ever has member declarations. 2611 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2612 assert(isa<UsingShadowDecl>(FoundDecl)); 2613 QualType URecordType = Context.getTypeDeclType( 2614 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2615 2616 // We only need to do this if the naming-class to declaring-class 2617 // conversion is non-trivial. 2618 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2619 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2620 CXXCastPath BasePath; 2621 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2622 FromLoc, FromRange, &BasePath)) 2623 return ExprError(); 2624 2625 QualType UType = URecordType; 2626 if (PointerConversions) 2627 UType = Context.getPointerType(UType); 2628 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2629 VK, &BasePath).get(); 2630 FromType = UType; 2631 FromRecordType = URecordType; 2632 } 2633 2634 // We don't do access control for the conversion from the 2635 // declaring class to the true declaring class. 2636 IgnoreAccess = true; 2637 } 2638 2639 CXXCastPath BasePath; 2640 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2641 FromLoc, FromRange, &BasePath, 2642 IgnoreAccess)) 2643 return ExprError(); 2644 2645 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2646 VK, &BasePath); 2647 } 2648 2649 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2650 const LookupResult &R, 2651 bool HasTrailingLParen) { 2652 // Only when used directly as the postfix-expression of a call. 2653 if (!HasTrailingLParen) 2654 return false; 2655 2656 // Never if a scope specifier was provided. 2657 if (SS.isSet()) 2658 return false; 2659 2660 // Only in C++ or ObjC++. 2661 if (!getLangOpts().CPlusPlus) 2662 return false; 2663 2664 // Turn off ADL when we find certain kinds of declarations during 2665 // normal lookup: 2666 for (NamedDecl *D : R) { 2667 // C++0x [basic.lookup.argdep]p3: 2668 // -- a declaration of a class member 2669 // Since using decls preserve this property, we check this on the 2670 // original decl. 2671 if (D->isCXXClassMember()) 2672 return false; 2673 2674 // C++0x [basic.lookup.argdep]p3: 2675 // -- a block-scope function declaration that is not a 2676 // using-declaration 2677 // NOTE: we also trigger this for function templates (in fact, we 2678 // don't check the decl type at all, since all other decl types 2679 // turn off ADL anyway). 2680 if (isa<UsingShadowDecl>(D)) 2681 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2682 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2683 return false; 2684 2685 // C++0x [basic.lookup.argdep]p3: 2686 // -- a declaration that is neither a function or a function 2687 // template 2688 // And also for builtin functions. 2689 if (isa<FunctionDecl>(D)) { 2690 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2691 2692 // But also builtin functions. 2693 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2694 return false; 2695 } else if (!isa<FunctionTemplateDecl>(D)) 2696 return false; 2697 } 2698 2699 return true; 2700 } 2701 2702 2703 /// Diagnoses obvious problems with the use of the given declaration 2704 /// as an expression. This is only actually called for lookups that 2705 /// were not overloaded, and it doesn't promise that the declaration 2706 /// will in fact be used. 2707 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2708 if (D->isInvalidDecl()) 2709 return true; 2710 2711 if (isa<TypedefNameDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 if (isa<ObjCInterfaceDecl>(D)) { 2717 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2718 return true; 2719 } 2720 2721 if (isa<NamespaceDecl>(D)) { 2722 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2723 return true; 2724 } 2725 2726 return false; 2727 } 2728 2729 // Certain multiversion types should be treated as overloaded even when there is 2730 // only one result. 2731 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2732 assert(R.isSingleResult() && "Expected only a single result"); 2733 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2734 return FD && 2735 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2736 } 2737 2738 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2739 LookupResult &R, bool NeedsADL, 2740 bool AcceptInvalidDecl) { 2741 // If this is a single, fully-resolved result and we don't need ADL, 2742 // just build an ordinary singleton decl ref. 2743 if (!NeedsADL && R.isSingleResult() && 2744 !R.getAsSingle<FunctionTemplateDecl>() && 2745 !ShouldLookupResultBeMultiVersionOverload(R)) 2746 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2747 R.getRepresentativeDecl(), nullptr, 2748 AcceptInvalidDecl); 2749 2750 // We only need to check the declaration if there's exactly one 2751 // result, because in the overloaded case the results can only be 2752 // functions and function templates. 2753 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2754 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2755 return ExprError(); 2756 2757 // Otherwise, just build an unresolved lookup expression. Suppress 2758 // any lookup-related diagnostics; we'll hash these out later, when 2759 // we've picked a target. 2760 R.suppressDiagnostics(); 2761 2762 UnresolvedLookupExpr *ULE 2763 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2764 SS.getWithLocInContext(Context), 2765 R.getLookupNameInfo(), 2766 NeedsADL, R.isOverloadedResult(), 2767 R.begin(), R.end()); 2768 2769 return ULE; 2770 } 2771 2772 static void 2773 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2774 ValueDecl *var, DeclContext *DC); 2775 2776 /// Complete semantic analysis for a reference to the given declaration. 2777 ExprResult Sema::BuildDeclarationNameExpr( 2778 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2779 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2780 bool AcceptInvalidDecl) { 2781 assert(D && "Cannot refer to a NULL declaration"); 2782 assert(!isa<FunctionTemplateDecl>(D) && 2783 "Cannot refer unambiguously to a function template"); 2784 2785 SourceLocation Loc = NameInfo.getLoc(); 2786 if (CheckDeclInExpr(*this, Loc, D)) 2787 return ExprError(); 2788 2789 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2790 // Specifically diagnose references to class templates that are missing 2791 // a template argument list. 2792 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2793 return ExprError(); 2794 } 2795 2796 // Make sure that we're referring to a value. 2797 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2798 if (!VD) { 2799 Diag(Loc, diag::err_ref_non_value) 2800 << D << SS.getRange(); 2801 Diag(D->getLocation(), diag::note_declared_at); 2802 return ExprError(); 2803 } 2804 2805 // Check whether this declaration can be used. Note that we suppress 2806 // this check when we're going to perform argument-dependent lookup 2807 // on this function name, because this might not be the function 2808 // that overload resolution actually selects. 2809 if (DiagnoseUseOfDecl(VD, Loc)) 2810 return ExprError(); 2811 2812 // Only create DeclRefExpr's for valid Decl's. 2813 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2814 return ExprError(); 2815 2816 // Handle members of anonymous structs and unions. If we got here, 2817 // and the reference is to a class member indirect field, then this 2818 // must be the subject of a pointer-to-member expression. 2819 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2820 if (!indirectField->isCXXClassMember()) 2821 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2822 indirectField); 2823 2824 { 2825 QualType type = VD->getType(); 2826 if (type.isNull()) 2827 return ExprError(); 2828 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2829 // C++ [except.spec]p17: 2830 // An exception-specification is considered to be needed when: 2831 // - in an expression, the function is the unique lookup result or 2832 // the selected member of a set of overloaded functions. 2833 ResolveExceptionSpec(Loc, FPT); 2834 type = VD->getType(); 2835 } 2836 ExprValueKind valueKind = VK_RValue; 2837 2838 switch (D->getKind()) { 2839 // Ignore all the non-ValueDecl kinds. 2840 #define ABSTRACT_DECL(kind) 2841 #define VALUE(type, base) 2842 #define DECL(type, base) \ 2843 case Decl::type: 2844 #include "clang/AST/DeclNodes.inc" 2845 llvm_unreachable("invalid value decl kind"); 2846 2847 // These shouldn't make it here. 2848 case Decl::ObjCAtDefsField: 2849 case Decl::ObjCIvar: 2850 llvm_unreachable("forming non-member reference to ivar?"); 2851 2852 // Enum constants are always r-values and never references. 2853 // Unresolved using declarations are dependent. 2854 case Decl::EnumConstant: 2855 case Decl::UnresolvedUsingValue: 2856 case Decl::OMPDeclareReduction: 2857 valueKind = VK_RValue; 2858 break; 2859 2860 // Fields and indirect fields that got here must be for 2861 // pointer-to-member expressions; we just call them l-values for 2862 // internal consistency, because this subexpression doesn't really 2863 // exist in the high-level semantics. 2864 case Decl::Field: 2865 case Decl::IndirectField: 2866 assert(getLangOpts().CPlusPlus && 2867 "building reference to field in C?"); 2868 2869 // These can't have reference type in well-formed programs, but 2870 // for internal consistency we do this anyway. 2871 type = type.getNonReferenceType(); 2872 valueKind = VK_LValue; 2873 break; 2874 2875 // Non-type template parameters are either l-values or r-values 2876 // depending on the type. 2877 case Decl::NonTypeTemplateParm: { 2878 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2879 type = reftype->getPointeeType(); 2880 valueKind = VK_LValue; // even if the parameter is an r-value reference 2881 break; 2882 } 2883 2884 // For non-references, we need to strip qualifiers just in case 2885 // the template parameter was declared as 'const int' or whatever. 2886 valueKind = VK_RValue; 2887 type = type.getUnqualifiedType(); 2888 break; 2889 } 2890 2891 case Decl::Var: 2892 case Decl::VarTemplateSpecialization: 2893 case Decl::VarTemplatePartialSpecialization: 2894 case Decl::Decomposition: 2895 case Decl::OMPCapturedExpr: 2896 // In C, "extern void blah;" is valid and is an r-value. 2897 if (!getLangOpts().CPlusPlus && 2898 !type.hasQualifiers() && 2899 type->isVoidType()) { 2900 valueKind = VK_RValue; 2901 break; 2902 } 2903 LLVM_FALLTHROUGH; 2904 2905 case Decl::ImplicitParam: 2906 case Decl::ParmVar: { 2907 // These are always l-values. 2908 valueKind = VK_LValue; 2909 type = type.getNonReferenceType(); 2910 2911 // FIXME: Does the addition of const really only apply in 2912 // potentially-evaluated contexts? Since the variable isn't actually 2913 // captured in an unevaluated context, it seems that the answer is no. 2914 if (!isUnevaluatedContext()) { 2915 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2916 if (!CapturedType.isNull()) 2917 type = CapturedType; 2918 } 2919 2920 break; 2921 } 2922 2923 case Decl::Binding: { 2924 // These are always lvalues. 2925 valueKind = VK_LValue; 2926 type = type.getNonReferenceType(); 2927 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2928 // decides how that's supposed to work. 2929 auto *BD = cast<BindingDecl>(VD); 2930 if (BD->getDeclContext()->isFunctionOrMethod() && 2931 BD->getDeclContext() != CurContext) 2932 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2933 break; 2934 } 2935 2936 case Decl::Function: { 2937 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2938 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2939 type = Context.BuiltinFnTy; 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 } 2944 2945 const FunctionType *fty = type->castAs<FunctionType>(); 2946 2947 // If we're referring to a function with an __unknown_anytype 2948 // result type, make the entire expression __unknown_anytype. 2949 if (fty->getReturnType() == Context.UnknownAnyTy) { 2950 type = Context.UnknownAnyTy; 2951 valueKind = VK_RValue; 2952 break; 2953 } 2954 2955 // Functions are l-values in C++. 2956 if (getLangOpts().CPlusPlus) { 2957 valueKind = VK_LValue; 2958 break; 2959 } 2960 2961 // C99 DR 316 says that, if a function type comes from a 2962 // function definition (without a prototype), that type is only 2963 // used for checking compatibility. Therefore, when referencing 2964 // the function, we pretend that we don't have the full function 2965 // type. 2966 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2967 isa<FunctionProtoType>(fty)) 2968 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2969 fty->getExtInfo()); 2970 2971 // Functions are r-values in C. 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 2976 case Decl::CXXDeductionGuide: 2977 llvm_unreachable("building reference to deduction guide"); 2978 2979 case Decl::MSProperty: 2980 valueKind = VK_LValue; 2981 break; 2982 2983 case Decl::CXXMethod: 2984 // If we're referring to a method with an __unknown_anytype 2985 // result type, make the entire expression __unknown_anytype. 2986 // This should only be possible with a type written directly. 2987 if (const FunctionProtoType *proto 2988 = dyn_cast<FunctionProtoType>(VD->getType())) 2989 if (proto->getReturnType() == Context.UnknownAnyTy) { 2990 type = Context.UnknownAnyTy; 2991 valueKind = VK_RValue; 2992 break; 2993 } 2994 2995 // C++ methods are l-values if static, r-values if non-static. 2996 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2997 valueKind = VK_LValue; 2998 break; 2999 } 3000 LLVM_FALLTHROUGH; 3001 3002 case Decl::CXXConversion: 3003 case Decl::CXXDestructor: 3004 case Decl::CXXConstructor: 3005 valueKind = VK_RValue; 3006 break; 3007 } 3008 3009 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3010 TemplateArgs); 3011 } 3012 } 3013 3014 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3015 SmallString<32> &Target) { 3016 Target.resize(CharByteWidth * (Source.size() + 1)); 3017 char *ResultPtr = &Target[0]; 3018 const llvm::UTF8 *ErrorPtr; 3019 bool success = 3020 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3021 (void)success; 3022 assert(success); 3023 Target.resize(ResultPtr - &Target[0]); 3024 } 3025 3026 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3027 PredefinedExpr::IdentType IT) { 3028 // Pick the current block, lambda, captured statement or function. 3029 Decl *currentDecl = nullptr; 3030 if (const BlockScopeInfo *BSI = getCurBlock()) 3031 currentDecl = BSI->TheDecl; 3032 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3033 currentDecl = LSI->CallOperator; 3034 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3035 currentDecl = CSI->TheCapturedDecl; 3036 else 3037 currentDecl = getCurFunctionOrMethodDecl(); 3038 3039 if (!currentDecl) { 3040 Diag(Loc, diag::ext_predef_outside_function); 3041 currentDecl = Context.getTranslationUnitDecl(); 3042 } 3043 3044 QualType ResTy; 3045 StringLiteral *SL = nullptr; 3046 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3047 ResTy = Context.DependentTy; 3048 else { 3049 // Pre-defined identifiers are of type char[x], where x is the length of 3050 // the string. 3051 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3052 unsigned Length = Str.length(); 3053 3054 llvm::APInt LengthI(32, Length + 1); 3055 if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) { 3056 ResTy = 3057 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3058 SmallString<32> RawChars; 3059 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3060 Str, RawChars); 3061 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3062 /*IndexTypeQuals*/ 0); 3063 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3064 /*Pascal*/ false, ResTy, Loc); 3065 } else { 3066 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3067 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3068 /*IndexTypeQuals*/ 0); 3069 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3070 /*Pascal*/ false, ResTy, Loc); 3071 } 3072 } 3073 3074 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3075 } 3076 3077 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3078 PredefinedExpr::IdentType IT; 3079 3080 switch (Kind) { 3081 default: llvm_unreachable("Unknown simple primary expr!"); 3082 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3083 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3084 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3085 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3086 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS] 3087 case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS] 3088 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3089 } 3090 3091 return BuildPredefinedExpr(Loc, IT); 3092 } 3093 3094 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3095 SmallString<16> CharBuffer; 3096 bool Invalid = false; 3097 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3098 if (Invalid) 3099 return ExprError(); 3100 3101 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3102 PP, Tok.getKind()); 3103 if (Literal.hadError()) 3104 return ExprError(); 3105 3106 QualType Ty; 3107 if (Literal.isWide()) 3108 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3109 else if (Literal.isUTF8() && getLangOpts().Char8) 3110 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3111 else if (Literal.isUTF16()) 3112 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3113 else if (Literal.isUTF32()) 3114 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3115 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3116 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3117 else 3118 Ty = Context.CharTy; // 'x' -> char in C++ 3119 3120 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3121 if (Literal.isWide()) 3122 Kind = CharacterLiteral::Wide; 3123 else if (Literal.isUTF16()) 3124 Kind = CharacterLiteral::UTF16; 3125 else if (Literal.isUTF32()) 3126 Kind = CharacterLiteral::UTF32; 3127 else if (Literal.isUTF8()) 3128 Kind = CharacterLiteral::UTF8; 3129 3130 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3131 Tok.getLocation()); 3132 3133 if (Literal.getUDSuffix().empty()) 3134 return Lit; 3135 3136 // We're building a user-defined literal. 3137 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3138 SourceLocation UDSuffixLoc = 3139 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3140 3141 // Make sure we're allowed user-defined literals here. 3142 if (!UDLScope) 3143 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3144 3145 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3146 // operator "" X (ch) 3147 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3148 Lit, Tok.getLocation()); 3149 } 3150 3151 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3152 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3153 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3154 Context.IntTy, Loc); 3155 } 3156 3157 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3158 QualType Ty, SourceLocation Loc) { 3159 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3160 3161 using llvm::APFloat; 3162 APFloat Val(Format); 3163 3164 APFloat::opStatus result = Literal.GetFloatValue(Val); 3165 3166 // Overflow is always an error, but underflow is only an error if 3167 // we underflowed to zero (APFloat reports denormals as underflow). 3168 if ((result & APFloat::opOverflow) || 3169 ((result & APFloat::opUnderflow) && Val.isZero())) { 3170 unsigned diagnostic; 3171 SmallString<20> buffer; 3172 if (result & APFloat::opOverflow) { 3173 diagnostic = diag::warn_float_overflow; 3174 APFloat::getLargest(Format).toString(buffer); 3175 } else { 3176 diagnostic = diag::warn_float_underflow; 3177 APFloat::getSmallest(Format).toString(buffer); 3178 } 3179 3180 S.Diag(Loc, diagnostic) 3181 << Ty 3182 << StringRef(buffer.data(), buffer.size()); 3183 } 3184 3185 bool isExact = (result == APFloat::opOK); 3186 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3187 } 3188 3189 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3190 assert(E && "Invalid expression"); 3191 3192 if (E->isValueDependent()) 3193 return false; 3194 3195 QualType QT = E->getType(); 3196 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3197 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3198 return true; 3199 } 3200 3201 llvm::APSInt ValueAPS; 3202 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3203 3204 if (R.isInvalid()) 3205 return true; 3206 3207 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3208 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3209 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3210 << ValueAPS.toString(10) << ValueIsPositive; 3211 return true; 3212 } 3213 3214 return false; 3215 } 3216 3217 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3218 // Fast path for a single digit (which is quite common). A single digit 3219 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3220 if (Tok.getLength() == 1) { 3221 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3222 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3223 } 3224 3225 SmallString<128> SpellingBuffer; 3226 // NumericLiteralParser wants to overread by one character. Add padding to 3227 // the buffer in case the token is copied to the buffer. If getSpelling() 3228 // returns a StringRef to the memory buffer, it should have a null char at 3229 // the EOF, so it is also safe. 3230 SpellingBuffer.resize(Tok.getLength() + 1); 3231 3232 // Get the spelling of the token, which eliminates trigraphs, etc. 3233 bool Invalid = false; 3234 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3235 if (Invalid) 3236 return ExprError(); 3237 3238 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3239 if (Literal.hadError) 3240 return ExprError(); 3241 3242 if (Literal.hasUDSuffix()) { 3243 // We're building a user-defined literal. 3244 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3245 SourceLocation UDSuffixLoc = 3246 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3247 3248 // Make sure we're allowed user-defined literals here. 3249 if (!UDLScope) 3250 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3251 3252 QualType CookedTy; 3253 if (Literal.isFloatingLiteral()) { 3254 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3255 // long double, the literal is treated as a call of the form 3256 // operator "" X (f L) 3257 CookedTy = Context.LongDoubleTy; 3258 } else { 3259 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3260 // unsigned long long, the literal is treated as a call of the form 3261 // operator "" X (n ULL) 3262 CookedTy = Context.UnsignedLongLongTy; 3263 } 3264 3265 DeclarationName OpName = 3266 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3267 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3268 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3269 3270 SourceLocation TokLoc = Tok.getLocation(); 3271 3272 // Perform literal operator lookup to determine if we're building a raw 3273 // literal or a cooked one. 3274 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3275 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3276 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3277 /*AllowStringTemplate*/ false, 3278 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3279 case LOLR_ErrorNoDiagnostic: 3280 // Lookup failure for imaginary constants isn't fatal, there's still the 3281 // GNU extension producing _Complex types. 3282 break; 3283 case LOLR_Error: 3284 return ExprError(); 3285 case LOLR_Cooked: { 3286 Expr *Lit; 3287 if (Literal.isFloatingLiteral()) { 3288 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3289 } else { 3290 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3291 if (Literal.GetIntegerValue(ResultVal)) 3292 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3293 << /* Unsigned */ 1; 3294 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3295 Tok.getLocation()); 3296 } 3297 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3298 } 3299 3300 case LOLR_Raw: { 3301 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3302 // literal is treated as a call of the form 3303 // operator "" X ("n") 3304 unsigned Length = Literal.getUDSuffixOffset(); 3305 QualType StrTy = Context.getConstantArrayType( 3306 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3307 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3308 Expr *Lit = StringLiteral::Create( 3309 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3310 /*Pascal*/false, StrTy, &TokLoc, 1); 3311 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3312 } 3313 3314 case LOLR_Template: { 3315 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3316 // template), L is treated as a call fo the form 3317 // operator "" X <'c1', 'c2', ... 'ck'>() 3318 // where n is the source character sequence c1 c2 ... ck. 3319 TemplateArgumentListInfo ExplicitArgs; 3320 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3321 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3322 llvm::APSInt Value(CharBits, CharIsUnsigned); 3323 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3324 Value = TokSpelling[I]; 3325 TemplateArgument Arg(Context, Value, Context.CharTy); 3326 TemplateArgumentLocInfo ArgInfo; 3327 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3328 } 3329 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3330 &ExplicitArgs); 3331 } 3332 case LOLR_StringTemplate: 3333 llvm_unreachable("unexpected literal operator lookup result"); 3334 } 3335 } 3336 3337 Expr *Res; 3338 3339 if (Literal.isFixedPointLiteral()) { 3340 QualType Ty; 3341 3342 if (Literal.isAccum) { 3343 if (Literal.isHalf) { 3344 Ty = Context.ShortAccumTy; 3345 } else if (Literal.isLong) { 3346 Ty = Context.LongAccumTy; 3347 } else { 3348 Ty = Context.AccumTy; 3349 } 3350 } else if (Literal.isFract) { 3351 if (Literal.isHalf) { 3352 Ty = Context.ShortFractTy; 3353 } else if (Literal.isLong) { 3354 Ty = Context.LongFractTy; 3355 } else { 3356 Ty = Context.FractTy; 3357 } 3358 } 3359 3360 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3361 3362 bool isSigned = !Literal.isUnsigned; 3363 unsigned scale = Context.getFixedPointScale(Ty); 3364 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3365 3366 llvm::APInt Val(bit_width, 0, isSigned); 3367 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3368 bool ValIsZero = Val.isNullValue() && !Overflowed; 3369 3370 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3371 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3372 // Clause 6.4.4 - The value of a constant shall be in the range of 3373 // representable values for its type, with exception for constants of a 3374 // fract type with a value of exactly 1; such a constant shall denote 3375 // the maximal value for the type. 3376 --Val; 3377 else if (Val.ugt(MaxVal) || Overflowed) 3378 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3379 3380 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3381 Tok.getLocation(), scale); 3382 } else if (Literal.isFloatingLiteral()) { 3383 QualType Ty; 3384 if (Literal.isHalf){ 3385 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3386 Ty = Context.HalfTy; 3387 else { 3388 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3389 return ExprError(); 3390 } 3391 } else if (Literal.isFloat) 3392 Ty = Context.FloatTy; 3393 else if (Literal.isLong) 3394 Ty = Context.LongDoubleTy; 3395 else if (Literal.isFloat16) 3396 Ty = Context.Float16Ty; 3397 else if (Literal.isFloat128) 3398 Ty = Context.Float128Ty; 3399 else 3400 Ty = Context.DoubleTy; 3401 3402 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3403 3404 if (Ty == Context.DoubleTy) { 3405 if (getLangOpts().SinglePrecisionConstants) { 3406 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3407 if (BTy->getKind() != BuiltinType::Float) { 3408 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3409 } 3410 } else if (getLangOpts().OpenCL && 3411 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3412 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3413 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3414 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3415 } 3416 } 3417 } else if (!Literal.isIntegerLiteral()) { 3418 return ExprError(); 3419 } else { 3420 QualType Ty; 3421 3422 // 'long long' is a C99 or C++11 feature. 3423 if (!getLangOpts().C99 && Literal.isLongLong) { 3424 if (getLangOpts().CPlusPlus) 3425 Diag(Tok.getLocation(), 3426 getLangOpts().CPlusPlus11 ? 3427 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3428 else 3429 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3430 } 3431 3432 // Get the value in the widest-possible width. 3433 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3434 llvm::APInt ResultVal(MaxWidth, 0); 3435 3436 if (Literal.GetIntegerValue(ResultVal)) { 3437 // If this value didn't fit into uintmax_t, error and force to ull. 3438 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3439 << /* Unsigned */ 1; 3440 Ty = Context.UnsignedLongLongTy; 3441 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3442 "long long is not intmax_t?"); 3443 } else { 3444 // If this value fits into a ULL, try to figure out what else it fits into 3445 // according to the rules of C99 6.4.4.1p5. 3446 3447 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3448 // be an unsigned int. 3449 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3450 3451 // Check from smallest to largest, picking the smallest type we can. 3452 unsigned Width = 0; 3453 3454 // Microsoft specific integer suffixes are explicitly sized. 3455 if (Literal.MicrosoftInteger) { 3456 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3457 Width = 8; 3458 Ty = Context.CharTy; 3459 } else { 3460 Width = Literal.MicrosoftInteger; 3461 Ty = Context.getIntTypeForBitwidth(Width, 3462 /*Signed=*/!Literal.isUnsigned); 3463 } 3464 } 3465 3466 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3467 // Are int/unsigned possibilities? 3468 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3469 3470 // Does it fit in a unsigned int? 3471 if (ResultVal.isIntN(IntSize)) { 3472 // Does it fit in a signed int? 3473 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3474 Ty = Context.IntTy; 3475 else if (AllowUnsigned) 3476 Ty = Context.UnsignedIntTy; 3477 Width = IntSize; 3478 } 3479 } 3480 3481 // Are long/unsigned long possibilities? 3482 if (Ty.isNull() && !Literal.isLongLong) { 3483 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3484 3485 // Does it fit in a unsigned long? 3486 if (ResultVal.isIntN(LongSize)) { 3487 // Does it fit in a signed long? 3488 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3489 Ty = Context.LongTy; 3490 else if (AllowUnsigned) 3491 Ty = Context.UnsignedLongTy; 3492 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3493 // is compatible. 3494 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3495 const unsigned LongLongSize = 3496 Context.getTargetInfo().getLongLongWidth(); 3497 Diag(Tok.getLocation(), 3498 getLangOpts().CPlusPlus 3499 ? Literal.isLong 3500 ? diag::warn_old_implicitly_unsigned_long_cxx 3501 : /*C++98 UB*/ diag:: 3502 ext_old_implicitly_unsigned_long_cxx 3503 : diag::warn_old_implicitly_unsigned_long) 3504 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3505 : /*will be ill-formed*/ 1); 3506 Ty = Context.UnsignedLongTy; 3507 } 3508 Width = LongSize; 3509 } 3510 } 3511 3512 // Check long long if needed. 3513 if (Ty.isNull()) { 3514 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3515 3516 // Does it fit in a unsigned long long? 3517 if (ResultVal.isIntN(LongLongSize)) { 3518 // Does it fit in a signed long long? 3519 // To be compatible with MSVC, hex integer literals ending with the 3520 // LL or i64 suffix are always signed in Microsoft mode. 3521 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3522 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3523 Ty = Context.LongLongTy; 3524 else if (AllowUnsigned) 3525 Ty = Context.UnsignedLongLongTy; 3526 Width = LongLongSize; 3527 } 3528 } 3529 3530 // If we still couldn't decide a type, we probably have something that 3531 // does not fit in a signed long long, but has no U suffix. 3532 if (Ty.isNull()) { 3533 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3534 Ty = Context.UnsignedLongLongTy; 3535 Width = Context.getTargetInfo().getLongLongWidth(); 3536 } 3537 3538 if (ResultVal.getBitWidth() != Width) 3539 ResultVal = ResultVal.trunc(Width); 3540 } 3541 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3542 } 3543 3544 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3545 if (Literal.isImaginary) { 3546 Res = new (Context) ImaginaryLiteral(Res, 3547 Context.getComplexType(Res->getType())); 3548 3549 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3550 } 3551 return Res; 3552 } 3553 3554 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3555 assert(E && "ActOnParenExpr() missing expr"); 3556 return new (Context) ParenExpr(L, R, E); 3557 } 3558 3559 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3560 SourceLocation Loc, 3561 SourceRange ArgRange) { 3562 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3563 // scalar or vector data type argument..." 3564 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3565 // type (C99 6.2.5p18) or void. 3566 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3567 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3568 << T << ArgRange; 3569 return true; 3570 } 3571 3572 assert((T->isVoidType() || !T->isIncompleteType()) && 3573 "Scalar types should always be complete"); 3574 return false; 3575 } 3576 3577 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3578 SourceLocation Loc, 3579 SourceRange ArgRange, 3580 UnaryExprOrTypeTrait TraitKind) { 3581 // Invalid types must be hard errors for SFINAE in C++. 3582 if (S.LangOpts.CPlusPlus) 3583 return true; 3584 3585 // C99 6.5.3.4p1: 3586 if (T->isFunctionType() && 3587 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3588 // sizeof(function)/alignof(function) is allowed as an extension. 3589 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3590 << TraitKind << ArgRange; 3591 return false; 3592 } 3593 3594 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3595 // this is an error (OpenCL v1.1 s6.3.k) 3596 if (T->isVoidType()) { 3597 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3598 : diag::ext_sizeof_alignof_void_type; 3599 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3600 return false; 3601 } 3602 3603 return true; 3604 } 3605 3606 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3607 SourceLocation Loc, 3608 SourceRange ArgRange, 3609 UnaryExprOrTypeTrait TraitKind) { 3610 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3611 // runtime doesn't allow it. 3612 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3613 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3614 << T << (TraitKind == UETT_SizeOf) 3615 << ArgRange; 3616 return true; 3617 } 3618 3619 return false; 3620 } 3621 3622 /// Check whether E is a pointer from a decayed array type (the decayed 3623 /// pointer type is equal to T) and emit a warning if it is. 3624 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3625 Expr *E) { 3626 // Don't warn if the operation changed the type. 3627 if (T != E->getType()) 3628 return; 3629 3630 // Now look for array decays. 3631 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3632 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3633 return; 3634 3635 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3636 << ICE->getType() 3637 << ICE->getSubExpr()->getType(); 3638 } 3639 3640 /// Check the constraints on expression operands to unary type expression 3641 /// and type traits. 3642 /// 3643 /// Completes any types necessary and validates the constraints on the operand 3644 /// expression. The logic mostly mirrors the type-based overload, but may modify 3645 /// the expression as it completes the type for that expression through template 3646 /// instantiation, etc. 3647 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3648 UnaryExprOrTypeTrait ExprKind) { 3649 QualType ExprTy = E->getType(); 3650 assert(!ExprTy->isReferenceType()); 3651 3652 if (ExprKind == UETT_VecStep) 3653 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3654 E->getSourceRange()); 3655 3656 // Whitelist some types as extensions 3657 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3658 E->getSourceRange(), ExprKind)) 3659 return false; 3660 3661 // 'alignof' applied to an expression only requires the base element type of 3662 // the expression to be complete. 'sizeof' requires the expression's type to 3663 // be complete (and will attempt to complete it if it's an array of unknown 3664 // bound). 3665 if (ExprKind == UETT_AlignOf) { 3666 if (RequireCompleteType(E->getExprLoc(), 3667 Context.getBaseElementType(E->getType()), 3668 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3669 E->getSourceRange())) 3670 return true; 3671 } else { 3672 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3673 ExprKind, E->getSourceRange())) 3674 return true; 3675 } 3676 3677 // Completing the expression's type may have changed it. 3678 ExprTy = E->getType(); 3679 assert(!ExprTy->isReferenceType()); 3680 3681 if (ExprTy->isFunctionType()) { 3682 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3683 << ExprKind << E->getSourceRange(); 3684 return true; 3685 } 3686 3687 // The operand for sizeof and alignof is in an unevaluated expression context, 3688 // so side effects could result in unintended consequences. 3689 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3690 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3691 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3692 3693 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3694 E->getSourceRange(), ExprKind)) 3695 return true; 3696 3697 if (ExprKind == UETT_SizeOf) { 3698 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3699 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3700 QualType OType = PVD->getOriginalType(); 3701 QualType Type = PVD->getType(); 3702 if (Type->isPointerType() && OType->isArrayType()) { 3703 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3704 << Type << OType; 3705 Diag(PVD->getLocation(), diag::note_declared_at); 3706 } 3707 } 3708 } 3709 3710 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3711 // decays into a pointer and returns an unintended result. This is most 3712 // likely a typo for "sizeof(array) op x". 3713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3714 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3715 BO->getLHS()); 3716 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3717 BO->getRHS()); 3718 } 3719 } 3720 3721 return false; 3722 } 3723 3724 /// Check the constraints on operands to unary expression and type 3725 /// traits. 3726 /// 3727 /// This will complete any types necessary, and validate the various constraints 3728 /// on those operands. 3729 /// 3730 /// The UsualUnaryConversions() function is *not* called by this routine. 3731 /// C99 6.3.2.1p[2-4] all state: 3732 /// Except when it is the operand of the sizeof operator ... 3733 /// 3734 /// C++ [expr.sizeof]p4 3735 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3736 /// standard conversions are not applied to the operand of sizeof. 3737 /// 3738 /// This policy is followed for all of the unary trait expressions. 3739 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3740 SourceLocation OpLoc, 3741 SourceRange ExprRange, 3742 UnaryExprOrTypeTrait ExprKind) { 3743 if (ExprType->isDependentType()) 3744 return false; 3745 3746 // C++ [expr.sizeof]p2: 3747 // When applied to a reference or a reference type, the result 3748 // is the size of the referenced type. 3749 // C++11 [expr.alignof]p3: 3750 // When alignof is applied to a reference type, the result 3751 // shall be the alignment of the referenced type. 3752 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3753 ExprType = Ref->getPointeeType(); 3754 3755 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3756 // When alignof or _Alignof is applied to an array type, the result 3757 // is the alignment of the element type. 3758 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3759 ExprType = Context.getBaseElementType(ExprType); 3760 3761 if (ExprKind == UETT_VecStep) 3762 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3763 3764 // Whitelist some types as extensions 3765 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3766 ExprKind)) 3767 return false; 3768 3769 if (RequireCompleteType(OpLoc, ExprType, 3770 diag::err_sizeof_alignof_incomplete_type, 3771 ExprKind, ExprRange)) 3772 return true; 3773 3774 if (ExprType->isFunctionType()) { 3775 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3776 << ExprKind << ExprRange; 3777 return true; 3778 } 3779 3780 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3781 ExprKind)) 3782 return true; 3783 3784 return false; 3785 } 3786 3787 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3788 E = E->IgnoreParens(); 3789 3790 // Cannot know anything else if the expression is dependent. 3791 if (E->isTypeDependent()) 3792 return false; 3793 3794 if (E->getObjectKind() == OK_BitField) { 3795 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3796 << 1 << E->getSourceRange(); 3797 return true; 3798 } 3799 3800 ValueDecl *D = nullptr; 3801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3802 D = DRE->getDecl(); 3803 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3804 D = ME->getMemberDecl(); 3805 } 3806 3807 // If it's a field, require the containing struct to have a 3808 // complete definition so that we can compute the layout. 3809 // 3810 // This can happen in C++11 onwards, either by naming the member 3811 // in a way that is not transformed into a member access expression 3812 // (in an unevaluated operand, for instance), or by naming the member 3813 // in a trailing-return-type. 3814 // 3815 // For the record, since __alignof__ on expressions is a GCC 3816 // extension, GCC seems to permit this but always gives the 3817 // nonsensical answer 0. 3818 // 3819 // We don't really need the layout here --- we could instead just 3820 // directly check for all the appropriate alignment-lowing 3821 // attributes --- but that would require duplicating a lot of 3822 // logic that just isn't worth duplicating for such a marginal 3823 // use-case. 3824 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3825 // Fast path this check, since we at least know the record has a 3826 // definition if we can find a member of it. 3827 if (!FD->getParent()->isCompleteDefinition()) { 3828 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3829 << E->getSourceRange(); 3830 return true; 3831 } 3832 3833 // Otherwise, if it's a field, and the field doesn't have 3834 // reference type, then it must have a complete type (or be a 3835 // flexible array member, which we explicitly want to 3836 // white-list anyway), which makes the following checks trivial. 3837 if (!FD->getType()->isReferenceType()) 3838 return false; 3839 } 3840 3841 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3842 } 3843 3844 bool Sema::CheckVecStepExpr(Expr *E) { 3845 E = E->IgnoreParens(); 3846 3847 // Cannot know anything else if the expression is dependent. 3848 if (E->isTypeDependent()) 3849 return false; 3850 3851 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3852 } 3853 3854 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3855 CapturingScopeInfo *CSI) { 3856 assert(T->isVariablyModifiedType()); 3857 assert(CSI != nullptr); 3858 3859 // We're going to walk down into the type and look for VLA expressions. 3860 do { 3861 const Type *Ty = T.getTypePtr(); 3862 switch (Ty->getTypeClass()) { 3863 #define TYPE(Class, Base) 3864 #define ABSTRACT_TYPE(Class, Base) 3865 #define NON_CANONICAL_TYPE(Class, Base) 3866 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3867 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3868 #include "clang/AST/TypeNodes.def" 3869 T = QualType(); 3870 break; 3871 // These types are never variably-modified. 3872 case Type::Builtin: 3873 case Type::Complex: 3874 case Type::Vector: 3875 case Type::ExtVector: 3876 case Type::Record: 3877 case Type::Enum: 3878 case Type::Elaborated: 3879 case Type::TemplateSpecialization: 3880 case Type::ObjCObject: 3881 case Type::ObjCInterface: 3882 case Type::ObjCObjectPointer: 3883 case Type::ObjCTypeParam: 3884 case Type::Pipe: 3885 llvm_unreachable("type class is never variably-modified!"); 3886 case Type::Adjusted: 3887 T = cast<AdjustedType>(Ty)->getOriginalType(); 3888 break; 3889 case Type::Decayed: 3890 T = cast<DecayedType>(Ty)->getPointeeType(); 3891 break; 3892 case Type::Pointer: 3893 T = cast<PointerType>(Ty)->getPointeeType(); 3894 break; 3895 case Type::BlockPointer: 3896 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::LValueReference: 3899 case Type::RValueReference: 3900 T = cast<ReferenceType>(Ty)->getPointeeType(); 3901 break; 3902 case Type::MemberPointer: 3903 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3904 break; 3905 case Type::ConstantArray: 3906 case Type::IncompleteArray: 3907 // Losing element qualification here is fine. 3908 T = cast<ArrayType>(Ty)->getElementType(); 3909 break; 3910 case Type::VariableArray: { 3911 // Losing element qualification here is fine. 3912 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3913 3914 // Unknown size indication requires no size computation. 3915 // Otherwise, evaluate and record it. 3916 if (auto Size = VAT->getSizeExpr()) { 3917 if (!CSI->isVLATypeCaptured(VAT)) { 3918 RecordDecl *CapRecord = nullptr; 3919 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3920 CapRecord = LSI->Lambda; 3921 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3922 CapRecord = CRSI->TheRecordDecl; 3923 } 3924 if (CapRecord) { 3925 auto ExprLoc = Size->getExprLoc(); 3926 auto SizeType = Context.getSizeType(); 3927 // Build the non-static data member. 3928 auto Field = 3929 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3930 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3931 /*BW*/ nullptr, /*Mutable*/ false, 3932 /*InitStyle*/ ICIS_NoInit); 3933 Field->setImplicit(true); 3934 Field->setAccess(AS_private); 3935 Field->setCapturedVLAType(VAT); 3936 CapRecord->addDecl(Field); 3937 3938 CSI->addVLATypeCapture(ExprLoc, SizeType); 3939 } 3940 } 3941 } 3942 T = VAT->getElementType(); 3943 break; 3944 } 3945 case Type::FunctionProto: 3946 case Type::FunctionNoProto: 3947 T = cast<FunctionType>(Ty)->getReturnType(); 3948 break; 3949 case Type::Paren: 3950 case Type::TypeOf: 3951 case Type::UnaryTransform: 3952 case Type::Attributed: 3953 case Type::SubstTemplateTypeParm: 3954 case Type::PackExpansion: 3955 // Keep walking after single level desugaring. 3956 T = T.getSingleStepDesugaredType(Context); 3957 break; 3958 case Type::Typedef: 3959 T = cast<TypedefType>(Ty)->desugar(); 3960 break; 3961 case Type::Decltype: 3962 T = cast<DecltypeType>(Ty)->desugar(); 3963 break; 3964 case Type::Auto: 3965 case Type::DeducedTemplateSpecialization: 3966 T = cast<DeducedType>(Ty)->getDeducedType(); 3967 break; 3968 case Type::TypeOfExpr: 3969 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3970 break; 3971 case Type::Atomic: 3972 T = cast<AtomicType>(Ty)->getValueType(); 3973 break; 3974 } 3975 } while (!T.isNull() && T->isVariablyModifiedType()); 3976 } 3977 3978 /// Build a sizeof or alignof expression given a type operand. 3979 ExprResult 3980 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3981 SourceLocation OpLoc, 3982 UnaryExprOrTypeTrait ExprKind, 3983 SourceRange R) { 3984 if (!TInfo) 3985 return ExprError(); 3986 3987 QualType T = TInfo->getType(); 3988 3989 if (!T->isDependentType() && 3990 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3991 return ExprError(); 3992 3993 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3994 if (auto *TT = T->getAs<TypedefType>()) { 3995 for (auto I = FunctionScopes.rbegin(), 3996 E = std::prev(FunctionScopes.rend()); 3997 I != E; ++I) { 3998 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3999 if (CSI == nullptr) 4000 break; 4001 DeclContext *DC = nullptr; 4002 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4003 DC = LSI->CallOperator; 4004 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4005 DC = CRSI->TheCapturedDecl; 4006 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4007 DC = BSI->TheDecl; 4008 if (DC) { 4009 if (DC->containsDecl(TT->getDecl())) 4010 break; 4011 captureVariablyModifiedType(Context, T, CSI); 4012 } 4013 } 4014 } 4015 } 4016 4017 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4018 return new (Context) UnaryExprOrTypeTraitExpr( 4019 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4020 } 4021 4022 /// Build a sizeof or alignof expression given an expression 4023 /// operand. 4024 ExprResult 4025 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4026 UnaryExprOrTypeTrait ExprKind) { 4027 ExprResult PE = CheckPlaceholderExpr(E); 4028 if (PE.isInvalid()) 4029 return ExprError(); 4030 4031 E = PE.get(); 4032 4033 // Verify that the operand is valid. 4034 bool isInvalid = false; 4035 if (E->isTypeDependent()) { 4036 // Delay type-checking for type-dependent expressions. 4037 } else if (ExprKind == UETT_AlignOf) { 4038 isInvalid = CheckAlignOfExpr(*this, E); 4039 } else if (ExprKind == UETT_VecStep) { 4040 isInvalid = CheckVecStepExpr(E); 4041 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4042 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4043 isInvalid = true; 4044 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4045 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4046 isInvalid = true; 4047 } else { 4048 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4049 } 4050 4051 if (isInvalid) 4052 return ExprError(); 4053 4054 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4055 PE = TransformToPotentiallyEvaluated(E); 4056 if (PE.isInvalid()) return ExprError(); 4057 E = PE.get(); 4058 } 4059 4060 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4061 return new (Context) UnaryExprOrTypeTraitExpr( 4062 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4063 } 4064 4065 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4066 /// expr and the same for @c alignof and @c __alignof 4067 /// Note that the ArgRange is invalid if isType is false. 4068 ExprResult 4069 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4070 UnaryExprOrTypeTrait ExprKind, bool IsType, 4071 void *TyOrEx, SourceRange ArgRange) { 4072 // If error parsing type, ignore. 4073 if (!TyOrEx) return ExprError(); 4074 4075 if (IsType) { 4076 TypeSourceInfo *TInfo; 4077 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4078 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4079 } 4080 4081 Expr *ArgEx = (Expr *)TyOrEx; 4082 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4083 return Result; 4084 } 4085 4086 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4087 bool IsReal) { 4088 if (V.get()->isTypeDependent()) 4089 return S.Context.DependentTy; 4090 4091 // _Real and _Imag are only l-values for normal l-values. 4092 if (V.get()->getObjectKind() != OK_Ordinary) { 4093 V = S.DefaultLvalueConversion(V.get()); 4094 if (V.isInvalid()) 4095 return QualType(); 4096 } 4097 4098 // These operators return the element type of a complex type. 4099 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4100 return CT->getElementType(); 4101 4102 // Otherwise they pass through real integer and floating point types here. 4103 if (V.get()->getType()->isArithmeticType()) 4104 return V.get()->getType(); 4105 4106 // Test for placeholders. 4107 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4108 if (PR.isInvalid()) return QualType(); 4109 if (PR.get() != V.get()) { 4110 V = PR; 4111 return CheckRealImagOperand(S, V, Loc, IsReal); 4112 } 4113 4114 // Reject anything else. 4115 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4116 << (IsReal ? "__real" : "__imag"); 4117 return QualType(); 4118 } 4119 4120 4121 4122 ExprResult 4123 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4124 tok::TokenKind Kind, Expr *Input) { 4125 UnaryOperatorKind Opc; 4126 switch (Kind) { 4127 default: llvm_unreachable("Unknown unary op!"); 4128 case tok::plusplus: Opc = UO_PostInc; break; 4129 case tok::minusminus: Opc = UO_PostDec; break; 4130 } 4131 4132 // Since this might is a postfix expression, get rid of ParenListExprs. 4133 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4134 if (Result.isInvalid()) return ExprError(); 4135 Input = Result.get(); 4136 4137 return BuildUnaryOp(S, OpLoc, Opc, Input); 4138 } 4139 4140 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4141 /// 4142 /// \return true on error 4143 static bool checkArithmeticOnObjCPointer(Sema &S, 4144 SourceLocation opLoc, 4145 Expr *op) { 4146 assert(op->getType()->isObjCObjectPointerType()); 4147 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4148 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4149 return false; 4150 4151 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4152 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4153 << op->getSourceRange(); 4154 return true; 4155 } 4156 4157 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4158 auto *BaseNoParens = Base->IgnoreParens(); 4159 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4160 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4161 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4162 } 4163 4164 ExprResult 4165 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4166 Expr *idx, SourceLocation rbLoc) { 4167 if (base && !base->getType().isNull() && 4168 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4169 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4170 /*Length=*/nullptr, rbLoc); 4171 4172 // Since this might be a postfix expression, get rid of ParenListExprs. 4173 if (isa<ParenListExpr>(base)) { 4174 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4175 if (result.isInvalid()) return ExprError(); 4176 base = result.get(); 4177 } 4178 4179 // Handle any non-overload placeholder types in the base and index 4180 // expressions. We can't handle overloads here because the other 4181 // operand might be an overloadable type, in which case the overload 4182 // resolution for the operator overload should get the first crack 4183 // at the overload. 4184 bool IsMSPropertySubscript = false; 4185 if (base->getType()->isNonOverloadPlaceholderType()) { 4186 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4187 if (!IsMSPropertySubscript) { 4188 ExprResult result = CheckPlaceholderExpr(base); 4189 if (result.isInvalid()) 4190 return ExprError(); 4191 base = result.get(); 4192 } 4193 } 4194 if (idx->getType()->isNonOverloadPlaceholderType()) { 4195 ExprResult result = CheckPlaceholderExpr(idx); 4196 if (result.isInvalid()) return ExprError(); 4197 idx = result.get(); 4198 } 4199 4200 // Build an unanalyzed expression if either operand is type-dependent. 4201 if (getLangOpts().CPlusPlus && 4202 (base->isTypeDependent() || idx->isTypeDependent())) { 4203 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4204 VK_LValue, OK_Ordinary, rbLoc); 4205 } 4206 4207 // MSDN, property (C++) 4208 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4209 // This attribute can also be used in the declaration of an empty array in a 4210 // class or structure definition. For example: 4211 // __declspec(property(get=GetX, put=PutX)) int x[]; 4212 // The above statement indicates that x[] can be used with one or more array 4213 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4214 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4215 if (IsMSPropertySubscript) { 4216 // Build MS property subscript expression if base is MS property reference 4217 // or MS property subscript. 4218 return new (Context) MSPropertySubscriptExpr( 4219 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4220 } 4221 4222 // Use C++ overloaded-operator rules if either operand has record 4223 // type. The spec says to do this if either type is *overloadable*, 4224 // but enum types can't declare subscript operators or conversion 4225 // operators, so there's nothing interesting for overload resolution 4226 // to do if there aren't any record types involved. 4227 // 4228 // ObjC pointers have their own subscripting logic that is not tied 4229 // to overload resolution and so should not take this path. 4230 if (getLangOpts().CPlusPlus && 4231 (base->getType()->isRecordType() || 4232 (!base->getType()->isObjCObjectPointerType() && 4233 idx->getType()->isRecordType()))) { 4234 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4235 } 4236 4237 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4238 } 4239 4240 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4241 Expr *LowerBound, 4242 SourceLocation ColonLoc, Expr *Length, 4243 SourceLocation RBLoc) { 4244 if (Base->getType()->isPlaceholderType() && 4245 !Base->getType()->isSpecificPlaceholderType( 4246 BuiltinType::OMPArraySection)) { 4247 ExprResult Result = CheckPlaceholderExpr(Base); 4248 if (Result.isInvalid()) 4249 return ExprError(); 4250 Base = Result.get(); 4251 } 4252 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4253 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4254 if (Result.isInvalid()) 4255 return ExprError(); 4256 Result = DefaultLvalueConversion(Result.get()); 4257 if (Result.isInvalid()) 4258 return ExprError(); 4259 LowerBound = Result.get(); 4260 } 4261 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4262 ExprResult Result = CheckPlaceholderExpr(Length); 4263 if (Result.isInvalid()) 4264 return ExprError(); 4265 Result = DefaultLvalueConversion(Result.get()); 4266 if (Result.isInvalid()) 4267 return ExprError(); 4268 Length = Result.get(); 4269 } 4270 4271 // Build an unanalyzed expression if either operand is type-dependent. 4272 if (Base->isTypeDependent() || 4273 (LowerBound && 4274 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4275 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4276 return new (Context) 4277 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4278 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4279 } 4280 4281 // Perform default conversions. 4282 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4283 QualType ResultTy; 4284 if (OriginalTy->isAnyPointerType()) { 4285 ResultTy = OriginalTy->getPointeeType(); 4286 } else if (OriginalTy->isArrayType()) { 4287 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4288 } else { 4289 return ExprError( 4290 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4291 << Base->getSourceRange()); 4292 } 4293 // C99 6.5.2.1p1 4294 if (LowerBound) { 4295 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4296 LowerBound); 4297 if (Res.isInvalid()) 4298 return ExprError(Diag(LowerBound->getExprLoc(), 4299 diag::err_omp_typecheck_section_not_integer) 4300 << 0 << LowerBound->getSourceRange()); 4301 LowerBound = Res.get(); 4302 4303 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4304 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4305 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4306 << 0 << LowerBound->getSourceRange(); 4307 } 4308 if (Length) { 4309 auto Res = 4310 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4311 if (Res.isInvalid()) 4312 return ExprError(Diag(Length->getExprLoc(), 4313 diag::err_omp_typecheck_section_not_integer) 4314 << 1 << Length->getSourceRange()); 4315 Length = Res.get(); 4316 4317 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4318 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4319 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4320 << 1 << Length->getSourceRange(); 4321 } 4322 4323 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4324 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4325 // type. Note that functions are not objects, and that (in C99 parlance) 4326 // incomplete types are not object types. 4327 if (ResultTy->isFunctionType()) { 4328 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4329 << ResultTy << Base->getSourceRange(); 4330 return ExprError(); 4331 } 4332 4333 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4334 diag::err_omp_section_incomplete_type, Base)) 4335 return ExprError(); 4336 4337 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4338 llvm::APSInt LowerBoundValue; 4339 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4340 // OpenMP 4.5, [2.4 Array Sections] 4341 // The array section must be a subset of the original array. 4342 if (LowerBoundValue.isNegative()) { 4343 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4344 << LowerBound->getSourceRange(); 4345 return ExprError(); 4346 } 4347 } 4348 } 4349 4350 if (Length) { 4351 llvm::APSInt LengthValue; 4352 if (Length->EvaluateAsInt(LengthValue, Context)) { 4353 // OpenMP 4.5, [2.4 Array Sections] 4354 // The length must evaluate to non-negative integers. 4355 if (LengthValue.isNegative()) { 4356 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4357 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4358 << Length->getSourceRange(); 4359 return ExprError(); 4360 } 4361 } 4362 } else if (ColonLoc.isValid() && 4363 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4364 !OriginalTy->isVariableArrayType()))) { 4365 // OpenMP 4.5, [2.4 Array Sections] 4366 // When the size of the array dimension is not known, the length must be 4367 // specified explicitly. 4368 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4369 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4370 return ExprError(); 4371 } 4372 4373 if (!Base->getType()->isSpecificPlaceholderType( 4374 BuiltinType::OMPArraySection)) { 4375 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4376 if (Result.isInvalid()) 4377 return ExprError(); 4378 Base = Result.get(); 4379 } 4380 return new (Context) 4381 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4382 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4383 } 4384 4385 ExprResult 4386 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4387 Expr *Idx, SourceLocation RLoc) { 4388 Expr *LHSExp = Base; 4389 Expr *RHSExp = Idx; 4390 4391 ExprValueKind VK = VK_LValue; 4392 ExprObjectKind OK = OK_Ordinary; 4393 4394 // Per C++ core issue 1213, the result is an xvalue if either operand is 4395 // a non-lvalue array, and an lvalue otherwise. 4396 if (getLangOpts().CPlusPlus11) { 4397 for (auto *Op : {LHSExp, RHSExp}) { 4398 Op = Op->IgnoreImplicit(); 4399 if (Op->getType()->isArrayType() && !Op->isLValue()) 4400 VK = VK_XValue; 4401 } 4402 } 4403 4404 // Perform default conversions. 4405 if (!LHSExp->getType()->getAs<VectorType>()) { 4406 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4407 if (Result.isInvalid()) 4408 return ExprError(); 4409 LHSExp = Result.get(); 4410 } 4411 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4412 if (Result.isInvalid()) 4413 return ExprError(); 4414 RHSExp = Result.get(); 4415 4416 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4417 4418 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4419 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4420 // in the subscript position. As a result, we need to derive the array base 4421 // and index from the expression types. 4422 Expr *BaseExpr, *IndexExpr; 4423 QualType ResultType; 4424 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 ResultType = Context.DependentTy; 4428 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4429 BaseExpr = LHSExp; 4430 IndexExpr = RHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 } else if (const ObjCObjectPointerType *PTy = 4433 LHSTy->getAs<ObjCObjectPointerType>()) { 4434 BaseExpr = LHSExp; 4435 IndexExpr = RHSExp; 4436 4437 // Use custom logic if this should be the pseudo-object subscript 4438 // expression. 4439 if (!LangOpts.isSubscriptPointerArithmetic()) 4440 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4441 nullptr); 4442 4443 ResultType = PTy->getPointeeType(); 4444 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4445 // Handle the uncommon case of "123[Ptr]". 4446 BaseExpr = RHSExp; 4447 IndexExpr = LHSExp; 4448 ResultType = PTy->getPointeeType(); 4449 } else if (const ObjCObjectPointerType *PTy = 4450 RHSTy->getAs<ObjCObjectPointerType>()) { 4451 // Handle the uncommon case of "123[Ptr]". 4452 BaseExpr = RHSExp; 4453 IndexExpr = LHSExp; 4454 ResultType = PTy->getPointeeType(); 4455 if (!LangOpts.isSubscriptPointerArithmetic()) { 4456 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4457 << ResultType << BaseExpr->getSourceRange(); 4458 return ExprError(); 4459 } 4460 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4461 BaseExpr = LHSExp; // vectors: V[123] 4462 IndexExpr = RHSExp; 4463 // We apply C++ DR1213 to vector subscripting too. 4464 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4465 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4466 if (Materialized.isInvalid()) 4467 return ExprError(); 4468 LHSExp = Materialized.get(); 4469 } 4470 VK = LHSExp->getValueKind(); 4471 if (VK != VK_RValue) 4472 OK = OK_VectorComponent; 4473 4474 ResultType = VTy->getElementType(); 4475 QualType BaseType = BaseExpr->getType(); 4476 Qualifiers BaseQuals = BaseType.getQualifiers(); 4477 Qualifiers MemberQuals = ResultType.getQualifiers(); 4478 Qualifiers Combined = BaseQuals + MemberQuals; 4479 if (Combined != MemberQuals) 4480 ResultType = Context.getQualifiedType(ResultType, Combined); 4481 } else if (LHSTy->isArrayType()) { 4482 // If we see an array that wasn't promoted by 4483 // DefaultFunctionArrayLvalueConversion, it must be an array that 4484 // wasn't promoted because of the C90 rule that doesn't 4485 // allow promoting non-lvalue arrays. Warn, then 4486 // force the promotion here. 4487 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4488 << LHSExp->getSourceRange(); 4489 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4490 CK_ArrayToPointerDecay).get(); 4491 LHSTy = LHSExp->getType(); 4492 4493 BaseExpr = LHSExp; 4494 IndexExpr = RHSExp; 4495 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4496 } else if (RHSTy->isArrayType()) { 4497 // Same as previous, except for 123[f().a] case 4498 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4499 << RHSExp->getSourceRange(); 4500 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4501 CK_ArrayToPointerDecay).get(); 4502 RHSTy = RHSExp->getType(); 4503 4504 BaseExpr = RHSExp; 4505 IndexExpr = LHSExp; 4506 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4507 } else { 4508 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4509 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4510 } 4511 // C99 6.5.2.1p1 4512 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4513 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4514 << IndexExpr->getSourceRange()); 4515 4516 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4517 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4518 && !IndexExpr->isTypeDependent()) 4519 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4520 4521 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4522 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4523 // type. Note that Functions are not objects, and that (in C99 parlance) 4524 // incomplete types are not object types. 4525 if (ResultType->isFunctionType()) { 4526 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4527 << ResultType << BaseExpr->getSourceRange(); 4528 return ExprError(); 4529 } 4530 4531 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4532 // GNU extension: subscripting on pointer to void 4533 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4534 << BaseExpr->getSourceRange(); 4535 4536 // C forbids expressions of unqualified void type from being l-values. 4537 // See IsCForbiddenLValueType. 4538 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4539 } else if (!ResultType->isDependentType() && 4540 RequireCompleteType(LLoc, ResultType, 4541 diag::err_subscript_incomplete_type, BaseExpr)) 4542 return ExprError(); 4543 4544 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4545 !ResultType.isCForbiddenLValueType()); 4546 4547 return new (Context) 4548 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4549 } 4550 4551 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4552 ParmVarDecl *Param) { 4553 if (Param->hasUnparsedDefaultArg()) { 4554 Diag(CallLoc, 4555 diag::err_use_of_default_argument_to_function_declared_later) << 4556 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4557 Diag(UnparsedDefaultArgLocs[Param], 4558 diag::note_default_argument_declared_here); 4559 return true; 4560 } 4561 4562 if (Param->hasUninstantiatedDefaultArg()) { 4563 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4564 4565 EnterExpressionEvaluationContext EvalContext( 4566 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4567 4568 // Instantiate the expression. 4569 // 4570 // FIXME: Pass in a correct Pattern argument, otherwise 4571 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4572 // 4573 // template<typename T> 4574 // struct A { 4575 // static int FooImpl(); 4576 // 4577 // template<typename Tp> 4578 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4579 // // template argument list [[T], [Tp]], should be [[Tp]]. 4580 // friend A<Tp> Foo(int a); 4581 // }; 4582 // 4583 // template<typename T> 4584 // A<T> Foo(int a = A<T>::FooImpl()); 4585 MultiLevelTemplateArgumentList MutiLevelArgList 4586 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4587 4588 InstantiatingTemplate Inst(*this, CallLoc, Param, 4589 MutiLevelArgList.getInnermost()); 4590 if (Inst.isInvalid()) 4591 return true; 4592 if (Inst.isAlreadyInstantiating()) { 4593 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4594 Param->setInvalidDecl(); 4595 return true; 4596 } 4597 4598 ExprResult Result; 4599 { 4600 // C++ [dcl.fct.default]p5: 4601 // The names in the [default argument] expression are bound, and 4602 // the semantic constraints are checked, at the point where the 4603 // default argument expression appears. 4604 ContextRAII SavedContext(*this, FD); 4605 LocalInstantiationScope Local(*this); 4606 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4607 /*DirectInit*/false); 4608 } 4609 if (Result.isInvalid()) 4610 return true; 4611 4612 // Check the expression as an initializer for the parameter. 4613 InitializedEntity Entity 4614 = InitializedEntity::InitializeParameter(Context, Param); 4615 InitializationKind Kind = InitializationKind::CreateCopy( 4616 Param->getLocation(), 4617 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4618 Expr *ResultE = Result.getAs<Expr>(); 4619 4620 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4621 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4622 if (Result.isInvalid()) 4623 return true; 4624 4625 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4626 Param->getOuterLocStart()); 4627 if (Result.isInvalid()) 4628 return true; 4629 4630 // Remember the instantiated default argument. 4631 Param->setDefaultArg(Result.getAs<Expr>()); 4632 if (ASTMutationListener *L = getASTMutationListener()) { 4633 L->DefaultArgumentInstantiated(Param); 4634 } 4635 } 4636 4637 // If the default argument expression is not set yet, we are building it now. 4638 if (!Param->hasInit()) { 4639 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4640 Param->setInvalidDecl(); 4641 return true; 4642 } 4643 4644 // If the default expression creates temporaries, we need to 4645 // push them to the current stack of expression temporaries so they'll 4646 // be properly destroyed. 4647 // FIXME: We should really be rebuilding the default argument with new 4648 // bound temporaries; see the comment in PR5810. 4649 // We don't need to do that with block decls, though, because 4650 // blocks in default argument expression can never capture anything. 4651 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4652 // Set the "needs cleanups" bit regardless of whether there are 4653 // any explicit objects. 4654 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4655 4656 // Append all the objects to the cleanup list. Right now, this 4657 // should always be a no-op, because blocks in default argument 4658 // expressions should never be able to capture anything. 4659 assert(!Init->getNumObjects() && 4660 "default argument expression has capturing blocks?"); 4661 } 4662 4663 // We already type-checked the argument, so we know it works. 4664 // Just mark all of the declarations in this potentially-evaluated expression 4665 // as being "referenced". 4666 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4667 /*SkipLocalVariables=*/true); 4668 return false; 4669 } 4670 4671 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4672 FunctionDecl *FD, ParmVarDecl *Param) { 4673 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4674 return ExprError(); 4675 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4676 } 4677 4678 Sema::VariadicCallType 4679 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4680 Expr *Fn) { 4681 if (Proto && Proto->isVariadic()) { 4682 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4683 return VariadicConstructor; 4684 else if (Fn && Fn->getType()->isBlockPointerType()) 4685 return VariadicBlock; 4686 else if (FDecl) { 4687 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4688 if (Method->isInstance()) 4689 return VariadicMethod; 4690 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4691 return VariadicMethod; 4692 return VariadicFunction; 4693 } 4694 return VariadicDoesNotApply; 4695 } 4696 4697 namespace { 4698 class FunctionCallCCC : public FunctionCallFilterCCC { 4699 public: 4700 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4701 unsigned NumArgs, MemberExpr *ME) 4702 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4703 FunctionName(FuncName) {} 4704 4705 bool ValidateCandidate(const TypoCorrection &candidate) override { 4706 if (!candidate.getCorrectionSpecifier() || 4707 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4708 return false; 4709 } 4710 4711 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4712 } 4713 4714 private: 4715 const IdentifierInfo *const FunctionName; 4716 }; 4717 } 4718 4719 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4720 FunctionDecl *FDecl, 4721 ArrayRef<Expr *> Args) { 4722 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4723 DeclarationName FuncName = FDecl->getDeclName(); 4724 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4725 4726 if (TypoCorrection Corrected = S.CorrectTypo( 4727 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4728 S.getScopeForContext(S.CurContext), nullptr, 4729 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4730 Args.size(), ME), 4731 Sema::CTK_ErrorRecovery)) { 4732 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4733 if (Corrected.isOverloaded()) { 4734 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4735 OverloadCandidateSet::iterator Best; 4736 for (NamedDecl *CD : Corrected) { 4737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4738 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4739 OCS); 4740 } 4741 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4742 case OR_Success: 4743 ND = Best->FoundDecl; 4744 Corrected.setCorrectionDecl(ND); 4745 break; 4746 default: 4747 break; 4748 } 4749 } 4750 ND = ND->getUnderlyingDecl(); 4751 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4752 return Corrected; 4753 } 4754 } 4755 return TypoCorrection(); 4756 } 4757 4758 /// ConvertArgumentsForCall - Converts the arguments specified in 4759 /// Args/NumArgs to the parameter types of the function FDecl with 4760 /// function prototype Proto. Call is the call expression itself, and 4761 /// Fn is the function expression. For a C++ member function, this 4762 /// routine does not attempt to convert the object argument. Returns 4763 /// true if the call is ill-formed. 4764 bool 4765 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4766 FunctionDecl *FDecl, 4767 const FunctionProtoType *Proto, 4768 ArrayRef<Expr *> Args, 4769 SourceLocation RParenLoc, 4770 bool IsExecConfig) { 4771 // Bail out early if calling a builtin with custom typechecking. 4772 if (FDecl) 4773 if (unsigned ID = FDecl->getBuiltinID()) 4774 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4775 return false; 4776 4777 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4778 // assignment, to the types of the corresponding parameter, ... 4779 unsigned NumParams = Proto->getNumParams(); 4780 bool Invalid = false; 4781 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4782 unsigned FnKind = Fn->getType()->isBlockPointerType() 4783 ? 1 /* block */ 4784 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4785 : 0 /* function */); 4786 4787 // If too few arguments are available (and we don't have default 4788 // arguments for the remaining parameters), don't make the call. 4789 if (Args.size() < NumParams) { 4790 if (Args.size() < MinArgs) { 4791 TypoCorrection TC; 4792 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4793 unsigned diag_id = 4794 MinArgs == NumParams && !Proto->isVariadic() 4795 ? diag::err_typecheck_call_too_few_args_suggest 4796 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4797 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4798 << static_cast<unsigned>(Args.size()) 4799 << TC.getCorrectionRange()); 4800 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4801 Diag(RParenLoc, 4802 MinArgs == NumParams && !Proto->isVariadic() 4803 ? diag::err_typecheck_call_too_few_args_one 4804 : diag::err_typecheck_call_too_few_args_at_least_one) 4805 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4806 else 4807 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4808 ? diag::err_typecheck_call_too_few_args 4809 : diag::err_typecheck_call_too_few_args_at_least) 4810 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4811 << Fn->getSourceRange(); 4812 4813 // Emit the location of the prototype. 4814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4815 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4816 4817 return true; 4818 } 4819 Call->setNumArgs(Context, NumParams); 4820 } 4821 4822 // If too many are passed and not variadic, error on the extras and drop 4823 // them. 4824 if (Args.size() > NumParams) { 4825 if (!Proto->isVariadic()) { 4826 TypoCorrection TC; 4827 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4828 unsigned diag_id = 4829 MinArgs == NumParams && !Proto->isVariadic() 4830 ? diag::err_typecheck_call_too_many_args_suggest 4831 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4832 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4833 << static_cast<unsigned>(Args.size()) 4834 << TC.getCorrectionRange()); 4835 } else if (NumParams == 1 && FDecl && 4836 FDecl->getParamDecl(0)->getDeclName()) 4837 Diag(Args[NumParams]->getBeginLoc(), 4838 MinArgs == NumParams 4839 ? diag::err_typecheck_call_too_many_args_one 4840 : diag::err_typecheck_call_too_many_args_at_most_one) 4841 << FnKind << FDecl->getParamDecl(0) 4842 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4843 << SourceRange(Args[NumParams]->getBeginLoc(), 4844 Args.back()->getEndLoc()); 4845 else 4846 Diag(Args[NumParams]->getBeginLoc(), 4847 MinArgs == NumParams 4848 ? diag::err_typecheck_call_too_many_args 4849 : diag::err_typecheck_call_too_many_args_at_most) 4850 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4851 << Fn->getSourceRange() 4852 << SourceRange(Args[NumParams]->getBeginLoc(), 4853 Args.back()->getEndLoc()); 4854 4855 // Emit the location of the prototype. 4856 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4857 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4858 4859 // This deletes the extra arguments. 4860 Call->setNumArgs(Context, NumParams); 4861 return true; 4862 } 4863 } 4864 SmallVector<Expr *, 8> AllArgs; 4865 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4866 4867 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4868 AllArgs, CallType); 4869 if (Invalid) 4870 return true; 4871 unsigned TotalNumArgs = AllArgs.size(); 4872 for (unsigned i = 0; i < TotalNumArgs; ++i) 4873 Call->setArg(i, AllArgs[i]); 4874 4875 return false; 4876 } 4877 4878 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4879 const FunctionProtoType *Proto, 4880 unsigned FirstParam, ArrayRef<Expr *> Args, 4881 SmallVectorImpl<Expr *> &AllArgs, 4882 VariadicCallType CallType, bool AllowExplicit, 4883 bool IsListInitialization) { 4884 unsigned NumParams = Proto->getNumParams(); 4885 bool Invalid = false; 4886 size_t ArgIx = 0; 4887 // Continue to check argument types (even if we have too few/many args). 4888 for (unsigned i = FirstParam; i < NumParams; i++) { 4889 QualType ProtoArgType = Proto->getParamType(i); 4890 4891 Expr *Arg; 4892 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4893 if (ArgIx < Args.size()) { 4894 Arg = Args[ArgIx++]; 4895 4896 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4897 diag::err_call_incomplete_argument, Arg)) 4898 return true; 4899 4900 // Strip the unbridged-cast placeholder expression off, if applicable. 4901 bool CFAudited = false; 4902 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4903 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4904 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4905 Arg = stripARCUnbridgedCast(Arg); 4906 else if (getLangOpts().ObjCAutoRefCount && 4907 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4908 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4909 CFAudited = true; 4910 4911 if (Proto->getExtParameterInfo(i).isNoEscape()) 4912 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4913 BE->getBlockDecl()->setDoesNotEscape(); 4914 4915 InitializedEntity Entity = 4916 Param ? InitializedEntity::InitializeParameter(Context, Param, 4917 ProtoArgType) 4918 : InitializedEntity::InitializeParameter( 4919 Context, ProtoArgType, Proto->isParamConsumed(i)); 4920 4921 // Remember that parameter belongs to a CF audited API. 4922 if (CFAudited) 4923 Entity.setParameterCFAudited(); 4924 4925 ExprResult ArgE = PerformCopyInitialization( 4926 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4927 if (ArgE.isInvalid()) 4928 return true; 4929 4930 Arg = ArgE.getAs<Expr>(); 4931 } else { 4932 assert(Param && "can't use default arguments without a known callee"); 4933 4934 ExprResult ArgExpr = 4935 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4936 if (ArgExpr.isInvalid()) 4937 return true; 4938 4939 Arg = ArgExpr.getAs<Expr>(); 4940 } 4941 4942 // Check for array bounds violations for each argument to the call. This 4943 // check only triggers warnings when the argument isn't a more complex Expr 4944 // with its own checking, such as a BinaryOperator. 4945 CheckArrayAccess(Arg); 4946 4947 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4948 CheckStaticArrayArgument(CallLoc, Param, Arg); 4949 4950 AllArgs.push_back(Arg); 4951 } 4952 4953 // If this is a variadic call, handle args passed through "...". 4954 if (CallType != VariadicDoesNotApply) { 4955 // Assume that extern "C" functions with variadic arguments that 4956 // return __unknown_anytype aren't *really* variadic. 4957 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4958 FDecl->isExternC()) { 4959 for (Expr *A : Args.slice(ArgIx)) { 4960 QualType paramType; // ignored 4961 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4962 Invalid |= arg.isInvalid(); 4963 AllArgs.push_back(arg.get()); 4964 } 4965 4966 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4967 } else { 4968 for (Expr *A : Args.slice(ArgIx)) { 4969 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4970 Invalid |= Arg.isInvalid(); 4971 AllArgs.push_back(Arg.get()); 4972 } 4973 } 4974 4975 // Check for array bounds violations. 4976 for (Expr *A : Args.slice(ArgIx)) 4977 CheckArrayAccess(A); 4978 } 4979 return Invalid; 4980 } 4981 4982 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4983 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4984 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4985 TL = DTL.getOriginalLoc(); 4986 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4987 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4988 << ATL.getLocalSourceRange(); 4989 } 4990 4991 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4992 /// array parameter, check that it is non-null, and that if it is formed by 4993 /// array-to-pointer decay, the underlying array is sufficiently large. 4994 /// 4995 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4996 /// array type derivation, then for each call to the function, the value of the 4997 /// corresponding actual argument shall provide access to the first element of 4998 /// an array with at least as many elements as specified by the size expression. 4999 void 5000 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5001 ParmVarDecl *Param, 5002 const Expr *ArgExpr) { 5003 // Static array parameters are not supported in C++. 5004 if (!Param || getLangOpts().CPlusPlus) 5005 return; 5006 5007 QualType OrigTy = Param->getOriginalType(); 5008 5009 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5010 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5011 return; 5012 5013 if (ArgExpr->isNullPointerConstant(Context, 5014 Expr::NPC_NeverValueDependent)) { 5015 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5016 DiagnoseCalleeStaticArrayParam(*this, Param); 5017 return; 5018 } 5019 5020 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5021 if (!CAT) 5022 return; 5023 5024 const ConstantArrayType *ArgCAT = 5025 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5026 if (!ArgCAT) 5027 return; 5028 5029 if (ArgCAT->getSize().ult(CAT->getSize())) { 5030 Diag(CallLoc, diag::warn_static_array_too_small) 5031 << ArgExpr->getSourceRange() 5032 << (unsigned) ArgCAT->getSize().getZExtValue() 5033 << (unsigned) CAT->getSize().getZExtValue(); 5034 DiagnoseCalleeStaticArrayParam(*this, Param); 5035 } 5036 } 5037 5038 /// Given a function expression of unknown-any type, try to rebuild it 5039 /// to have a function type. 5040 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5041 5042 /// Is the given type a placeholder that we need to lower out 5043 /// immediately during argument processing? 5044 static bool isPlaceholderToRemoveAsArg(QualType type) { 5045 // Placeholders are never sugared. 5046 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5047 if (!placeholder) return false; 5048 5049 switch (placeholder->getKind()) { 5050 // Ignore all the non-placeholder types. 5051 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5052 case BuiltinType::Id: 5053 #include "clang/Basic/OpenCLImageTypes.def" 5054 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5055 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5056 #include "clang/AST/BuiltinTypes.def" 5057 return false; 5058 5059 // We cannot lower out overload sets; they might validly be resolved 5060 // by the call machinery. 5061 case BuiltinType::Overload: 5062 return false; 5063 5064 // Unbridged casts in ARC can be handled in some call positions and 5065 // should be left in place. 5066 case BuiltinType::ARCUnbridgedCast: 5067 return false; 5068 5069 // Pseudo-objects should be converted as soon as possible. 5070 case BuiltinType::PseudoObject: 5071 return true; 5072 5073 // The debugger mode could theoretically but currently does not try 5074 // to resolve unknown-typed arguments based on known parameter types. 5075 case BuiltinType::UnknownAny: 5076 return true; 5077 5078 // These are always invalid as call arguments and should be reported. 5079 case BuiltinType::BoundMember: 5080 case BuiltinType::BuiltinFn: 5081 case BuiltinType::OMPArraySection: 5082 return true; 5083 5084 } 5085 llvm_unreachable("bad builtin type kind"); 5086 } 5087 5088 /// Check an argument list for placeholders that we won't try to 5089 /// handle later. 5090 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5091 // Apply this processing to all the arguments at once instead of 5092 // dying at the first failure. 5093 bool hasInvalid = false; 5094 for (size_t i = 0, e = args.size(); i != e; i++) { 5095 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5096 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5097 if (result.isInvalid()) hasInvalid = true; 5098 else args[i] = result.get(); 5099 } else if (hasInvalid) { 5100 (void)S.CorrectDelayedTyposInExpr(args[i]); 5101 } 5102 } 5103 return hasInvalid; 5104 } 5105 5106 /// If a builtin function has a pointer argument with no explicit address 5107 /// space, then it should be able to accept a pointer to any address 5108 /// space as input. In order to do this, we need to replace the 5109 /// standard builtin declaration with one that uses the same address space 5110 /// as the call. 5111 /// 5112 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5113 /// it does not contain any pointer arguments without 5114 /// an address space qualifer. Otherwise the rewritten 5115 /// FunctionDecl is returned. 5116 /// TODO: Handle pointer return types. 5117 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5118 const FunctionDecl *FDecl, 5119 MultiExprArg ArgExprs) { 5120 5121 QualType DeclType = FDecl->getType(); 5122 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5123 5124 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5125 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5126 return nullptr; 5127 5128 bool NeedsNewDecl = false; 5129 unsigned i = 0; 5130 SmallVector<QualType, 8> OverloadParams; 5131 5132 for (QualType ParamType : FT->param_types()) { 5133 5134 // Convert array arguments to pointer to simplify type lookup. 5135 ExprResult ArgRes = 5136 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5137 if (ArgRes.isInvalid()) 5138 return nullptr; 5139 Expr *Arg = ArgRes.get(); 5140 QualType ArgType = Arg->getType(); 5141 if (!ParamType->isPointerType() || 5142 ParamType.getQualifiers().hasAddressSpace() || 5143 !ArgType->isPointerType() || 5144 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5145 OverloadParams.push_back(ParamType); 5146 continue; 5147 } 5148 5149 QualType PointeeType = ParamType->getPointeeType(); 5150 if (PointeeType.getQualifiers().hasAddressSpace()) 5151 continue; 5152 5153 NeedsNewDecl = true; 5154 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5155 5156 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5157 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5158 } 5159 5160 if (!NeedsNewDecl) 5161 return nullptr; 5162 5163 FunctionProtoType::ExtProtoInfo EPI; 5164 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5165 OverloadParams, EPI); 5166 DeclContext *Parent = Context.getTranslationUnitDecl(); 5167 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5168 FDecl->getLocation(), 5169 FDecl->getLocation(), 5170 FDecl->getIdentifier(), 5171 OverloadTy, 5172 /*TInfo=*/nullptr, 5173 SC_Extern, false, 5174 /*hasPrototype=*/true); 5175 SmallVector<ParmVarDecl*, 16> Params; 5176 FT = cast<FunctionProtoType>(OverloadTy); 5177 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5178 QualType ParamType = FT->getParamType(i); 5179 ParmVarDecl *Parm = 5180 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5181 SourceLocation(), nullptr, ParamType, 5182 /*TInfo=*/nullptr, SC_None, nullptr); 5183 Parm->setScopeInfo(0, i); 5184 Params.push_back(Parm); 5185 } 5186 OverloadDecl->setParams(Params); 5187 return OverloadDecl; 5188 } 5189 5190 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5191 FunctionDecl *Callee, 5192 MultiExprArg ArgExprs) { 5193 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5194 // similar attributes) really don't like it when functions are called with an 5195 // invalid number of args. 5196 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5197 /*PartialOverloading=*/false) && 5198 !Callee->isVariadic()) 5199 return; 5200 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5201 return; 5202 5203 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5204 S.Diag(Fn->getBeginLoc(), 5205 isa<CXXMethodDecl>(Callee) 5206 ? diag::err_ovl_no_viable_member_function_in_call 5207 : diag::err_ovl_no_viable_function_in_call) 5208 << Callee << Callee->getSourceRange(); 5209 S.Diag(Callee->getLocation(), 5210 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5211 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5212 return; 5213 } 5214 } 5215 5216 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5217 const UnresolvedMemberExpr *const UME, Sema &S) { 5218 5219 const auto GetFunctionLevelDCIfCXXClass = 5220 [](Sema &S) -> const CXXRecordDecl * { 5221 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5222 if (!DC || !DC->getParent()) 5223 return nullptr; 5224 5225 // If the call to some member function was made from within a member 5226 // function body 'M' return return 'M's parent. 5227 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5228 return MD->getParent()->getCanonicalDecl(); 5229 // else the call was made from within a default member initializer of a 5230 // class, so return the class. 5231 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5232 return RD->getCanonicalDecl(); 5233 return nullptr; 5234 }; 5235 // If our DeclContext is neither a member function nor a class (in the 5236 // case of a lambda in a default member initializer), we can't have an 5237 // enclosing 'this'. 5238 5239 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5240 if (!CurParentClass) 5241 return false; 5242 5243 // The naming class for implicit member functions call is the class in which 5244 // name lookup starts. 5245 const CXXRecordDecl *const NamingClass = 5246 UME->getNamingClass()->getCanonicalDecl(); 5247 assert(NamingClass && "Must have naming class even for implicit access"); 5248 5249 // If the unresolved member functions were found in a 'naming class' that is 5250 // related (either the same or derived from) to the class that contains the 5251 // member function that itself contained the implicit member access. 5252 5253 return CurParentClass == NamingClass || 5254 CurParentClass->isDerivedFrom(NamingClass); 5255 } 5256 5257 static void 5258 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5259 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5260 5261 if (!UME) 5262 return; 5263 5264 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5265 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5266 // already been captured, or if this is an implicit member function call (if 5267 // it isn't, an attempt to capture 'this' should already have been made). 5268 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5269 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5270 return; 5271 5272 // Check if the naming class in which the unresolved members were found is 5273 // related (same as or is a base of) to the enclosing class. 5274 5275 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5276 return; 5277 5278 5279 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5280 // If the enclosing function is not dependent, then this lambda is 5281 // capture ready, so if we can capture this, do so. 5282 if (!EnclosingFunctionCtx->isDependentContext()) { 5283 // If the current lambda and all enclosing lambdas can capture 'this' - 5284 // then go ahead and capture 'this' (since our unresolved overload set 5285 // contains at least one non-static member function). 5286 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5287 S.CheckCXXThisCapture(CallLoc); 5288 } else if (S.CurContext->isDependentContext()) { 5289 // ... since this is an implicit member reference, that might potentially 5290 // involve a 'this' capture, mark 'this' for potential capture in 5291 // enclosing lambdas. 5292 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5293 CurLSI->addPotentialThisCapture(CallLoc); 5294 } 5295 } 5296 5297 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5298 /// This provides the location of the left/right parens and a list of comma 5299 /// locations. 5300 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5301 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5302 Expr *ExecConfig, bool IsExecConfig) { 5303 // Since this might be a postfix expression, get rid of ParenListExprs. 5304 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5305 if (Result.isInvalid()) return ExprError(); 5306 Fn = Result.get(); 5307 5308 if (checkArgsForPlaceholders(*this, ArgExprs)) 5309 return ExprError(); 5310 5311 if (getLangOpts().CPlusPlus) { 5312 // If this is a pseudo-destructor expression, build the call immediately. 5313 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5314 if (!ArgExprs.empty()) { 5315 // Pseudo-destructor calls should not have any arguments. 5316 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5317 << FixItHint::CreateRemoval( 5318 SourceRange(ArgExprs.front()->getBeginLoc(), 5319 ArgExprs.back()->getEndLoc())); 5320 } 5321 5322 return new (Context) 5323 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5324 } 5325 if (Fn->getType() == Context.PseudoObjectTy) { 5326 ExprResult result = CheckPlaceholderExpr(Fn); 5327 if (result.isInvalid()) return ExprError(); 5328 Fn = result.get(); 5329 } 5330 5331 // Determine whether this is a dependent call inside a C++ template, 5332 // in which case we won't do any semantic analysis now. 5333 bool Dependent = false; 5334 if (Fn->isTypeDependent()) 5335 Dependent = true; 5336 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5337 Dependent = true; 5338 5339 if (Dependent) { 5340 if (ExecConfig) { 5341 return new (Context) CUDAKernelCallExpr( 5342 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5343 Context.DependentTy, VK_RValue, RParenLoc); 5344 } else { 5345 5346 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5347 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5348 Fn->getBeginLoc()); 5349 5350 return new (Context) CallExpr( 5351 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5352 } 5353 } 5354 5355 // Determine whether this is a call to an object (C++ [over.call.object]). 5356 if (Fn->getType()->isRecordType()) 5357 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5358 RParenLoc); 5359 5360 if (Fn->getType() == Context.UnknownAnyTy) { 5361 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5362 if (result.isInvalid()) return ExprError(); 5363 Fn = result.get(); 5364 } 5365 5366 if (Fn->getType() == Context.BoundMemberTy) { 5367 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5368 RParenLoc); 5369 } 5370 } 5371 5372 // Check for overloaded calls. This can happen even in C due to extensions. 5373 if (Fn->getType() == Context.OverloadTy) { 5374 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5375 5376 // We aren't supposed to apply this logic if there's an '&' involved. 5377 if (!find.HasFormOfMemberPointer) { 5378 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5379 return new (Context) CallExpr( 5380 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5381 OverloadExpr *ovl = find.Expression; 5382 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5383 return BuildOverloadedCallExpr( 5384 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5385 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5386 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5387 RParenLoc); 5388 } 5389 } 5390 5391 // If we're directly calling a function, get the appropriate declaration. 5392 if (Fn->getType() == Context.UnknownAnyTy) { 5393 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5394 if (result.isInvalid()) return ExprError(); 5395 Fn = result.get(); 5396 } 5397 5398 Expr *NakedFn = Fn->IgnoreParens(); 5399 5400 bool CallingNDeclIndirectly = false; 5401 NamedDecl *NDecl = nullptr; 5402 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5403 if (UnOp->getOpcode() == UO_AddrOf) { 5404 CallingNDeclIndirectly = true; 5405 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5406 } 5407 } 5408 5409 if (isa<DeclRefExpr>(NakedFn)) { 5410 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5411 5412 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5413 if (FDecl && FDecl->getBuiltinID()) { 5414 // Rewrite the function decl for this builtin by replacing parameters 5415 // with no explicit address space with the address space of the arguments 5416 // in ArgExprs. 5417 if ((FDecl = 5418 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5419 NDecl = FDecl; 5420 Fn = DeclRefExpr::Create( 5421 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5422 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5423 } 5424 } 5425 } else if (isa<MemberExpr>(NakedFn)) 5426 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5427 5428 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5429 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5430 FD, /*Complain=*/true, Fn->getBeginLoc())) 5431 return ExprError(); 5432 5433 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5434 return ExprError(); 5435 5436 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5437 } 5438 5439 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5440 ExecConfig, IsExecConfig); 5441 } 5442 5443 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5444 /// 5445 /// __builtin_astype( value, dst type ) 5446 /// 5447 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5448 SourceLocation BuiltinLoc, 5449 SourceLocation RParenLoc) { 5450 ExprValueKind VK = VK_RValue; 5451 ExprObjectKind OK = OK_Ordinary; 5452 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5453 QualType SrcTy = E->getType(); 5454 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5455 return ExprError(Diag(BuiltinLoc, 5456 diag::err_invalid_astype_of_different_size) 5457 << DstTy 5458 << SrcTy 5459 << E->getSourceRange()); 5460 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5461 } 5462 5463 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5464 /// provided arguments. 5465 /// 5466 /// __builtin_convertvector( value, dst type ) 5467 /// 5468 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5469 SourceLocation BuiltinLoc, 5470 SourceLocation RParenLoc) { 5471 TypeSourceInfo *TInfo; 5472 GetTypeFromParser(ParsedDestTy, &TInfo); 5473 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5474 } 5475 5476 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5477 /// i.e. an expression not of \p OverloadTy. The expression should 5478 /// unary-convert to an expression of function-pointer or 5479 /// block-pointer type. 5480 /// 5481 /// \param NDecl the declaration being called, if available 5482 ExprResult 5483 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5484 SourceLocation LParenLoc, 5485 ArrayRef<Expr *> Args, 5486 SourceLocation RParenLoc, 5487 Expr *Config, bool IsExecConfig) { 5488 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5489 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5490 5491 // Functions with 'interrupt' attribute cannot be called directly. 5492 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5493 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5494 return ExprError(); 5495 } 5496 5497 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5498 // so there's some risk when calling out to non-interrupt handler functions 5499 // that the callee might not preserve them. This is easy to diagnose here, 5500 // but can be very challenging to debug. 5501 if (auto *Caller = getCurFunctionDecl()) 5502 if (Caller->hasAttr<ARMInterruptAttr>()) { 5503 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5504 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5505 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5506 } 5507 5508 // Promote the function operand. 5509 // We special-case function promotion here because we only allow promoting 5510 // builtin functions to function pointers in the callee of a call. 5511 ExprResult Result; 5512 if (BuiltinID && 5513 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5514 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5515 CK_BuiltinFnToFnPtr).get(); 5516 } else { 5517 Result = CallExprUnaryConversions(Fn); 5518 } 5519 if (Result.isInvalid()) 5520 return ExprError(); 5521 Fn = Result.get(); 5522 5523 // Make the call expr early, before semantic checks. This guarantees cleanup 5524 // of arguments and function on error. 5525 CallExpr *TheCall; 5526 if (Config) 5527 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5528 cast<CallExpr>(Config), Args, 5529 Context.BoolTy, VK_RValue, 5530 RParenLoc); 5531 else 5532 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5533 VK_RValue, RParenLoc); 5534 5535 if (!getLangOpts().CPlusPlus) { 5536 // C cannot always handle TypoExpr nodes in builtin calls and direct 5537 // function calls as their argument checking don't necessarily handle 5538 // dependent types properly, so make sure any TypoExprs have been 5539 // dealt with. 5540 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5541 if (!Result.isUsable()) return ExprError(); 5542 TheCall = dyn_cast<CallExpr>(Result.get()); 5543 if (!TheCall) return Result; 5544 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5545 } 5546 5547 // Bail out early if calling a builtin with custom typechecking. 5548 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5549 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5550 5551 retry: 5552 const FunctionType *FuncT; 5553 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5554 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5555 // have type pointer to function". 5556 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5557 if (!FuncT) 5558 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5559 << Fn->getType() << Fn->getSourceRange()); 5560 } else if (const BlockPointerType *BPT = 5561 Fn->getType()->getAs<BlockPointerType>()) { 5562 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5563 } else { 5564 // Handle calls to expressions of unknown-any type. 5565 if (Fn->getType() == Context.UnknownAnyTy) { 5566 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5567 if (rewrite.isInvalid()) return ExprError(); 5568 Fn = rewrite.get(); 5569 TheCall->setCallee(Fn); 5570 goto retry; 5571 } 5572 5573 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5574 << Fn->getType() << Fn->getSourceRange()); 5575 } 5576 5577 if (getLangOpts().CUDA) { 5578 if (Config) { 5579 // CUDA: Kernel calls must be to global functions 5580 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5581 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5582 << FDecl << Fn->getSourceRange()); 5583 5584 // CUDA: Kernel function must have 'void' return type 5585 if (!FuncT->getReturnType()->isVoidType()) 5586 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5587 << Fn->getType() << Fn->getSourceRange()); 5588 } else { 5589 // CUDA: Calls to global functions must be configured 5590 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5591 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5592 << FDecl << Fn->getSourceRange()); 5593 } 5594 } 5595 5596 // Check for a valid return type 5597 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5598 FDecl)) 5599 return ExprError(); 5600 5601 // We know the result type of the call, set it. 5602 TheCall->setType(FuncT->getCallResultType(Context)); 5603 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5604 5605 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5606 if (Proto) { 5607 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5608 IsExecConfig)) 5609 return ExprError(); 5610 } else { 5611 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5612 5613 if (FDecl) { 5614 // Check if we have too few/too many template arguments, based 5615 // on our knowledge of the function definition. 5616 const FunctionDecl *Def = nullptr; 5617 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5618 Proto = Def->getType()->getAs<FunctionProtoType>(); 5619 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5620 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5621 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5622 } 5623 5624 // If the function we're calling isn't a function prototype, but we have 5625 // a function prototype from a prior declaratiom, use that prototype. 5626 if (!FDecl->hasPrototype()) 5627 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5628 } 5629 5630 // Promote the arguments (C99 6.5.2.2p6). 5631 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5632 Expr *Arg = Args[i]; 5633 5634 if (Proto && i < Proto->getNumParams()) { 5635 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5636 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5637 ExprResult ArgE = 5638 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5639 if (ArgE.isInvalid()) 5640 return true; 5641 5642 Arg = ArgE.getAs<Expr>(); 5643 5644 } else { 5645 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5646 5647 if (ArgE.isInvalid()) 5648 return true; 5649 5650 Arg = ArgE.getAs<Expr>(); 5651 } 5652 5653 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5654 diag::err_call_incomplete_argument, Arg)) 5655 return ExprError(); 5656 5657 TheCall->setArg(i, Arg); 5658 } 5659 } 5660 5661 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5662 if (!Method->isStatic()) 5663 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5664 << Fn->getSourceRange()); 5665 5666 // Check for sentinels 5667 if (NDecl) 5668 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5669 5670 // Do special checking on direct calls to functions. 5671 if (FDecl) { 5672 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5673 return ExprError(); 5674 5675 if (BuiltinID) 5676 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5677 } else if (NDecl) { 5678 if (CheckPointerCall(NDecl, TheCall, Proto)) 5679 return ExprError(); 5680 } else { 5681 if (CheckOtherCall(TheCall, Proto)) 5682 return ExprError(); 5683 } 5684 5685 return MaybeBindToTemporary(TheCall); 5686 } 5687 5688 ExprResult 5689 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5690 SourceLocation RParenLoc, Expr *InitExpr) { 5691 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5692 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5693 5694 TypeSourceInfo *TInfo; 5695 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5696 if (!TInfo) 5697 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5698 5699 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5700 } 5701 5702 ExprResult 5703 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5704 SourceLocation RParenLoc, Expr *LiteralExpr) { 5705 QualType literalType = TInfo->getType(); 5706 5707 if (literalType->isArrayType()) { 5708 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5709 diag::err_illegal_decl_array_incomplete_type, 5710 SourceRange(LParenLoc, 5711 LiteralExpr->getSourceRange().getEnd()))) 5712 return ExprError(); 5713 if (literalType->isVariableArrayType()) 5714 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5715 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5716 } else if (!literalType->isDependentType() && 5717 RequireCompleteType(LParenLoc, literalType, 5718 diag::err_typecheck_decl_incomplete_type, 5719 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5720 return ExprError(); 5721 5722 InitializedEntity Entity 5723 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5724 InitializationKind Kind 5725 = InitializationKind::CreateCStyleCast(LParenLoc, 5726 SourceRange(LParenLoc, RParenLoc), 5727 /*InitList=*/true); 5728 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5729 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5730 &literalType); 5731 if (Result.isInvalid()) 5732 return ExprError(); 5733 LiteralExpr = Result.get(); 5734 5735 bool isFileScope = !CurContext->isFunctionOrMethod(); 5736 if (isFileScope && 5737 !LiteralExpr->isTypeDependent() && 5738 !LiteralExpr->isValueDependent() && 5739 !literalType->isDependentType()) { // 6.5.2.5p3 5740 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5741 return ExprError(); 5742 } 5743 5744 // In C, compound literals are l-values for some reason. 5745 // For GCC compatibility, in C++, file-scope array compound literals with 5746 // constant initializers are also l-values, and compound literals are 5747 // otherwise prvalues. 5748 // 5749 // (GCC also treats C++ list-initialized file-scope array prvalues with 5750 // constant initializers as l-values, but that's non-conforming, so we don't 5751 // follow it there.) 5752 // 5753 // FIXME: It would be better to handle the lvalue cases as materializing and 5754 // lifetime-extending a temporary object, but our materialized temporaries 5755 // representation only supports lifetime extension from a variable, not "out 5756 // of thin air". 5757 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5758 // is bound to the result of applying array-to-pointer decay to the compound 5759 // literal. 5760 // FIXME: GCC supports compound literals of reference type, which should 5761 // obviously have a value kind derived from the kind of reference involved. 5762 ExprValueKind VK = 5763 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5764 ? VK_RValue 5765 : VK_LValue; 5766 5767 return MaybeBindToTemporary( 5768 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5769 VK, LiteralExpr, isFileScope)); 5770 } 5771 5772 ExprResult 5773 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5774 SourceLocation RBraceLoc) { 5775 // Immediately handle non-overload placeholders. Overloads can be 5776 // resolved contextually, but everything else here can't. 5777 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5778 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5779 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5780 5781 // Ignore failures; dropping the entire initializer list because 5782 // of one failure would be terrible for indexing/etc. 5783 if (result.isInvalid()) continue; 5784 5785 InitArgList[I] = result.get(); 5786 } 5787 } 5788 5789 // Semantic analysis for initializers is done by ActOnDeclarator() and 5790 // CheckInitializer() - it requires knowledge of the object being initialized. 5791 5792 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5793 RBraceLoc); 5794 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5795 return E; 5796 } 5797 5798 /// Do an explicit extend of the given block pointer if we're in ARC. 5799 void Sema::maybeExtendBlockObject(ExprResult &E) { 5800 assert(E.get()->getType()->isBlockPointerType()); 5801 assert(E.get()->isRValue()); 5802 5803 // Only do this in an r-value context. 5804 if (!getLangOpts().ObjCAutoRefCount) return; 5805 5806 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5807 CK_ARCExtendBlockObject, E.get(), 5808 /*base path*/ nullptr, VK_RValue); 5809 Cleanup.setExprNeedsCleanups(true); 5810 } 5811 5812 /// Prepare a conversion of the given expression to an ObjC object 5813 /// pointer type. 5814 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5815 QualType type = E.get()->getType(); 5816 if (type->isObjCObjectPointerType()) { 5817 return CK_BitCast; 5818 } else if (type->isBlockPointerType()) { 5819 maybeExtendBlockObject(E); 5820 return CK_BlockPointerToObjCPointerCast; 5821 } else { 5822 assert(type->isPointerType()); 5823 return CK_CPointerToObjCPointerCast; 5824 } 5825 } 5826 5827 /// Prepares for a scalar cast, performing all the necessary stages 5828 /// except the final cast and returning the kind required. 5829 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5830 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5831 // Also, callers should have filtered out the invalid cases with 5832 // pointers. Everything else should be possible. 5833 5834 QualType SrcTy = Src.get()->getType(); 5835 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5836 return CK_NoOp; 5837 5838 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5839 case Type::STK_MemberPointer: 5840 llvm_unreachable("member pointer type in C"); 5841 5842 case Type::STK_CPointer: 5843 case Type::STK_BlockPointer: 5844 case Type::STK_ObjCObjectPointer: 5845 switch (DestTy->getScalarTypeKind()) { 5846 case Type::STK_CPointer: { 5847 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5848 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5849 if (SrcAS != DestAS) 5850 return CK_AddressSpaceConversion; 5851 return CK_BitCast; 5852 } 5853 case Type::STK_BlockPointer: 5854 return (SrcKind == Type::STK_BlockPointer 5855 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5856 case Type::STK_ObjCObjectPointer: 5857 if (SrcKind == Type::STK_ObjCObjectPointer) 5858 return CK_BitCast; 5859 if (SrcKind == Type::STK_CPointer) 5860 return CK_CPointerToObjCPointerCast; 5861 maybeExtendBlockObject(Src); 5862 return CK_BlockPointerToObjCPointerCast; 5863 case Type::STK_Bool: 5864 return CK_PointerToBoolean; 5865 case Type::STK_Integral: 5866 return CK_PointerToIntegral; 5867 case Type::STK_Floating: 5868 case Type::STK_FloatingComplex: 5869 case Type::STK_IntegralComplex: 5870 case Type::STK_MemberPointer: 5871 llvm_unreachable("illegal cast from pointer"); 5872 } 5873 llvm_unreachable("Should have returned before this"); 5874 5875 case Type::STK_Bool: // casting from bool is like casting from an integer 5876 case Type::STK_Integral: 5877 switch (DestTy->getScalarTypeKind()) { 5878 case Type::STK_CPointer: 5879 case Type::STK_ObjCObjectPointer: 5880 case Type::STK_BlockPointer: 5881 if (Src.get()->isNullPointerConstant(Context, 5882 Expr::NPC_ValueDependentIsNull)) 5883 return CK_NullToPointer; 5884 return CK_IntegralToPointer; 5885 case Type::STK_Bool: 5886 return CK_IntegralToBoolean; 5887 case Type::STK_Integral: 5888 return CK_IntegralCast; 5889 case Type::STK_Floating: 5890 return CK_IntegralToFloating; 5891 case Type::STK_IntegralComplex: 5892 Src = ImpCastExprToType(Src.get(), 5893 DestTy->castAs<ComplexType>()->getElementType(), 5894 CK_IntegralCast); 5895 return CK_IntegralRealToComplex; 5896 case Type::STK_FloatingComplex: 5897 Src = ImpCastExprToType(Src.get(), 5898 DestTy->castAs<ComplexType>()->getElementType(), 5899 CK_IntegralToFloating); 5900 return CK_FloatingRealToComplex; 5901 case Type::STK_MemberPointer: 5902 llvm_unreachable("member pointer type in C"); 5903 } 5904 llvm_unreachable("Should have returned before this"); 5905 5906 case Type::STK_Floating: 5907 switch (DestTy->getScalarTypeKind()) { 5908 case Type::STK_Floating: 5909 return CK_FloatingCast; 5910 case Type::STK_Bool: 5911 return CK_FloatingToBoolean; 5912 case Type::STK_Integral: 5913 return CK_FloatingToIntegral; 5914 case Type::STK_FloatingComplex: 5915 Src = ImpCastExprToType(Src.get(), 5916 DestTy->castAs<ComplexType>()->getElementType(), 5917 CK_FloatingCast); 5918 return CK_FloatingRealToComplex; 5919 case Type::STK_IntegralComplex: 5920 Src = ImpCastExprToType(Src.get(), 5921 DestTy->castAs<ComplexType>()->getElementType(), 5922 CK_FloatingToIntegral); 5923 return CK_IntegralRealToComplex; 5924 case Type::STK_CPointer: 5925 case Type::STK_ObjCObjectPointer: 5926 case Type::STK_BlockPointer: 5927 llvm_unreachable("valid float->pointer cast?"); 5928 case Type::STK_MemberPointer: 5929 llvm_unreachable("member pointer type in C"); 5930 } 5931 llvm_unreachable("Should have returned before this"); 5932 5933 case Type::STK_FloatingComplex: 5934 switch (DestTy->getScalarTypeKind()) { 5935 case Type::STK_FloatingComplex: 5936 return CK_FloatingComplexCast; 5937 case Type::STK_IntegralComplex: 5938 return CK_FloatingComplexToIntegralComplex; 5939 case Type::STK_Floating: { 5940 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5941 if (Context.hasSameType(ET, DestTy)) 5942 return CK_FloatingComplexToReal; 5943 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5944 return CK_FloatingCast; 5945 } 5946 case Type::STK_Bool: 5947 return CK_FloatingComplexToBoolean; 5948 case Type::STK_Integral: 5949 Src = ImpCastExprToType(Src.get(), 5950 SrcTy->castAs<ComplexType>()->getElementType(), 5951 CK_FloatingComplexToReal); 5952 return CK_FloatingToIntegral; 5953 case Type::STK_CPointer: 5954 case Type::STK_ObjCObjectPointer: 5955 case Type::STK_BlockPointer: 5956 llvm_unreachable("valid complex float->pointer cast?"); 5957 case Type::STK_MemberPointer: 5958 llvm_unreachable("member pointer type in C"); 5959 } 5960 llvm_unreachable("Should have returned before this"); 5961 5962 case Type::STK_IntegralComplex: 5963 switch (DestTy->getScalarTypeKind()) { 5964 case Type::STK_FloatingComplex: 5965 return CK_IntegralComplexToFloatingComplex; 5966 case Type::STK_IntegralComplex: 5967 return CK_IntegralComplexCast; 5968 case Type::STK_Integral: { 5969 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5970 if (Context.hasSameType(ET, DestTy)) 5971 return CK_IntegralComplexToReal; 5972 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5973 return CK_IntegralCast; 5974 } 5975 case Type::STK_Bool: 5976 return CK_IntegralComplexToBoolean; 5977 case Type::STK_Floating: 5978 Src = ImpCastExprToType(Src.get(), 5979 SrcTy->castAs<ComplexType>()->getElementType(), 5980 CK_IntegralComplexToReal); 5981 return CK_IntegralToFloating; 5982 case Type::STK_CPointer: 5983 case Type::STK_ObjCObjectPointer: 5984 case Type::STK_BlockPointer: 5985 llvm_unreachable("valid complex int->pointer cast?"); 5986 case Type::STK_MemberPointer: 5987 llvm_unreachable("member pointer type in C"); 5988 } 5989 llvm_unreachable("Should have returned before this"); 5990 } 5991 5992 llvm_unreachable("Unhandled scalar cast"); 5993 } 5994 5995 static bool breakDownVectorType(QualType type, uint64_t &len, 5996 QualType &eltType) { 5997 // Vectors are simple. 5998 if (const VectorType *vecType = type->getAs<VectorType>()) { 5999 len = vecType->getNumElements(); 6000 eltType = vecType->getElementType(); 6001 assert(eltType->isScalarType()); 6002 return true; 6003 } 6004 6005 // We allow lax conversion to and from non-vector types, but only if 6006 // they're real types (i.e. non-complex, non-pointer scalar types). 6007 if (!type->isRealType()) return false; 6008 6009 len = 1; 6010 eltType = type; 6011 return true; 6012 } 6013 6014 /// Are the two types lax-compatible vector types? That is, given 6015 /// that one of them is a vector, do they have equal storage sizes, 6016 /// where the storage size is the number of elements times the element 6017 /// size? 6018 /// 6019 /// This will also return false if either of the types is neither a 6020 /// vector nor a real type. 6021 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6022 assert(destTy->isVectorType() || srcTy->isVectorType()); 6023 6024 // Disallow lax conversions between scalars and ExtVectors (these 6025 // conversions are allowed for other vector types because common headers 6026 // depend on them). Most scalar OP ExtVector cases are handled by the 6027 // splat path anyway, which does what we want (convert, not bitcast). 6028 // What this rules out for ExtVectors is crazy things like char4*float. 6029 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6030 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6031 6032 uint64_t srcLen, destLen; 6033 QualType srcEltTy, destEltTy; 6034 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6035 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6036 6037 // ASTContext::getTypeSize will return the size rounded up to a 6038 // power of 2, so instead of using that, we need to use the raw 6039 // element size multiplied by the element count. 6040 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6041 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6042 6043 return (srcLen * srcEltSize == destLen * destEltSize); 6044 } 6045 6046 /// Is this a legal conversion between two types, one of which is 6047 /// known to be a vector type? 6048 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6049 assert(destTy->isVectorType() || srcTy->isVectorType()); 6050 6051 if (!Context.getLangOpts().LaxVectorConversions) 6052 return false; 6053 return areLaxCompatibleVectorTypes(srcTy, destTy); 6054 } 6055 6056 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6057 CastKind &Kind) { 6058 assert(VectorTy->isVectorType() && "Not a vector type!"); 6059 6060 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6061 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6062 return Diag(R.getBegin(), 6063 Ty->isVectorType() ? 6064 diag::err_invalid_conversion_between_vectors : 6065 diag::err_invalid_conversion_between_vector_and_integer) 6066 << VectorTy << Ty << R; 6067 } else 6068 return Diag(R.getBegin(), 6069 diag::err_invalid_conversion_between_vector_and_scalar) 6070 << VectorTy << Ty << R; 6071 6072 Kind = CK_BitCast; 6073 return false; 6074 } 6075 6076 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6077 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6078 6079 if (DestElemTy == SplattedExpr->getType()) 6080 return SplattedExpr; 6081 6082 assert(DestElemTy->isFloatingType() || 6083 DestElemTy->isIntegralOrEnumerationType()); 6084 6085 CastKind CK; 6086 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6087 // OpenCL requires that we convert `true` boolean expressions to -1, but 6088 // only when splatting vectors. 6089 if (DestElemTy->isFloatingType()) { 6090 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6091 // in two steps: boolean to signed integral, then to floating. 6092 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6093 CK_BooleanToSignedIntegral); 6094 SplattedExpr = CastExprRes.get(); 6095 CK = CK_IntegralToFloating; 6096 } else { 6097 CK = CK_BooleanToSignedIntegral; 6098 } 6099 } else { 6100 ExprResult CastExprRes = SplattedExpr; 6101 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6102 if (CastExprRes.isInvalid()) 6103 return ExprError(); 6104 SplattedExpr = CastExprRes.get(); 6105 } 6106 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6107 } 6108 6109 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6110 Expr *CastExpr, CastKind &Kind) { 6111 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6112 6113 QualType SrcTy = CastExpr->getType(); 6114 6115 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6116 // an ExtVectorType. 6117 // In OpenCL, casts between vectors of different types are not allowed. 6118 // (See OpenCL 6.2). 6119 if (SrcTy->isVectorType()) { 6120 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6121 (getLangOpts().OpenCL && 6122 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6123 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6124 << DestTy << SrcTy << R; 6125 return ExprError(); 6126 } 6127 Kind = CK_BitCast; 6128 return CastExpr; 6129 } 6130 6131 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6132 // conversion will take place first from scalar to elt type, and then 6133 // splat from elt type to vector. 6134 if (SrcTy->isPointerType()) 6135 return Diag(R.getBegin(), 6136 diag::err_invalid_conversion_between_vector_and_scalar) 6137 << DestTy << SrcTy << R; 6138 6139 Kind = CK_VectorSplat; 6140 return prepareVectorSplat(DestTy, CastExpr); 6141 } 6142 6143 ExprResult 6144 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6145 Declarator &D, ParsedType &Ty, 6146 SourceLocation RParenLoc, Expr *CastExpr) { 6147 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6148 "ActOnCastExpr(): missing type or expr"); 6149 6150 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6151 if (D.isInvalidType()) 6152 return ExprError(); 6153 6154 if (getLangOpts().CPlusPlus) { 6155 // Check that there are no default arguments (C++ only). 6156 CheckExtraCXXDefaultArguments(D); 6157 } else { 6158 // Make sure any TypoExprs have been dealt with. 6159 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6160 if (!Res.isUsable()) 6161 return ExprError(); 6162 CastExpr = Res.get(); 6163 } 6164 6165 checkUnusedDeclAttributes(D); 6166 6167 QualType castType = castTInfo->getType(); 6168 Ty = CreateParsedType(castType, castTInfo); 6169 6170 bool isVectorLiteral = false; 6171 6172 // Check for an altivec or OpenCL literal, 6173 // i.e. all the elements are integer constants. 6174 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6175 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6176 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6177 && castType->isVectorType() && (PE || PLE)) { 6178 if (PLE && PLE->getNumExprs() == 0) { 6179 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6180 return ExprError(); 6181 } 6182 if (PE || PLE->getNumExprs() == 1) { 6183 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6184 if (!E->getType()->isVectorType()) 6185 isVectorLiteral = true; 6186 } 6187 else 6188 isVectorLiteral = true; 6189 } 6190 6191 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6192 // then handle it as such. 6193 if (isVectorLiteral) 6194 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6195 6196 // If the Expr being casted is a ParenListExpr, handle it specially. 6197 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6198 // sequence of BinOp comma operators. 6199 if (isa<ParenListExpr>(CastExpr)) { 6200 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6201 if (Result.isInvalid()) return ExprError(); 6202 CastExpr = Result.get(); 6203 } 6204 6205 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6206 !getSourceManager().isInSystemMacro(LParenLoc)) 6207 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6208 6209 CheckTollFreeBridgeCast(castType, CastExpr); 6210 6211 CheckObjCBridgeRelatedCast(castType, CastExpr); 6212 6213 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6214 6215 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6216 } 6217 6218 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6219 SourceLocation RParenLoc, Expr *E, 6220 TypeSourceInfo *TInfo) { 6221 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6222 "Expected paren or paren list expression"); 6223 6224 Expr **exprs; 6225 unsigned numExprs; 6226 Expr *subExpr; 6227 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6228 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6229 LiteralLParenLoc = PE->getLParenLoc(); 6230 LiteralRParenLoc = PE->getRParenLoc(); 6231 exprs = PE->getExprs(); 6232 numExprs = PE->getNumExprs(); 6233 } else { // isa<ParenExpr> by assertion at function entrance 6234 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6235 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6236 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6237 exprs = &subExpr; 6238 numExprs = 1; 6239 } 6240 6241 QualType Ty = TInfo->getType(); 6242 assert(Ty->isVectorType() && "Expected vector type"); 6243 6244 SmallVector<Expr *, 8> initExprs; 6245 const VectorType *VTy = Ty->getAs<VectorType>(); 6246 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6247 6248 // '(...)' form of vector initialization in AltiVec: the number of 6249 // initializers must be one or must match the size of the vector. 6250 // If a single value is specified in the initializer then it will be 6251 // replicated to all the components of the vector 6252 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6253 // The number of initializers must be one or must match the size of the 6254 // vector. If a single value is specified in the initializer then it will 6255 // be replicated to all the components of the vector 6256 if (numExprs == 1) { 6257 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6258 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6259 if (Literal.isInvalid()) 6260 return ExprError(); 6261 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6262 PrepareScalarCast(Literal, ElemTy)); 6263 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6264 } 6265 else if (numExprs < numElems) { 6266 Diag(E->getExprLoc(), 6267 diag::err_incorrect_number_of_vector_initializers); 6268 return ExprError(); 6269 } 6270 else 6271 initExprs.append(exprs, exprs + numExprs); 6272 } 6273 else { 6274 // For OpenCL, when the number of initializers is a single value, 6275 // it will be replicated to all components of the vector. 6276 if (getLangOpts().OpenCL && 6277 VTy->getVectorKind() == VectorType::GenericVector && 6278 numExprs == 1) { 6279 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6280 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6281 if (Literal.isInvalid()) 6282 return ExprError(); 6283 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6284 PrepareScalarCast(Literal, ElemTy)); 6285 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6286 } 6287 6288 initExprs.append(exprs, exprs + numExprs); 6289 } 6290 // FIXME: This means that pretty-printing the final AST will produce curly 6291 // braces instead of the original commas. 6292 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6293 initExprs, LiteralRParenLoc); 6294 initE->setType(Ty); 6295 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6296 } 6297 6298 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6299 /// the ParenListExpr into a sequence of comma binary operators. 6300 ExprResult 6301 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6302 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6303 if (!E) 6304 return OrigExpr; 6305 6306 ExprResult Result(E->getExpr(0)); 6307 6308 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6309 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6310 E->getExpr(i)); 6311 6312 if (Result.isInvalid()) return ExprError(); 6313 6314 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6315 } 6316 6317 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6318 SourceLocation R, 6319 MultiExprArg Val) { 6320 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6321 return expr; 6322 } 6323 6324 /// Emit a specialized diagnostic when one expression is a null pointer 6325 /// constant and the other is not a pointer. Returns true if a diagnostic is 6326 /// emitted. 6327 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6328 SourceLocation QuestionLoc) { 6329 Expr *NullExpr = LHSExpr; 6330 Expr *NonPointerExpr = RHSExpr; 6331 Expr::NullPointerConstantKind NullKind = 6332 NullExpr->isNullPointerConstant(Context, 6333 Expr::NPC_ValueDependentIsNotNull); 6334 6335 if (NullKind == Expr::NPCK_NotNull) { 6336 NullExpr = RHSExpr; 6337 NonPointerExpr = LHSExpr; 6338 NullKind = 6339 NullExpr->isNullPointerConstant(Context, 6340 Expr::NPC_ValueDependentIsNotNull); 6341 } 6342 6343 if (NullKind == Expr::NPCK_NotNull) 6344 return false; 6345 6346 if (NullKind == Expr::NPCK_ZeroExpression) 6347 return false; 6348 6349 if (NullKind == Expr::NPCK_ZeroLiteral) { 6350 // In this case, check to make sure that we got here from a "NULL" 6351 // string in the source code. 6352 NullExpr = NullExpr->IgnoreParenImpCasts(); 6353 SourceLocation loc = NullExpr->getExprLoc(); 6354 if (!findMacroSpelling(loc, "NULL")) 6355 return false; 6356 } 6357 6358 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6359 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6360 << NonPointerExpr->getType() << DiagType 6361 << NonPointerExpr->getSourceRange(); 6362 return true; 6363 } 6364 6365 /// Return false if the condition expression is valid, true otherwise. 6366 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6367 QualType CondTy = Cond->getType(); 6368 6369 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6370 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6371 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6372 << CondTy << Cond->getSourceRange(); 6373 return true; 6374 } 6375 6376 // C99 6.5.15p2 6377 if (CondTy->isScalarType()) return false; 6378 6379 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6380 << CondTy << Cond->getSourceRange(); 6381 return true; 6382 } 6383 6384 /// Handle when one or both operands are void type. 6385 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6386 ExprResult &RHS) { 6387 Expr *LHSExpr = LHS.get(); 6388 Expr *RHSExpr = RHS.get(); 6389 6390 if (!LHSExpr->getType()->isVoidType()) 6391 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6392 << RHSExpr->getSourceRange(); 6393 if (!RHSExpr->getType()->isVoidType()) 6394 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6395 << LHSExpr->getSourceRange(); 6396 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6397 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6398 return S.Context.VoidTy; 6399 } 6400 6401 /// Return false if the NullExpr can be promoted to PointerTy, 6402 /// true otherwise. 6403 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6404 QualType PointerTy) { 6405 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6406 !NullExpr.get()->isNullPointerConstant(S.Context, 6407 Expr::NPC_ValueDependentIsNull)) 6408 return true; 6409 6410 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6411 return false; 6412 } 6413 6414 /// Checks compatibility between two pointers and return the resulting 6415 /// type. 6416 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6417 ExprResult &RHS, 6418 SourceLocation Loc) { 6419 QualType LHSTy = LHS.get()->getType(); 6420 QualType RHSTy = RHS.get()->getType(); 6421 6422 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6423 // Two identical pointers types are always compatible. 6424 return LHSTy; 6425 } 6426 6427 QualType lhptee, rhptee; 6428 6429 // Get the pointee types. 6430 bool IsBlockPointer = false; 6431 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6432 lhptee = LHSBTy->getPointeeType(); 6433 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6434 IsBlockPointer = true; 6435 } else { 6436 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6437 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6438 } 6439 6440 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6441 // differently qualified versions of compatible types, the result type is 6442 // a pointer to an appropriately qualified version of the composite 6443 // type. 6444 6445 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6446 // clause doesn't make sense for our extensions. E.g. address space 2 should 6447 // be incompatible with address space 3: they may live on different devices or 6448 // anything. 6449 Qualifiers lhQual = lhptee.getQualifiers(); 6450 Qualifiers rhQual = rhptee.getQualifiers(); 6451 6452 LangAS ResultAddrSpace = LangAS::Default; 6453 LangAS LAddrSpace = lhQual.getAddressSpace(); 6454 LangAS RAddrSpace = rhQual.getAddressSpace(); 6455 6456 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6457 // spaces is disallowed. 6458 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6459 ResultAddrSpace = LAddrSpace; 6460 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6461 ResultAddrSpace = RAddrSpace; 6462 else { 6463 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6464 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6465 << RHS.get()->getSourceRange(); 6466 return QualType(); 6467 } 6468 6469 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6470 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6471 lhQual.removeCVRQualifiers(); 6472 rhQual.removeCVRQualifiers(); 6473 6474 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6475 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6476 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6477 // qual types are compatible iff 6478 // * corresponded types are compatible 6479 // * CVR qualifiers are equal 6480 // * address spaces are equal 6481 // Thus for conditional operator we merge CVR and address space unqualified 6482 // pointees and if there is a composite type we return a pointer to it with 6483 // merged qualifiers. 6484 LHSCastKind = 6485 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6486 RHSCastKind = 6487 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6488 lhQual.removeAddressSpace(); 6489 rhQual.removeAddressSpace(); 6490 6491 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6492 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6493 6494 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6495 6496 if (CompositeTy.isNull()) { 6497 // In this situation, we assume void* type. No especially good 6498 // reason, but this is what gcc does, and we do have to pick 6499 // to get a consistent AST. 6500 QualType incompatTy; 6501 incompatTy = S.Context.getPointerType( 6502 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6503 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6504 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6505 6506 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6507 // for casts between types with incompatible address space qualifiers. 6508 // For the following code the compiler produces casts between global and 6509 // local address spaces of the corresponded innermost pointees: 6510 // local int *global *a; 6511 // global int *global *b; 6512 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6513 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6514 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6515 << RHS.get()->getSourceRange(); 6516 6517 return incompatTy; 6518 } 6519 6520 // The pointer types are compatible. 6521 // In case of OpenCL ResultTy should have the address space qualifier 6522 // which is a superset of address spaces of both the 2nd and the 3rd 6523 // operands of the conditional operator. 6524 QualType ResultTy = [&, ResultAddrSpace]() { 6525 if (S.getLangOpts().OpenCL) { 6526 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6527 CompositeQuals.setAddressSpace(ResultAddrSpace); 6528 return S.Context 6529 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6530 .withCVRQualifiers(MergedCVRQual); 6531 } 6532 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6533 }(); 6534 if (IsBlockPointer) 6535 ResultTy = S.Context.getBlockPointerType(ResultTy); 6536 else 6537 ResultTy = S.Context.getPointerType(ResultTy); 6538 6539 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6540 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6541 return ResultTy; 6542 } 6543 6544 /// Return the resulting type when the operands are both block pointers. 6545 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6546 ExprResult &LHS, 6547 ExprResult &RHS, 6548 SourceLocation Loc) { 6549 QualType LHSTy = LHS.get()->getType(); 6550 QualType RHSTy = RHS.get()->getType(); 6551 6552 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6553 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6554 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6555 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6556 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6557 return destType; 6558 } 6559 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6560 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6561 << RHS.get()->getSourceRange(); 6562 return QualType(); 6563 } 6564 6565 // We have 2 block pointer types. 6566 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6567 } 6568 6569 /// Return the resulting type when the operands are both pointers. 6570 static QualType 6571 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6572 ExprResult &RHS, 6573 SourceLocation Loc) { 6574 // get the pointer types 6575 QualType LHSTy = LHS.get()->getType(); 6576 QualType RHSTy = RHS.get()->getType(); 6577 6578 // get the "pointed to" types 6579 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6580 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6581 6582 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6583 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6584 // Figure out necessary qualifiers (C99 6.5.15p6) 6585 QualType destPointee 6586 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6587 QualType destType = S.Context.getPointerType(destPointee); 6588 // Add qualifiers if necessary. 6589 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6590 // Promote to void*. 6591 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6592 return destType; 6593 } 6594 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6595 QualType destPointee 6596 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6597 QualType destType = S.Context.getPointerType(destPointee); 6598 // Add qualifiers if necessary. 6599 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6600 // Promote to void*. 6601 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6602 return destType; 6603 } 6604 6605 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6606 } 6607 6608 /// Return false if the first expression is not an integer and the second 6609 /// expression is not a pointer, true otherwise. 6610 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6611 Expr* PointerExpr, SourceLocation Loc, 6612 bool IsIntFirstExpr) { 6613 if (!PointerExpr->getType()->isPointerType() || 6614 !Int.get()->getType()->isIntegerType()) 6615 return false; 6616 6617 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6618 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6619 6620 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6621 << Expr1->getType() << Expr2->getType() 6622 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6623 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6624 CK_IntegralToPointer); 6625 return true; 6626 } 6627 6628 /// Simple conversion between integer and floating point types. 6629 /// 6630 /// Used when handling the OpenCL conditional operator where the 6631 /// condition is a vector while the other operands are scalar. 6632 /// 6633 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6634 /// types are either integer or floating type. Between the two 6635 /// operands, the type with the higher rank is defined as the "result 6636 /// type". The other operand needs to be promoted to the same type. No 6637 /// other type promotion is allowed. We cannot use 6638 /// UsualArithmeticConversions() for this purpose, since it always 6639 /// promotes promotable types. 6640 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6641 ExprResult &RHS, 6642 SourceLocation QuestionLoc) { 6643 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6644 if (LHS.isInvalid()) 6645 return QualType(); 6646 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6647 if (RHS.isInvalid()) 6648 return QualType(); 6649 6650 // For conversion purposes, we ignore any qualifiers. 6651 // For example, "const float" and "float" are equivalent. 6652 QualType LHSType = 6653 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6654 QualType RHSType = 6655 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6656 6657 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6658 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6659 << LHSType << LHS.get()->getSourceRange(); 6660 return QualType(); 6661 } 6662 6663 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6664 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6665 << RHSType << RHS.get()->getSourceRange(); 6666 return QualType(); 6667 } 6668 6669 // If both types are identical, no conversion is needed. 6670 if (LHSType == RHSType) 6671 return LHSType; 6672 6673 // Now handle "real" floating types (i.e. float, double, long double). 6674 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6675 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6676 /*IsCompAssign = */ false); 6677 6678 // Finally, we have two differing integer types. 6679 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6680 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6681 } 6682 6683 /// Convert scalar operands to a vector that matches the 6684 /// condition in length. 6685 /// 6686 /// Used when handling the OpenCL conditional operator where the 6687 /// condition is a vector while the other operands are scalar. 6688 /// 6689 /// We first compute the "result type" for the scalar operands 6690 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6691 /// into a vector of that type where the length matches the condition 6692 /// vector type. s6.11.6 requires that the element types of the result 6693 /// and the condition must have the same number of bits. 6694 static QualType 6695 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6696 QualType CondTy, SourceLocation QuestionLoc) { 6697 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6698 if (ResTy.isNull()) return QualType(); 6699 6700 const VectorType *CV = CondTy->getAs<VectorType>(); 6701 assert(CV); 6702 6703 // Determine the vector result type 6704 unsigned NumElements = CV->getNumElements(); 6705 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6706 6707 // Ensure that all types have the same number of bits 6708 if (S.Context.getTypeSize(CV->getElementType()) 6709 != S.Context.getTypeSize(ResTy)) { 6710 // Since VectorTy is created internally, it does not pretty print 6711 // with an OpenCL name. Instead, we just print a description. 6712 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6713 SmallString<64> Str; 6714 llvm::raw_svector_ostream OS(Str); 6715 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6716 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6717 << CondTy << OS.str(); 6718 return QualType(); 6719 } 6720 6721 // Convert operands to the vector result type 6722 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6723 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6724 6725 return VectorTy; 6726 } 6727 6728 /// Return false if this is a valid OpenCL condition vector 6729 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6730 SourceLocation QuestionLoc) { 6731 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6732 // integral type. 6733 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6734 assert(CondTy); 6735 QualType EleTy = CondTy->getElementType(); 6736 if (EleTy->isIntegerType()) return false; 6737 6738 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6739 << Cond->getType() << Cond->getSourceRange(); 6740 return true; 6741 } 6742 6743 /// Return false if the vector condition type and the vector 6744 /// result type are compatible. 6745 /// 6746 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6747 /// number of elements, and their element types have the same number 6748 /// of bits. 6749 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6750 SourceLocation QuestionLoc) { 6751 const VectorType *CV = CondTy->getAs<VectorType>(); 6752 const VectorType *RV = VecResTy->getAs<VectorType>(); 6753 assert(CV && RV); 6754 6755 if (CV->getNumElements() != RV->getNumElements()) { 6756 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6757 << CondTy << VecResTy; 6758 return true; 6759 } 6760 6761 QualType CVE = CV->getElementType(); 6762 QualType RVE = RV->getElementType(); 6763 6764 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6765 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6766 << CondTy << VecResTy; 6767 return true; 6768 } 6769 6770 return false; 6771 } 6772 6773 /// Return the resulting type for the conditional operator in 6774 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6775 /// s6.3.i) when the condition is a vector type. 6776 static QualType 6777 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6778 ExprResult &LHS, ExprResult &RHS, 6779 SourceLocation QuestionLoc) { 6780 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6781 if (Cond.isInvalid()) 6782 return QualType(); 6783 QualType CondTy = Cond.get()->getType(); 6784 6785 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6786 return QualType(); 6787 6788 // If either operand is a vector then find the vector type of the 6789 // result as specified in OpenCL v1.1 s6.3.i. 6790 if (LHS.get()->getType()->isVectorType() || 6791 RHS.get()->getType()->isVectorType()) { 6792 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6793 /*isCompAssign*/false, 6794 /*AllowBothBool*/true, 6795 /*AllowBoolConversions*/false); 6796 if (VecResTy.isNull()) return QualType(); 6797 // The result type must match the condition type as specified in 6798 // OpenCL v1.1 s6.11.6. 6799 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6800 return QualType(); 6801 return VecResTy; 6802 } 6803 6804 // Both operands are scalar. 6805 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6806 } 6807 6808 /// Return true if the Expr is block type 6809 static bool checkBlockType(Sema &S, const Expr *E) { 6810 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6811 QualType Ty = CE->getCallee()->getType(); 6812 if (Ty->isBlockPointerType()) { 6813 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6814 return true; 6815 } 6816 } 6817 return false; 6818 } 6819 6820 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6821 /// In that case, LHS = cond. 6822 /// C99 6.5.15 6823 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6824 ExprResult &RHS, ExprValueKind &VK, 6825 ExprObjectKind &OK, 6826 SourceLocation QuestionLoc) { 6827 6828 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6829 if (!LHSResult.isUsable()) return QualType(); 6830 LHS = LHSResult; 6831 6832 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6833 if (!RHSResult.isUsable()) return QualType(); 6834 RHS = RHSResult; 6835 6836 // C++ is sufficiently different to merit its own checker. 6837 if (getLangOpts().CPlusPlus) 6838 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6839 6840 VK = VK_RValue; 6841 OK = OK_Ordinary; 6842 6843 // The OpenCL operator with a vector condition is sufficiently 6844 // different to merit its own checker. 6845 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6846 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6847 6848 // First, check the condition. 6849 Cond = UsualUnaryConversions(Cond.get()); 6850 if (Cond.isInvalid()) 6851 return QualType(); 6852 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6853 return QualType(); 6854 6855 // Now check the two expressions. 6856 if (LHS.get()->getType()->isVectorType() || 6857 RHS.get()->getType()->isVectorType()) 6858 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6859 /*AllowBothBool*/true, 6860 /*AllowBoolConversions*/false); 6861 6862 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6863 if (LHS.isInvalid() || RHS.isInvalid()) 6864 return QualType(); 6865 6866 QualType LHSTy = LHS.get()->getType(); 6867 QualType RHSTy = RHS.get()->getType(); 6868 6869 // Diagnose attempts to convert between __float128 and long double where 6870 // such conversions currently can't be handled. 6871 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6872 Diag(QuestionLoc, 6873 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6875 return QualType(); 6876 } 6877 6878 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6879 // selection operator (?:). 6880 if (getLangOpts().OpenCL && 6881 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6882 return QualType(); 6883 } 6884 6885 // If both operands have arithmetic type, do the usual arithmetic conversions 6886 // to find a common type: C99 6.5.15p3,5. 6887 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6888 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6889 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6890 6891 return ResTy; 6892 } 6893 6894 // If both operands are the same structure or union type, the result is that 6895 // type. 6896 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6897 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6898 if (LHSRT->getDecl() == RHSRT->getDecl()) 6899 // "If both the operands have structure or union type, the result has 6900 // that type." This implies that CV qualifiers are dropped. 6901 return LHSTy.getUnqualifiedType(); 6902 // FIXME: Type of conditional expression must be complete in C mode. 6903 } 6904 6905 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6906 // The following || allows only one side to be void (a GCC-ism). 6907 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6908 return checkConditionalVoidType(*this, LHS, RHS); 6909 } 6910 6911 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6912 // the type of the other operand." 6913 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6914 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6915 6916 // All objective-c pointer type analysis is done here. 6917 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6918 QuestionLoc); 6919 if (LHS.isInvalid() || RHS.isInvalid()) 6920 return QualType(); 6921 if (!compositeType.isNull()) 6922 return compositeType; 6923 6924 6925 // Handle block pointer types. 6926 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6927 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6928 QuestionLoc); 6929 6930 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6931 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6932 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6933 QuestionLoc); 6934 6935 // GCC compatibility: soften pointer/integer mismatch. Note that 6936 // null pointers have been filtered out by this point. 6937 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6938 /*isIntFirstExpr=*/true)) 6939 return RHSTy; 6940 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6941 /*isIntFirstExpr=*/false)) 6942 return LHSTy; 6943 6944 // Emit a better diagnostic if one of the expressions is a null pointer 6945 // constant and the other is not a pointer type. In this case, the user most 6946 // likely forgot to take the address of the other expression. 6947 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6948 return QualType(); 6949 6950 // Otherwise, the operands are not compatible. 6951 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6952 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6953 << RHS.get()->getSourceRange(); 6954 return QualType(); 6955 } 6956 6957 /// FindCompositeObjCPointerType - Helper method to find composite type of 6958 /// two objective-c pointer types of the two input expressions. 6959 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6960 SourceLocation QuestionLoc) { 6961 QualType LHSTy = LHS.get()->getType(); 6962 QualType RHSTy = RHS.get()->getType(); 6963 6964 // Handle things like Class and struct objc_class*. Here we case the result 6965 // to the pseudo-builtin, because that will be implicitly cast back to the 6966 // redefinition type if an attempt is made to access its fields. 6967 if (LHSTy->isObjCClassType() && 6968 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6969 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6970 return LHSTy; 6971 } 6972 if (RHSTy->isObjCClassType() && 6973 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6974 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6975 return RHSTy; 6976 } 6977 // And the same for struct objc_object* / id 6978 if (LHSTy->isObjCIdType() && 6979 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6980 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6981 return LHSTy; 6982 } 6983 if (RHSTy->isObjCIdType() && 6984 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6985 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6986 return RHSTy; 6987 } 6988 // And the same for struct objc_selector* / SEL 6989 if (Context.isObjCSelType(LHSTy) && 6990 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6991 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6992 return LHSTy; 6993 } 6994 if (Context.isObjCSelType(RHSTy) && 6995 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6996 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6997 return RHSTy; 6998 } 6999 // Check constraints for Objective-C object pointers types. 7000 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7001 7002 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7003 // Two identical object pointer types are always compatible. 7004 return LHSTy; 7005 } 7006 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7007 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7008 QualType compositeType = LHSTy; 7009 7010 // If both operands are interfaces and either operand can be 7011 // assigned to the other, use that type as the composite 7012 // type. This allows 7013 // xxx ? (A*) a : (B*) b 7014 // where B is a subclass of A. 7015 // 7016 // Additionally, as for assignment, if either type is 'id' 7017 // allow silent coercion. Finally, if the types are 7018 // incompatible then make sure to use 'id' as the composite 7019 // type so the result is acceptable for sending messages to. 7020 7021 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7022 // It could return the composite type. 7023 if (!(compositeType = 7024 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7025 // Nothing more to do. 7026 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7027 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7028 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7029 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7030 } else if ((LHSTy->isObjCQualifiedIdType() || 7031 RHSTy->isObjCQualifiedIdType()) && 7032 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7033 // Need to handle "id<xx>" explicitly. 7034 // GCC allows qualified id and any Objective-C type to devolve to 7035 // id. Currently localizing to here until clear this should be 7036 // part of ObjCQualifiedIdTypesAreCompatible. 7037 compositeType = Context.getObjCIdType(); 7038 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7039 compositeType = Context.getObjCIdType(); 7040 } else { 7041 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7042 << LHSTy << RHSTy 7043 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7044 QualType incompatTy = Context.getObjCIdType(); 7045 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7046 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7047 return incompatTy; 7048 } 7049 // The object pointer types are compatible. 7050 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7051 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7052 return compositeType; 7053 } 7054 // Check Objective-C object pointer types and 'void *' 7055 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7056 if (getLangOpts().ObjCAutoRefCount) { 7057 // ARC forbids the implicit conversion of object pointers to 'void *', 7058 // so these types are not compatible. 7059 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7061 LHS = RHS = true; 7062 return QualType(); 7063 } 7064 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7065 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7066 QualType destPointee 7067 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7068 QualType destType = Context.getPointerType(destPointee); 7069 // Add qualifiers if necessary. 7070 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7071 // Promote to void*. 7072 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7073 return destType; 7074 } 7075 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7076 if (getLangOpts().ObjCAutoRefCount) { 7077 // ARC forbids the implicit conversion of object pointers to 'void *', 7078 // so these types are not compatible. 7079 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7080 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7081 LHS = RHS = true; 7082 return QualType(); 7083 } 7084 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7085 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7086 QualType destPointee 7087 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7088 QualType destType = Context.getPointerType(destPointee); 7089 // Add qualifiers if necessary. 7090 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7091 // Promote to void*. 7092 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7093 return destType; 7094 } 7095 return QualType(); 7096 } 7097 7098 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7099 /// ParenRange in parentheses. 7100 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7101 const PartialDiagnostic &Note, 7102 SourceRange ParenRange) { 7103 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7104 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7105 EndLoc.isValid()) { 7106 Self.Diag(Loc, Note) 7107 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7108 << FixItHint::CreateInsertion(EndLoc, ")"); 7109 } else { 7110 // We can't display the parentheses, so just show the bare note. 7111 Self.Diag(Loc, Note) << ParenRange; 7112 } 7113 } 7114 7115 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7116 return BinaryOperator::isAdditiveOp(Opc) || 7117 BinaryOperator::isMultiplicativeOp(Opc) || 7118 BinaryOperator::isShiftOp(Opc); 7119 } 7120 7121 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7122 /// expression, either using a built-in or overloaded operator, 7123 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7124 /// expression. 7125 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7126 Expr **RHSExprs) { 7127 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7128 E = E->IgnoreImpCasts(); 7129 E = E->IgnoreConversionOperator(); 7130 E = E->IgnoreImpCasts(); 7131 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7132 E = MTE->GetTemporaryExpr(); 7133 E = E->IgnoreImpCasts(); 7134 } 7135 7136 // Built-in binary operator. 7137 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7138 if (IsArithmeticOp(OP->getOpcode())) { 7139 *Opcode = OP->getOpcode(); 7140 *RHSExprs = OP->getRHS(); 7141 return true; 7142 } 7143 } 7144 7145 // Overloaded operator. 7146 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7147 if (Call->getNumArgs() != 2) 7148 return false; 7149 7150 // Make sure this is really a binary operator that is safe to pass into 7151 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7152 OverloadedOperatorKind OO = Call->getOperator(); 7153 if (OO < OO_Plus || OO > OO_Arrow || 7154 OO == OO_PlusPlus || OO == OO_MinusMinus) 7155 return false; 7156 7157 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7158 if (IsArithmeticOp(OpKind)) { 7159 *Opcode = OpKind; 7160 *RHSExprs = Call->getArg(1); 7161 return true; 7162 } 7163 } 7164 7165 return false; 7166 } 7167 7168 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7169 /// or is a logical expression such as (x==y) which has int type, but is 7170 /// commonly interpreted as boolean. 7171 static bool ExprLooksBoolean(Expr *E) { 7172 E = E->IgnoreParenImpCasts(); 7173 7174 if (E->getType()->isBooleanType()) 7175 return true; 7176 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7177 return OP->isComparisonOp() || OP->isLogicalOp(); 7178 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7179 return OP->getOpcode() == UO_LNot; 7180 if (E->getType()->isPointerType()) 7181 return true; 7182 // FIXME: What about overloaded operator calls returning "unspecified boolean 7183 // type"s (commonly pointer-to-members)? 7184 7185 return false; 7186 } 7187 7188 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7189 /// and binary operator are mixed in a way that suggests the programmer assumed 7190 /// the conditional operator has higher precedence, for example: 7191 /// "int x = a + someBinaryCondition ? 1 : 2". 7192 static void DiagnoseConditionalPrecedence(Sema &Self, 7193 SourceLocation OpLoc, 7194 Expr *Condition, 7195 Expr *LHSExpr, 7196 Expr *RHSExpr) { 7197 BinaryOperatorKind CondOpcode; 7198 Expr *CondRHS; 7199 7200 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7201 return; 7202 if (!ExprLooksBoolean(CondRHS)) 7203 return; 7204 7205 // The condition is an arithmetic binary expression, with a right- 7206 // hand side that looks boolean, so warn. 7207 7208 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7209 << Condition->getSourceRange() 7210 << BinaryOperator::getOpcodeStr(CondOpcode); 7211 7212 SuggestParentheses( 7213 Self, OpLoc, 7214 Self.PDiag(diag::note_precedence_silence) 7215 << BinaryOperator::getOpcodeStr(CondOpcode), 7216 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7217 7218 SuggestParentheses(Self, OpLoc, 7219 Self.PDiag(diag::note_precedence_conditional_first), 7220 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7221 } 7222 7223 /// Compute the nullability of a conditional expression. 7224 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7225 QualType LHSTy, QualType RHSTy, 7226 ASTContext &Ctx) { 7227 if (!ResTy->isAnyPointerType()) 7228 return ResTy; 7229 7230 auto GetNullability = [&Ctx](QualType Ty) { 7231 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7232 if (Kind) 7233 return *Kind; 7234 return NullabilityKind::Unspecified; 7235 }; 7236 7237 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7238 NullabilityKind MergedKind; 7239 7240 // Compute nullability of a binary conditional expression. 7241 if (IsBin) { 7242 if (LHSKind == NullabilityKind::NonNull) 7243 MergedKind = NullabilityKind::NonNull; 7244 else 7245 MergedKind = RHSKind; 7246 // Compute nullability of a normal conditional expression. 7247 } else { 7248 if (LHSKind == NullabilityKind::Nullable || 7249 RHSKind == NullabilityKind::Nullable) 7250 MergedKind = NullabilityKind::Nullable; 7251 else if (LHSKind == NullabilityKind::NonNull) 7252 MergedKind = RHSKind; 7253 else if (RHSKind == NullabilityKind::NonNull) 7254 MergedKind = LHSKind; 7255 else 7256 MergedKind = NullabilityKind::Unspecified; 7257 } 7258 7259 // Return if ResTy already has the correct nullability. 7260 if (GetNullability(ResTy) == MergedKind) 7261 return ResTy; 7262 7263 // Strip all nullability from ResTy. 7264 while (ResTy->getNullability(Ctx)) 7265 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7266 7267 // Create a new AttributedType with the new nullability kind. 7268 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7269 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7270 } 7271 7272 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7273 /// in the case of a the GNU conditional expr extension. 7274 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7275 SourceLocation ColonLoc, 7276 Expr *CondExpr, Expr *LHSExpr, 7277 Expr *RHSExpr) { 7278 if (!getLangOpts().CPlusPlus) { 7279 // C cannot handle TypoExpr nodes in the condition because it 7280 // doesn't handle dependent types properly, so make sure any TypoExprs have 7281 // been dealt with before checking the operands. 7282 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7283 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7284 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7285 7286 if (!CondResult.isUsable()) 7287 return ExprError(); 7288 7289 if (LHSExpr) { 7290 if (!LHSResult.isUsable()) 7291 return ExprError(); 7292 } 7293 7294 if (!RHSResult.isUsable()) 7295 return ExprError(); 7296 7297 CondExpr = CondResult.get(); 7298 LHSExpr = LHSResult.get(); 7299 RHSExpr = RHSResult.get(); 7300 } 7301 7302 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7303 // was the condition. 7304 OpaqueValueExpr *opaqueValue = nullptr; 7305 Expr *commonExpr = nullptr; 7306 if (!LHSExpr) { 7307 commonExpr = CondExpr; 7308 // Lower out placeholder types first. This is important so that we don't 7309 // try to capture a placeholder. This happens in few cases in C++; such 7310 // as Objective-C++'s dictionary subscripting syntax. 7311 if (commonExpr->hasPlaceholderType()) { 7312 ExprResult result = CheckPlaceholderExpr(commonExpr); 7313 if (!result.isUsable()) return ExprError(); 7314 commonExpr = result.get(); 7315 } 7316 // We usually want to apply unary conversions *before* saving, except 7317 // in the special case of a C++ l-value conditional. 7318 if (!(getLangOpts().CPlusPlus 7319 && !commonExpr->isTypeDependent() 7320 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7321 && commonExpr->isGLValue() 7322 && commonExpr->isOrdinaryOrBitFieldObject() 7323 && RHSExpr->isOrdinaryOrBitFieldObject() 7324 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7325 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7326 if (commonRes.isInvalid()) 7327 return ExprError(); 7328 commonExpr = commonRes.get(); 7329 } 7330 7331 // If the common expression is a class or array prvalue, materialize it 7332 // so that we can safely refer to it multiple times. 7333 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7334 commonExpr->getType()->isArrayType())) { 7335 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7336 if (MatExpr.isInvalid()) 7337 return ExprError(); 7338 commonExpr = MatExpr.get(); 7339 } 7340 7341 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7342 commonExpr->getType(), 7343 commonExpr->getValueKind(), 7344 commonExpr->getObjectKind(), 7345 commonExpr); 7346 LHSExpr = CondExpr = opaqueValue; 7347 } 7348 7349 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7350 ExprValueKind VK = VK_RValue; 7351 ExprObjectKind OK = OK_Ordinary; 7352 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7353 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7354 VK, OK, QuestionLoc); 7355 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7356 RHS.isInvalid()) 7357 return ExprError(); 7358 7359 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7360 RHS.get()); 7361 7362 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7363 7364 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7365 Context); 7366 7367 if (!commonExpr) 7368 return new (Context) 7369 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7370 RHS.get(), result, VK, OK); 7371 7372 return new (Context) BinaryConditionalOperator( 7373 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7374 ColonLoc, result, VK, OK); 7375 } 7376 7377 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7378 // being closely modeled after the C99 spec:-). The odd characteristic of this 7379 // routine is it effectively iqnores the qualifiers on the top level pointee. 7380 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7381 // FIXME: add a couple examples in this comment. 7382 static Sema::AssignConvertType 7383 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7384 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7385 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7386 7387 // get the "pointed to" type (ignoring qualifiers at the top level) 7388 const Type *lhptee, *rhptee; 7389 Qualifiers lhq, rhq; 7390 std::tie(lhptee, lhq) = 7391 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7392 std::tie(rhptee, rhq) = 7393 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7394 7395 Sema::AssignConvertType ConvTy = Sema::Compatible; 7396 7397 // C99 6.5.16.1p1: This following citation is common to constraints 7398 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7399 // qualifiers of the type *pointed to* by the right; 7400 7401 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7402 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7403 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7404 // Ignore lifetime for further calculation. 7405 lhq.removeObjCLifetime(); 7406 rhq.removeObjCLifetime(); 7407 } 7408 7409 if (!lhq.compatiblyIncludes(rhq)) { 7410 // Treat address-space mismatches as fatal. TODO: address subspaces 7411 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7412 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7413 7414 // It's okay to add or remove GC or lifetime qualifiers when converting to 7415 // and from void*. 7416 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7417 .compatiblyIncludes( 7418 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7419 && (lhptee->isVoidType() || rhptee->isVoidType())) 7420 ; // keep old 7421 7422 // Treat lifetime mismatches as fatal. 7423 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7424 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7425 7426 // For GCC/MS compatibility, other qualifier mismatches are treated 7427 // as still compatible in C. 7428 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7429 } 7430 7431 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7432 // incomplete type and the other is a pointer to a qualified or unqualified 7433 // version of void... 7434 if (lhptee->isVoidType()) { 7435 if (rhptee->isIncompleteOrObjectType()) 7436 return ConvTy; 7437 7438 // As an extension, we allow cast to/from void* to function pointer. 7439 assert(rhptee->isFunctionType()); 7440 return Sema::FunctionVoidPointer; 7441 } 7442 7443 if (rhptee->isVoidType()) { 7444 if (lhptee->isIncompleteOrObjectType()) 7445 return ConvTy; 7446 7447 // As an extension, we allow cast to/from void* to function pointer. 7448 assert(lhptee->isFunctionType()); 7449 return Sema::FunctionVoidPointer; 7450 } 7451 7452 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7453 // unqualified versions of compatible types, ... 7454 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7455 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7456 // Check if the pointee types are compatible ignoring the sign. 7457 // We explicitly check for char so that we catch "char" vs 7458 // "unsigned char" on systems where "char" is unsigned. 7459 if (lhptee->isCharType()) 7460 ltrans = S.Context.UnsignedCharTy; 7461 else if (lhptee->hasSignedIntegerRepresentation()) 7462 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7463 7464 if (rhptee->isCharType()) 7465 rtrans = S.Context.UnsignedCharTy; 7466 else if (rhptee->hasSignedIntegerRepresentation()) 7467 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7468 7469 if (ltrans == rtrans) { 7470 // Types are compatible ignoring the sign. Qualifier incompatibility 7471 // takes priority over sign incompatibility because the sign 7472 // warning can be disabled. 7473 if (ConvTy != Sema::Compatible) 7474 return ConvTy; 7475 7476 return Sema::IncompatiblePointerSign; 7477 } 7478 7479 // If we are a multi-level pointer, it's possible that our issue is simply 7480 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7481 // the eventual target type is the same and the pointers have the same 7482 // level of indirection, this must be the issue. 7483 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7484 do { 7485 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7486 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7487 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7488 7489 if (lhptee == rhptee) 7490 return Sema::IncompatibleNestedPointerQualifiers; 7491 } 7492 7493 // General pointer incompatibility takes priority over qualifiers. 7494 return Sema::IncompatiblePointer; 7495 } 7496 if (!S.getLangOpts().CPlusPlus && 7497 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7498 return Sema::IncompatiblePointer; 7499 return ConvTy; 7500 } 7501 7502 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7503 /// block pointer types are compatible or whether a block and normal pointer 7504 /// are compatible. It is more restrict than comparing two function pointer 7505 // types. 7506 static Sema::AssignConvertType 7507 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7508 QualType RHSType) { 7509 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7510 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7511 7512 QualType lhptee, rhptee; 7513 7514 // get the "pointed to" type (ignoring qualifiers at the top level) 7515 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7516 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7517 7518 // In C++, the types have to match exactly. 7519 if (S.getLangOpts().CPlusPlus) 7520 return Sema::IncompatibleBlockPointer; 7521 7522 Sema::AssignConvertType ConvTy = Sema::Compatible; 7523 7524 // For blocks we enforce that qualifiers are identical. 7525 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7526 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7527 if (S.getLangOpts().OpenCL) { 7528 LQuals.removeAddressSpace(); 7529 RQuals.removeAddressSpace(); 7530 } 7531 if (LQuals != RQuals) 7532 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7533 7534 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7535 // assignment. 7536 // The current behavior is similar to C++ lambdas. A block might be 7537 // assigned to a variable iff its return type and parameters are compatible 7538 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7539 // an assignment. Presumably it should behave in way that a function pointer 7540 // assignment does in C, so for each parameter and return type: 7541 // * CVR and address space of LHS should be a superset of CVR and address 7542 // space of RHS. 7543 // * unqualified types should be compatible. 7544 if (S.getLangOpts().OpenCL) { 7545 if (!S.Context.typesAreBlockPointerCompatible( 7546 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7547 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7548 return Sema::IncompatibleBlockPointer; 7549 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7550 return Sema::IncompatibleBlockPointer; 7551 7552 return ConvTy; 7553 } 7554 7555 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7556 /// for assignment compatibility. 7557 static Sema::AssignConvertType 7558 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7559 QualType RHSType) { 7560 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7561 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7562 7563 if (LHSType->isObjCBuiltinType()) { 7564 // Class is not compatible with ObjC object pointers. 7565 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7566 !RHSType->isObjCQualifiedClassType()) 7567 return Sema::IncompatiblePointer; 7568 return Sema::Compatible; 7569 } 7570 if (RHSType->isObjCBuiltinType()) { 7571 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7572 !LHSType->isObjCQualifiedClassType()) 7573 return Sema::IncompatiblePointer; 7574 return Sema::Compatible; 7575 } 7576 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7577 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7578 7579 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7580 // make an exception for id<P> 7581 !LHSType->isObjCQualifiedIdType()) 7582 return Sema::CompatiblePointerDiscardsQualifiers; 7583 7584 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7585 return Sema::Compatible; 7586 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7587 return Sema::IncompatibleObjCQualifiedId; 7588 return Sema::IncompatiblePointer; 7589 } 7590 7591 Sema::AssignConvertType 7592 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7593 QualType LHSType, QualType RHSType) { 7594 // Fake up an opaque expression. We don't actually care about what 7595 // cast operations are required, so if CheckAssignmentConstraints 7596 // adds casts to this they'll be wasted, but fortunately that doesn't 7597 // usually happen on valid code. 7598 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7599 ExprResult RHSPtr = &RHSExpr; 7600 CastKind K; 7601 7602 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7603 } 7604 7605 /// This helper function returns true if QT is a vector type that has element 7606 /// type ElementType. 7607 static bool isVector(QualType QT, QualType ElementType) { 7608 if (const VectorType *VT = QT->getAs<VectorType>()) 7609 return VT->getElementType() == ElementType; 7610 return false; 7611 } 7612 7613 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7614 /// has code to accommodate several GCC extensions when type checking 7615 /// pointers. Here are some objectionable examples that GCC considers warnings: 7616 /// 7617 /// int a, *pint; 7618 /// short *pshort; 7619 /// struct foo *pfoo; 7620 /// 7621 /// pint = pshort; // warning: assignment from incompatible pointer type 7622 /// a = pint; // warning: assignment makes integer from pointer without a cast 7623 /// pint = a; // warning: assignment makes pointer from integer without a cast 7624 /// pint = pfoo; // warning: assignment from incompatible pointer type 7625 /// 7626 /// As a result, the code for dealing with pointers is more complex than the 7627 /// C99 spec dictates. 7628 /// 7629 /// Sets 'Kind' for any result kind except Incompatible. 7630 Sema::AssignConvertType 7631 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7632 CastKind &Kind, bool ConvertRHS) { 7633 QualType RHSType = RHS.get()->getType(); 7634 QualType OrigLHSType = LHSType; 7635 7636 // Get canonical types. We're not formatting these types, just comparing 7637 // them. 7638 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7639 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7640 7641 // Common case: no conversion required. 7642 if (LHSType == RHSType) { 7643 Kind = CK_NoOp; 7644 return Compatible; 7645 } 7646 7647 // If we have an atomic type, try a non-atomic assignment, then just add an 7648 // atomic qualification step. 7649 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7650 Sema::AssignConvertType result = 7651 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7652 if (result != Compatible) 7653 return result; 7654 if (Kind != CK_NoOp && ConvertRHS) 7655 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7656 Kind = CK_NonAtomicToAtomic; 7657 return Compatible; 7658 } 7659 7660 // If the left-hand side is a reference type, then we are in a 7661 // (rare!) case where we've allowed the use of references in C, 7662 // e.g., as a parameter type in a built-in function. In this case, 7663 // just make sure that the type referenced is compatible with the 7664 // right-hand side type. The caller is responsible for adjusting 7665 // LHSType so that the resulting expression does not have reference 7666 // type. 7667 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7668 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7669 Kind = CK_LValueBitCast; 7670 return Compatible; 7671 } 7672 return Incompatible; 7673 } 7674 7675 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7676 // to the same ExtVector type. 7677 if (LHSType->isExtVectorType()) { 7678 if (RHSType->isExtVectorType()) 7679 return Incompatible; 7680 if (RHSType->isArithmeticType()) { 7681 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7682 if (ConvertRHS) 7683 RHS = prepareVectorSplat(LHSType, RHS.get()); 7684 Kind = CK_VectorSplat; 7685 return Compatible; 7686 } 7687 } 7688 7689 // Conversions to or from vector type. 7690 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7691 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7692 // Allow assignments of an AltiVec vector type to an equivalent GCC 7693 // vector type and vice versa 7694 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7695 Kind = CK_BitCast; 7696 return Compatible; 7697 } 7698 7699 // If we are allowing lax vector conversions, and LHS and RHS are both 7700 // vectors, the total size only needs to be the same. This is a bitcast; 7701 // no bits are changed but the result type is different. 7702 if (isLaxVectorConversion(RHSType, LHSType)) { 7703 Kind = CK_BitCast; 7704 return IncompatibleVectors; 7705 } 7706 } 7707 7708 // When the RHS comes from another lax conversion (e.g. binops between 7709 // scalars and vectors) the result is canonicalized as a vector. When the 7710 // LHS is also a vector, the lax is allowed by the condition above. Handle 7711 // the case where LHS is a scalar. 7712 if (LHSType->isScalarType()) { 7713 const VectorType *VecType = RHSType->getAs<VectorType>(); 7714 if (VecType && VecType->getNumElements() == 1 && 7715 isLaxVectorConversion(RHSType, LHSType)) { 7716 ExprResult *VecExpr = &RHS; 7717 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7718 Kind = CK_BitCast; 7719 return Compatible; 7720 } 7721 } 7722 7723 return Incompatible; 7724 } 7725 7726 // Diagnose attempts to convert between __float128 and long double where 7727 // such conversions currently can't be handled. 7728 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7729 return Incompatible; 7730 7731 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7732 // discards the imaginary part. 7733 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7734 !LHSType->getAs<ComplexType>()) 7735 return Incompatible; 7736 7737 // Arithmetic conversions. 7738 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7739 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7740 if (ConvertRHS) 7741 Kind = PrepareScalarCast(RHS, LHSType); 7742 return Compatible; 7743 } 7744 7745 // Conversions to normal pointers. 7746 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7747 // U* -> T* 7748 if (isa<PointerType>(RHSType)) { 7749 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7750 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7751 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7752 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7753 } 7754 7755 // int -> T* 7756 if (RHSType->isIntegerType()) { 7757 Kind = CK_IntegralToPointer; // FIXME: null? 7758 return IntToPointer; 7759 } 7760 7761 // C pointers are not compatible with ObjC object pointers, 7762 // with two exceptions: 7763 if (isa<ObjCObjectPointerType>(RHSType)) { 7764 // - conversions to void* 7765 if (LHSPointer->getPointeeType()->isVoidType()) { 7766 Kind = CK_BitCast; 7767 return Compatible; 7768 } 7769 7770 // - conversions from 'Class' to the redefinition type 7771 if (RHSType->isObjCClassType() && 7772 Context.hasSameType(LHSType, 7773 Context.getObjCClassRedefinitionType())) { 7774 Kind = CK_BitCast; 7775 return Compatible; 7776 } 7777 7778 Kind = CK_BitCast; 7779 return IncompatiblePointer; 7780 } 7781 7782 // U^ -> void* 7783 if (RHSType->getAs<BlockPointerType>()) { 7784 if (LHSPointer->getPointeeType()->isVoidType()) { 7785 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7786 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7787 ->getPointeeType() 7788 .getAddressSpace(); 7789 Kind = 7790 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7791 return Compatible; 7792 } 7793 } 7794 7795 return Incompatible; 7796 } 7797 7798 // Conversions to block pointers. 7799 if (isa<BlockPointerType>(LHSType)) { 7800 // U^ -> T^ 7801 if (RHSType->isBlockPointerType()) { 7802 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7803 ->getPointeeType() 7804 .getAddressSpace(); 7805 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7806 ->getPointeeType() 7807 .getAddressSpace(); 7808 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7809 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7810 } 7811 7812 // int or null -> T^ 7813 if (RHSType->isIntegerType()) { 7814 Kind = CK_IntegralToPointer; // FIXME: null 7815 return IntToBlockPointer; 7816 } 7817 7818 // id -> T^ 7819 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7820 Kind = CK_AnyPointerToBlockPointerCast; 7821 return Compatible; 7822 } 7823 7824 // void* -> T^ 7825 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7826 if (RHSPT->getPointeeType()->isVoidType()) { 7827 Kind = CK_AnyPointerToBlockPointerCast; 7828 return Compatible; 7829 } 7830 7831 return Incompatible; 7832 } 7833 7834 // Conversions to Objective-C pointers. 7835 if (isa<ObjCObjectPointerType>(LHSType)) { 7836 // A* -> B* 7837 if (RHSType->isObjCObjectPointerType()) { 7838 Kind = CK_BitCast; 7839 Sema::AssignConvertType result = 7840 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7841 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7842 result == Compatible && 7843 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7844 result = IncompatibleObjCWeakRef; 7845 return result; 7846 } 7847 7848 // int or null -> A* 7849 if (RHSType->isIntegerType()) { 7850 Kind = CK_IntegralToPointer; // FIXME: null 7851 return IntToPointer; 7852 } 7853 7854 // In general, C pointers are not compatible with ObjC object pointers, 7855 // with two exceptions: 7856 if (isa<PointerType>(RHSType)) { 7857 Kind = CK_CPointerToObjCPointerCast; 7858 7859 // - conversions from 'void*' 7860 if (RHSType->isVoidPointerType()) { 7861 return Compatible; 7862 } 7863 7864 // - conversions to 'Class' from its redefinition type 7865 if (LHSType->isObjCClassType() && 7866 Context.hasSameType(RHSType, 7867 Context.getObjCClassRedefinitionType())) { 7868 return Compatible; 7869 } 7870 7871 return IncompatiblePointer; 7872 } 7873 7874 // Only under strict condition T^ is compatible with an Objective-C pointer. 7875 if (RHSType->isBlockPointerType() && 7876 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7877 if (ConvertRHS) 7878 maybeExtendBlockObject(RHS); 7879 Kind = CK_BlockPointerToObjCPointerCast; 7880 return Compatible; 7881 } 7882 7883 return Incompatible; 7884 } 7885 7886 // Conversions from pointers that are not covered by the above. 7887 if (isa<PointerType>(RHSType)) { 7888 // T* -> _Bool 7889 if (LHSType == Context.BoolTy) { 7890 Kind = CK_PointerToBoolean; 7891 return Compatible; 7892 } 7893 7894 // T* -> int 7895 if (LHSType->isIntegerType()) { 7896 Kind = CK_PointerToIntegral; 7897 return PointerToInt; 7898 } 7899 7900 return Incompatible; 7901 } 7902 7903 // Conversions from Objective-C pointers that are not covered by the above. 7904 if (isa<ObjCObjectPointerType>(RHSType)) { 7905 // T* -> _Bool 7906 if (LHSType == Context.BoolTy) { 7907 Kind = CK_PointerToBoolean; 7908 return Compatible; 7909 } 7910 7911 // T* -> int 7912 if (LHSType->isIntegerType()) { 7913 Kind = CK_PointerToIntegral; 7914 return PointerToInt; 7915 } 7916 7917 return Incompatible; 7918 } 7919 7920 // struct A -> struct B 7921 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7922 if (Context.typesAreCompatible(LHSType, RHSType)) { 7923 Kind = CK_NoOp; 7924 return Compatible; 7925 } 7926 } 7927 7928 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7929 Kind = CK_IntToOCLSampler; 7930 return Compatible; 7931 } 7932 7933 return Incompatible; 7934 } 7935 7936 /// Constructs a transparent union from an expression that is 7937 /// used to initialize the transparent union. 7938 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7939 ExprResult &EResult, QualType UnionType, 7940 FieldDecl *Field) { 7941 // Build an initializer list that designates the appropriate member 7942 // of the transparent union. 7943 Expr *E = EResult.get(); 7944 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7945 E, SourceLocation()); 7946 Initializer->setType(UnionType); 7947 Initializer->setInitializedFieldInUnion(Field); 7948 7949 // Build a compound literal constructing a value of the transparent 7950 // union type from this initializer list. 7951 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7952 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7953 VK_RValue, Initializer, false); 7954 } 7955 7956 Sema::AssignConvertType 7957 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7958 ExprResult &RHS) { 7959 QualType RHSType = RHS.get()->getType(); 7960 7961 // If the ArgType is a Union type, we want to handle a potential 7962 // transparent_union GCC extension. 7963 const RecordType *UT = ArgType->getAsUnionType(); 7964 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7965 return Incompatible; 7966 7967 // The field to initialize within the transparent union. 7968 RecordDecl *UD = UT->getDecl(); 7969 FieldDecl *InitField = nullptr; 7970 // It's compatible if the expression matches any of the fields. 7971 for (auto *it : UD->fields()) { 7972 if (it->getType()->isPointerType()) { 7973 // If the transparent union contains a pointer type, we allow: 7974 // 1) void pointer 7975 // 2) null pointer constant 7976 if (RHSType->isPointerType()) 7977 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7978 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7979 InitField = it; 7980 break; 7981 } 7982 7983 if (RHS.get()->isNullPointerConstant(Context, 7984 Expr::NPC_ValueDependentIsNull)) { 7985 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7986 CK_NullToPointer); 7987 InitField = it; 7988 break; 7989 } 7990 } 7991 7992 CastKind Kind; 7993 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7994 == Compatible) { 7995 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7996 InitField = it; 7997 break; 7998 } 7999 } 8000 8001 if (!InitField) 8002 return Incompatible; 8003 8004 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8005 return Compatible; 8006 } 8007 8008 Sema::AssignConvertType 8009 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8010 bool Diagnose, 8011 bool DiagnoseCFAudited, 8012 bool ConvertRHS) { 8013 // We need to be able to tell the caller whether we diagnosed a problem, if 8014 // they ask us to issue diagnostics. 8015 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8016 8017 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8018 // we can't avoid *all* modifications at the moment, so we need some somewhere 8019 // to put the updated value. 8020 ExprResult LocalRHS = CallerRHS; 8021 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8022 8023 if (getLangOpts().CPlusPlus) { 8024 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8025 // C++ 5.17p3: If the left operand is not of class type, the 8026 // expression is implicitly converted (C++ 4) to the 8027 // cv-unqualified type of the left operand. 8028 QualType RHSType = RHS.get()->getType(); 8029 if (Diagnose) { 8030 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8031 AA_Assigning); 8032 } else { 8033 ImplicitConversionSequence ICS = 8034 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8035 /*SuppressUserConversions=*/false, 8036 /*AllowExplicit=*/false, 8037 /*InOverloadResolution=*/false, 8038 /*CStyle=*/false, 8039 /*AllowObjCWritebackConversion=*/false); 8040 if (ICS.isFailure()) 8041 return Incompatible; 8042 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8043 ICS, AA_Assigning); 8044 } 8045 if (RHS.isInvalid()) 8046 return Incompatible; 8047 Sema::AssignConvertType result = Compatible; 8048 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8049 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8050 result = IncompatibleObjCWeakRef; 8051 return result; 8052 } 8053 8054 // FIXME: Currently, we fall through and treat C++ classes like C 8055 // structures. 8056 // FIXME: We also fall through for atomics; not sure what should 8057 // happen there, though. 8058 } else if (RHS.get()->getType() == Context.OverloadTy) { 8059 // As a set of extensions to C, we support overloading on functions. These 8060 // functions need to be resolved here. 8061 DeclAccessPair DAP; 8062 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8063 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8064 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8065 else 8066 return Incompatible; 8067 } 8068 8069 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8070 // a null pointer constant. 8071 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8072 LHSType->isBlockPointerType()) && 8073 RHS.get()->isNullPointerConstant(Context, 8074 Expr::NPC_ValueDependentIsNull)) { 8075 if (Diagnose || ConvertRHS) { 8076 CastKind Kind; 8077 CXXCastPath Path; 8078 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8079 /*IgnoreBaseAccess=*/false, Diagnose); 8080 if (ConvertRHS) 8081 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8082 } 8083 return Compatible; 8084 } 8085 8086 // This check seems unnatural, however it is necessary to ensure the proper 8087 // conversion of functions/arrays. If the conversion were done for all 8088 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8089 // expressions that suppress this implicit conversion (&, sizeof). 8090 // 8091 // Suppress this for references: C++ 8.5.3p5. 8092 if (!LHSType->isReferenceType()) { 8093 // FIXME: We potentially allocate here even if ConvertRHS is false. 8094 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8095 if (RHS.isInvalid()) 8096 return Incompatible; 8097 } 8098 CastKind Kind; 8099 Sema::AssignConvertType result = 8100 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8101 8102 // C99 6.5.16.1p2: The value of the right operand is converted to the 8103 // type of the assignment expression. 8104 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8105 // so that we can use references in built-in functions even in C. 8106 // The getNonReferenceType() call makes sure that the resulting expression 8107 // does not have reference type. 8108 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8109 QualType Ty = LHSType.getNonLValueExprType(Context); 8110 Expr *E = RHS.get(); 8111 8112 // Check for various Objective-C errors. If we are not reporting 8113 // diagnostics and just checking for errors, e.g., during overload 8114 // resolution, return Incompatible to indicate the failure. 8115 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8116 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8117 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8118 if (!Diagnose) 8119 return Incompatible; 8120 } 8121 if (getLangOpts().ObjC1 && 8122 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8123 E->getType(), E, Diagnose) || 8124 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8125 if (!Diagnose) 8126 return Incompatible; 8127 // Replace the expression with a corrected version and continue so we 8128 // can find further errors. 8129 RHS = E; 8130 return Compatible; 8131 } 8132 8133 if (ConvertRHS) 8134 RHS = ImpCastExprToType(E, Ty, Kind); 8135 } 8136 return result; 8137 } 8138 8139 namespace { 8140 /// The original operand to an operator, prior to the application of the usual 8141 /// arithmetic conversions and converting the arguments of a builtin operator 8142 /// candidate. 8143 struct OriginalOperand { 8144 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8145 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8146 Op = MTE->GetTemporaryExpr(); 8147 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8148 Op = BTE->getSubExpr(); 8149 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8150 Orig = ICE->getSubExprAsWritten(); 8151 Conversion = ICE->getConversionFunction(); 8152 } 8153 } 8154 8155 QualType getType() const { return Orig->getType(); } 8156 8157 Expr *Orig; 8158 NamedDecl *Conversion; 8159 }; 8160 } 8161 8162 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8163 ExprResult &RHS) { 8164 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8165 8166 Diag(Loc, diag::err_typecheck_invalid_operands) 8167 << OrigLHS.getType() << OrigRHS.getType() 8168 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8169 8170 // If a user-defined conversion was applied to either of the operands prior 8171 // to applying the built-in operator rules, tell the user about it. 8172 if (OrigLHS.Conversion) { 8173 Diag(OrigLHS.Conversion->getLocation(), 8174 diag::note_typecheck_invalid_operands_converted) 8175 << 0 << LHS.get()->getType(); 8176 } 8177 if (OrigRHS.Conversion) { 8178 Diag(OrigRHS.Conversion->getLocation(), 8179 diag::note_typecheck_invalid_operands_converted) 8180 << 1 << RHS.get()->getType(); 8181 } 8182 8183 return QualType(); 8184 } 8185 8186 // Diagnose cases where a scalar was implicitly converted to a vector and 8187 // diagnose the underlying types. Otherwise, diagnose the error 8188 // as invalid vector logical operands for non-C++ cases. 8189 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8190 ExprResult &RHS) { 8191 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8192 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8193 8194 bool LHSNatVec = LHSType->isVectorType(); 8195 bool RHSNatVec = RHSType->isVectorType(); 8196 8197 if (!(LHSNatVec && RHSNatVec)) { 8198 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8199 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8200 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8201 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8202 << Vector->getSourceRange(); 8203 return QualType(); 8204 } 8205 8206 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8207 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8208 << RHS.get()->getSourceRange(); 8209 8210 return QualType(); 8211 } 8212 8213 /// Try to convert a value of non-vector type to a vector type by converting 8214 /// the type to the element type of the vector and then performing a splat. 8215 /// If the language is OpenCL, we only use conversions that promote scalar 8216 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8217 /// for float->int. 8218 /// 8219 /// OpenCL V2.0 6.2.6.p2: 8220 /// An error shall occur if any scalar operand type has greater rank 8221 /// than the type of the vector element. 8222 /// 8223 /// \param scalar - if non-null, actually perform the conversions 8224 /// \return true if the operation fails (but without diagnosing the failure) 8225 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8226 QualType scalarTy, 8227 QualType vectorEltTy, 8228 QualType vectorTy, 8229 unsigned &DiagID) { 8230 // The conversion to apply to the scalar before splatting it, 8231 // if necessary. 8232 CastKind scalarCast = CK_NoOp; 8233 8234 if (vectorEltTy->isIntegralType(S.Context)) { 8235 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8236 (scalarTy->isIntegerType() && 8237 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8238 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8239 return true; 8240 } 8241 if (!scalarTy->isIntegralType(S.Context)) 8242 return true; 8243 scalarCast = CK_IntegralCast; 8244 } else if (vectorEltTy->isRealFloatingType()) { 8245 if (scalarTy->isRealFloatingType()) { 8246 if (S.getLangOpts().OpenCL && 8247 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8248 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8249 return true; 8250 } 8251 scalarCast = CK_FloatingCast; 8252 } 8253 else if (scalarTy->isIntegralType(S.Context)) 8254 scalarCast = CK_IntegralToFloating; 8255 else 8256 return true; 8257 } else { 8258 return true; 8259 } 8260 8261 // Adjust scalar if desired. 8262 if (scalar) { 8263 if (scalarCast != CK_NoOp) 8264 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8265 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8266 } 8267 return false; 8268 } 8269 8270 /// Convert vector E to a vector with the same number of elements but different 8271 /// element type. 8272 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8273 const auto *VecTy = E->getType()->getAs<VectorType>(); 8274 assert(VecTy && "Expression E must be a vector"); 8275 QualType NewVecTy = S.Context.getVectorType(ElementType, 8276 VecTy->getNumElements(), 8277 VecTy->getVectorKind()); 8278 8279 // Look through the implicit cast. Return the subexpression if its type is 8280 // NewVecTy. 8281 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8282 if (ICE->getSubExpr()->getType() == NewVecTy) 8283 return ICE->getSubExpr(); 8284 8285 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8286 return S.ImpCastExprToType(E, NewVecTy, Cast); 8287 } 8288 8289 /// Test if a (constant) integer Int can be casted to another integer type 8290 /// IntTy without losing precision. 8291 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8292 QualType OtherIntTy) { 8293 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8294 8295 // Reject cases where the value of the Int is unknown as that would 8296 // possibly cause truncation, but accept cases where the scalar can be 8297 // demoted without loss of precision. 8298 llvm::APSInt Result; 8299 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8300 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8301 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8302 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8303 8304 if (CstInt) { 8305 // If the scalar is constant and is of a higher order and has more active 8306 // bits that the vector element type, reject it. 8307 unsigned NumBits = IntSigned 8308 ? (Result.isNegative() ? Result.getMinSignedBits() 8309 : Result.getActiveBits()) 8310 : Result.getActiveBits(); 8311 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8312 return true; 8313 8314 // If the signedness of the scalar type and the vector element type 8315 // differs and the number of bits is greater than that of the vector 8316 // element reject it. 8317 return (IntSigned != OtherIntSigned && 8318 NumBits > S.Context.getIntWidth(OtherIntTy)); 8319 } 8320 8321 // Reject cases where the value of the scalar is not constant and it's 8322 // order is greater than that of the vector element type. 8323 return (Order < 0); 8324 } 8325 8326 /// Test if a (constant) integer Int can be casted to floating point type 8327 /// FloatTy without losing precision. 8328 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8329 QualType FloatTy) { 8330 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8331 8332 // Determine if the integer constant can be expressed as a floating point 8333 // number of the appropriate type. 8334 llvm::APSInt Result; 8335 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8336 uint64_t Bits = 0; 8337 if (CstInt) { 8338 // Reject constants that would be truncated if they were converted to 8339 // the floating point type. Test by simple to/from conversion. 8340 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8341 // could be avoided if there was a convertFromAPInt method 8342 // which could signal back if implicit truncation occurred. 8343 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8344 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8345 llvm::APFloat::rmTowardZero); 8346 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8347 !IntTy->hasSignedIntegerRepresentation()); 8348 bool Ignored = false; 8349 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8350 &Ignored); 8351 if (Result != ConvertBack) 8352 return true; 8353 } else { 8354 // Reject types that cannot be fully encoded into the mantissa of 8355 // the float. 8356 Bits = S.Context.getTypeSize(IntTy); 8357 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8358 S.Context.getFloatTypeSemantics(FloatTy)); 8359 if (Bits > FloatPrec) 8360 return true; 8361 } 8362 8363 return false; 8364 } 8365 8366 /// Attempt to convert and splat Scalar into a vector whose types matches 8367 /// Vector following GCC conversion rules. The rule is that implicit 8368 /// conversion can occur when Scalar can be casted to match Vector's element 8369 /// type without causing truncation of Scalar. 8370 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8371 ExprResult *Vector) { 8372 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8373 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8374 const VectorType *VT = VectorTy->getAs<VectorType>(); 8375 8376 assert(!isa<ExtVectorType>(VT) && 8377 "ExtVectorTypes should not be handled here!"); 8378 8379 QualType VectorEltTy = VT->getElementType(); 8380 8381 // Reject cases where the vector element type or the scalar element type are 8382 // not integral or floating point types. 8383 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8384 return true; 8385 8386 // The conversion to apply to the scalar before splatting it, 8387 // if necessary. 8388 CastKind ScalarCast = CK_NoOp; 8389 8390 // Accept cases where the vector elements are integers and the scalar is 8391 // an integer. 8392 // FIXME: Notionally if the scalar was a floating point value with a precise 8393 // integral representation, we could cast it to an appropriate integer 8394 // type and then perform the rest of the checks here. GCC will perform 8395 // this conversion in some cases as determined by the input language. 8396 // We should accept it on a language independent basis. 8397 if (VectorEltTy->isIntegralType(S.Context) && 8398 ScalarTy->isIntegralType(S.Context) && 8399 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8400 8401 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8402 return true; 8403 8404 ScalarCast = CK_IntegralCast; 8405 } else if (VectorEltTy->isRealFloatingType()) { 8406 if (ScalarTy->isRealFloatingType()) { 8407 8408 // Reject cases where the scalar type is not a constant and has a higher 8409 // Order than the vector element type. 8410 llvm::APFloat Result(0.0); 8411 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8412 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8413 if (!CstScalar && Order < 0) 8414 return true; 8415 8416 // If the scalar cannot be safely casted to the vector element type, 8417 // reject it. 8418 if (CstScalar) { 8419 bool Truncated = false; 8420 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8421 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8422 if (Truncated) 8423 return true; 8424 } 8425 8426 ScalarCast = CK_FloatingCast; 8427 } else if (ScalarTy->isIntegralType(S.Context)) { 8428 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8429 return true; 8430 8431 ScalarCast = CK_IntegralToFloating; 8432 } else 8433 return true; 8434 } 8435 8436 // Adjust scalar if desired. 8437 if (Scalar) { 8438 if (ScalarCast != CK_NoOp) 8439 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8440 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8441 } 8442 return false; 8443 } 8444 8445 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8446 SourceLocation Loc, bool IsCompAssign, 8447 bool AllowBothBool, 8448 bool AllowBoolConversions) { 8449 if (!IsCompAssign) { 8450 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8451 if (LHS.isInvalid()) 8452 return QualType(); 8453 } 8454 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8455 if (RHS.isInvalid()) 8456 return QualType(); 8457 8458 // For conversion purposes, we ignore any qualifiers. 8459 // For example, "const float" and "float" are equivalent. 8460 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8461 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8462 8463 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8464 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8465 assert(LHSVecType || RHSVecType); 8466 8467 // AltiVec-style "vector bool op vector bool" combinations are allowed 8468 // for some operators but not others. 8469 if (!AllowBothBool && 8470 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8471 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8472 return InvalidOperands(Loc, LHS, RHS); 8473 8474 // If the vector types are identical, return. 8475 if (Context.hasSameType(LHSType, RHSType)) 8476 return LHSType; 8477 8478 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8479 if (LHSVecType && RHSVecType && 8480 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8481 if (isa<ExtVectorType>(LHSVecType)) { 8482 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8483 return LHSType; 8484 } 8485 8486 if (!IsCompAssign) 8487 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8488 return RHSType; 8489 } 8490 8491 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8492 // can be mixed, with the result being the non-bool type. The non-bool 8493 // operand must have integer element type. 8494 if (AllowBoolConversions && LHSVecType && RHSVecType && 8495 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8496 (Context.getTypeSize(LHSVecType->getElementType()) == 8497 Context.getTypeSize(RHSVecType->getElementType()))) { 8498 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8499 LHSVecType->getElementType()->isIntegerType() && 8500 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8501 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8502 return LHSType; 8503 } 8504 if (!IsCompAssign && 8505 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8506 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8507 RHSVecType->getElementType()->isIntegerType()) { 8508 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8509 return RHSType; 8510 } 8511 } 8512 8513 // If there's a vector type and a scalar, try to convert the scalar to 8514 // the vector element type and splat. 8515 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8516 if (!RHSVecType) { 8517 if (isa<ExtVectorType>(LHSVecType)) { 8518 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8519 LHSVecType->getElementType(), LHSType, 8520 DiagID)) 8521 return LHSType; 8522 } else { 8523 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8524 return LHSType; 8525 } 8526 } 8527 if (!LHSVecType) { 8528 if (isa<ExtVectorType>(RHSVecType)) { 8529 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8530 LHSType, RHSVecType->getElementType(), 8531 RHSType, DiagID)) 8532 return RHSType; 8533 } else { 8534 if (LHS.get()->getValueKind() == VK_LValue || 8535 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8536 return RHSType; 8537 } 8538 } 8539 8540 // FIXME: The code below also handles conversion between vectors and 8541 // non-scalars, we should break this down into fine grained specific checks 8542 // and emit proper diagnostics. 8543 QualType VecType = LHSVecType ? LHSType : RHSType; 8544 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8545 QualType OtherType = LHSVecType ? RHSType : LHSType; 8546 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8547 if (isLaxVectorConversion(OtherType, VecType)) { 8548 // If we're allowing lax vector conversions, only the total (data) size 8549 // needs to be the same. For non compound assignment, if one of the types is 8550 // scalar, the result is always the vector type. 8551 if (!IsCompAssign) { 8552 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8553 return VecType; 8554 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8555 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8556 // type. Note that this is already done by non-compound assignments in 8557 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8558 // <1 x T> -> T. The result is also a vector type. 8559 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8560 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8561 ExprResult *RHSExpr = &RHS; 8562 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8563 return VecType; 8564 } 8565 } 8566 8567 // Okay, the expression is invalid. 8568 8569 // If there's a non-vector, non-real operand, diagnose that. 8570 if ((!RHSVecType && !RHSType->isRealType()) || 8571 (!LHSVecType && !LHSType->isRealType())) { 8572 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8573 << LHSType << RHSType 8574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8575 return QualType(); 8576 } 8577 8578 // OpenCL V1.1 6.2.6.p1: 8579 // If the operands are of more than one vector type, then an error shall 8580 // occur. Implicit conversions between vector types are not permitted, per 8581 // section 6.2.1. 8582 if (getLangOpts().OpenCL && 8583 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8584 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8585 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8586 << RHSType; 8587 return QualType(); 8588 } 8589 8590 8591 // If there is a vector type that is not a ExtVector and a scalar, we reach 8592 // this point if scalar could not be converted to the vector's element type 8593 // without truncation. 8594 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8595 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8596 QualType Scalar = LHSVecType ? RHSType : LHSType; 8597 QualType Vector = LHSVecType ? LHSType : RHSType; 8598 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8599 Diag(Loc, 8600 diag::err_typecheck_vector_not_convertable_implict_truncation) 8601 << ScalarOrVector << Scalar << Vector; 8602 8603 return QualType(); 8604 } 8605 8606 // Otherwise, use the generic diagnostic. 8607 Diag(Loc, DiagID) 8608 << LHSType << RHSType 8609 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8610 return QualType(); 8611 } 8612 8613 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8614 // expression. These are mainly cases where the null pointer is used as an 8615 // integer instead of a pointer. 8616 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8617 SourceLocation Loc, bool IsCompare) { 8618 // The canonical way to check for a GNU null is with isNullPointerConstant, 8619 // but we use a bit of a hack here for speed; this is a relatively 8620 // hot path, and isNullPointerConstant is slow. 8621 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8622 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8623 8624 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8625 8626 // Avoid analyzing cases where the result will either be invalid (and 8627 // diagnosed as such) or entirely valid and not something to warn about. 8628 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8629 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8630 return; 8631 8632 // Comparison operations would not make sense with a null pointer no matter 8633 // what the other expression is. 8634 if (!IsCompare) { 8635 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8636 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8637 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8638 return; 8639 } 8640 8641 // The rest of the operations only make sense with a null pointer 8642 // if the other expression is a pointer. 8643 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8644 NonNullType->canDecayToPointerType()) 8645 return; 8646 8647 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8648 << LHSNull /* LHS is NULL */ << NonNullType 8649 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8650 } 8651 8652 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8653 ExprResult &RHS, 8654 SourceLocation Loc, bool IsDiv) { 8655 // Check for division/remainder by zero. 8656 llvm::APSInt RHSValue; 8657 if (!RHS.get()->isValueDependent() && 8658 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8659 S.DiagRuntimeBehavior(Loc, RHS.get(), 8660 S.PDiag(diag::warn_remainder_division_by_zero) 8661 << IsDiv << RHS.get()->getSourceRange()); 8662 } 8663 8664 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8665 SourceLocation Loc, 8666 bool IsCompAssign, bool IsDiv) { 8667 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8668 8669 if (LHS.get()->getType()->isVectorType() || 8670 RHS.get()->getType()->isVectorType()) 8671 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8672 /*AllowBothBool*/getLangOpts().AltiVec, 8673 /*AllowBoolConversions*/false); 8674 8675 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8676 if (LHS.isInvalid() || RHS.isInvalid()) 8677 return QualType(); 8678 8679 8680 if (compType.isNull() || !compType->isArithmeticType()) 8681 return InvalidOperands(Loc, LHS, RHS); 8682 if (IsDiv) 8683 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8684 return compType; 8685 } 8686 8687 QualType Sema::CheckRemainderOperands( 8688 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8689 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8690 8691 if (LHS.get()->getType()->isVectorType() || 8692 RHS.get()->getType()->isVectorType()) { 8693 if (LHS.get()->getType()->hasIntegerRepresentation() && 8694 RHS.get()->getType()->hasIntegerRepresentation()) 8695 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8696 /*AllowBothBool*/getLangOpts().AltiVec, 8697 /*AllowBoolConversions*/false); 8698 return InvalidOperands(Loc, LHS, RHS); 8699 } 8700 8701 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8702 if (LHS.isInvalid() || RHS.isInvalid()) 8703 return QualType(); 8704 8705 if (compType.isNull() || !compType->isIntegerType()) 8706 return InvalidOperands(Loc, LHS, RHS); 8707 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8708 return compType; 8709 } 8710 8711 /// Diagnose invalid arithmetic on two void pointers. 8712 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8713 Expr *LHSExpr, Expr *RHSExpr) { 8714 S.Diag(Loc, S.getLangOpts().CPlusPlus 8715 ? diag::err_typecheck_pointer_arith_void_type 8716 : diag::ext_gnu_void_ptr) 8717 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8718 << RHSExpr->getSourceRange(); 8719 } 8720 8721 /// Diagnose invalid arithmetic on a void pointer. 8722 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8723 Expr *Pointer) { 8724 S.Diag(Loc, S.getLangOpts().CPlusPlus 8725 ? diag::err_typecheck_pointer_arith_void_type 8726 : diag::ext_gnu_void_ptr) 8727 << 0 /* one pointer */ << Pointer->getSourceRange(); 8728 } 8729 8730 /// Diagnose invalid arithmetic on a null pointer. 8731 /// 8732 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8733 /// idiom, which we recognize as a GNU extension. 8734 /// 8735 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8736 Expr *Pointer, bool IsGNUIdiom) { 8737 if (IsGNUIdiom) 8738 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8739 << Pointer->getSourceRange(); 8740 else 8741 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8742 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8743 } 8744 8745 /// Diagnose invalid arithmetic on two function pointers. 8746 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8747 Expr *LHS, Expr *RHS) { 8748 assert(LHS->getType()->isAnyPointerType()); 8749 assert(RHS->getType()->isAnyPointerType()); 8750 S.Diag(Loc, S.getLangOpts().CPlusPlus 8751 ? diag::err_typecheck_pointer_arith_function_type 8752 : diag::ext_gnu_ptr_func_arith) 8753 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8754 // We only show the second type if it differs from the first. 8755 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8756 RHS->getType()) 8757 << RHS->getType()->getPointeeType() 8758 << LHS->getSourceRange() << RHS->getSourceRange(); 8759 } 8760 8761 /// Diagnose invalid arithmetic on a function pointer. 8762 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8763 Expr *Pointer) { 8764 assert(Pointer->getType()->isAnyPointerType()); 8765 S.Diag(Loc, S.getLangOpts().CPlusPlus 8766 ? diag::err_typecheck_pointer_arith_function_type 8767 : diag::ext_gnu_ptr_func_arith) 8768 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8769 << 0 /* one pointer, so only one type */ 8770 << Pointer->getSourceRange(); 8771 } 8772 8773 /// Emit error if Operand is incomplete pointer type 8774 /// 8775 /// \returns True if pointer has incomplete type 8776 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8777 Expr *Operand) { 8778 QualType ResType = Operand->getType(); 8779 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8780 ResType = ResAtomicType->getValueType(); 8781 8782 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8783 QualType PointeeTy = ResType->getPointeeType(); 8784 return S.RequireCompleteType(Loc, PointeeTy, 8785 diag::err_typecheck_arithmetic_incomplete_type, 8786 PointeeTy, Operand->getSourceRange()); 8787 } 8788 8789 /// Check the validity of an arithmetic pointer operand. 8790 /// 8791 /// If the operand has pointer type, this code will check for pointer types 8792 /// which are invalid in arithmetic operations. These will be diagnosed 8793 /// appropriately, including whether or not the use is supported as an 8794 /// extension. 8795 /// 8796 /// \returns True when the operand is valid to use (even if as an extension). 8797 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8798 Expr *Operand) { 8799 QualType ResType = Operand->getType(); 8800 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8801 ResType = ResAtomicType->getValueType(); 8802 8803 if (!ResType->isAnyPointerType()) return true; 8804 8805 QualType PointeeTy = ResType->getPointeeType(); 8806 if (PointeeTy->isVoidType()) { 8807 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8808 return !S.getLangOpts().CPlusPlus; 8809 } 8810 if (PointeeTy->isFunctionType()) { 8811 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8812 return !S.getLangOpts().CPlusPlus; 8813 } 8814 8815 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8816 8817 return true; 8818 } 8819 8820 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8821 /// operands. 8822 /// 8823 /// This routine will diagnose any invalid arithmetic on pointer operands much 8824 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8825 /// for emitting a single diagnostic even for operations where both LHS and RHS 8826 /// are (potentially problematic) pointers. 8827 /// 8828 /// \returns True when the operand is valid to use (even if as an extension). 8829 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8830 Expr *LHSExpr, Expr *RHSExpr) { 8831 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8832 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8833 if (!isLHSPointer && !isRHSPointer) return true; 8834 8835 QualType LHSPointeeTy, RHSPointeeTy; 8836 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8837 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8838 8839 // if both are pointers check if operation is valid wrt address spaces 8840 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8841 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8842 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8843 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8844 S.Diag(Loc, 8845 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8846 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8847 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8848 return false; 8849 } 8850 } 8851 8852 // Check for arithmetic on pointers to incomplete types. 8853 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8854 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8855 if (isLHSVoidPtr || isRHSVoidPtr) { 8856 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8857 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8858 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8859 8860 return !S.getLangOpts().CPlusPlus; 8861 } 8862 8863 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8864 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8865 if (isLHSFuncPtr || isRHSFuncPtr) { 8866 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8867 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8868 RHSExpr); 8869 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8870 8871 return !S.getLangOpts().CPlusPlus; 8872 } 8873 8874 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8875 return false; 8876 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8877 return false; 8878 8879 return true; 8880 } 8881 8882 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8883 /// literal. 8884 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8885 Expr *LHSExpr, Expr *RHSExpr) { 8886 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8887 Expr* IndexExpr = RHSExpr; 8888 if (!StrExpr) { 8889 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8890 IndexExpr = LHSExpr; 8891 } 8892 8893 bool IsStringPlusInt = StrExpr && 8894 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8895 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8896 return; 8897 8898 llvm::APSInt index; 8899 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8900 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8901 if (index.isNonNegative() && 8902 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8903 index.isUnsigned())) 8904 return; 8905 } 8906 8907 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8908 Self.Diag(OpLoc, diag::warn_string_plus_int) 8909 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8910 8911 // Only print a fixit for "str" + int, not for int + "str". 8912 if (IndexExpr == RHSExpr) { 8913 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8914 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8915 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8916 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8917 << FixItHint::CreateInsertion(EndLoc, "]"); 8918 } else 8919 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8920 } 8921 8922 /// Emit a warning when adding a char literal to a string. 8923 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8924 Expr *LHSExpr, Expr *RHSExpr) { 8925 const Expr *StringRefExpr = LHSExpr; 8926 const CharacterLiteral *CharExpr = 8927 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8928 8929 if (!CharExpr) { 8930 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8931 StringRefExpr = RHSExpr; 8932 } 8933 8934 if (!CharExpr || !StringRefExpr) 8935 return; 8936 8937 const QualType StringType = StringRefExpr->getType(); 8938 8939 // Return if not a PointerType. 8940 if (!StringType->isAnyPointerType()) 8941 return; 8942 8943 // Return if not a CharacterType. 8944 if (!StringType->getPointeeType()->isAnyCharacterType()) 8945 return; 8946 8947 ASTContext &Ctx = Self.getASTContext(); 8948 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8949 8950 const QualType CharType = CharExpr->getType(); 8951 if (!CharType->isAnyCharacterType() && 8952 CharType->isIntegerType() && 8953 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8954 Self.Diag(OpLoc, diag::warn_string_plus_char) 8955 << DiagRange << Ctx.CharTy; 8956 } else { 8957 Self.Diag(OpLoc, diag::warn_string_plus_char) 8958 << DiagRange << CharExpr->getType(); 8959 } 8960 8961 // Only print a fixit for str + char, not for char + str. 8962 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8963 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8964 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8965 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8966 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8967 << FixItHint::CreateInsertion(EndLoc, "]"); 8968 } else { 8969 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8970 } 8971 } 8972 8973 /// Emit error when two pointers are incompatible. 8974 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8975 Expr *LHSExpr, Expr *RHSExpr) { 8976 assert(LHSExpr->getType()->isAnyPointerType()); 8977 assert(RHSExpr->getType()->isAnyPointerType()); 8978 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8979 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8980 << RHSExpr->getSourceRange(); 8981 } 8982 8983 // C99 6.5.6 8984 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8985 SourceLocation Loc, BinaryOperatorKind Opc, 8986 QualType* CompLHSTy) { 8987 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8988 8989 if (LHS.get()->getType()->isVectorType() || 8990 RHS.get()->getType()->isVectorType()) { 8991 QualType compType = CheckVectorOperands( 8992 LHS, RHS, Loc, CompLHSTy, 8993 /*AllowBothBool*/getLangOpts().AltiVec, 8994 /*AllowBoolConversions*/getLangOpts().ZVector); 8995 if (CompLHSTy) *CompLHSTy = compType; 8996 return compType; 8997 } 8998 8999 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9000 if (LHS.isInvalid() || RHS.isInvalid()) 9001 return QualType(); 9002 9003 // Diagnose "string literal" '+' int and string '+' "char literal". 9004 if (Opc == BO_Add) { 9005 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9006 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9007 } 9008 9009 // handle the common case first (both operands are arithmetic). 9010 if (!compType.isNull() && compType->isArithmeticType()) { 9011 if (CompLHSTy) *CompLHSTy = compType; 9012 return compType; 9013 } 9014 9015 // Type-checking. Ultimately the pointer's going to be in PExp; 9016 // note that we bias towards the LHS being the pointer. 9017 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9018 9019 bool isObjCPointer; 9020 if (PExp->getType()->isPointerType()) { 9021 isObjCPointer = false; 9022 } else if (PExp->getType()->isObjCObjectPointerType()) { 9023 isObjCPointer = true; 9024 } else { 9025 std::swap(PExp, IExp); 9026 if (PExp->getType()->isPointerType()) { 9027 isObjCPointer = false; 9028 } else if (PExp->getType()->isObjCObjectPointerType()) { 9029 isObjCPointer = true; 9030 } else { 9031 return InvalidOperands(Loc, LHS, RHS); 9032 } 9033 } 9034 assert(PExp->getType()->isAnyPointerType()); 9035 9036 if (!IExp->getType()->isIntegerType()) 9037 return InvalidOperands(Loc, LHS, RHS); 9038 9039 // Adding to a null pointer results in undefined behavior. 9040 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9041 Context, Expr::NPC_ValueDependentIsNotNull)) { 9042 // In C++ adding zero to a null pointer is defined. 9043 llvm::APSInt KnownVal; 9044 if (!getLangOpts().CPlusPlus || 9045 (!IExp->isValueDependent() && 9046 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9047 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9048 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9049 Context, BO_Add, PExp, IExp); 9050 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9051 } 9052 } 9053 9054 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9055 return QualType(); 9056 9057 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9058 return QualType(); 9059 9060 // Check array bounds for pointer arithemtic 9061 CheckArrayAccess(PExp, IExp); 9062 9063 if (CompLHSTy) { 9064 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9065 if (LHSTy.isNull()) { 9066 LHSTy = LHS.get()->getType(); 9067 if (LHSTy->isPromotableIntegerType()) 9068 LHSTy = Context.getPromotedIntegerType(LHSTy); 9069 } 9070 *CompLHSTy = LHSTy; 9071 } 9072 9073 return PExp->getType(); 9074 } 9075 9076 // C99 6.5.6 9077 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9078 SourceLocation Loc, 9079 QualType* CompLHSTy) { 9080 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9081 9082 if (LHS.get()->getType()->isVectorType() || 9083 RHS.get()->getType()->isVectorType()) { 9084 QualType compType = CheckVectorOperands( 9085 LHS, RHS, Loc, CompLHSTy, 9086 /*AllowBothBool*/getLangOpts().AltiVec, 9087 /*AllowBoolConversions*/getLangOpts().ZVector); 9088 if (CompLHSTy) *CompLHSTy = compType; 9089 return compType; 9090 } 9091 9092 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9093 if (LHS.isInvalid() || RHS.isInvalid()) 9094 return QualType(); 9095 9096 // Enforce type constraints: C99 6.5.6p3. 9097 9098 // Handle the common case first (both operands are arithmetic). 9099 if (!compType.isNull() && compType->isArithmeticType()) { 9100 if (CompLHSTy) *CompLHSTy = compType; 9101 return compType; 9102 } 9103 9104 // Either ptr - int or ptr - ptr. 9105 if (LHS.get()->getType()->isAnyPointerType()) { 9106 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9107 9108 // Diagnose bad cases where we step over interface counts. 9109 if (LHS.get()->getType()->isObjCObjectPointerType() && 9110 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9111 return QualType(); 9112 9113 // The result type of a pointer-int computation is the pointer type. 9114 if (RHS.get()->getType()->isIntegerType()) { 9115 // Subtracting from a null pointer should produce a warning. 9116 // The last argument to the diagnose call says this doesn't match the 9117 // GNU int-to-pointer idiom. 9118 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9119 Expr::NPC_ValueDependentIsNotNull)) { 9120 // In C++ adding zero to a null pointer is defined. 9121 llvm::APSInt KnownVal; 9122 if (!getLangOpts().CPlusPlus || 9123 (!RHS.get()->isValueDependent() && 9124 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9125 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9126 } 9127 } 9128 9129 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9130 return QualType(); 9131 9132 // Check array bounds for pointer arithemtic 9133 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9134 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9135 9136 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9137 return LHS.get()->getType(); 9138 } 9139 9140 // Handle pointer-pointer subtractions. 9141 if (const PointerType *RHSPTy 9142 = RHS.get()->getType()->getAs<PointerType>()) { 9143 QualType rpointee = RHSPTy->getPointeeType(); 9144 9145 if (getLangOpts().CPlusPlus) { 9146 // Pointee types must be the same: C++ [expr.add] 9147 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9148 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9149 } 9150 } else { 9151 // Pointee types must be compatible C99 6.5.6p3 9152 if (!Context.typesAreCompatible( 9153 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9154 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9155 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9156 return QualType(); 9157 } 9158 } 9159 9160 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9161 LHS.get(), RHS.get())) 9162 return QualType(); 9163 9164 // FIXME: Add warnings for nullptr - ptr. 9165 9166 // The pointee type may have zero size. As an extension, a structure or 9167 // union may have zero size or an array may have zero length. In this 9168 // case subtraction does not make sense. 9169 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9170 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9171 if (ElementSize.isZero()) { 9172 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9173 << rpointee.getUnqualifiedType() 9174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9175 } 9176 } 9177 9178 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9179 return Context.getPointerDiffType(); 9180 } 9181 } 9182 9183 return InvalidOperands(Loc, LHS, RHS); 9184 } 9185 9186 static bool isScopedEnumerationType(QualType T) { 9187 if (const EnumType *ET = T->getAs<EnumType>()) 9188 return ET->getDecl()->isScoped(); 9189 return false; 9190 } 9191 9192 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9193 SourceLocation Loc, BinaryOperatorKind Opc, 9194 QualType LHSType) { 9195 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9196 // so skip remaining warnings as we don't want to modify values within Sema. 9197 if (S.getLangOpts().OpenCL) 9198 return; 9199 9200 llvm::APSInt Right; 9201 // Check right/shifter operand 9202 if (RHS.get()->isValueDependent() || 9203 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9204 return; 9205 9206 if (Right.isNegative()) { 9207 S.DiagRuntimeBehavior(Loc, RHS.get(), 9208 S.PDiag(diag::warn_shift_negative) 9209 << RHS.get()->getSourceRange()); 9210 return; 9211 } 9212 llvm::APInt LeftBits(Right.getBitWidth(), 9213 S.Context.getTypeSize(LHS.get()->getType())); 9214 if (Right.uge(LeftBits)) { 9215 S.DiagRuntimeBehavior(Loc, RHS.get(), 9216 S.PDiag(diag::warn_shift_gt_typewidth) 9217 << RHS.get()->getSourceRange()); 9218 return; 9219 } 9220 if (Opc != BO_Shl) 9221 return; 9222 9223 // When left shifting an ICE which is signed, we can check for overflow which 9224 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9225 // integers have defined behavior modulo one more than the maximum value 9226 // representable in the result type, so never warn for those. 9227 llvm::APSInt Left; 9228 if (LHS.get()->isValueDependent() || 9229 LHSType->hasUnsignedIntegerRepresentation() || 9230 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9231 return; 9232 9233 // If LHS does not have a signed type and non-negative value 9234 // then, the behavior is undefined. Warn about it. 9235 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9236 S.DiagRuntimeBehavior(Loc, LHS.get(), 9237 S.PDiag(diag::warn_shift_lhs_negative) 9238 << LHS.get()->getSourceRange()); 9239 return; 9240 } 9241 9242 llvm::APInt ResultBits = 9243 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9244 if (LeftBits.uge(ResultBits)) 9245 return; 9246 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9247 Result = Result.shl(Right); 9248 9249 // Print the bit representation of the signed integer as an unsigned 9250 // hexadecimal number. 9251 SmallString<40> HexResult; 9252 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9253 9254 // If we are only missing a sign bit, this is less likely to result in actual 9255 // bugs -- if the result is cast back to an unsigned type, it will have the 9256 // expected value. Thus we place this behind a different warning that can be 9257 // turned off separately if needed. 9258 if (LeftBits == ResultBits - 1) { 9259 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9260 << HexResult << LHSType 9261 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9262 return; 9263 } 9264 9265 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9266 << HexResult.str() << Result.getMinSignedBits() << LHSType 9267 << Left.getBitWidth() << LHS.get()->getSourceRange() 9268 << RHS.get()->getSourceRange(); 9269 } 9270 9271 /// Return the resulting type when a vector is shifted 9272 /// by a scalar or vector shift amount. 9273 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9274 SourceLocation Loc, bool IsCompAssign) { 9275 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9276 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9277 !LHS.get()->getType()->isVectorType()) { 9278 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9279 << RHS.get()->getType() << LHS.get()->getType() 9280 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9281 return QualType(); 9282 } 9283 9284 if (!IsCompAssign) { 9285 LHS = S.UsualUnaryConversions(LHS.get()); 9286 if (LHS.isInvalid()) return QualType(); 9287 } 9288 9289 RHS = S.UsualUnaryConversions(RHS.get()); 9290 if (RHS.isInvalid()) return QualType(); 9291 9292 QualType LHSType = LHS.get()->getType(); 9293 // Note that LHS might be a scalar because the routine calls not only in 9294 // OpenCL case. 9295 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9296 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9297 9298 // Note that RHS might not be a vector. 9299 QualType RHSType = RHS.get()->getType(); 9300 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9301 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9302 9303 // The operands need to be integers. 9304 if (!LHSEleType->isIntegerType()) { 9305 S.Diag(Loc, diag::err_typecheck_expect_int) 9306 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9307 return QualType(); 9308 } 9309 9310 if (!RHSEleType->isIntegerType()) { 9311 S.Diag(Loc, diag::err_typecheck_expect_int) 9312 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9313 return QualType(); 9314 } 9315 9316 if (!LHSVecTy) { 9317 assert(RHSVecTy); 9318 if (IsCompAssign) 9319 return RHSType; 9320 if (LHSEleType != RHSEleType) { 9321 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9322 LHSEleType = RHSEleType; 9323 } 9324 QualType VecTy = 9325 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9326 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9327 LHSType = VecTy; 9328 } else if (RHSVecTy) { 9329 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9330 // are applied component-wise. So if RHS is a vector, then ensure 9331 // that the number of elements is the same as LHS... 9332 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9333 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9334 << LHS.get()->getType() << RHS.get()->getType() 9335 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9336 return QualType(); 9337 } 9338 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9339 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9340 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9341 if (LHSBT != RHSBT && 9342 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9343 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9344 << LHS.get()->getType() << RHS.get()->getType() 9345 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9346 } 9347 } 9348 } else { 9349 // ...else expand RHS to match the number of elements in LHS. 9350 QualType VecTy = 9351 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9352 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9353 } 9354 9355 return LHSType; 9356 } 9357 9358 // C99 6.5.7 9359 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9360 SourceLocation Loc, BinaryOperatorKind Opc, 9361 bool IsCompAssign) { 9362 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9363 9364 // Vector shifts promote their scalar inputs to vector type. 9365 if (LHS.get()->getType()->isVectorType() || 9366 RHS.get()->getType()->isVectorType()) { 9367 if (LangOpts.ZVector) { 9368 // The shift operators for the z vector extensions work basically 9369 // like general shifts, except that neither the LHS nor the RHS is 9370 // allowed to be a "vector bool". 9371 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9372 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9373 return InvalidOperands(Loc, LHS, RHS); 9374 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9375 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9376 return InvalidOperands(Loc, LHS, RHS); 9377 } 9378 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9379 } 9380 9381 // Shifts don't perform usual arithmetic conversions, they just do integer 9382 // promotions on each operand. C99 6.5.7p3 9383 9384 // For the LHS, do usual unary conversions, but then reset them away 9385 // if this is a compound assignment. 9386 ExprResult OldLHS = LHS; 9387 LHS = UsualUnaryConversions(LHS.get()); 9388 if (LHS.isInvalid()) 9389 return QualType(); 9390 QualType LHSType = LHS.get()->getType(); 9391 if (IsCompAssign) LHS = OldLHS; 9392 9393 // The RHS is simpler. 9394 RHS = UsualUnaryConversions(RHS.get()); 9395 if (RHS.isInvalid()) 9396 return QualType(); 9397 QualType RHSType = RHS.get()->getType(); 9398 9399 // C99 6.5.7p2: Each of the operands shall have integer type. 9400 if (!LHSType->hasIntegerRepresentation() || 9401 !RHSType->hasIntegerRepresentation()) 9402 return InvalidOperands(Loc, LHS, RHS); 9403 9404 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9405 // hasIntegerRepresentation() above instead of this. 9406 if (isScopedEnumerationType(LHSType) || 9407 isScopedEnumerationType(RHSType)) { 9408 return InvalidOperands(Loc, LHS, RHS); 9409 } 9410 // Sanity-check shift operands 9411 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9412 9413 // "The type of the result is that of the promoted left operand." 9414 return LHSType; 9415 } 9416 9417 /// If two different enums are compared, raise a warning. 9418 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9419 Expr *RHS) { 9420 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9421 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9422 9423 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9424 if (!LHSEnumType) 9425 return; 9426 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9427 if (!RHSEnumType) 9428 return; 9429 9430 // Ignore anonymous enums. 9431 if (!LHSEnumType->getDecl()->getIdentifier() && 9432 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9433 return; 9434 if (!RHSEnumType->getDecl()->getIdentifier() && 9435 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9436 return; 9437 9438 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9439 return; 9440 9441 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9442 << LHSStrippedType << RHSStrippedType 9443 << LHS->getSourceRange() << RHS->getSourceRange(); 9444 } 9445 9446 /// Diagnose bad pointer comparisons. 9447 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9448 ExprResult &LHS, ExprResult &RHS, 9449 bool IsError) { 9450 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9451 : diag::ext_typecheck_comparison_of_distinct_pointers) 9452 << LHS.get()->getType() << RHS.get()->getType() 9453 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9454 } 9455 9456 /// Returns false if the pointers are converted to a composite type, 9457 /// true otherwise. 9458 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9459 ExprResult &LHS, ExprResult &RHS) { 9460 // C++ [expr.rel]p2: 9461 // [...] Pointer conversions (4.10) and qualification 9462 // conversions (4.4) are performed on pointer operands (or on 9463 // a pointer operand and a null pointer constant) to bring 9464 // them to their composite pointer type. [...] 9465 // 9466 // C++ [expr.eq]p1 uses the same notion for (in)equality 9467 // comparisons of pointers. 9468 9469 QualType LHSType = LHS.get()->getType(); 9470 QualType RHSType = RHS.get()->getType(); 9471 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9472 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9473 9474 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9475 if (T.isNull()) { 9476 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9477 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9478 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9479 else 9480 S.InvalidOperands(Loc, LHS, RHS); 9481 return true; 9482 } 9483 9484 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9485 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9486 return false; 9487 } 9488 9489 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9490 ExprResult &LHS, 9491 ExprResult &RHS, 9492 bool IsError) { 9493 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9494 : diag::ext_typecheck_comparison_of_fptr_to_void) 9495 << LHS.get()->getType() << RHS.get()->getType() 9496 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9497 } 9498 9499 static bool isObjCObjectLiteral(ExprResult &E) { 9500 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9501 case Stmt::ObjCArrayLiteralClass: 9502 case Stmt::ObjCDictionaryLiteralClass: 9503 case Stmt::ObjCStringLiteralClass: 9504 case Stmt::ObjCBoxedExprClass: 9505 return true; 9506 default: 9507 // Note that ObjCBoolLiteral is NOT an object literal! 9508 return false; 9509 } 9510 } 9511 9512 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9513 const ObjCObjectPointerType *Type = 9514 LHS->getType()->getAs<ObjCObjectPointerType>(); 9515 9516 // If this is not actually an Objective-C object, bail out. 9517 if (!Type) 9518 return false; 9519 9520 // Get the LHS object's interface type. 9521 QualType InterfaceType = Type->getPointeeType(); 9522 9523 // If the RHS isn't an Objective-C object, bail out. 9524 if (!RHS->getType()->isObjCObjectPointerType()) 9525 return false; 9526 9527 // Try to find the -isEqual: method. 9528 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9529 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9530 InterfaceType, 9531 /*instance=*/true); 9532 if (!Method) { 9533 if (Type->isObjCIdType()) { 9534 // For 'id', just check the global pool. 9535 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9536 /*receiverId=*/true); 9537 } else { 9538 // Check protocols. 9539 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9540 /*instance=*/true); 9541 } 9542 } 9543 9544 if (!Method) 9545 return false; 9546 9547 QualType T = Method->parameters()[0]->getType(); 9548 if (!T->isObjCObjectPointerType()) 9549 return false; 9550 9551 QualType R = Method->getReturnType(); 9552 if (!R->isScalarType()) 9553 return false; 9554 9555 return true; 9556 } 9557 9558 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9559 FromE = FromE->IgnoreParenImpCasts(); 9560 switch (FromE->getStmtClass()) { 9561 default: 9562 break; 9563 case Stmt::ObjCStringLiteralClass: 9564 // "string literal" 9565 return LK_String; 9566 case Stmt::ObjCArrayLiteralClass: 9567 // "array literal" 9568 return LK_Array; 9569 case Stmt::ObjCDictionaryLiteralClass: 9570 // "dictionary literal" 9571 return LK_Dictionary; 9572 case Stmt::BlockExprClass: 9573 return LK_Block; 9574 case Stmt::ObjCBoxedExprClass: { 9575 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9576 switch (Inner->getStmtClass()) { 9577 case Stmt::IntegerLiteralClass: 9578 case Stmt::FloatingLiteralClass: 9579 case Stmt::CharacterLiteralClass: 9580 case Stmt::ObjCBoolLiteralExprClass: 9581 case Stmt::CXXBoolLiteralExprClass: 9582 // "numeric literal" 9583 return LK_Numeric; 9584 case Stmt::ImplicitCastExprClass: { 9585 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9586 // Boolean literals can be represented by implicit casts. 9587 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9588 return LK_Numeric; 9589 break; 9590 } 9591 default: 9592 break; 9593 } 9594 return LK_Boxed; 9595 } 9596 } 9597 return LK_None; 9598 } 9599 9600 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9601 ExprResult &LHS, ExprResult &RHS, 9602 BinaryOperator::Opcode Opc){ 9603 Expr *Literal; 9604 Expr *Other; 9605 if (isObjCObjectLiteral(LHS)) { 9606 Literal = LHS.get(); 9607 Other = RHS.get(); 9608 } else { 9609 Literal = RHS.get(); 9610 Other = LHS.get(); 9611 } 9612 9613 // Don't warn on comparisons against nil. 9614 Other = Other->IgnoreParenCasts(); 9615 if (Other->isNullPointerConstant(S.getASTContext(), 9616 Expr::NPC_ValueDependentIsNotNull)) 9617 return; 9618 9619 // This should be kept in sync with warn_objc_literal_comparison. 9620 // LK_String should always be after the other literals, since it has its own 9621 // warning flag. 9622 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9623 assert(LiteralKind != Sema::LK_Block); 9624 if (LiteralKind == Sema::LK_None) { 9625 llvm_unreachable("Unknown Objective-C object literal kind"); 9626 } 9627 9628 if (LiteralKind == Sema::LK_String) 9629 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9630 << Literal->getSourceRange(); 9631 else 9632 S.Diag(Loc, diag::warn_objc_literal_comparison) 9633 << LiteralKind << Literal->getSourceRange(); 9634 9635 if (BinaryOperator::isEqualityOp(Opc) && 9636 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9637 SourceLocation Start = LHS.get()->getBeginLoc(); 9638 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9639 CharSourceRange OpRange = 9640 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9641 9642 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9643 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9644 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9645 << FixItHint::CreateInsertion(End, "]"); 9646 } 9647 } 9648 9649 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9650 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9651 ExprResult &RHS, SourceLocation Loc, 9652 BinaryOperatorKind Opc) { 9653 // Check that left hand side is !something. 9654 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9655 if (!UO || UO->getOpcode() != UO_LNot) return; 9656 9657 // Only check if the right hand side is non-bool arithmetic type. 9658 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9659 9660 // Make sure that the something in !something is not bool. 9661 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9662 if (SubExpr->isKnownToHaveBooleanValue()) return; 9663 9664 // Emit warning. 9665 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9666 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9667 << Loc << IsBitwiseOp; 9668 9669 // First note suggest !(x < y) 9670 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9671 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9672 FirstClose = S.getLocForEndOfToken(FirstClose); 9673 if (FirstClose.isInvalid()) 9674 FirstOpen = SourceLocation(); 9675 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9676 << IsBitwiseOp 9677 << FixItHint::CreateInsertion(FirstOpen, "(") 9678 << FixItHint::CreateInsertion(FirstClose, ")"); 9679 9680 // Second note suggests (!x) < y 9681 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9682 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9683 SecondClose = S.getLocForEndOfToken(SecondClose); 9684 if (SecondClose.isInvalid()) 9685 SecondOpen = SourceLocation(); 9686 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9687 << FixItHint::CreateInsertion(SecondOpen, "(") 9688 << FixItHint::CreateInsertion(SecondClose, ")"); 9689 } 9690 9691 // Get the decl for a simple expression: a reference to a variable, 9692 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9693 static ValueDecl *getCompareDecl(Expr *E) { 9694 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9695 return DR->getDecl(); 9696 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9697 if (Ivar->isFreeIvar()) 9698 return Ivar->getDecl(); 9699 } 9700 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9701 if (Mem->isImplicitAccess()) 9702 return Mem->getMemberDecl(); 9703 } 9704 return nullptr; 9705 } 9706 9707 /// Diagnose some forms of syntactically-obvious tautological comparison. 9708 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9709 Expr *LHS, Expr *RHS, 9710 BinaryOperatorKind Opc) { 9711 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9712 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9713 9714 QualType LHSType = LHS->getType(); 9715 QualType RHSType = RHS->getType(); 9716 if (LHSType->hasFloatingRepresentation() || 9717 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9718 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9719 S.inTemplateInstantiation()) 9720 return; 9721 9722 // Comparisons between two array types are ill-formed for operator<=>, so 9723 // we shouldn't emit any additional warnings about it. 9724 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9725 return; 9726 9727 // For non-floating point types, check for self-comparisons of the form 9728 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9729 // often indicate logic errors in the program. 9730 // 9731 // NOTE: Don't warn about comparison expressions resulting from macro 9732 // expansion. Also don't warn about comparisons which are only self 9733 // comparisons within a template instantiation. The warnings should catch 9734 // obvious cases in the definition of the template anyways. The idea is to 9735 // warn when the typed comparison operator will always evaluate to the same 9736 // result. 9737 ValueDecl *DL = getCompareDecl(LHSStripped); 9738 ValueDecl *DR = getCompareDecl(RHSStripped); 9739 if (DL && DR && declaresSameEntity(DL, DR)) { 9740 StringRef Result; 9741 switch (Opc) { 9742 case BO_EQ: case BO_LE: case BO_GE: 9743 Result = "true"; 9744 break; 9745 case BO_NE: case BO_LT: case BO_GT: 9746 Result = "false"; 9747 break; 9748 case BO_Cmp: 9749 Result = "'std::strong_ordering::equal'"; 9750 break; 9751 default: 9752 break; 9753 } 9754 S.DiagRuntimeBehavior(Loc, nullptr, 9755 S.PDiag(diag::warn_comparison_always) 9756 << 0 /*self-comparison*/ << !Result.empty() 9757 << Result); 9758 } else if (DL && DR && 9759 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9760 !DL->isWeak() && !DR->isWeak()) { 9761 // What is it always going to evaluate to? 9762 StringRef Result; 9763 switch(Opc) { 9764 case BO_EQ: // e.g. array1 == array2 9765 Result = "false"; 9766 break; 9767 case BO_NE: // e.g. array1 != array2 9768 Result = "true"; 9769 break; 9770 default: // e.g. array1 <= array2 9771 // The best we can say is 'a constant' 9772 break; 9773 } 9774 S.DiagRuntimeBehavior(Loc, nullptr, 9775 S.PDiag(diag::warn_comparison_always) 9776 << 1 /*array comparison*/ 9777 << !Result.empty() << Result); 9778 } 9779 9780 if (isa<CastExpr>(LHSStripped)) 9781 LHSStripped = LHSStripped->IgnoreParenCasts(); 9782 if (isa<CastExpr>(RHSStripped)) 9783 RHSStripped = RHSStripped->IgnoreParenCasts(); 9784 9785 // Warn about comparisons against a string constant (unless the other 9786 // operand is null); the user probably wants strcmp. 9787 Expr *LiteralString = nullptr; 9788 Expr *LiteralStringStripped = nullptr; 9789 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9790 !RHSStripped->isNullPointerConstant(S.Context, 9791 Expr::NPC_ValueDependentIsNull)) { 9792 LiteralString = LHS; 9793 LiteralStringStripped = LHSStripped; 9794 } else if ((isa<StringLiteral>(RHSStripped) || 9795 isa<ObjCEncodeExpr>(RHSStripped)) && 9796 !LHSStripped->isNullPointerConstant(S.Context, 9797 Expr::NPC_ValueDependentIsNull)) { 9798 LiteralString = RHS; 9799 LiteralStringStripped = RHSStripped; 9800 } 9801 9802 if (LiteralString) { 9803 S.DiagRuntimeBehavior(Loc, nullptr, 9804 S.PDiag(diag::warn_stringcompare) 9805 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9806 << LiteralString->getSourceRange()); 9807 } 9808 } 9809 9810 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9811 switch (CK) { 9812 default: { 9813 #ifndef NDEBUG 9814 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9815 << "\n"; 9816 #endif 9817 llvm_unreachable("unhandled cast kind"); 9818 } 9819 case CK_UserDefinedConversion: 9820 return ICK_Identity; 9821 case CK_LValueToRValue: 9822 return ICK_Lvalue_To_Rvalue; 9823 case CK_ArrayToPointerDecay: 9824 return ICK_Array_To_Pointer; 9825 case CK_FunctionToPointerDecay: 9826 return ICK_Function_To_Pointer; 9827 case CK_IntegralCast: 9828 return ICK_Integral_Conversion; 9829 case CK_FloatingCast: 9830 return ICK_Floating_Conversion; 9831 case CK_IntegralToFloating: 9832 case CK_FloatingToIntegral: 9833 return ICK_Floating_Integral; 9834 case CK_IntegralComplexCast: 9835 case CK_FloatingComplexCast: 9836 case CK_FloatingComplexToIntegralComplex: 9837 case CK_IntegralComplexToFloatingComplex: 9838 return ICK_Complex_Conversion; 9839 case CK_FloatingComplexToReal: 9840 case CK_FloatingRealToComplex: 9841 case CK_IntegralComplexToReal: 9842 case CK_IntegralRealToComplex: 9843 return ICK_Complex_Real; 9844 } 9845 } 9846 9847 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9848 QualType FromType, 9849 SourceLocation Loc) { 9850 // Check for a narrowing implicit conversion. 9851 StandardConversionSequence SCS; 9852 SCS.setAsIdentityConversion(); 9853 SCS.setToType(0, FromType); 9854 SCS.setToType(1, ToType); 9855 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9856 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9857 9858 APValue PreNarrowingValue; 9859 QualType PreNarrowingType; 9860 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9861 PreNarrowingType, 9862 /*IgnoreFloatToIntegralConversion*/ true)) { 9863 case NK_Dependent_Narrowing: 9864 // Implicit conversion to a narrower type, but the expression is 9865 // value-dependent so we can't tell whether it's actually narrowing. 9866 case NK_Not_Narrowing: 9867 return false; 9868 9869 case NK_Constant_Narrowing: 9870 // Implicit conversion to a narrower type, and the value is not a constant 9871 // expression. 9872 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9873 << /*Constant*/ 1 9874 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9875 return true; 9876 9877 case NK_Variable_Narrowing: 9878 // Implicit conversion to a narrower type, and the value is not a constant 9879 // expression. 9880 case NK_Type_Narrowing: 9881 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9882 << /*Constant*/ 0 << FromType << ToType; 9883 // TODO: It's not a constant expression, but what if the user intended it 9884 // to be? Can we produce notes to help them figure out why it isn't? 9885 return true; 9886 } 9887 llvm_unreachable("unhandled case in switch"); 9888 } 9889 9890 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9891 ExprResult &LHS, 9892 ExprResult &RHS, 9893 SourceLocation Loc) { 9894 using CCT = ComparisonCategoryType; 9895 9896 QualType LHSType = LHS.get()->getType(); 9897 QualType RHSType = RHS.get()->getType(); 9898 // Dig out the original argument type and expression before implicit casts 9899 // were applied. These are the types/expressions we need to check the 9900 // [expr.spaceship] requirements against. 9901 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9902 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9903 QualType LHSStrippedType = LHSStripped.get()->getType(); 9904 QualType RHSStrippedType = RHSStripped.get()->getType(); 9905 9906 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9907 // other is not, the program is ill-formed. 9908 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9909 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9910 return QualType(); 9911 } 9912 9913 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9914 RHSStrippedType->isEnumeralType(); 9915 if (NumEnumArgs == 1) { 9916 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9917 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9918 if (OtherTy->hasFloatingRepresentation()) { 9919 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9920 return QualType(); 9921 } 9922 } 9923 if (NumEnumArgs == 2) { 9924 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9925 // type E, the operator yields the result of converting the operands 9926 // to the underlying type of E and applying <=> to the converted operands. 9927 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 9928 S.InvalidOperands(Loc, LHS, RHS); 9929 return QualType(); 9930 } 9931 QualType IntType = 9932 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 9933 assert(IntType->isArithmeticType()); 9934 9935 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 9936 // promote the boolean type, and all other promotable integer types, to 9937 // avoid this. 9938 if (IntType->isPromotableIntegerType()) 9939 IntType = S.Context.getPromotedIntegerType(IntType); 9940 9941 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 9942 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 9943 LHSType = RHSType = IntType; 9944 } 9945 9946 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 9947 // usual arithmetic conversions are applied to the operands. 9948 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9949 if (LHS.isInvalid() || RHS.isInvalid()) 9950 return QualType(); 9951 if (Type.isNull()) 9952 return S.InvalidOperands(Loc, LHS, RHS); 9953 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9954 9955 bool HasNarrowing = checkThreeWayNarrowingConversion( 9956 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 9957 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 9958 RHS.get()->getBeginLoc()); 9959 if (HasNarrowing) 9960 return QualType(); 9961 9962 assert(!Type.isNull() && "composite type for <=> has not been set"); 9963 9964 auto TypeKind = [&]() { 9965 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 9966 if (CT->getElementType()->hasFloatingRepresentation()) 9967 return CCT::WeakEquality; 9968 return CCT::StrongEquality; 9969 } 9970 if (Type->isIntegralOrEnumerationType()) 9971 return CCT::StrongOrdering; 9972 if (Type->hasFloatingRepresentation()) 9973 return CCT::PartialOrdering; 9974 llvm_unreachable("other types are unimplemented"); 9975 }(); 9976 9977 return S.CheckComparisonCategoryType(TypeKind, Loc); 9978 } 9979 9980 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9981 ExprResult &RHS, 9982 SourceLocation Loc, 9983 BinaryOperatorKind Opc) { 9984 if (Opc == BO_Cmp) 9985 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 9986 9987 // C99 6.5.8p3 / C99 6.5.9p4 9988 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9989 if (LHS.isInvalid() || RHS.isInvalid()) 9990 return QualType(); 9991 if (Type.isNull()) 9992 return S.InvalidOperands(Loc, LHS, RHS); 9993 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9994 9995 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9996 9997 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 9998 return S.InvalidOperands(Loc, LHS, RHS); 9999 10000 // Check for comparisons of floating point operands using != and ==. 10001 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10002 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10003 10004 // The result of comparisons is 'bool' in C++, 'int' in C. 10005 return S.Context.getLogicalOperationType(); 10006 } 10007 10008 // C99 6.5.8, C++ [expr.rel] 10009 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10010 SourceLocation Loc, 10011 BinaryOperatorKind Opc) { 10012 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10013 bool IsThreeWay = Opc == BO_Cmp; 10014 auto IsAnyPointerType = [](ExprResult E) { 10015 QualType Ty = E.get()->getType(); 10016 return Ty->isPointerType() || Ty->isMemberPointerType(); 10017 }; 10018 10019 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10020 // type, array-to-pointer, ..., conversions are performed on both operands to 10021 // bring them to their composite type. 10022 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10023 // any type-related checks. 10024 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10025 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10026 if (LHS.isInvalid()) 10027 return QualType(); 10028 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10029 if (RHS.isInvalid()) 10030 return QualType(); 10031 } else { 10032 LHS = DefaultLvalueConversion(LHS.get()); 10033 if (LHS.isInvalid()) 10034 return QualType(); 10035 RHS = DefaultLvalueConversion(RHS.get()); 10036 if (RHS.isInvalid()) 10037 return QualType(); 10038 } 10039 10040 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10041 10042 // Handle vector comparisons separately. 10043 if (LHS.get()->getType()->isVectorType() || 10044 RHS.get()->getType()->isVectorType()) 10045 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10046 10047 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10048 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10049 10050 QualType LHSType = LHS.get()->getType(); 10051 QualType RHSType = RHS.get()->getType(); 10052 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10053 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10054 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10055 10056 const Expr::NullPointerConstantKind LHSNullKind = 10057 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10058 const Expr::NullPointerConstantKind RHSNullKind = 10059 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10060 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10061 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10062 10063 auto computeResultTy = [&]() { 10064 if (Opc != BO_Cmp) 10065 return Context.getLogicalOperationType(); 10066 assert(getLangOpts().CPlusPlus); 10067 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10068 10069 QualType CompositeTy = LHS.get()->getType(); 10070 assert(!CompositeTy->isReferenceType()); 10071 10072 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10073 return CheckComparisonCategoryType(Kind, Loc); 10074 }; 10075 10076 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10077 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10078 // result is of type std::strong_equality 10079 if (CompositeTy->isFunctionPointerType() || 10080 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10081 // FIXME: consider making the function pointer case produce 10082 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10083 // and direction polls 10084 return buildResultTy(ComparisonCategoryType::StrongEquality); 10085 10086 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10087 // pointer type, p <=> q is of type std::strong_ordering. 10088 if (CompositeTy->isPointerType()) { 10089 // P0946R0: Comparisons between a null pointer constant and an object 10090 // pointer result in std::strong_equality 10091 if (LHSIsNull != RHSIsNull) 10092 return buildResultTy(ComparisonCategoryType::StrongEquality); 10093 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10094 } 10095 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10096 // TODO: Extend support for operator<=> to ObjC types. 10097 return InvalidOperands(Loc, LHS, RHS); 10098 }; 10099 10100 10101 if (!IsRelational && LHSIsNull != RHSIsNull) { 10102 bool IsEquality = Opc == BO_EQ; 10103 if (RHSIsNull) 10104 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10105 RHS.get()->getSourceRange()); 10106 else 10107 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10108 LHS.get()->getSourceRange()); 10109 } 10110 10111 if ((LHSType->isIntegerType() && !LHSIsNull) || 10112 (RHSType->isIntegerType() && !RHSIsNull)) { 10113 // Skip normal pointer conversion checks in this case; we have better 10114 // diagnostics for this below. 10115 } else if (getLangOpts().CPlusPlus) { 10116 // Equality comparison of a function pointer to a void pointer is invalid, 10117 // but we allow it as an extension. 10118 // FIXME: If we really want to allow this, should it be part of composite 10119 // pointer type computation so it works in conditionals too? 10120 if (!IsRelational && 10121 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10122 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10123 // This is a gcc extension compatibility comparison. 10124 // In a SFINAE context, we treat this as a hard error to maintain 10125 // conformance with the C++ standard. 10126 diagnoseFunctionPointerToVoidComparison( 10127 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10128 10129 if (isSFINAEContext()) 10130 return QualType(); 10131 10132 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10133 return computeResultTy(); 10134 } 10135 10136 // C++ [expr.eq]p2: 10137 // If at least one operand is a pointer [...] bring them to their 10138 // composite pointer type. 10139 // C++ [expr.spaceship]p6 10140 // If at least one of the operands is of pointer type, [...] bring them 10141 // to their composite pointer type. 10142 // C++ [expr.rel]p2: 10143 // If both operands are pointers, [...] bring them to their composite 10144 // pointer type. 10145 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10146 (IsRelational ? 2 : 1) && 10147 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10148 RHSType->isObjCObjectPointerType()))) { 10149 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10150 return QualType(); 10151 return computeResultTy(); 10152 } 10153 } else if (LHSType->isPointerType() && 10154 RHSType->isPointerType()) { // C99 6.5.8p2 10155 // All of the following pointer-related warnings are GCC extensions, except 10156 // when handling null pointer constants. 10157 QualType LCanPointeeTy = 10158 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10159 QualType RCanPointeeTy = 10160 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10161 10162 // C99 6.5.9p2 and C99 6.5.8p2 10163 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10164 RCanPointeeTy.getUnqualifiedType())) { 10165 // Valid unless a relational comparison of function pointers 10166 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10167 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10168 << LHSType << RHSType << LHS.get()->getSourceRange() 10169 << RHS.get()->getSourceRange(); 10170 } 10171 } else if (!IsRelational && 10172 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10173 // Valid unless comparison between non-null pointer and function pointer 10174 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10175 && !LHSIsNull && !RHSIsNull) 10176 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10177 /*isError*/false); 10178 } else { 10179 // Invalid 10180 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10181 } 10182 if (LCanPointeeTy != RCanPointeeTy) { 10183 // Treat NULL constant as a special case in OpenCL. 10184 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10185 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10186 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10187 Diag(Loc, 10188 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10189 << LHSType << RHSType << 0 /* comparison */ 10190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10191 } 10192 } 10193 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10194 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10195 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10196 : CK_BitCast; 10197 if (LHSIsNull && !RHSIsNull) 10198 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10199 else 10200 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10201 } 10202 return computeResultTy(); 10203 } 10204 10205 if (getLangOpts().CPlusPlus) { 10206 // C++ [expr.eq]p4: 10207 // Two operands of type std::nullptr_t or one operand of type 10208 // std::nullptr_t and the other a null pointer constant compare equal. 10209 if (!IsRelational && LHSIsNull && RHSIsNull) { 10210 if (LHSType->isNullPtrType()) { 10211 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10212 return computeResultTy(); 10213 } 10214 if (RHSType->isNullPtrType()) { 10215 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10216 return computeResultTy(); 10217 } 10218 } 10219 10220 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10221 // These aren't covered by the composite pointer type rules. 10222 if (!IsRelational && RHSType->isNullPtrType() && 10223 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10224 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10225 return computeResultTy(); 10226 } 10227 if (!IsRelational && LHSType->isNullPtrType() && 10228 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10229 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10230 return computeResultTy(); 10231 } 10232 10233 if (IsRelational && 10234 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10235 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10236 // HACK: Relational comparison of nullptr_t against a pointer type is 10237 // invalid per DR583, but we allow it within std::less<> and friends, 10238 // since otherwise common uses of it break. 10239 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10240 // friends to have std::nullptr_t overload candidates. 10241 DeclContext *DC = CurContext; 10242 if (isa<FunctionDecl>(DC)) 10243 DC = DC->getParent(); 10244 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10245 if (CTSD->isInStdNamespace() && 10246 llvm::StringSwitch<bool>(CTSD->getName()) 10247 .Cases("less", "less_equal", "greater", "greater_equal", true) 10248 .Default(false)) { 10249 if (RHSType->isNullPtrType()) 10250 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10251 else 10252 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10253 return computeResultTy(); 10254 } 10255 } 10256 } 10257 10258 // C++ [expr.eq]p2: 10259 // If at least one operand is a pointer to member, [...] bring them to 10260 // their composite pointer type. 10261 if (!IsRelational && 10262 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10263 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10264 return QualType(); 10265 else 10266 return computeResultTy(); 10267 } 10268 } 10269 10270 // Handle block pointer types. 10271 if (!IsRelational && LHSType->isBlockPointerType() && 10272 RHSType->isBlockPointerType()) { 10273 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10274 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10275 10276 if (!LHSIsNull && !RHSIsNull && 10277 !Context.typesAreCompatible(lpointee, rpointee)) { 10278 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10279 << LHSType << RHSType << LHS.get()->getSourceRange() 10280 << RHS.get()->getSourceRange(); 10281 } 10282 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10283 return computeResultTy(); 10284 } 10285 10286 // Allow block pointers to be compared with null pointer constants. 10287 if (!IsRelational 10288 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10289 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10290 if (!LHSIsNull && !RHSIsNull) { 10291 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10292 ->getPointeeType()->isVoidType()) 10293 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10294 ->getPointeeType()->isVoidType()))) 10295 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10296 << LHSType << RHSType << LHS.get()->getSourceRange() 10297 << RHS.get()->getSourceRange(); 10298 } 10299 if (LHSIsNull && !RHSIsNull) 10300 LHS = ImpCastExprToType(LHS.get(), RHSType, 10301 RHSType->isPointerType() ? CK_BitCast 10302 : CK_AnyPointerToBlockPointerCast); 10303 else 10304 RHS = ImpCastExprToType(RHS.get(), LHSType, 10305 LHSType->isPointerType() ? CK_BitCast 10306 : CK_AnyPointerToBlockPointerCast); 10307 return computeResultTy(); 10308 } 10309 10310 if (LHSType->isObjCObjectPointerType() || 10311 RHSType->isObjCObjectPointerType()) { 10312 const PointerType *LPT = LHSType->getAs<PointerType>(); 10313 const PointerType *RPT = RHSType->getAs<PointerType>(); 10314 if (LPT || RPT) { 10315 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10316 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10317 10318 if (!LPtrToVoid && !RPtrToVoid && 10319 !Context.typesAreCompatible(LHSType, RHSType)) { 10320 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10321 /*isError*/false); 10322 } 10323 if (LHSIsNull && !RHSIsNull) { 10324 Expr *E = LHS.get(); 10325 if (getLangOpts().ObjCAutoRefCount) 10326 CheckObjCConversion(SourceRange(), RHSType, E, 10327 CCK_ImplicitConversion); 10328 LHS = ImpCastExprToType(E, RHSType, 10329 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10330 } 10331 else { 10332 Expr *E = RHS.get(); 10333 if (getLangOpts().ObjCAutoRefCount) 10334 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10335 /*Diagnose=*/true, 10336 /*DiagnoseCFAudited=*/false, Opc); 10337 RHS = ImpCastExprToType(E, LHSType, 10338 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10339 } 10340 return computeResultTy(); 10341 } 10342 if (LHSType->isObjCObjectPointerType() && 10343 RHSType->isObjCObjectPointerType()) { 10344 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10345 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10346 /*isError*/false); 10347 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10348 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10349 10350 if (LHSIsNull && !RHSIsNull) 10351 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10352 else 10353 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10354 return computeResultTy(); 10355 } 10356 10357 if (!IsRelational && LHSType->isBlockPointerType() && 10358 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10359 LHS = ImpCastExprToType(LHS.get(), RHSType, 10360 CK_BlockPointerToObjCPointerCast); 10361 return computeResultTy(); 10362 } else if (!IsRelational && 10363 LHSType->isBlockCompatibleObjCPointerType(Context) && 10364 RHSType->isBlockPointerType()) { 10365 RHS = ImpCastExprToType(RHS.get(), LHSType, 10366 CK_BlockPointerToObjCPointerCast); 10367 return computeResultTy(); 10368 } 10369 } 10370 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10371 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10372 unsigned DiagID = 0; 10373 bool isError = false; 10374 if (LangOpts.DebuggerSupport) { 10375 // Under a debugger, allow the comparison of pointers to integers, 10376 // since users tend to want to compare addresses. 10377 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10378 (RHSIsNull && RHSType->isIntegerType())) { 10379 if (IsRelational) { 10380 isError = getLangOpts().CPlusPlus; 10381 DiagID = 10382 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10383 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10384 } 10385 } else if (getLangOpts().CPlusPlus) { 10386 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10387 isError = true; 10388 } else if (IsRelational) 10389 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10390 else 10391 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10392 10393 if (DiagID) { 10394 Diag(Loc, DiagID) 10395 << LHSType << RHSType << LHS.get()->getSourceRange() 10396 << RHS.get()->getSourceRange(); 10397 if (isError) 10398 return QualType(); 10399 } 10400 10401 if (LHSType->isIntegerType()) 10402 LHS = ImpCastExprToType(LHS.get(), RHSType, 10403 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10404 else 10405 RHS = ImpCastExprToType(RHS.get(), LHSType, 10406 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10407 return computeResultTy(); 10408 } 10409 10410 // Handle block pointers. 10411 if (!IsRelational && RHSIsNull 10412 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10413 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10414 return computeResultTy(); 10415 } 10416 if (!IsRelational && LHSIsNull 10417 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10418 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10419 return computeResultTy(); 10420 } 10421 10422 if (getLangOpts().OpenCLVersion >= 200) { 10423 if (LHSIsNull && RHSType->isQueueT()) { 10424 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10425 return computeResultTy(); 10426 } 10427 10428 if (LHSType->isQueueT() && RHSIsNull) { 10429 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10430 return computeResultTy(); 10431 } 10432 } 10433 10434 return InvalidOperands(Loc, LHS, RHS); 10435 } 10436 10437 // Return a signed ext_vector_type that is of identical size and number of 10438 // elements. For floating point vectors, return an integer type of identical 10439 // size and number of elements. In the non ext_vector_type case, search from 10440 // the largest type to the smallest type to avoid cases where long long == long, 10441 // where long gets picked over long long. 10442 QualType Sema::GetSignedVectorType(QualType V) { 10443 const VectorType *VTy = V->getAs<VectorType>(); 10444 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10445 10446 if (isa<ExtVectorType>(VTy)) { 10447 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10448 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10449 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10450 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10451 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10452 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10453 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10454 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10455 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10456 "Unhandled vector element size in vector compare"); 10457 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10458 } 10459 10460 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10461 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10462 VectorType::GenericVector); 10463 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10464 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10465 VectorType::GenericVector); 10466 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10467 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10468 VectorType::GenericVector); 10469 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10470 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10471 VectorType::GenericVector); 10472 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10473 "Unhandled vector element size in vector compare"); 10474 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10475 VectorType::GenericVector); 10476 } 10477 10478 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10479 /// operates on extended vector types. Instead of producing an IntTy result, 10480 /// like a scalar comparison, a vector comparison produces a vector of integer 10481 /// types. 10482 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10483 SourceLocation Loc, 10484 BinaryOperatorKind Opc) { 10485 // Check to make sure we're operating on vectors of the same type and width, 10486 // Allowing one side to be a scalar of element type. 10487 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10488 /*AllowBothBool*/true, 10489 /*AllowBoolConversions*/getLangOpts().ZVector); 10490 if (vType.isNull()) 10491 return vType; 10492 10493 QualType LHSType = LHS.get()->getType(); 10494 10495 // If AltiVec, the comparison results in a numeric type, i.e. 10496 // bool for C++, int for C 10497 if (getLangOpts().AltiVec && 10498 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10499 return Context.getLogicalOperationType(); 10500 10501 // For non-floating point types, check for self-comparisons of the form 10502 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10503 // often indicate logic errors in the program. 10504 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10505 10506 // Check for comparisons of floating point operands using != and ==. 10507 if (BinaryOperator::isEqualityOp(Opc) && 10508 LHSType->hasFloatingRepresentation()) { 10509 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10510 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10511 } 10512 10513 // Return a signed type for the vector. 10514 return GetSignedVectorType(vType); 10515 } 10516 10517 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10518 SourceLocation Loc) { 10519 // Ensure that either both operands are of the same vector type, or 10520 // one operand is of a vector type and the other is of its element type. 10521 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10522 /*AllowBothBool*/true, 10523 /*AllowBoolConversions*/false); 10524 if (vType.isNull()) 10525 return InvalidOperands(Loc, LHS, RHS); 10526 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10527 vType->hasFloatingRepresentation()) 10528 return InvalidOperands(Loc, LHS, RHS); 10529 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10530 // usage of the logical operators && and || with vectors in C. This 10531 // check could be notionally dropped. 10532 if (!getLangOpts().CPlusPlus && 10533 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10534 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10535 10536 return GetSignedVectorType(LHS.get()->getType()); 10537 } 10538 10539 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10540 SourceLocation Loc, 10541 BinaryOperatorKind Opc) { 10542 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10543 10544 bool IsCompAssign = 10545 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10546 10547 if (LHS.get()->getType()->isVectorType() || 10548 RHS.get()->getType()->isVectorType()) { 10549 if (LHS.get()->getType()->hasIntegerRepresentation() && 10550 RHS.get()->getType()->hasIntegerRepresentation()) 10551 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10552 /*AllowBothBool*/true, 10553 /*AllowBoolConversions*/getLangOpts().ZVector); 10554 return InvalidOperands(Loc, LHS, RHS); 10555 } 10556 10557 if (Opc == BO_And) 10558 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10559 10560 ExprResult LHSResult = LHS, RHSResult = RHS; 10561 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10562 IsCompAssign); 10563 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10564 return QualType(); 10565 LHS = LHSResult.get(); 10566 RHS = RHSResult.get(); 10567 10568 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10569 return compType; 10570 return InvalidOperands(Loc, LHS, RHS); 10571 } 10572 10573 // C99 6.5.[13,14] 10574 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10575 SourceLocation Loc, 10576 BinaryOperatorKind Opc) { 10577 // Check vector operands differently. 10578 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10579 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10580 10581 // Diagnose cases where the user write a logical and/or but probably meant a 10582 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10583 // is a constant. 10584 if (LHS.get()->getType()->isIntegerType() && 10585 !LHS.get()->getType()->isBooleanType() && 10586 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10587 // Don't warn in macros or template instantiations. 10588 !Loc.isMacroID() && !inTemplateInstantiation()) { 10589 // If the RHS can be constant folded, and if it constant folds to something 10590 // that isn't 0 or 1 (which indicate a potential logical operation that 10591 // happened to fold to true/false) then warn. 10592 // Parens on the RHS are ignored. 10593 llvm::APSInt Result; 10594 if (RHS.get()->EvaluateAsInt(Result, Context)) 10595 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10596 !RHS.get()->getExprLoc().isMacroID()) || 10597 (Result != 0 && Result != 1)) { 10598 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10599 << RHS.get()->getSourceRange() 10600 << (Opc == BO_LAnd ? "&&" : "||"); 10601 // Suggest replacing the logical operator with the bitwise version 10602 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10603 << (Opc == BO_LAnd ? "&" : "|") 10604 << FixItHint::CreateReplacement(SourceRange( 10605 Loc, getLocForEndOfToken(Loc)), 10606 Opc == BO_LAnd ? "&" : "|"); 10607 if (Opc == BO_LAnd) 10608 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10609 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10610 << FixItHint::CreateRemoval( 10611 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10612 RHS.get()->getEndLoc())); 10613 } 10614 } 10615 10616 if (!Context.getLangOpts().CPlusPlus) { 10617 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10618 // not operate on the built-in scalar and vector float types. 10619 if (Context.getLangOpts().OpenCL && 10620 Context.getLangOpts().OpenCLVersion < 120) { 10621 if (LHS.get()->getType()->isFloatingType() || 10622 RHS.get()->getType()->isFloatingType()) 10623 return InvalidOperands(Loc, LHS, RHS); 10624 } 10625 10626 LHS = UsualUnaryConversions(LHS.get()); 10627 if (LHS.isInvalid()) 10628 return QualType(); 10629 10630 RHS = UsualUnaryConversions(RHS.get()); 10631 if (RHS.isInvalid()) 10632 return QualType(); 10633 10634 if (!LHS.get()->getType()->isScalarType() || 10635 !RHS.get()->getType()->isScalarType()) 10636 return InvalidOperands(Loc, LHS, RHS); 10637 10638 return Context.IntTy; 10639 } 10640 10641 // The following is safe because we only use this method for 10642 // non-overloadable operands. 10643 10644 // C++ [expr.log.and]p1 10645 // C++ [expr.log.or]p1 10646 // The operands are both contextually converted to type bool. 10647 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10648 if (LHSRes.isInvalid()) 10649 return InvalidOperands(Loc, LHS, RHS); 10650 LHS = LHSRes; 10651 10652 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10653 if (RHSRes.isInvalid()) 10654 return InvalidOperands(Loc, LHS, RHS); 10655 RHS = RHSRes; 10656 10657 // C++ [expr.log.and]p2 10658 // C++ [expr.log.or]p2 10659 // The result is a bool. 10660 return Context.BoolTy; 10661 } 10662 10663 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10664 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10665 if (!ME) return false; 10666 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10667 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10668 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10669 if (!Base) return false; 10670 return Base->getMethodDecl() != nullptr; 10671 } 10672 10673 /// Is the given expression (which must be 'const') a reference to a 10674 /// variable which was originally non-const, but which has become 10675 /// 'const' due to being captured within a block? 10676 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10677 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10678 assert(E->isLValue() && E->getType().isConstQualified()); 10679 E = E->IgnoreParens(); 10680 10681 // Must be a reference to a declaration from an enclosing scope. 10682 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10683 if (!DRE) return NCCK_None; 10684 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10685 10686 // The declaration must be a variable which is not declared 'const'. 10687 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10688 if (!var) return NCCK_None; 10689 if (var->getType().isConstQualified()) return NCCK_None; 10690 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10691 10692 // Decide whether the first capture was for a block or a lambda. 10693 DeclContext *DC = S.CurContext, *Prev = nullptr; 10694 // Decide whether the first capture was for a block or a lambda. 10695 while (DC) { 10696 // For init-capture, it is possible that the variable belongs to the 10697 // template pattern of the current context. 10698 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10699 if (var->isInitCapture() && 10700 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10701 break; 10702 if (DC == var->getDeclContext()) 10703 break; 10704 Prev = DC; 10705 DC = DC->getParent(); 10706 } 10707 // Unless we have an init-capture, we've gone one step too far. 10708 if (!var->isInitCapture()) 10709 DC = Prev; 10710 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10711 } 10712 10713 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10714 Ty = Ty.getNonReferenceType(); 10715 if (IsDereference && Ty->isPointerType()) 10716 Ty = Ty->getPointeeType(); 10717 return !Ty.isConstQualified(); 10718 } 10719 10720 // Update err_typecheck_assign_const and note_typecheck_assign_const 10721 // when this enum is changed. 10722 enum { 10723 ConstFunction, 10724 ConstVariable, 10725 ConstMember, 10726 ConstMethod, 10727 NestedConstMember, 10728 ConstUnknown, // Keep as last element 10729 }; 10730 10731 /// Emit the "read-only variable not assignable" error and print notes to give 10732 /// more information about why the variable is not assignable, such as pointing 10733 /// to the declaration of a const variable, showing that a method is const, or 10734 /// that the function is returning a const reference. 10735 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10736 SourceLocation Loc) { 10737 SourceRange ExprRange = E->getSourceRange(); 10738 10739 // Only emit one error on the first const found. All other consts will emit 10740 // a note to the error. 10741 bool DiagnosticEmitted = false; 10742 10743 // Track if the current expression is the result of a dereference, and if the 10744 // next checked expression is the result of a dereference. 10745 bool IsDereference = false; 10746 bool NextIsDereference = false; 10747 10748 // Loop to process MemberExpr chains. 10749 while (true) { 10750 IsDereference = NextIsDereference; 10751 10752 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10753 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10754 NextIsDereference = ME->isArrow(); 10755 const ValueDecl *VD = ME->getMemberDecl(); 10756 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10757 // Mutable fields can be modified even if the class is const. 10758 if (Field->isMutable()) { 10759 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10760 break; 10761 } 10762 10763 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10764 if (!DiagnosticEmitted) { 10765 S.Diag(Loc, diag::err_typecheck_assign_const) 10766 << ExprRange << ConstMember << false /*static*/ << Field 10767 << Field->getType(); 10768 DiagnosticEmitted = true; 10769 } 10770 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10771 << ConstMember << false /*static*/ << Field << Field->getType() 10772 << Field->getSourceRange(); 10773 } 10774 E = ME->getBase(); 10775 continue; 10776 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10777 if (VDecl->getType().isConstQualified()) { 10778 if (!DiagnosticEmitted) { 10779 S.Diag(Loc, diag::err_typecheck_assign_const) 10780 << ExprRange << ConstMember << true /*static*/ << VDecl 10781 << VDecl->getType(); 10782 DiagnosticEmitted = true; 10783 } 10784 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10785 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10786 << VDecl->getSourceRange(); 10787 } 10788 // Static fields do not inherit constness from parents. 10789 break; 10790 } 10791 break; // End MemberExpr 10792 } else if (const ArraySubscriptExpr *ASE = 10793 dyn_cast<ArraySubscriptExpr>(E)) { 10794 E = ASE->getBase()->IgnoreParenImpCasts(); 10795 continue; 10796 } else if (const ExtVectorElementExpr *EVE = 10797 dyn_cast<ExtVectorElementExpr>(E)) { 10798 E = EVE->getBase()->IgnoreParenImpCasts(); 10799 continue; 10800 } 10801 break; 10802 } 10803 10804 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10805 // Function calls 10806 const FunctionDecl *FD = CE->getDirectCallee(); 10807 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10808 if (!DiagnosticEmitted) { 10809 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10810 << ConstFunction << FD; 10811 DiagnosticEmitted = true; 10812 } 10813 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10814 diag::note_typecheck_assign_const) 10815 << ConstFunction << FD << FD->getReturnType() 10816 << FD->getReturnTypeSourceRange(); 10817 } 10818 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10819 // Point to variable declaration. 10820 if (const ValueDecl *VD = DRE->getDecl()) { 10821 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10822 if (!DiagnosticEmitted) { 10823 S.Diag(Loc, diag::err_typecheck_assign_const) 10824 << ExprRange << ConstVariable << VD << VD->getType(); 10825 DiagnosticEmitted = true; 10826 } 10827 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10828 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10829 } 10830 } 10831 } else if (isa<CXXThisExpr>(E)) { 10832 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10833 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10834 if (MD->isConst()) { 10835 if (!DiagnosticEmitted) { 10836 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10837 << ConstMethod << MD; 10838 DiagnosticEmitted = true; 10839 } 10840 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10841 << ConstMethod << MD << MD->getSourceRange(); 10842 } 10843 } 10844 } 10845 } 10846 10847 if (DiagnosticEmitted) 10848 return; 10849 10850 // Can't determine a more specific message, so display the generic error. 10851 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10852 } 10853 10854 enum OriginalExprKind { 10855 OEK_Variable, 10856 OEK_Member, 10857 OEK_LValue 10858 }; 10859 10860 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10861 const RecordType *Ty, 10862 SourceLocation Loc, SourceRange Range, 10863 OriginalExprKind OEK, 10864 bool &DiagnosticEmitted, 10865 bool IsNested = false) { 10866 // We walk the record hierarchy breadth-first to ensure that we print 10867 // diagnostics in field nesting order. 10868 // First, check every field for constness. 10869 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10870 if (Field->getType().isConstQualified()) { 10871 if (!DiagnosticEmitted) { 10872 S.Diag(Loc, diag::err_typecheck_assign_const) 10873 << Range << NestedConstMember << OEK << VD 10874 << IsNested << Field; 10875 DiagnosticEmitted = true; 10876 } 10877 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10878 << NestedConstMember << IsNested << Field 10879 << Field->getType() << Field->getSourceRange(); 10880 } 10881 } 10882 // Then, recurse. 10883 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10884 QualType FTy = Field->getType(); 10885 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10886 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10887 OEK, DiagnosticEmitted, true); 10888 } 10889 } 10890 10891 /// Emit an error for the case where a record we are trying to assign to has a 10892 /// const-qualified field somewhere in its hierarchy. 10893 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10894 SourceLocation Loc) { 10895 QualType Ty = E->getType(); 10896 assert(Ty->isRecordType() && "lvalue was not record?"); 10897 SourceRange Range = E->getSourceRange(); 10898 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10899 bool DiagEmitted = false; 10900 10901 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10902 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10903 Range, OEK_Member, DiagEmitted); 10904 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10905 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10906 Range, OEK_Variable, DiagEmitted); 10907 else 10908 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10909 Range, OEK_LValue, DiagEmitted); 10910 if (!DiagEmitted) 10911 DiagnoseConstAssignment(S, E, Loc); 10912 } 10913 10914 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10915 /// emit an error and return true. If so, return false. 10916 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10917 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10918 10919 S.CheckShadowingDeclModification(E, Loc); 10920 10921 SourceLocation OrigLoc = Loc; 10922 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10923 &Loc); 10924 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10925 IsLV = Expr::MLV_InvalidMessageExpression; 10926 if (IsLV == Expr::MLV_Valid) 10927 return false; 10928 10929 unsigned DiagID = 0; 10930 bool NeedType = false; 10931 switch (IsLV) { // C99 6.5.16p2 10932 case Expr::MLV_ConstQualified: 10933 // Use a specialized diagnostic when we're assigning to an object 10934 // from an enclosing function or block. 10935 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10936 if (NCCK == NCCK_Block) 10937 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10938 else 10939 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10940 break; 10941 } 10942 10943 // In ARC, use some specialized diagnostics for occasions where we 10944 // infer 'const'. These are always pseudo-strong variables. 10945 if (S.getLangOpts().ObjCAutoRefCount) { 10946 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10947 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10948 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10949 10950 // Use the normal diagnostic if it's pseudo-__strong but the 10951 // user actually wrote 'const'. 10952 if (var->isARCPseudoStrong() && 10953 (!var->getTypeSourceInfo() || 10954 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10955 // There are two pseudo-strong cases: 10956 // - self 10957 ObjCMethodDecl *method = S.getCurMethodDecl(); 10958 if (method && var == method->getSelfDecl()) 10959 DiagID = method->isClassMethod() 10960 ? diag::err_typecheck_arc_assign_self_class_method 10961 : diag::err_typecheck_arc_assign_self; 10962 10963 // - fast enumeration variables 10964 else 10965 DiagID = diag::err_typecheck_arr_assign_enumeration; 10966 10967 SourceRange Assign; 10968 if (Loc != OrigLoc) 10969 Assign = SourceRange(OrigLoc, OrigLoc); 10970 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10971 // We need to preserve the AST regardless, so migration tool 10972 // can do its job. 10973 return false; 10974 } 10975 } 10976 } 10977 10978 // If none of the special cases above are triggered, then this is a 10979 // simple const assignment. 10980 if (DiagID == 0) { 10981 DiagnoseConstAssignment(S, E, Loc); 10982 return true; 10983 } 10984 10985 break; 10986 case Expr::MLV_ConstAddrSpace: 10987 DiagnoseConstAssignment(S, E, Loc); 10988 return true; 10989 case Expr::MLV_ConstQualifiedField: 10990 DiagnoseRecursiveConstFields(S, E, Loc); 10991 return true; 10992 case Expr::MLV_ArrayType: 10993 case Expr::MLV_ArrayTemporary: 10994 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10995 NeedType = true; 10996 break; 10997 case Expr::MLV_NotObjectType: 10998 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10999 NeedType = true; 11000 break; 11001 case Expr::MLV_LValueCast: 11002 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11003 break; 11004 case Expr::MLV_Valid: 11005 llvm_unreachable("did not take early return for MLV_Valid"); 11006 case Expr::MLV_InvalidExpression: 11007 case Expr::MLV_MemberFunction: 11008 case Expr::MLV_ClassTemporary: 11009 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11010 break; 11011 case Expr::MLV_IncompleteType: 11012 case Expr::MLV_IncompleteVoidType: 11013 return S.RequireCompleteType(Loc, E->getType(), 11014 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11015 case Expr::MLV_DuplicateVectorComponents: 11016 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11017 break; 11018 case Expr::MLV_NoSetterProperty: 11019 llvm_unreachable("readonly properties should be processed differently"); 11020 case Expr::MLV_InvalidMessageExpression: 11021 DiagID = diag::err_readonly_message_assignment; 11022 break; 11023 case Expr::MLV_SubObjCPropertySetting: 11024 DiagID = diag::err_no_subobject_property_setting; 11025 break; 11026 } 11027 11028 SourceRange Assign; 11029 if (Loc != OrigLoc) 11030 Assign = SourceRange(OrigLoc, OrigLoc); 11031 if (NeedType) 11032 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11033 else 11034 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11035 return true; 11036 } 11037 11038 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11039 SourceLocation Loc, 11040 Sema &Sema) { 11041 if (Sema.inTemplateInstantiation()) 11042 return; 11043 if (Sema.isUnevaluatedContext()) 11044 return; 11045 if (Loc.isInvalid() || Loc.isMacroID()) 11046 return; 11047 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11048 return; 11049 11050 // C / C++ fields 11051 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11052 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11053 if (ML && MR) { 11054 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11055 return; 11056 const ValueDecl *LHSDecl = 11057 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11058 const ValueDecl *RHSDecl = 11059 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11060 if (LHSDecl != RHSDecl) 11061 return; 11062 if (LHSDecl->getType().isVolatileQualified()) 11063 return; 11064 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11065 if (RefTy->getPointeeType().isVolatileQualified()) 11066 return; 11067 11068 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11069 } 11070 11071 // Objective-C instance variables 11072 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11073 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11074 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11075 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11076 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11077 if (RL && RR && RL->getDecl() == RR->getDecl()) 11078 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11079 } 11080 } 11081 11082 // C99 6.5.16.1 11083 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11084 SourceLocation Loc, 11085 QualType CompoundType) { 11086 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11087 11088 // Verify that LHS is a modifiable lvalue, and emit error if not. 11089 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11090 return QualType(); 11091 11092 QualType LHSType = LHSExpr->getType(); 11093 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11094 CompoundType; 11095 // OpenCL v1.2 s6.1.1.1 p2: 11096 // The half data type can only be used to declare a pointer to a buffer that 11097 // contains half values 11098 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11099 LHSType->isHalfType()) { 11100 Diag(Loc, diag::err_opencl_half_load_store) << 1 11101 << LHSType.getUnqualifiedType(); 11102 return QualType(); 11103 } 11104 11105 AssignConvertType ConvTy; 11106 if (CompoundType.isNull()) { 11107 Expr *RHSCheck = RHS.get(); 11108 11109 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11110 11111 QualType LHSTy(LHSType); 11112 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11113 if (RHS.isInvalid()) 11114 return QualType(); 11115 // Special case of NSObject attributes on c-style pointer types. 11116 if (ConvTy == IncompatiblePointer && 11117 ((Context.isObjCNSObjectType(LHSType) && 11118 RHSType->isObjCObjectPointerType()) || 11119 (Context.isObjCNSObjectType(RHSType) && 11120 LHSType->isObjCObjectPointerType()))) 11121 ConvTy = Compatible; 11122 11123 if (ConvTy == Compatible && 11124 LHSType->isObjCObjectType()) 11125 Diag(Loc, diag::err_objc_object_assignment) 11126 << LHSType; 11127 11128 // If the RHS is a unary plus or minus, check to see if they = and + are 11129 // right next to each other. If so, the user may have typo'd "x =+ 4" 11130 // instead of "x += 4". 11131 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11132 RHSCheck = ICE->getSubExpr(); 11133 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11134 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11135 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11136 // Only if the two operators are exactly adjacent. 11137 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11138 // And there is a space or other character before the subexpr of the 11139 // unary +/-. We don't want to warn on "x=-1". 11140 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11141 UO->getSubExpr()->getBeginLoc().isFileID()) { 11142 Diag(Loc, diag::warn_not_compound_assign) 11143 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11144 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11145 } 11146 } 11147 11148 if (ConvTy == Compatible) { 11149 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11150 // Warn about retain cycles where a block captures the LHS, but 11151 // not if the LHS is a simple variable into which the block is 11152 // being stored...unless that variable can be captured by reference! 11153 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11154 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11155 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11156 checkRetainCycles(LHSExpr, RHS.get()); 11157 } 11158 11159 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11160 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11161 // It is safe to assign a weak reference into a strong variable. 11162 // Although this code can still have problems: 11163 // id x = self.weakProp; 11164 // id y = self.weakProp; 11165 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11166 // paths through the function. This should be revisited if 11167 // -Wrepeated-use-of-weak is made flow-sensitive. 11168 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11169 // variable, which will be valid for the current autorelease scope. 11170 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11171 RHS.get()->getBeginLoc())) 11172 getCurFunction()->markSafeWeakUse(RHS.get()); 11173 11174 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11175 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11176 } 11177 } 11178 } else { 11179 // Compound assignment "x += y" 11180 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11181 } 11182 11183 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11184 RHS.get(), AA_Assigning)) 11185 return QualType(); 11186 11187 CheckForNullPointerDereference(*this, LHSExpr); 11188 11189 // C99 6.5.16p3: The type of an assignment expression is the type of the 11190 // left operand unless the left operand has qualified type, in which case 11191 // it is the unqualified version of the type of the left operand. 11192 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11193 // is converted to the type of the assignment expression (above). 11194 // C++ 5.17p1: the type of the assignment expression is that of its left 11195 // operand. 11196 return (getLangOpts().CPlusPlus 11197 ? LHSType : LHSType.getUnqualifiedType()); 11198 } 11199 11200 // Only ignore explicit casts to void. 11201 static bool IgnoreCommaOperand(const Expr *E) { 11202 E = E->IgnoreParens(); 11203 11204 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11205 if (CE->getCastKind() == CK_ToVoid) { 11206 return true; 11207 } 11208 } 11209 11210 return false; 11211 } 11212 11213 // Look for instances where it is likely the comma operator is confused with 11214 // another operator. There is a whitelist of acceptable expressions for the 11215 // left hand side of the comma operator, otherwise emit a warning. 11216 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11217 // No warnings in macros 11218 if (Loc.isMacroID()) 11219 return; 11220 11221 // Don't warn in template instantiations. 11222 if (inTemplateInstantiation()) 11223 return; 11224 11225 // Scope isn't fine-grained enough to whitelist the specific cases, so 11226 // instead, skip more than needed, then call back into here with the 11227 // CommaVisitor in SemaStmt.cpp. 11228 // The whitelisted locations are the initialization and increment portions 11229 // of a for loop. The additional checks are on the condition of 11230 // if statements, do/while loops, and for loops. 11231 const unsigned ForIncrementFlags = 11232 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 11233 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11234 const unsigned ScopeFlags = getCurScope()->getFlags(); 11235 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11236 (ScopeFlags & ForInitFlags) == ForInitFlags) 11237 return; 11238 11239 // If there are multiple comma operators used together, get the RHS of the 11240 // of the comma operator as the LHS. 11241 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11242 if (BO->getOpcode() != BO_Comma) 11243 break; 11244 LHS = BO->getRHS(); 11245 } 11246 11247 // Only allow some expressions on LHS to not warn. 11248 if (IgnoreCommaOperand(LHS)) 11249 return; 11250 11251 Diag(Loc, diag::warn_comma_operator); 11252 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11253 << LHS->getSourceRange() 11254 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11255 LangOpts.CPlusPlus ? "static_cast<void>(" 11256 : "(void)(") 11257 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11258 ")"); 11259 } 11260 11261 // C99 6.5.17 11262 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11263 SourceLocation Loc) { 11264 LHS = S.CheckPlaceholderExpr(LHS.get()); 11265 RHS = S.CheckPlaceholderExpr(RHS.get()); 11266 if (LHS.isInvalid() || RHS.isInvalid()) 11267 return QualType(); 11268 11269 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11270 // operands, but not unary promotions. 11271 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11272 11273 // So we treat the LHS as a ignored value, and in C++ we allow the 11274 // containing site to determine what should be done with the RHS. 11275 LHS = S.IgnoredValueConversions(LHS.get()); 11276 if (LHS.isInvalid()) 11277 return QualType(); 11278 11279 S.DiagnoseUnusedExprResult(LHS.get()); 11280 11281 if (!S.getLangOpts().CPlusPlus) { 11282 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11283 if (RHS.isInvalid()) 11284 return QualType(); 11285 if (!RHS.get()->getType()->isVoidType()) 11286 S.RequireCompleteType(Loc, RHS.get()->getType(), 11287 diag::err_incomplete_type); 11288 } 11289 11290 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11291 S.DiagnoseCommaOperator(LHS.get(), Loc); 11292 11293 return RHS.get()->getType(); 11294 } 11295 11296 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11297 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11298 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11299 ExprValueKind &VK, 11300 ExprObjectKind &OK, 11301 SourceLocation OpLoc, 11302 bool IsInc, bool IsPrefix) { 11303 if (Op->isTypeDependent()) 11304 return S.Context.DependentTy; 11305 11306 QualType ResType = Op->getType(); 11307 // Atomic types can be used for increment / decrement where the non-atomic 11308 // versions can, so ignore the _Atomic() specifier for the purpose of 11309 // checking. 11310 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11311 ResType = ResAtomicType->getValueType(); 11312 11313 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11314 11315 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11316 // Decrement of bool is not allowed. 11317 if (!IsInc) { 11318 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11319 return QualType(); 11320 } 11321 // Increment of bool sets it to true, but is deprecated. 11322 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11323 : diag::warn_increment_bool) 11324 << Op->getSourceRange(); 11325 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11326 // Error on enum increments and decrements in C++ mode 11327 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11328 return QualType(); 11329 } else if (ResType->isRealType()) { 11330 // OK! 11331 } else if (ResType->isPointerType()) { 11332 // C99 6.5.2.4p2, 6.5.6p2 11333 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11334 return QualType(); 11335 } else if (ResType->isObjCObjectPointerType()) { 11336 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11337 // Otherwise, we just need a complete type. 11338 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11339 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11340 return QualType(); 11341 } else if (ResType->isAnyComplexType()) { 11342 // C99 does not support ++/-- on complex types, we allow as an extension. 11343 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11344 << ResType << Op->getSourceRange(); 11345 } else if (ResType->isPlaceholderType()) { 11346 ExprResult PR = S.CheckPlaceholderExpr(Op); 11347 if (PR.isInvalid()) return QualType(); 11348 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11349 IsInc, IsPrefix); 11350 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11351 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11352 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11353 (ResType->getAs<VectorType>()->getVectorKind() != 11354 VectorType::AltiVecBool)) { 11355 // The z vector extensions allow ++ and -- for non-bool vectors. 11356 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11357 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11358 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11359 } else { 11360 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11361 << ResType << int(IsInc) << Op->getSourceRange(); 11362 return QualType(); 11363 } 11364 // At this point, we know we have a real, complex or pointer type. 11365 // Now make sure the operand is a modifiable lvalue. 11366 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11367 return QualType(); 11368 // In C++, a prefix increment is the same type as the operand. Otherwise 11369 // (in C or with postfix), the increment is the unqualified type of the 11370 // operand. 11371 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11372 VK = VK_LValue; 11373 OK = Op->getObjectKind(); 11374 return ResType; 11375 } else { 11376 VK = VK_RValue; 11377 return ResType.getUnqualifiedType(); 11378 } 11379 } 11380 11381 11382 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11383 /// This routine allows us to typecheck complex/recursive expressions 11384 /// where the declaration is needed for type checking. We only need to 11385 /// handle cases when the expression references a function designator 11386 /// or is an lvalue. Here are some examples: 11387 /// - &(x) => x 11388 /// - &*****f => f for f a function designator. 11389 /// - &s.xx => s 11390 /// - &s.zz[1].yy -> s, if zz is an array 11391 /// - *(x + 1) -> x, if x is an array 11392 /// - &"123"[2] -> 0 11393 /// - & __real__ x -> x 11394 static ValueDecl *getPrimaryDecl(Expr *E) { 11395 switch (E->getStmtClass()) { 11396 case Stmt::DeclRefExprClass: 11397 return cast<DeclRefExpr>(E)->getDecl(); 11398 case Stmt::MemberExprClass: 11399 // If this is an arrow operator, the address is an offset from 11400 // the base's value, so the object the base refers to is 11401 // irrelevant. 11402 if (cast<MemberExpr>(E)->isArrow()) 11403 return nullptr; 11404 // Otherwise, the expression refers to a part of the base 11405 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11406 case Stmt::ArraySubscriptExprClass: { 11407 // FIXME: This code shouldn't be necessary! We should catch the implicit 11408 // promotion of register arrays earlier. 11409 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11410 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11411 if (ICE->getSubExpr()->getType()->isArrayType()) 11412 return getPrimaryDecl(ICE->getSubExpr()); 11413 } 11414 return nullptr; 11415 } 11416 case Stmt::UnaryOperatorClass: { 11417 UnaryOperator *UO = cast<UnaryOperator>(E); 11418 11419 switch(UO->getOpcode()) { 11420 case UO_Real: 11421 case UO_Imag: 11422 case UO_Extension: 11423 return getPrimaryDecl(UO->getSubExpr()); 11424 default: 11425 return nullptr; 11426 } 11427 } 11428 case Stmt::ParenExprClass: 11429 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11430 case Stmt::ImplicitCastExprClass: 11431 // If the result of an implicit cast is an l-value, we care about 11432 // the sub-expression; otherwise, the result here doesn't matter. 11433 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11434 default: 11435 return nullptr; 11436 } 11437 } 11438 11439 namespace { 11440 enum { 11441 AO_Bit_Field = 0, 11442 AO_Vector_Element = 1, 11443 AO_Property_Expansion = 2, 11444 AO_Register_Variable = 3, 11445 AO_No_Error = 4 11446 }; 11447 } 11448 /// Diagnose invalid operand for address of operations. 11449 /// 11450 /// \param Type The type of operand which cannot have its address taken. 11451 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11452 Expr *E, unsigned Type) { 11453 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11454 } 11455 11456 /// CheckAddressOfOperand - The operand of & must be either a function 11457 /// designator or an lvalue designating an object. If it is an lvalue, the 11458 /// object cannot be declared with storage class register or be a bit field. 11459 /// Note: The usual conversions are *not* applied to the operand of the & 11460 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11461 /// In C++, the operand might be an overloaded function name, in which case 11462 /// we allow the '&' but retain the overloaded-function type. 11463 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11464 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11465 if (PTy->getKind() == BuiltinType::Overload) { 11466 Expr *E = OrigOp.get()->IgnoreParens(); 11467 if (!isa<OverloadExpr>(E)) { 11468 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11469 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11470 << OrigOp.get()->getSourceRange(); 11471 return QualType(); 11472 } 11473 11474 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11475 if (isa<UnresolvedMemberExpr>(Ovl)) 11476 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11477 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11478 << OrigOp.get()->getSourceRange(); 11479 return QualType(); 11480 } 11481 11482 return Context.OverloadTy; 11483 } 11484 11485 if (PTy->getKind() == BuiltinType::UnknownAny) 11486 return Context.UnknownAnyTy; 11487 11488 if (PTy->getKind() == BuiltinType::BoundMember) { 11489 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11490 << OrigOp.get()->getSourceRange(); 11491 return QualType(); 11492 } 11493 11494 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11495 if (OrigOp.isInvalid()) return QualType(); 11496 } 11497 11498 if (OrigOp.get()->isTypeDependent()) 11499 return Context.DependentTy; 11500 11501 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11502 11503 // Make sure to ignore parentheses in subsequent checks 11504 Expr *op = OrigOp.get()->IgnoreParens(); 11505 11506 // In OpenCL captures for blocks called as lambda functions 11507 // are located in the private address space. Blocks used in 11508 // enqueue_kernel can be located in a different address space 11509 // depending on a vendor implementation. Thus preventing 11510 // taking an address of the capture to avoid invalid AS casts. 11511 if (LangOpts.OpenCL) { 11512 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11513 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11514 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11515 return QualType(); 11516 } 11517 } 11518 11519 if (getLangOpts().C99) { 11520 // Implement C99-only parts of addressof rules. 11521 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11522 if (uOp->getOpcode() == UO_Deref) 11523 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11524 // (assuming the deref expression is valid). 11525 return uOp->getSubExpr()->getType(); 11526 } 11527 // Technically, there should be a check for array subscript 11528 // expressions here, but the result of one is always an lvalue anyway. 11529 } 11530 ValueDecl *dcl = getPrimaryDecl(op); 11531 11532 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11533 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11534 op->getBeginLoc())) 11535 return QualType(); 11536 11537 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11538 unsigned AddressOfError = AO_No_Error; 11539 11540 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11541 bool sfinae = (bool)isSFINAEContext(); 11542 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11543 : diag::ext_typecheck_addrof_temporary) 11544 << op->getType() << op->getSourceRange(); 11545 if (sfinae) 11546 return QualType(); 11547 // Materialize the temporary as an lvalue so that we can take its address. 11548 OrigOp = op = 11549 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11550 } else if (isa<ObjCSelectorExpr>(op)) { 11551 return Context.getPointerType(op->getType()); 11552 } else if (lval == Expr::LV_MemberFunction) { 11553 // If it's an instance method, make a member pointer. 11554 // The expression must have exactly the form &A::foo. 11555 11556 // If the underlying expression isn't a decl ref, give up. 11557 if (!isa<DeclRefExpr>(op)) { 11558 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11559 << OrigOp.get()->getSourceRange(); 11560 return QualType(); 11561 } 11562 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11563 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11564 11565 // The id-expression was parenthesized. 11566 if (OrigOp.get() != DRE) { 11567 Diag(OpLoc, diag::err_parens_pointer_member_function) 11568 << OrigOp.get()->getSourceRange(); 11569 11570 // The method was named without a qualifier. 11571 } else if (!DRE->getQualifier()) { 11572 if (MD->getParent()->getName().empty()) 11573 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11574 << op->getSourceRange(); 11575 else { 11576 SmallString<32> Str; 11577 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11578 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11579 << op->getSourceRange() 11580 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11581 } 11582 } 11583 11584 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11585 if (isa<CXXDestructorDecl>(MD)) 11586 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11587 11588 QualType MPTy = Context.getMemberPointerType( 11589 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11590 // Under the MS ABI, lock down the inheritance model now. 11591 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11592 (void)isCompleteType(OpLoc, MPTy); 11593 return MPTy; 11594 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11595 // C99 6.5.3.2p1 11596 // The operand must be either an l-value or a function designator 11597 if (!op->getType()->isFunctionType()) { 11598 // Use a special diagnostic for loads from property references. 11599 if (isa<PseudoObjectExpr>(op)) { 11600 AddressOfError = AO_Property_Expansion; 11601 } else { 11602 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11603 << op->getType() << op->getSourceRange(); 11604 return QualType(); 11605 } 11606 } 11607 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11608 // The operand cannot be a bit-field 11609 AddressOfError = AO_Bit_Field; 11610 } else if (op->getObjectKind() == OK_VectorComponent) { 11611 // The operand cannot be an element of a vector 11612 AddressOfError = AO_Vector_Element; 11613 } else if (dcl) { // C99 6.5.3.2p1 11614 // We have an lvalue with a decl. Make sure the decl is not declared 11615 // with the register storage-class specifier. 11616 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11617 // in C++ it is not error to take address of a register 11618 // variable (c++03 7.1.1P3) 11619 if (vd->getStorageClass() == SC_Register && 11620 !getLangOpts().CPlusPlus) { 11621 AddressOfError = AO_Register_Variable; 11622 } 11623 } else if (isa<MSPropertyDecl>(dcl)) { 11624 AddressOfError = AO_Property_Expansion; 11625 } else if (isa<FunctionTemplateDecl>(dcl)) { 11626 return Context.OverloadTy; 11627 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11628 // Okay: we can take the address of a field. 11629 // Could be a pointer to member, though, if there is an explicit 11630 // scope qualifier for the class. 11631 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11632 DeclContext *Ctx = dcl->getDeclContext(); 11633 if (Ctx && Ctx->isRecord()) { 11634 if (dcl->getType()->isReferenceType()) { 11635 Diag(OpLoc, 11636 diag::err_cannot_form_pointer_to_member_of_reference_type) 11637 << dcl->getDeclName() << dcl->getType(); 11638 return QualType(); 11639 } 11640 11641 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11642 Ctx = Ctx->getParent(); 11643 11644 QualType MPTy = Context.getMemberPointerType( 11645 op->getType(), 11646 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11647 // Under the MS ABI, lock down the inheritance model now. 11648 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11649 (void)isCompleteType(OpLoc, MPTy); 11650 return MPTy; 11651 } 11652 } 11653 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11654 !isa<BindingDecl>(dcl)) 11655 llvm_unreachable("Unknown/unexpected decl type"); 11656 } 11657 11658 if (AddressOfError != AO_No_Error) { 11659 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11660 return QualType(); 11661 } 11662 11663 if (lval == Expr::LV_IncompleteVoidType) { 11664 // Taking the address of a void variable is technically illegal, but we 11665 // allow it in cases which are otherwise valid. 11666 // Example: "extern void x; void* y = &x;". 11667 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11668 } 11669 11670 // If the operand has type "type", the result has type "pointer to type". 11671 if (op->getType()->isObjCObjectType()) 11672 return Context.getObjCObjectPointerType(op->getType()); 11673 11674 CheckAddressOfPackedMember(op); 11675 11676 return Context.getPointerType(op->getType()); 11677 } 11678 11679 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11680 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11681 if (!DRE) 11682 return; 11683 const Decl *D = DRE->getDecl(); 11684 if (!D) 11685 return; 11686 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11687 if (!Param) 11688 return; 11689 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11690 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11691 return; 11692 if (FunctionScopeInfo *FD = S.getCurFunction()) 11693 if (!FD->ModifiedNonNullParams.count(Param)) 11694 FD->ModifiedNonNullParams.insert(Param); 11695 } 11696 11697 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11698 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11699 SourceLocation OpLoc) { 11700 if (Op->isTypeDependent()) 11701 return S.Context.DependentTy; 11702 11703 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11704 if (ConvResult.isInvalid()) 11705 return QualType(); 11706 Op = ConvResult.get(); 11707 QualType OpTy = Op->getType(); 11708 QualType Result; 11709 11710 if (isa<CXXReinterpretCastExpr>(Op)) { 11711 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11712 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11713 Op->getSourceRange()); 11714 } 11715 11716 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11717 { 11718 Result = PT->getPointeeType(); 11719 } 11720 else if (const ObjCObjectPointerType *OPT = 11721 OpTy->getAs<ObjCObjectPointerType>()) 11722 Result = OPT->getPointeeType(); 11723 else { 11724 ExprResult PR = S.CheckPlaceholderExpr(Op); 11725 if (PR.isInvalid()) return QualType(); 11726 if (PR.get() != Op) 11727 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11728 } 11729 11730 if (Result.isNull()) { 11731 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11732 << OpTy << Op->getSourceRange(); 11733 return QualType(); 11734 } 11735 11736 // Note that per both C89 and C99, indirection is always legal, even if Result 11737 // is an incomplete type or void. It would be possible to warn about 11738 // dereferencing a void pointer, but it's completely well-defined, and such a 11739 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11740 // for pointers to 'void' but is fine for any other pointer type: 11741 // 11742 // C++ [expr.unary.op]p1: 11743 // [...] the expression to which [the unary * operator] is applied shall 11744 // be a pointer to an object type, or a pointer to a function type 11745 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11746 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11747 << OpTy << Op->getSourceRange(); 11748 11749 // Dereferences are usually l-values... 11750 VK = VK_LValue; 11751 11752 // ...except that certain expressions are never l-values in C. 11753 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11754 VK = VK_RValue; 11755 11756 return Result; 11757 } 11758 11759 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11760 BinaryOperatorKind Opc; 11761 switch (Kind) { 11762 default: llvm_unreachable("Unknown binop!"); 11763 case tok::periodstar: Opc = BO_PtrMemD; break; 11764 case tok::arrowstar: Opc = BO_PtrMemI; break; 11765 case tok::star: Opc = BO_Mul; break; 11766 case tok::slash: Opc = BO_Div; break; 11767 case tok::percent: Opc = BO_Rem; break; 11768 case tok::plus: Opc = BO_Add; break; 11769 case tok::minus: Opc = BO_Sub; break; 11770 case tok::lessless: Opc = BO_Shl; break; 11771 case tok::greatergreater: Opc = BO_Shr; break; 11772 case tok::lessequal: Opc = BO_LE; break; 11773 case tok::less: Opc = BO_LT; break; 11774 case tok::greaterequal: Opc = BO_GE; break; 11775 case tok::greater: Opc = BO_GT; break; 11776 case tok::exclaimequal: Opc = BO_NE; break; 11777 case tok::equalequal: Opc = BO_EQ; break; 11778 case tok::spaceship: Opc = BO_Cmp; break; 11779 case tok::amp: Opc = BO_And; break; 11780 case tok::caret: Opc = BO_Xor; break; 11781 case tok::pipe: Opc = BO_Or; break; 11782 case tok::ampamp: Opc = BO_LAnd; break; 11783 case tok::pipepipe: Opc = BO_LOr; break; 11784 case tok::equal: Opc = BO_Assign; break; 11785 case tok::starequal: Opc = BO_MulAssign; break; 11786 case tok::slashequal: Opc = BO_DivAssign; break; 11787 case tok::percentequal: Opc = BO_RemAssign; break; 11788 case tok::plusequal: Opc = BO_AddAssign; break; 11789 case tok::minusequal: Opc = BO_SubAssign; break; 11790 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11791 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11792 case tok::ampequal: Opc = BO_AndAssign; break; 11793 case tok::caretequal: Opc = BO_XorAssign; break; 11794 case tok::pipeequal: Opc = BO_OrAssign; break; 11795 case tok::comma: Opc = BO_Comma; break; 11796 } 11797 return Opc; 11798 } 11799 11800 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11801 tok::TokenKind Kind) { 11802 UnaryOperatorKind Opc; 11803 switch (Kind) { 11804 default: llvm_unreachable("Unknown unary op!"); 11805 case tok::plusplus: Opc = UO_PreInc; break; 11806 case tok::minusminus: Opc = UO_PreDec; break; 11807 case tok::amp: Opc = UO_AddrOf; break; 11808 case tok::star: Opc = UO_Deref; break; 11809 case tok::plus: Opc = UO_Plus; break; 11810 case tok::minus: Opc = UO_Minus; break; 11811 case tok::tilde: Opc = UO_Not; break; 11812 case tok::exclaim: Opc = UO_LNot; break; 11813 case tok::kw___real: Opc = UO_Real; break; 11814 case tok::kw___imag: Opc = UO_Imag; break; 11815 case tok::kw___extension__: Opc = UO_Extension; break; 11816 } 11817 return Opc; 11818 } 11819 11820 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11821 /// This warning suppressed in the event of macro expansions. 11822 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11823 SourceLocation OpLoc, bool IsBuiltin) { 11824 if (S.inTemplateInstantiation()) 11825 return; 11826 if (S.isUnevaluatedContext()) 11827 return; 11828 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11829 return; 11830 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11831 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11832 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11833 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11834 if (!LHSDeclRef || !RHSDeclRef || 11835 LHSDeclRef->getLocation().isMacroID() || 11836 RHSDeclRef->getLocation().isMacroID()) 11837 return; 11838 const ValueDecl *LHSDecl = 11839 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11840 const ValueDecl *RHSDecl = 11841 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11842 if (LHSDecl != RHSDecl) 11843 return; 11844 if (LHSDecl->getType().isVolatileQualified()) 11845 return; 11846 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11847 if (RefTy->getPointeeType().isVolatileQualified()) 11848 return; 11849 11850 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11851 : diag::warn_self_assignment_overloaded) 11852 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11853 << RHSExpr->getSourceRange(); 11854 } 11855 11856 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11857 /// is usually indicative of introspection within the Objective-C pointer. 11858 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11859 SourceLocation OpLoc) { 11860 if (!S.getLangOpts().ObjC1) 11861 return; 11862 11863 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11864 const Expr *LHS = L.get(); 11865 const Expr *RHS = R.get(); 11866 11867 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11868 ObjCPointerExpr = LHS; 11869 OtherExpr = RHS; 11870 } 11871 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11872 ObjCPointerExpr = RHS; 11873 OtherExpr = LHS; 11874 } 11875 11876 // This warning is deliberately made very specific to reduce false 11877 // positives with logic that uses '&' for hashing. This logic mainly 11878 // looks for code trying to introspect into tagged pointers, which 11879 // code should generally never do. 11880 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11881 unsigned Diag = diag::warn_objc_pointer_masking; 11882 // Determine if we are introspecting the result of performSelectorXXX. 11883 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11884 // Special case messages to -performSelector and friends, which 11885 // can return non-pointer values boxed in a pointer value. 11886 // Some clients may wish to silence warnings in this subcase. 11887 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11888 Selector S = ME->getSelector(); 11889 StringRef SelArg0 = S.getNameForSlot(0); 11890 if (SelArg0.startswith("performSelector")) 11891 Diag = diag::warn_objc_pointer_masking_performSelector; 11892 } 11893 11894 S.Diag(OpLoc, Diag) 11895 << ObjCPointerExpr->getSourceRange(); 11896 } 11897 } 11898 11899 static NamedDecl *getDeclFromExpr(Expr *E) { 11900 if (!E) 11901 return nullptr; 11902 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11903 return DRE->getDecl(); 11904 if (auto *ME = dyn_cast<MemberExpr>(E)) 11905 return ME->getMemberDecl(); 11906 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11907 return IRE->getDecl(); 11908 return nullptr; 11909 } 11910 11911 // This helper function promotes a binary operator's operands (which are of a 11912 // half vector type) to a vector of floats and then truncates the result to 11913 // a vector of either half or short. 11914 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11915 BinaryOperatorKind Opc, QualType ResultTy, 11916 ExprValueKind VK, ExprObjectKind OK, 11917 bool IsCompAssign, SourceLocation OpLoc, 11918 FPOptions FPFeatures) { 11919 auto &Context = S.getASTContext(); 11920 assert((isVector(ResultTy, Context.HalfTy) || 11921 isVector(ResultTy, Context.ShortTy)) && 11922 "Result must be a vector of half or short"); 11923 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11924 isVector(RHS.get()->getType(), Context.HalfTy) && 11925 "both operands expected to be a half vector"); 11926 11927 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11928 QualType BinOpResTy = RHS.get()->getType(); 11929 11930 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11931 // change BinOpResTy to a vector of ints. 11932 if (isVector(ResultTy, Context.ShortTy)) 11933 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11934 11935 if (IsCompAssign) 11936 return new (Context) CompoundAssignOperator( 11937 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11938 OpLoc, FPFeatures); 11939 11940 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11941 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11942 VK, OK, OpLoc, FPFeatures); 11943 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11944 } 11945 11946 static std::pair<ExprResult, ExprResult> 11947 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11948 Expr *RHSExpr) { 11949 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11950 if (!S.getLangOpts().CPlusPlus) { 11951 // C cannot handle TypoExpr nodes on either side of a binop because it 11952 // doesn't handle dependent types properly, so make sure any TypoExprs have 11953 // been dealt with before checking the operands. 11954 LHS = S.CorrectDelayedTyposInExpr(LHS); 11955 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11956 if (Opc != BO_Assign) 11957 return ExprResult(E); 11958 // Avoid correcting the RHS to the same Expr as the LHS. 11959 Decl *D = getDeclFromExpr(E); 11960 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11961 }); 11962 } 11963 return std::make_pair(LHS, RHS); 11964 } 11965 11966 /// Returns true if conversion between vectors of halfs and vectors of floats 11967 /// is needed. 11968 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11969 QualType SrcType) { 11970 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11971 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11972 isVector(SrcType, Ctx.HalfTy); 11973 } 11974 11975 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11976 /// operator @p Opc at location @c TokLoc. This routine only supports 11977 /// built-in operations; ActOnBinOp handles overloaded operators. 11978 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11979 BinaryOperatorKind Opc, 11980 Expr *LHSExpr, Expr *RHSExpr) { 11981 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11982 // The syntax only allows initializer lists on the RHS of assignment, 11983 // so we don't need to worry about accepting invalid code for 11984 // non-assignment operators. 11985 // C++11 5.17p9: 11986 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11987 // of x = {} is x = T(). 11988 InitializationKind Kind = InitializationKind::CreateDirectList( 11989 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11990 InitializedEntity Entity = 11991 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11992 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11993 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11994 if (Init.isInvalid()) 11995 return Init; 11996 RHSExpr = Init.get(); 11997 } 11998 11999 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12000 QualType ResultTy; // Result type of the binary operator. 12001 // The following two variables are used for compound assignment operators 12002 QualType CompLHSTy; // Type of LHS after promotions for computation 12003 QualType CompResultTy; // Type of computation result 12004 ExprValueKind VK = VK_RValue; 12005 ExprObjectKind OK = OK_Ordinary; 12006 bool ConvertHalfVec = false; 12007 12008 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12009 if (!LHS.isUsable() || !RHS.isUsable()) 12010 return ExprError(); 12011 12012 if (getLangOpts().OpenCL) { 12013 QualType LHSTy = LHSExpr->getType(); 12014 QualType RHSTy = RHSExpr->getType(); 12015 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12016 // the ATOMIC_VAR_INIT macro. 12017 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12018 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12019 if (BO_Assign == Opc) 12020 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12021 else 12022 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12023 return ExprError(); 12024 } 12025 12026 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12027 // only with a builtin functions and therefore should be disallowed here. 12028 if (LHSTy->isImageType() || RHSTy->isImageType() || 12029 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12030 LHSTy->isPipeType() || RHSTy->isPipeType() || 12031 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12032 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12033 return ExprError(); 12034 } 12035 } 12036 12037 switch (Opc) { 12038 case BO_Assign: 12039 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12040 if (getLangOpts().CPlusPlus && 12041 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12042 VK = LHS.get()->getValueKind(); 12043 OK = LHS.get()->getObjectKind(); 12044 } 12045 if (!ResultTy.isNull()) { 12046 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12047 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12048 } 12049 RecordModifiableNonNullParam(*this, LHS.get()); 12050 break; 12051 case BO_PtrMemD: 12052 case BO_PtrMemI: 12053 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12054 Opc == BO_PtrMemI); 12055 break; 12056 case BO_Mul: 12057 case BO_Div: 12058 ConvertHalfVec = true; 12059 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12060 Opc == BO_Div); 12061 break; 12062 case BO_Rem: 12063 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12064 break; 12065 case BO_Add: 12066 ConvertHalfVec = true; 12067 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12068 break; 12069 case BO_Sub: 12070 ConvertHalfVec = true; 12071 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12072 break; 12073 case BO_Shl: 12074 case BO_Shr: 12075 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12076 break; 12077 case BO_LE: 12078 case BO_LT: 12079 case BO_GE: 12080 case BO_GT: 12081 ConvertHalfVec = true; 12082 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12083 break; 12084 case BO_EQ: 12085 case BO_NE: 12086 ConvertHalfVec = true; 12087 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12088 break; 12089 case BO_Cmp: 12090 ConvertHalfVec = true; 12091 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12092 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12093 break; 12094 case BO_And: 12095 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12096 LLVM_FALLTHROUGH; 12097 case BO_Xor: 12098 case BO_Or: 12099 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12100 break; 12101 case BO_LAnd: 12102 case BO_LOr: 12103 ConvertHalfVec = true; 12104 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12105 break; 12106 case BO_MulAssign: 12107 case BO_DivAssign: 12108 ConvertHalfVec = true; 12109 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12110 Opc == BO_DivAssign); 12111 CompLHSTy = CompResultTy; 12112 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12113 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12114 break; 12115 case BO_RemAssign: 12116 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12117 CompLHSTy = CompResultTy; 12118 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12119 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12120 break; 12121 case BO_AddAssign: 12122 ConvertHalfVec = true; 12123 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12124 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12125 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12126 break; 12127 case BO_SubAssign: 12128 ConvertHalfVec = true; 12129 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12130 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12131 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12132 break; 12133 case BO_ShlAssign: 12134 case BO_ShrAssign: 12135 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12136 CompLHSTy = CompResultTy; 12137 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12138 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12139 break; 12140 case BO_AndAssign: 12141 case BO_OrAssign: // fallthrough 12142 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12143 LLVM_FALLTHROUGH; 12144 case BO_XorAssign: 12145 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12146 CompLHSTy = CompResultTy; 12147 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12148 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12149 break; 12150 case BO_Comma: 12151 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12152 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12153 VK = RHS.get()->getValueKind(); 12154 OK = RHS.get()->getObjectKind(); 12155 } 12156 break; 12157 } 12158 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12159 return ExprError(); 12160 12161 // Some of the binary operations require promoting operands of half vector to 12162 // float vectors and truncating the result back to half vector. For now, we do 12163 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12164 // arm64). 12165 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12166 isVector(LHS.get()->getType(), Context.HalfTy) && 12167 "both sides are half vectors or neither sides are"); 12168 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12169 LHS.get()->getType()); 12170 12171 // Check for array bounds violations for both sides of the BinaryOperator 12172 CheckArrayAccess(LHS.get()); 12173 CheckArrayAccess(RHS.get()); 12174 12175 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12176 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12177 &Context.Idents.get("object_setClass"), 12178 SourceLocation(), LookupOrdinaryName); 12179 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12180 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12181 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12182 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12183 "object_setClass(") 12184 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12185 ",") 12186 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12187 } 12188 else 12189 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12190 } 12191 else if (const ObjCIvarRefExpr *OIRE = 12192 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12193 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12194 12195 // Opc is not a compound assignment if CompResultTy is null. 12196 if (CompResultTy.isNull()) { 12197 if (ConvertHalfVec) 12198 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12199 OpLoc, FPFeatures); 12200 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12201 OK, OpLoc, FPFeatures); 12202 } 12203 12204 // Handle compound assignments. 12205 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12206 OK_ObjCProperty) { 12207 VK = VK_LValue; 12208 OK = LHS.get()->getObjectKind(); 12209 } 12210 12211 if (ConvertHalfVec) 12212 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12213 OpLoc, FPFeatures); 12214 12215 return new (Context) CompoundAssignOperator( 12216 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12217 OpLoc, FPFeatures); 12218 } 12219 12220 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12221 /// operators are mixed in a way that suggests that the programmer forgot that 12222 /// comparison operators have higher precedence. The most typical example of 12223 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12224 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12225 SourceLocation OpLoc, Expr *LHSExpr, 12226 Expr *RHSExpr) { 12227 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12228 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12229 12230 // Check that one of the sides is a comparison operator and the other isn't. 12231 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12232 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12233 if (isLeftComp == isRightComp) 12234 return; 12235 12236 // Bitwise operations are sometimes used as eager logical ops. 12237 // Don't diagnose this. 12238 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12239 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12240 if (isLeftBitwise || isRightBitwise) 12241 return; 12242 12243 SourceRange DiagRange = isLeftComp 12244 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12245 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12246 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12247 SourceRange ParensRange = 12248 isLeftComp 12249 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12250 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12251 12252 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12253 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12254 SuggestParentheses(Self, OpLoc, 12255 Self.PDiag(diag::note_precedence_silence) << OpStr, 12256 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12257 SuggestParentheses(Self, OpLoc, 12258 Self.PDiag(diag::note_precedence_bitwise_first) 12259 << BinaryOperator::getOpcodeStr(Opc), 12260 ParensRange); 12261 } 12262 12263 /// It accepts a '&&' expr that is inside a '||' one. 12264 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12265 /// in parentheses. 12266 static void 12267 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12268 BinaryOperator *Bop) { 12269 assert(Bop->getOpcode() == BO_LAnd); 12270 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12271 << Bop->getSourceRange() << OpLoc; 12272 SuggestParentheses(Self, Bop->getOperatorLoc(), 12273 Self.PDiag(diag::note_precedence_silence) 12274 << Bop->getOpcodeStr(), 12275 Bop->getSourceRange()); 12276 } 12277 12278 /// Returns true if the given expression can be evaluated as a constant 12279 /// 'true'. 12280 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12281 bool Res; 12282 return !E->isValueDependent() && 12283 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12284 } 12285 12286 /// Returns true if the given expression can be evaluated as a constant 12287 /// 'false'. 12288 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12289 bool Res; 12290 return !E->isValueDependent() && 12291 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12292 } 12293 12294 /// Look for '&&' in the left hand of a '||' expr. 12295 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12296 Expr *LHSExpr, Expr *RHSExpr) { 12297 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12298 if (Bop->getOpcode() == BO_LAnd) { 12299 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12300 if (EvaluatesAsFalse(S, RHSExpr)) 12301 return; 12302 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12303 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12304 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12305 } else if (Bop->getOpcode() == BO_LOr) { 12306 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12307 // If it's "a || b && 1 || c" we didn't warn earlier for 12308 // "a || b && 1", but warn now. 12309 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12310 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12311 } 12312 } 12313 } 12314 } 12315 12316 /// Look for '&&' in the right hand of a '||' expr. 12317 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12318 Expr *LHSExpr, Expr *RHSExpr) { 12319 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12320 if (Bop->getOpcode() == BO_LAnd) { 12321 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12322 if (EvaluatesAsFalse(S, LHSExpr)) 12323 return; 12324 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12325 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12326 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12327 } 12328 } 12329 } 12330 12331 /// Look for bitwise op in the left or right hand of a bitwise op with 12332 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12333 /// the '&' expression in parentheses. 12334 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12335 SourceLocation OpLoc, Expr *SubExpr) { 12336 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12337 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12338 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12339 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12340 << Bop->getSourceRange() << OpLoc; 12341 SuggestParentheses(S, Bop->getOperatorLoc(), 12342 S.PDiag(diag::note_precedence_silence) 12343 << Bop->getOpcodeStr(), 12344 Bop->getSourceRange()); 12345 } 12346 } 12347 } 12348 12349 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12350 Expr *SubExpr, StringRef Shift) { 12351 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12352 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12353 StringRef Op = Bop->getOpcodeStr(); 12354 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12355 << Bop->getSourceRange() << OpLoc << Shift << Op; 12356 SuggestParentheses(S, Bop->getOperatorLoc(), 12357 S.PDiag(diag::note_precedence_silence) << Op, 12358 Bop->getSourceRange()); 12359 } 12360 } 12361 } 12362 12363 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12364 Expr *LHSExpr, Expr *RHSExpr) { 12365 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12366 if (!OCE) 12367 return; 12368 12369 FunctionDecl *FD = OCE->getDirectCallee(); 12370 if (!FD || !FD->isOverloadedOperator()) 12371 return; 12372 12373 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12374 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12375 return; 12376 12377 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12378 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12379 << (Kind == OO_LessLess); 12380 SuggestParentheses(S, OCE->getOperatorLoc(), 12381 S.PDiag(diag::note_precedence_silence) 12382 << (Kind == OO_LessLess ? "<<" : ">>"), 12383 OCE->getSourceRange()); 12384 SuggestParentheses( 12385 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12386 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12387 } 12388 12389 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12390 /// precedence. 12391 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12392 SourceLocation OpLoc, Expr *LHSExpr, 12393 Expr *RHSExpr){ 12394 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12395 if (BinaryOperator::isBitwiseOp(Opc)) 12396 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12397 12398 // Diagnose "arg1 & arg2 | arg3" 12399 if ((Opc == BO_Or || Opc == BO_Xor) && 12400 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12401 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12402 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12403 } 12404 12405 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12406 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12407 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12408 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12409 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12410 } 12411 12412 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12413 || Opc == BO_Shr) { 12414 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12415 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12416 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12417 } 12418 12419 // Warn on overloaded shift operators and comparisons, such as: 12420 // cout << 5 == 4; 12421 if (BinaryOperator::isComparisonOp(Opc)) 12422 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12423 } 12424 12425 // Binary Operators. 'Tok' is the token for the operator. 12426 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12427 tok::TokenKind Kind, 12428 Expr *LHSExpr, Expr *RHSExpr) { 12429 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12430 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12431 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12432 12433 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12434 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12435 12436 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12437 } 12438 12439 /// Build an overloaded binary operator expression in the given scope. 12440 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12441 BinaryOperatorKind Opc, 12442 Expr *LHS, Expr *RHS) { 12443 switch (Opc) { 12444 case BO_Assign: 12445 case BO_DivAssign: 12446 case BO_RemAssign: 12447 case BO_SubAssign: 12448 case BO_AndAssign: 12449 case BO_OrAssign: 12450 case BO_XorAssign: 12451 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12452 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12453 break; 12454 default: 12455 break; 12456 } 12457 12458 // Find all of the overloaded operators visible from this 12459 // point. We perform both an operator-name lookup from the local 12460 // scope and an argument-dependent lookup based on the types of 12461 // the arguments. 12462 UnresolvedSet<16> Functions; 12463 OverloadedOperatorKind OverOp 12464 = BinaryOperator::getOverloadedOperator(Opc); 12465 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12466 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12467 RHS->getType(), Functions); 12468 12469 // Build the (potentially-overloaded, potentially-dependent) 12470 // binary operation. 12471 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12472 } 12473 12474 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12475 BinaryOperatorKind Opc, 12476 Expr *LHSExpr, Expr *RHSExpr) { 12477 ExprResult LHS, RHS; 12478 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12479 if (!LHS.isUsable() || !RHS.isUsable()) 12480 return ExprError(); 12481 LHSExpr = LHS.get(); 12482 RHSExpr = RHS.get(); 12483 12484 // We want to end up calling one of checkPseudoObjectAssignment 12485 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12486 // both expressions are overloadable or either is type-dependent), 12487 // or CreateBuiltinBinOp (in any other case). We also want to get 12488 // any placeholder types out of the way. 12489 12490 // Handle pseudo-objects in the LHS. 12491 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12492 // Assignments with a pseudo-object l-value need special analysis. 12493 if (pty->getKind() == BuiltinType::PseudoObject && 12494 BinaryOperator::isAssignmentOp(Opc)) 12495 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12496 12497 // Don't resolve overloads if the other type is overloadable. 12498 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12499 // We can't actually test that if we still have a placeholder, 12500 // though. Fortunately, none of the exceptions we see in that 12501 // code below are valid when the LHS is an overload set. Note 12502 // that an overload set can be dependently-typed, but it never 12503 // instantiates to having an overloadable type. 12504 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12505 if (resolvedRHS.isInvalid()) return ExprError(); 12506 RHSExpr = resolvedRHS.get(); 12507 12508 if (RHSExpr->isTypeDependent() || 12509 RHSExpr->getType()->isOverloadableType()) 12510 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12511 } 12512 12513 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12514 // template, diagnose the missing 'template' keyword instead of diagnosing 12515 // an invalid use of a bound member function. 12516 // 12517 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12518 // to C++1z [over.over]/1.4, but we already checked for that case above. 12519 if (Opc == BO_LT && inTemplateInstantiation() && 12520 (pty->getKind() == BuiltinType::BoundMember || 12521 pty->getKind() == BuiltinType::Overload)) { 12522 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12523 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12524 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12525 return isa<FunctionTemplateDecl>(ND); 12526 })) { 12527 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12528 : OE->getNameLoc(), 12529 diag::err_template_kw_missing) 12530 << OE->getName().getAsString() << ""; 12531 return ExprError(); 12532 } 12533 } 12534 12535 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12536 if (LHS.isInvalid()) return ExprError(); 12537 LHSExpr = LHS.get(); 12538 } 12539 12540 // Handle pseudo-objects in the RHS. 12541 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12542 // An overload in the RHS can potentially be resolved by the type 12543 // being assigned to. 12544 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12545 if (getLangOpts().CPlusPlus && 12546 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12547 LHSExpr->getType()->isOverloadableType())) 12548 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12549 12550 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12551 } 12552 12553 // Don't resolve overloads if the other type is overloadable. 12554 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12555 LHSExpr->getType()->isOverloadableType()) 12556 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12557 12558 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12559 if (!resolvedRHS.isUsable()) return ExprError(); 12560 RHSExpr = resolvedRHS.get(); 12561 } 12562 12563 if (getLangOpts().CPlusPlus) { 12564 // If either expression is type-dependent, always build an 12565 // overloaded op. 12566 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12567 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12568 12569 // Otherwise, build an overloaded op if either expression has an 12570 // overloadable type. 12571 if (LHSExpr->getType()->isOverloadableType() || 12572 RHSExpr->getType()->isOverloadableType()) 12573 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12574 } 12575 12576 // Build a built-in binary operation. 12577 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12578 } 12579 12580 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12581 if (T.isNull() || T->isDependentType()) 12582 return false; 12583 12584 if (!T->isPromotableIntegerType()) 12585 return true; 12586 12587 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12588 } 12589 12590 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12591 UnaryOperatorKind Opc, 12592 Expr *InputExpr) { 12593 ExprResult Input = InputExpr; 12594 ExprValueKind VK = VK_RValue; 12595 ExprObjectKind OK = OK_Ordinary; 12596 QualType resultType; 12597 bool CanOverflow = false; 12598 12599 bool ConvertHalfVec = false; 12600 if (getLangOpts().OpenCL) { 12601 QualType Ty = InputExpr->getType(); 12602 // The only legal unary operation for atomics is '&'. 12603 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12604 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12605 // only with a builtin functions and therefore should be disallowed here. 12606 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12607 || Ty->isBlockPointerType())) { 12608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12609 << InputExpr->getType() 12610 << Input.get()->getSourceRange()); 12611 } 12612 } 12613 switch (Opc) { 12614 case UO_PreInc: 12615 case UO_PreDec: 12616 case UO_PostInc: 12617 case UO_PostDec: 12618 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12619 OpLoc, 12620 Opc == UO_PreInc || 12621 Opc == UO_PostInc, 12622 Opc == UO_PreInc || 12623 Opc == UO_PreDec); 12624 CanOverflow = isOverflowingIntegerType(Context, resultType); 12625 break; 12626 case UO_AddrOf: 12627 resultType = CheckAddressOfOperand(Input, OpLoc); 12628 RecordModifiableNonNullParam(*this, InputExpr); 12629 break; 12630 case UO_Deref: { 12631 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12632 if (Input.isInvalid()) return ExprError(); 12633 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12634 break; 12635 } 12636 case UO_Plus: 12637 case UO_Minus: 12638 CanOverflow = Opc == UO_Minus && 12639 isOverflowingIntegerType(Context, Input.get()->getType()); 12640 Input = UsualUnaryConversions(Input.get()); 12641 if (Input.isInvalid()) return ExprError(); 12642 // Unary plus and minus require promoting an operand of half vector to a 12643 // float vector and truncating the result back to a half vector. For now, we 12644 // do this only when HalfArgsAndReturns is set (that is, when the target is 12645 // arm or arm64). 12646 ConvertHalfVec = 12647 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12648 12649 // If the operand is a half vector, promote it to a float vector. 12650 if (ConvertHalfVec) 12651 Input = convertVector(Input.get(), Context.FloatTy, *this); 12652 resultType = Input.get()->getType(); 12653 if (resultType->isDependentType()) 12654 break; 12655 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12656 break; 12657 else if (resultType->isVectorType() && 12658 // The z vector extensions don't allow + or - with bool vectors. 12659 (!Context.getLangOpts().ZVector || 12660 resultType->getAs<VectorType>()->getVectorKind() != 12661 VectorType::AltiVecBool)) 12662 break; 12663 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12664 Opc == UO_Plus && 12665 resultType->isPointerType()) 12666 break; 12667 12668 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12669 << resultType << Input.get()->getSourceRange()); 12670 12671 case UO_Not: // bitwise complement 12672 Input = UsualUnaryConversions(Input.get()); 12673 if (Input.isInvalid()) 12674 return ExprError(); 12675 resultType = Input.get()->getType(); 12676 12677 if (resultType->isDependentType()) 12678 break; 12679 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12680 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12681 // C99 does not support '~' for complex conjugation. 12682 Diag(OpLoc, diag::ext_integer_complement_complex) 12683 << resultType << Input.get()->getSourceRange(); 12684 else if (resultType->hasIntegerRepresentation()) 12685 break; 12686 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12687 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12688 // on vector float types. 12689 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12690 if (!T->isIntegerType()) 12691 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12692 << resultType << Input.get()->getSourceRange()); 12693 } else { 12694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12695 << resultType << Input.get()->getSourceRange()); 12696 } 12697 break; 12698 12699 case UO_LNot: // logical negation 12700 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12701 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12702 if (Input.isInvalid()) return ExprError(); 12703 resultType = Input.get()->getType(); 12704 12705 // Though we still have to promote half FP to float... 12706 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12707 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12708 resultType = Context.FloatTy; 12709 } 12710 12711 if (resultType->isDependentType()) 12712 break; 12713 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12714 // C99 6.5.3.3p1: ok, fallthrough; 12715 if (Context.getLangOpts().CPlusPlus) { 12716 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12717 // operand contextually converted to bool. 12718 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12719 ScalarTypeToBooleanCastKind(resultType)); 12720 } else if (Context.getLangOpts().OpenCL && 12721 Context.getLangOpts().OpenCLVersion < 120) { 12722 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12723 // operate on scalar float types. 12724 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12725 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12726 << resultType << Input.get()->getSourceRange()); 12727 } 12728 } else if (resultType->isExtVectorType()) { 12729 if (Context.getLangOpts().OpenCL && 12730 Context.getLangOpts().OpenCLVersion < 120) { 12731 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12732 // operate on vector float types. 12733 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12734 if (!T->isIntegerType()) 12735 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12736 << resultType << Input.get()->getSourceRange()); 12737 } 12738 // Vector logical not returns the signed variant of the operand type. 12739 resultType = GetSignedVectorType(resultType); 12740 break; 12741 } else { 12742 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12743 // type in C++. We should allow that here too. 12744 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12745 << resultType << Input.get()->getSourceRange()); 12746 } 12747 12748 // LNot always has type int. C99 6.5.3.3p5. 12749 // In C++, it's bool. C++ 5.3.1p8 12750 resultType = Context.getLogicalOperationType(); 12751 break; 12752 case UO_Real: 12753 case UO_Imag: 12754 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12755 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12756 // complex l-values to ordinary l-values and all other values to r-values. 12757 if (Input.isInvalid()) return ExprError(); 12758 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12759 if (Input.get()->getValueKind() != VK_RValue && 12760 Input.get()->getObjectKind() == OK_Ordinary) 12761 VK = Input.get()->getValueKind(); 12762 } else if (!getLangOpts().CPlusPlus) { 12763 // In C, a volatile scalar is read by __imag. In C++, it is not. 12764 Input = DefaultLvalueConversion(Input.get()); 12765 } 12766 break; 12767 case UO_Extension: 12768 resultType = Input.get()->getType(); 12769 VK = Input.get()->getValueKind(); 12770 OK = Input.get()->getObjectKind(); 12771 break; 12772 case UO_Coawait: 12773 // It's unnecessary to represent the pass-through operator co_await in the 12774 // AST; just return the input expression instead. 12775 assert(!Input.get()->getType()->isDependentType() && 12776 "the co_await expression must be non-dependant before " 12777 "building operator co_await"); 12778 return Input; 12779 } 12780 if (resultType.isNull() || Input.isInvalid()) 12781 return ExprError(); 12782 12783 // Check for array bounds violations in the operand of the UnaryOperator, 12784 // except for the '*' and '&' operators that have to be handled specially 12785 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12786 // that are explicitly defined as valid by the standard). 12787 if (Opc != UO_AddrOf && Opc != UO_Deref) 12788 CheckArrayAccess(Input.get()); 12789 12790 auto *UO = new (Context) 12791 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12792 // Convert the result back to a half vector. 12793 if (ConvertHalfVec) 12794 return convertVector(UO, Context.HalfTy, *this); 12795 return UO; 12796 } 12797 12798 /// Determine whether the given expression is a qualified member 12799 /// access expression, of a form that could be turned into a pointer to member 12800 /// with the address-of operator. 12801 bool Sema::isQualifiedMemberAccess(Expr *E) { 12802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12803 if (!DRE->getQualifier()) 12804 return false; 12805 12806 ValueDecl *VD = DRE->getDecl(); 12807 if (!VD->isCXXClassMember()) 12808 return false; 12809 12810 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12811 return true; 12812 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12813 return Method->isInstance(); 12814 12815 return false; 12816 } 12817 12818 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12819 if (!ULE->getQualifier()) 12820 return false; 12821 12822 for (NamedDecl *D : ULE->decls()) { 12823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12824 if (Method->isInstance()) 12825 return true; 12826 } else { 12827 // Overload set does not contain methods. 12828 break; 12829 } 12830 } 12831 12832 return false; 12833 } 12834 12835 return false; 12836 } 12837 12838 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12839 UnaryOperatorKind Opc, Expr *Input) { 12840 // First things first: handle placeholders so that the 12841 // overloaded-operator check considers the right type. 12842 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12843 // Increment and decrement of pseudo-object references. 12844 if (pty->getKind() == BuiltinType::PseudoObject && 12845 UnaryOperator::isIncrementDecrementOp(Opc)) 12846 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12847 12848 // extension is always a builtin operator. 12849 if (Opc == UO_Extension) 12850 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12851 12852 // & gets special logic for several kinds of placeholder. 12853 // The builtin code knows what to do. 12854 if (Opc == UO_AddrOf && 12855 (pty->getKind() == BuiltinType::Overload || 12856 pty->getKind() == BuiltinType::UnknownAny || 12857 pty->getKind() == BuiltinType::BoundMember)) 12858 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12859 12860 // Anything else needs to be handled now. 12861 ExprResult Result = CheckPlaceholderExpr(Input); 12862 if (Result.isInvalid()) return ExprError(); 12863 Input = Result.get(); 12864 } 12865 12866 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12867 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12868 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12869 // Find all of the overloaded operators visible from this 12870 // point. We perform both an operator-name lookup from the local 12871 // scope and an argument-dependent lookup based on the types of 12872 // the arguments. 12873 UnresolvedSet<16> Functions; 12874 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12875 if (S && OverOp != OO_None) 12876 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12877 Functions); 12878 12879 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12880 } 12881 12882 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12883 } 12884 12885 // Unary Operators. 'Tok' is the token for the operator. 12886 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12887 tok::TokenKind Op, Expr *Input) { 12888 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12889 } 12890 12891 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12892 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12893 LabelDecl *TheDecl) { 12894 TheDecl->markUsed(Context); 12895 // Create the AST node. The address of a label always has type 'void*'. 12896 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12897 Context.getPointerType(Context.VoidTy)); 12898 } 12899 12900 /// Given the last statement in a statement-expression, check whether 12901 /// the result is a producing expression (like a call to an 12902 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12903 /// release out of the full-expression. Otherwise, return null. 12904 /// Cannot fail. 12905 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12906 // Should always be wrapped with one of these. 12907 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12908 if (!cleanups) return nullptr; 12909 12910 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12911 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12912 return nullptr; 12913 12914 // Splice out the cast. This shouldn't modify any interesting 12915 // features of the statement. 12916 Expr *producer = cast->getSubExpr(); 12917 assert(producer->getType() == cast->getType()); 12918 assert(producer->getValueKind() == cast->getValueKind()); 12919 cleanups->setSubExpr(producer); 12920 return cleanups; 12921 } 12922 12923 void Sema::ActOnStartStmtExpr() { 12924 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12925 } 12926 12927 void Sema::ActOnStmtExprError() { 12928 // Note that function is also called by TreeTransform when leaving a 12929 // StmtExpr scope without rebuilding anything. 12930 12931 DiscardCleanupsInEvaluationContext(); 12932 PopExpressionEvaluationContext(); 12933 } 12934 12935 ExprResult 12936 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12937 SourceLocation RPLoc) { // "({..})" 12938 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12939 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12940 12941 if (hasAnyUnrecoverableErrorsInThisFunction()) 12942 DiscardCleanupsInEvaluationContext(); 12943 assert(!Cleanup.exprNeedsCleanups() && 12944 "cleanups within StmtExpr not correctly bound!"); 12945 PopExpressionEvaluationContext(); 12946 12947 // FIXME: there are a variety of strange constraints to enforce here, for 12948 // example, it is not possible to goto into a stmt expression apparently. 12949 // More semantic analysis is needed. 12950 12951 // If there are sub-stmts in the compound stmt, take the type of the last one 12952 // as the type of the stmtexpr. 12953 QualType Ty = Context.VoidTy; 12954 bool StmtExprMayBindToTemp = false; 12955 if (!Compound->body_empty()) { 12956 Stmt *LastStmt = Compound->body_back(); 12957 LabelStmt *LastLabelStmt = nullptr; 12958 // If LastStmt is a label, skip down through into the body. 12959 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12960 LastLabelStmt = Label; 12961 LastStmt = Label->getSubStmt(); 12962 } 12963 12964 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12965 // Do function/array conversion on the last expression, but not 12966 // lvalue-to-rvalue. However, initialize an unqualified type. 12967 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12968 if (LastExpr.isInvalid()) 12969 return ExprError(); 12970 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12971 12972 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12973 // In ARC, if the final expression ends in a consume, splice 12974 // the consume out and bind it later. In the alternate case 12975 // (when dealing with a retainable type), the result 12976 // initialization will create a produce. In both cases the 12977 // result will be +1, and we'll need to balance that out with 12978 // a bind. 12979 if (Expr *rebuiltLastStmt 12980 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12981 LastExpr = rebuiltLastStmt; 12982 } else { 12983 LastExpr = PerformCopyInitialization( 12984 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 12985 SourceLocation(), LastExpr); 12986 } 12987 12988 if (LastExpr.isInvalid()) 12989 return ExprError(); 12990 if (LastExpr.get() != nullptr) { 12991 if (!LastLabelStmt) 12992 Compound->setLastStmt(LastExpr.get()); 12993 else 12994 LastLabelStmt->setSubStmt(LastExpr.get()); 12995 StmtExprMayBindToTemp = true; 12996 } 12997 } 12998 } 12999 } 13000 13001 // FIXME: Check that expression type is complete/non-abstract; statement 13002 // expressions are not lvalues. 13003 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13004 if (StmtExprMayBindToTemp) 13005 return MaybeBindToTemporary(ResStmtExpr); 13006 return ResStmtExpr; 13007 } 13008 13009 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13010 TypeSourceInfo *TInfo, 13011 ArrayRef<OffsetOfComponent> Components, 13012 SourceLocation RParenLoc) { 13013 QualType ArgTy = TInfo->getType(); 13014 bool Dependent = ArgTy->isDependentType(); 13015 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13016 13017 // We must have at least one component that refers to the type, and the first 13018 // one is known to be a field designator. Verify that the ArgTy represents 13019 // a struct/union/class. 13020 if (!Dependent && !ArgTy->isRecordType()) 13021 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13022 << ArgTy << TypeRange); 13023 13024 // Type must be complete per C99 7.17p3 because a declaring a variable 13025 // with an incomplete type would be ill-formed. 13026 if (!Dependent 13027 && RequireCompleteType(BuiltinLoc, ArgTy, 13028 diag::err_offsetof_incomplete_type, TypeRange)) 13029 return ExprError(); 13030 13031 bool DidWarnAboutNonPOD = false; 13032 QualType CurrentType = ArgTy; 13033 SmallVector<OffsetOfNode, 4> Comps; 13034 SmallVector<Expr*, 4> Exprs; 13035 for (const OffsetOfComponent &OC : Components) { 13036 if (OC.isBrackets) { 13037 // Offset of an array sub-field. TODO: Should we allow vector elements? 13038 if (!CurrentType->isDependentType()) { 13039 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13040 if(!AT) 13041 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13042 << CurrentType); 13043 CurrentType = AT->getElementType(); 13044 } else 13045 CurrentType = Context.DependentTy; 13046 13047 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13048 if (IdxRval.isInvalid()) 13049 return ExprError(); 13050 Expr *Idx = IdxRval.get(); 13051 13052 // The expression must be an integral expression. 13053 // FIXME: An integral constant expression? 13054 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13055 !Idx->getType()->isIntegerType()) 13056 return ExprError( 13057 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13058 << Idx->getSourceRange()); 13059 13060 // Record this array index. 13061 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13062 Exprs.push_back(Idx); 13063 continue; 13064 } 13065 13066 // Offset of a field. 13067 if (CurrentType->isDependentType()) { 13068 // We have the offset of a field, but we can't look into the dependent 13069 // type. Just record the identifier of the field. 13070 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13071 CurrentType = Context.DependentTy; 13072 continue; 13073 } 13074 13075 // We need to have a complete type to look into. 13076 if (RequireCompleteType(OC.LocStart, CurrentType, 13077 diag::err_offsetof_incomplete_type)) 13078 return ExprError(); 13079 13080 // Look for the designated field. 13081 const RecordType *RC = CurrentType->getAs<RecordType>(); 13082 if (!RC) 13083 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13084 << CurrentType); 13085 RecordDecl *RD = RC->getDecl(); 13086 13087 // C++ [lib.support.types]p5: 13088 // The macro offsetof accepts a restricted set of type arguments in this 13089 // International Standard. type shall be a POD structure or a POD union 13090 // (clause 9). 13091 // C++11 [support.types]p4: 13092 // If type is not a standard-layout class (Clause 9), the results are 13093 // undefined. 13094 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13095 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13096 unsigned DiagID = 13097 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13098 : diag::ext_offsetof_non_pod_type; 13099 13100 if (!IsSafe && !DidWarnAboutNonPOD && 13101 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13102 PDiag(DiagID) 13103 << SourceRange(Components[0].LocStart, OC.LocEnd) 13104 << CurrentType)) 13105 DidWarnAboutNonPOD = true; 13106 } 13107 13108 // Look for the field. 13109 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13110 LookupQualifiedName(R, RD); 13111 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13112 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13113 if (!MemberDecl) { 13114 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13115 MemberDecl = IndirectMemberDecl->getAnonField(); 13116 } 13117 13118 if (!MemberDecl) 13119 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13120 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13121 OC.LocEnd)); 13122 13123 // C99 7.17p3: 13124 // (If the specified member is a bit-field, the behavior is undefined.) 13125 // 13126 // We diagnose this as an error. 13127 if (MemberDecl->isBitField()) { 13128 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13129 << MemberDecl->getDeclName() 13130 << SourceRange(BuiltinLoc, RParenLoc); 13131 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13132 return ExprError(); 13133 } 13134 13135 RecordDecl *Parent = MemberDecl->getParent(); 13136 if (IndirectMemberDecl) 13137 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13138 13139 // If the member was found in a base class, introduce OffsetOfNodes for 13140 // the base class indirections. 13141 CXXBasePaths Paths; 13142 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13143 Paths)) { 13144 if (Paths.getDetectedVirtual()) { 13145 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13146 << MemberDecl->getDeclName() 13147 << SourceRange(BuiltinLoc, RParenLoc); 13148 return ExprError(); 13149 } 13150 13151 CXXBasePath &Path = Paths.front(); 13152 for (const CXXBasePathElement &B : Path) 13153 Comps.push_back(OffsetOfNode(B.Base)); 13154 } 13155 13156 if (IndirectMemberDecl) { 13157 for (auto *FI : IndirectMemberDecl->chain()) { 13158 assert(isa<FieldDecl>(FI)); 13159 Comps.push_back(OffsetOfNode(OC.LocStart, 13160 cast<FieldDecl>(FI), OC.LocEnd)); 13161 } 13162 } else 13163 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13164 13165 CurrentType = MemberDecl->getType().getNonReferenceType(); 13166 } 13167 13168 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13169 Comps, Exprs, RParenLoc); 13170 } 13171 13172 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13173 SourceLocation BuiltinLoc, 13174 SourceLocation TypeLoc, 13175 ParsedType ParsedArgTy, 13176 ArrayRef<OffsetOfComponent> Components, 13177 SourceLocation RParenLoc) { 13178 13179 TypeSourceInfo *ArgTInfo; 13180 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13181 if (ArgTy.isNull()) 13182 return ExprError(); 13183 13184 if (!ArgTInfo) 13185 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13186 13187 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13188 } 13189 13190 13191 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13192 Expr *CondExpr, 13193 Expr *LHSExpr, Expr *RHSExpr, 13194 SourceLocation RPLoc) { 13195 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13196 13197 ExprValueKind VK = VK_RValue; 13198 ExprObjectKind OK = OK_Ordinary; 13199 QualType resType; 13200 bool ValueDependent = false; 13201 bool CondIsTrue = false; 13202 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13203 resType = Context.DependentTy; 13204 ValueDependent = true; 13205 } else { 13206 // The conditional expression is required to be a constant expression. 13207 llvm::APSInt condEval(32); 13208 ExprResult CondICE 13209 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13210 diag::err_typecheck_choose_expr_requires_constant, false); 13211 if (CondICE.isInvalid()) 13212 return ExprError(); 13213 CondExpr = CondICE.get(); 13214 CondIsTrue = condEval.getZExtValue(); 13215 13216 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13217 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13218 13219 resType = ActiveExpr->getType(); 13220 ValueDependent = ActiveExpr->isValueDependent(); 13221 VK = ActiveExpr->getValueKind(); 13222 OK = ActiveExpr->getObjectKind(); 13223 } 13224 13225 return new (Context) 13226 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13227 CondIsTrue, resType->isDependentType(), ValueDependent); 13228 } 13229 13230 //===----------------------------------------------------------------------===// 13231 // Clang Extensions. 13232 //===----------------------------------------------------------------------===// 13233 13234 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13235 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13236 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13237 13238 if (LangOpts.CPlusPlus) { 13239 Decl *ManglingContextDecl; 13240 if (MangleNumberingContext *MCtx = 13241 getCurrentMangleNumberContext(Block->getDeclContext(), 13242 ManglingContextDecl)) { 13243 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13244 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13245 } 13246 } 13247 13248 PushBlockScope(CurScope, Block); 13249 CurContext->addDecl(Block); 13250 if (CurScope) 13251 PushDeclContext(CurScope, Block); 13252 else 13253 CurContext = Block; 13254 13255 getCurBlock()->HasImplicitReturnType = true; 13256 13257 // Enter a new evaluation context to insulate the block from any 13258 // cleanups from the enclosing full-expression. 13259 PushExpressionEvaluationContext( 13260 ExpressionEvaluationContext::PotentiallyEvaluated); 13261 } 13262 13263 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13264 Scope *CurScope) { 13265 assert(ParamInfo.getIdentifier() == nullptr && 13266 "block-id should have no identifier!"); 13267 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13268 BlockScopeInfo *CurBlock = getCurBlock(); 13269 13270 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13271 QualType T = Sig->getType(); 13272 13273 // FIXME: We should allow unexpanded parameter packs here, but that would, 13274 // in turn, make the block expression contain unexpanded parameter packs. 13275 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13276 // Drop the parameters. 13277 FunctionProtoType::ExtProtoInfo EPI; 13278 EPI.HasTrailingReturn = false; 13279 EPI.TypeQuals |= DeclSpec::TQ_const; 13280 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13281 Sig = Context.getTrivialTypeSourceInfo(T); 13282 } 13283 13284 // GetTypeForDeclarator always produces a function type for a block 13285 // literal signature. Furthermore, it is always a FunctionProtoType 13286 // unless the function was written with a typedef. 13287 assert(T->isFunctionType() && 13288 "GetTypeForDeclarator made a non-function block signature"); 13289 13290 // Look for an explicit signature in that function type. 13291 FunctionProtoTypeLoc ExplicitSignature; 13292 13293 if ((ExplicitSignature = 13294 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13295 13296 // Check whether that explicit signature was synthesized by 13297 // GetTypeForDeclarator. If so, don't save that as part of the 13298 // written signature. 13299 if (ExplicitSignature.getLocalRangeBegin() == 13300 ExplicitSignature.getLocalRangeEnd()) { 13301 // This would be much cheaper if we stored TypeLocs instead of 13302 // TypeSourceInfos. 13303 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13304 unsigned Size = Result.getFullDataSize(); 13305 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13306 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13307 13308 ExplicitSignature = FunctionProtoTypeLoc(); 13309 } 13310 } 13311 13312 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13313 CurBlock->FunctionType = T; 13314 13315 const FunctionType *Fn = T->getAs<FunctionType>(); 13316 QualType RetTy = Fn->getReturnType(); 13317 bool isVariadic = 13318 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13319 13320 CurBlock->TheDecl->setIsVariadic(isVariadic); 13321 13322 // Context.DependentTy is used as a placeholder for a missing block 13323 // return type. TODO: what should we do with declarators like: 13324 // ^ * { ... } 13325 // If the answer is "apply template argument deduction".... 13326 if (RetTy != Context.DependentTy) { 13327 CurBlock->ReturnType = RetTy; 13328 CurBlock->TheDecl->setBlockMissingReturnType(false); 13329 CurBlock->HasImplicitReturnType = false; 13330 } 13331 13332 // Push block parameters from the declarator if we had them. 13333 SmallVector<ParmVarDecl*, 8> Params; 13334 if (ExplicitSignature) { 13335 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13336 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13337 if (Param->getIdentifier() == nullptr && 13338 !Param->isImplicit() && 13339 !Param->isInvalidDecl() && 13340 !getLangOpts().CPlusPlus) 13341 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13342 Params.push_back(Param); 13343 } 13344 13345 // Fake up parameter variables if we have a typedef, like 13346 // ^ fntype { ... } 13347 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13348 for (const auto &I : Fn->param_types()) { 13349 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13350 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13351 Params.push_back(Param); 13352 } 13353 } 13354 13355 // Set the parameters on the block decl. 13356 if (!Params.empty()) { 13357 CurBlock->TheDecl->setParams(Params); 13358 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13359 /*CheckParameterNames=*/false); 13360 } 13361 13362 // Finally we can process decl attributes. 13363 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13364 13365 // Put the parameter variables in scope. 13366 for (auto AI : CurBlock->TheDecl->parameters()) { 13367 AI->setOwningFunction(CurBlock->TheDecl); 13368 13369 // If this has an identifier, add it to the scope stack. 13370 if (AI->getIdentifier()) { 13371 CheckShadow(CurBlock->TheScope, AI); 13372 13373 PushOnScopeChains(AI, CurBlock->TheScope); 13374 } 13375 } 13376 } 13377 13378 /// ActOnBlockError - If there is an error parsing a block, this callback 13379 /// is invoked to pop the information about the block from the action impl. 13380 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13381 // Leave the expression-evaluation context. 13382 DiscardCleanupsInEvaluationContext(); 13383 PopExpressionEvaluationContext(); 13384 13385 // Pop off CurBlock, handle nested blocks. 13386 PopDeclContext(); 13387 PopFunctionScopeInfo(); 13388 } 13389 13390 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13391 /// literal was successfully completed. ^(int x){...} 13392 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13393 Stmt *Body, Scope *CurScope) { 13394 // If blocks are disabled, emit an error. 13395 if (!LangOpts.Blocks) 13396 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13397 13398 // Leave the expression-evaluation context. 13399 if (hasAnyUnrecoverableErrorsInThisFunction()) 13400 DiscardCleanupsInEvaluationContext(); 13401 assert(!Cleanup.exprNeedsCleanups() && 13402 "cleanups within block not correctly bound!"); 13403 PopExpressionEvaluationContext(); 13404 13405 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13406 13407 if (BSI->HasImplicitReturnType) 13408 deduceClosureReturnType(*BSI); 13409 13410 PopDeclContext(); 13411 13412 QualType RetTy = Context.VoidTy; 13413 if (!BSI->ReturnType.isNull()) 13414 RetTy = BSI->ReturnType; 13415 13416 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13417 QualType BlockTy; 13418 13419 // Set the captured variables on the block. 13420 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13421 SmallVector<BlockDecl::Capture, 4> Captures; 13422 for (Capture &Cap : BSI->Captures) { 13423 if (Cap.isThisCapture()) 13424 continue; 13425 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13426 Cap.isNested(), Cap.getInitExpr()); 13427 Captures.push_back(NewCap); 13428 } 13429 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13430 13431 // If the user wrote a function type in some form, try to use that. 13432 if (!BSI->FunctionType.isNull()) { 13433 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13434 13435 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13436 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13437 13438 // Turn protoless block types into nullary block types. 13439 if (isa<FunctionNoProtoType>(FTy)) { 13440 FunctionProtoType::ExtProtoInfo EPI; 13441 EPI.ExtInfo = Ext; 13442 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13443 13444 // Otherwise, if we don't need to change anything about the function type, 13445 // preserve its sugar structure. 13446 } else if (FTy->getReturnType() == RetTy && 13447 (!NoReturn || FTy->getNoReturnAttr())) { 13448 BlockTy = BSI->FunctionType; 13449 13450 // Otherwise, make the minimal modifications to the function type. 13451 } else { 13452 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13453 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13454 EPI.TypeQuals = 0; // FIXME: silently? 13455 EPI.ExtInfo = Ext; 13456 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13457 } 13458 13459 // If we don't have a function type, just build one from nothing. 13460 } else { 13461 FunctionProtoType::ExtProtoInfo EPI; 13462 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13463 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13464 } 13465 13466 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13467 BlockTy = Context.getBlockPointerType(BlockTy); 13468 13469 // If needed, diagnose invalid gotos and switches in the block. 13470 if (getCurFunction()->NeedsScopeChecking() && 13471 !PP.isCodeCompletionEnabled()) 13472 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13473 13474 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13475 13476 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13477 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13478 13479 // Try to apply the named return value optimization. We have to check again 13480 // if we can do this, though, because blocks keep return statements around 13481 // to deduce an implicit return type. 13482 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13483 !BSI->TheDecl->isDependentContext()) 13484 computeNRVO(Body, BSI); 13485 13486 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13487 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13488 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13489 13490 // If the block isn't obviously global, i.e. it captures anything at 13491 // all, then we need to do a few things in the surrounding context: 13492 if (Result->getBlockDecl()->hasCaptures()) { 13493 // First, this expression has a new cleanup object. 13494 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13495 Cleanup.setExprNeedsCleanups(true); 13496 13497 // It also gets a branch-protected scope if any of the captured 13498 // variables needs destruction. 13499 for (const auto &CI : Result->getBlockDecl()->captures()) { 13500 const VarDecl *var = CI.getVariable(); 13501 if (var->getType().isDestructedType() != QualType::DK_none) { 13502 setFunctionHasBranchProtectedScope(); 13503 break; 13504 } 13505 } 13506 } 13507 13508 return Result; 13509 } 13510 13511 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13512 SourceLocation RPLoc) { 13513 TypeSourceInfo *TInfo; 13514 GetTypeFromParser(Ty, &TInfo); 13515 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13516 } 13517 13518 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13519 Expr *E, TypeSourceInfo *TInfo, 13520 SourceLocation RPLoc) { 13521 Expr *OrigExpr = E; 13522 bool IsMS = false; 13523 13524 // CUDA device code does not support varargs. 13525 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13526 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13527 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13528 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13529 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13530 } 13531 } 13532 13533 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13534 // as Microsoft ABI on an actual Microsoft platform, where 13535 // __builtin_ms_va_list and __builtin_va_list are the same.) 13536 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13537 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13538 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13539 if (Context.hasSameType(MSVaListType, E->getType())) { 13540 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13541 return ExprError(); 13542 IsMS = true; 13543 } 13544 } 13545 13546 // Get the va_list type 13547 QualType VaListType = Context.getBuiltinVaListType(); 13548 if (!IsMS) { 13549 if (VaListType->isArrayType()) { 13550 // Deal with implicit array decay; for example, on x86-64, 13551 // va_list is an array, but it's supposed to decay to 13552 // a pointer for va_arg. 13553 VaListType = Context.getArrayDecayedType(VaListType); 13554 // Make sure the input expression also decays appropriately. 13555 ExprResult Result = UsualUnaryConversions(E); 13556 if (Result.isInvalid()) 13557 return ExprError(); 13558 E = Result.get(); 13559 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13560 // If va_list is a record type and we are compiling in C++ mode, 13561 // check the argument using reference binding. 13562 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13563 Context, Context.getLValueReferenceType(VaListType), false); 13564 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13565 if (Init.isInvalid()) 13566 return ExprError(); 13567 E = Init.getAs<Expr>(); 13568 } else { 13569 // Otherwise, the va_list argument must be an l-value because 13570 // it is modified by va_arg. 13571 if (!E->isTypeDependent() && 13572 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13573 return ExprError(); 13574 } 13575 } 13576 13577 if (!IsMS && !E->isTypeDependent() && 13578 !Context.hasSameType(VaListType, E->getType())) 13579 return ExprError( 13580 Diag(E->getBeginLoc(), 13581 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13582 << OrigExpr->getType() << E->getSourceRange()); 13583 13584 if (!TInfo->getType()->isDependentType()) { 13585 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13586 diag::err_second_parameter_to_va_arg_incomplete, 13587 TInfo->getTypeLoc())) 13588 return ExprError(); 13589 13590 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13591 TInfo->getType(), 13592 diag::err_second_parameter_to_va_arg_abstract, 13593 TInfo->getTypeLoc())) 13594 return ExprError(); 13595 13596 if (!TInfo->getType().isPODType(Context)) { 13597 Diag(TInfo->getTypeLoc().getBeginLoc(), 13598 TInfo->getType()->isObjCLifetimeType() 13599 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13600 : diag::warn_second_parameter_to_va_arg_not_pod) 13601 << TInfo->getType() 13602 << TInfo->getTypeLoc().getSourceRange(); 13603 } 13604 13605 // Check for va_arg where arguments of the given type will be promoted 13606 // (i.e. this va_arg is guaranteed to have undefined behavior). 13607 QualType PromoteType; 13608 if (TInfo->getType()->isPromotableIntegerType()) { 13609 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13610 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13611 PromoteType = QualType(); 13612 } 13613 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13614 PromoteType = Context.DoubleTy; 13615 if (!PromoteType.isNull()) 13616 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13617 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13618 << TInfo->getType() 13619 << PromoteType 13620 << TInfo->getTypeLoc().getSourceRange()); 13621 } 13622 13623 QualType T = TInfo->getType().getNonLValueExprType(Context); 13624 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13625 } 13626 13627 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13628 // The type of __null will be int or long, depending on the size of 13629 // pointers on the target. 13630 QualType Ty; 13631 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13632 if (pw == Context.getTargetInfo().getIntWidth()) 13633 Ty = Context.IntTy; 13634 else if (pw == Context.getTargetInfo().getLongWidth()) 13635 Ty = Context.LongTy; 13636 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13637 Ty = Context.LongLongTy; 13638 else { 13639 llvm_unreachable("I don't know size of pointer!"); 13640 } 13641 13642 return new (Context) GNUNullExpr(Ty, TokenLoc); 13643 } 13644 13645 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13646 bool Diagnose) { 13647 if (!getLangOpts().ObjC1) 13648 return false; 13649 13650 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13651 if (!PT) 13652 return false; 13653 13654 if (!PT->isObjCIdType()) { 13655 // Check if the destination is the 'NSString' interface. 13656 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13657 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13658 return false; 13659 } 13660 13661 // Ignore any parens, implicit casts (should only be 13662 // array-to-pointer decays), and not-so-opaque values. The last is 13663 // important for making this trigger for property assignments. 13664 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13665 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13666 if (OV->getSourceExpr()) 13667 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13668 13669 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13670 if (!SL || !SL->isAscii()) 13671 return false; 13672 if (Diagnose) { 13673 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13674 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13675 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13676 } 13677 return true; 13678 } 13679 13680 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13681 const Expr *SrcExpr) { 13682 if (!DstType->isFunctionPointerType() || 13683 !SrcExpr->getType()->isFunctionType()) 13684 return false; 13685 13686 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13687 if (!DRE) 13688 return false; 13689 13690 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13691 if (!FD) 13692 return false; 13693 13694 return !S.checkAddressOfFunctionIsAvailable(FD, 13695 /*Complain=*/true, 13696 SrcExpr->getBeginLoc()); 13697 } 13698 13699 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13700 SourceLocation Loc, 13701 QualType DstType, QualType SrcType, 13702 Expr *SrcExpr, AssignmentAction Action, 13703 bool *Complained) { 13704 if (Complained) 13705 *Complained = false; 13706 13707 // Decode the result (notice that AST's are still created for extensions). 13708 bool CheckInferredResultType = false; 13709 bool isInvalid = false; 13710 unsigned DiagKind = 0; 13711 FixItHint Hint; 13712 ConversionFixItGenerator ConvHints; 13713 bool MayHaveConvFixit = false; 13714 bool MayHaveFunctionDiff = false; 13715 const ObjCInterfaceDecl *IFace = nullptr; 13716 const ObjCProtocolDecl *PDecl = nullptr; 13717 13718 switch (ConvTy) { 13719 case Compatible: 13720 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13721 return false; 13722 13723 case PointerToInt: 13724 DiagKind = diag::ext_typecheck_convert_pointer_int; 13725 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13726 MayHaveConvFixit = true; 13727 break; 13728 case IntToPointer: 13729 DiagKind = diag::ext_typecheck_convert_int_pointer; 13730 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13731 MayHaveConvFixit = true; 13732 break; 13733 case IncompatiblePointer: 13734 if (Action == AA_Passing_CFAudited) 13735 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13736 else if (SrcType->isFunctionPointerType() && 13737 DstType->isFunctionPointerType()) 13738 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13739 else 13740 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13741 13742 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13743 SrcType->isObjCObjectPointerType(); 13744 if (Hint.isNull() && !CheckInferredResultType) { 13745 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13746 } 13747 else if (CheckInferredResultType) { 13748 SrcType = SrcType.getUnqualifiedType(); 13749 DstType = DstType.getUnqualifiedType(); 13750 } 13751 MayHaveConvFixit = true; 13752 break; 13753 case IncompatiblePointerSign: 13754 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13755 break; 13756 case FunctionVoidPointer: 13757 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13758 break; 13759 case IncompatiblePointerDiscardsQualifiers: { 13760 // Perform array-to-pointer decay if necessary. 13761 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13762 13763 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13764 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13765 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13766 DiagKind = diag::err_typecheck_incompatible_address_space; 13767 break; 13768 13769 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13770 DiagKind = diag::err_typecheck_incompatible_ownership; 13771 break; 13772 } 13773 13774 llvm_unreachable("unknown error case for discarding qualifiers!"); 13775 // fallthrough 13776 } 13777 case CompatiblePointerDiscardsQualifiers: 13778 // If the qualifiers lost were because we were applying the 13779 // (deprecated) C++ conversion from a string literal to a char* 13780 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13781 // Ideally, this check would be performed in 13782 // checkPointerTypesForAssignment. However, that would require a 13783 // bit of refactoring (so that the second argument is an 13784 // expression, rather than a type), which should be done as part 13785 // of a larger effort to fix checkPointerTypesForAssignment for 13786 // C++ semantics. 13787 if (getLangOpts().CPlusPlus && 13788 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13789 return false; 13790 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13791 break; 13792 case IncompatibleNestedPointerQualifiers: 13793 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13794 break; 13795 case IntToBlockPointer: 13796 DiagKind = diag::err_int_to_block_pointer; 13797 break; 13798 case IncompatibleBlockPointer: 13799 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13800 break; 13801 case IncompatibleObjCQualifiedId: { 13802 if (SrcType->isObjCQualifiedIdType()) { 13803 const ObjCObjectPointerType *srcOPT = 13804 SrcType->getAs<ObjCObjectPointerType>(); 13805 for (auto *srcProto : srcOPT->quals()) { 13806 PDecl = srcProto; 13807 break; 13808 } 13809 if (const ObjCInterfaceType *IFaceT = 13810 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13811 IFace = IFaceT->getDecl(); 13812 } 13813 else if (DstType->isObjCQualifiedIdType()) { 13814 const ObjCObjectPointerType *dstOPT = 13815 DstType->getAs<ObjCObjectPointerType>(); 13816 for (auto *dstProto : dstOPT->quals()) { 13817 PDecl = dstProto; 13818 break; 13819 } 13820 if (const ObjCInterfaceType *IFaceT = 13821 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13822 IFace = IFaceT->getDecl(); 13823 } 13824 DiagKind = diag::warn_incompatible_qualified_id; 13825 break; 13826 } 13827 case IncompatibleVectors: 13828 DiagKind = diag::warn_incompatible_vectors; 13829 break; 13830 case IncompatibleObjCWeakRef: 13831 DiagKind = diag::err_arc_weak_unavailable_assign; 13832 break; 13833 case Incompatible: 13834 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13835 if (Complained) 13836 *Complained = true; 13837 return true; 13838 } 13839 13840 DiagKind = diag::err_typecheck_convert_incompatible; 13841 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13842 MayHaveConvFixit = true; 13843 isInvalid = true; 13844 MayHaveFunctionDiff = true; 13845 break; 13846 } 13847 13848 QualType FirstType, SecondType; 13849 switch (Action) { 13850 case AA_Assigning: 13851 case AA_Initializing: 13852 // The destination type comes first. 13853 FirstType = DstType; 13854 SecondType = SrcType; 13855 break; 13856 13857 case AA_Returning: 13858 case AA_Passing: 13859 case AA_Passing_CFAudited: 13860 case AA_Converting: 13861 case AA_Sending: 13862 case AA_Casting: 13863 // The source type comes first. 13864 FirstType = SrcType; 13865 SecondType = DstType; 13866 break; 13867 } 13868 13869 PartialDiagnostic FDiag = PDiag(DiagKind); 13870 if (Action == AA_Passing_CFAudited) 13871 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13872 else 13873 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13874 13875 // If we can fix the conversion, suggest the FixIts. 13876 assert(ConvHints.isNull() || Hint.isNull()); 13877 if (!ConvHints.isNull()) { 13878 for (FixItHint &H : ConvHints.Hints) 13879 FDiag << H; 13880 } else { 13881 FDiag << Hint; 13882 } 13883 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13884 13885 if (MayHaveFunctionDiff) 13886 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13887 13888 Diag(Loc, FDiag); 13889 if (DiagKind == diag::warn_incompatible_qualified_id && 13890 PDecl && IFace && !IFace->hasDefinition()) 13891 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13892 << IFace << PDecl; 13893 13894 if (SecondType == Context.OverloadTy) 13895 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13896 FirstType, /*TakingAddress=*/true); 13897 13898 if (CheckInferredResultType) 13899 EmitRelatedResultTypeNote(SrcExpr); 13900 13901 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13902 EmitRelatedResultTypeNoteForReturn(DstType); 13903 13904 if (Complained) 13905 *Complained = true; 13906 return isInvalid; 13907 } 13908 13909 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13910 llvm::APSInt *Result) { 13911 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13912 public: 13913 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13914 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13915 } 13916 } Diagnoser; 13917 13918 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13919 } 13920 13921 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13922 llvm::APSInt *Result, 13923 unsigned DiagID, 13924 bool AllowFold) { 13925 class IDDiagnoser : public VerifyICEDiagnoser { 13926 unsigned DiagID; 13927 13928 public: 13929 IDDiagnoser(unsigned DiagID) 13930 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13931 13932 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13933 S.Diag(Loc, DiagID) << SR; 13934 } 13935 } Diagnoser(DiagID); 13936 13937 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13938 } 13939 13940 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13941 SourceRange SR) { 13942 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13943 } 13944 13945 ExprResult 13946 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13947 VerifyICEDiagnoser &Diagnoser, 13948 bool AllowFold) { 13949 SourceLocation DiagLoc = E->getBeginLoc(); 13950 13951 if (getLangOpts().CPlusPlus11) { 13952 // C++11 [expr.const]p5: 13953 // If an expression of literal class type is used in a context where an 13954 // integral constant expression is required, then that class type shall 13955 // have a single non-explicit conversion function to an integral or 13956 // unscoped enumeration type 13957 ExprResult Converted; 13958 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13959 public: 13960 CXX11ConvertDiagnoser(bool Silent) 13961 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13962 Silent, true) {} 13963 13964 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13965 QualType T) override { 13966 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13967 } 13968 13969 SemaDiagnosticBuilder diagnoseIncomplete( 13970 Sema &S, SourceLocation Loc, QualType T) override { 13971 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13972 } 13973 13974 SemaDiagnosticBuilder diagnoseExplicitConv( 13975 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13976 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13977 } 13978 13979 SemaDiagnosticBuilder noteExplicitConv( 13980 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13981 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13982 << ConvTy->isEnumeralType() << ConvTy; 13983 } 13984 13985 SemaDiagnosticBuilder diagnoseAmbiguous( 13986 Sema &S, SourceLocation Loc, QualType T) override { 13987 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13988 } 13989 13990 SemaDiagnosticBuilder noteAmbiguous( 13991 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13992 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13993 << ConvTy->isEnumeralType() << ConvTy; 13994 } 13995 13996 SemaDiagnosticBuilder diagnoseConversion( 13997 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13998 llvm_unreachable("conversion functions are permitted"); 13999 } 14000 } ConvertDiagnoser(Diagnoser.Suppress); 14001 14002 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14003 ConvertDiagnoser); 14004 if (Converted.isInvalid()) 14005 return Converted; 14006 E = Converted.get(); 14007 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14008 return ExprError(); 14009 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14010 // An ICE must be of integral or unscoped enumeration type. 14011 if (!Diagnoser.Suppress) 14012 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14013 return ExprError(); 14014 } 14015 14016 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14017 // in the non-ICE case. 14018 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14019 if (Result) 14020 *Result = E->EvaluateKnownConstInt(Context); 14021 return E; 14022 } 14023 14024 Expr::EvalResult EvalResult; 14025 SmallVector<PartialDiagnosticAt, 8> Notes; 14026 EvalResult.Diag = &Notes; 14027 14028 // Try to evaluate the expression, and produce diagnostics explaining why it's 14029 // not a constant expression as a side-effect. 14030 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14031 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14032 14033 // In C++11, we can rely on diagnostics being produced for any expression 14034 // which is not a constant expression. If no diagnostics were produced, then 14035 // this is a constant expression. 14036 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14037 if (Result) 14038 *Result = EvalResult.Val.getInt(); 14039 return E; 14040 } 14041 14042 // If our only note is the usual "invalid subexpression" note, just point 14043 // the caret at its location rather than producing an essentially 14044 // redundant note. 14045 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14046 diag::note_invalid_subexpr_in_const_expr) { 14047 DiagLoc = Notes[0].first; 14048 Notes.clear(); 14049 } 14050 14051 if (!Folded || !AllowFold) { 14052 if (!Diagnoser.Suppress) { 14053 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14054 for (const PartialDiagnosticAt &Note : Notes) 14055 Diag(Note.first, Note.second); 14056 } 14057 14058 return ExprError(); 14059 } 14060 14061 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14062 for (const PartialDiagnosticAt &Note : Notes) 14063 Diag(Note.first, Note.second); 14064 14065 if (Result) 14066 *Result = EvalResult.Val.getInt(); 14067 return E; 14068 } 14069 14070 namespace { 14071 // Handle the case where we conclude a expression which we speculatively 14072 // considered to be unevaluated is actually evaluated. 14073 class TransformToPE : public TreeTransform<TransformToPE> { 14074 typedef TreeTransform<TransformToPE> BaseTransform; 14075 14076 public: 14077 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14078 14079 // Make sure we redo semantic analysis 14080 bool AlwaysRebuild() { return true; } 14081 14082 // Make sure we handle LabelStmts correctly. 14083 // FIXME: This does the right thing, but maybe we need a more general 14084 // fix to TreeTransform? 14085 StmtResult TransformLabelStmt(LabelStmt *S) { 14086 S->getDecl()->setStmt(nullptr); 14087 return BaseTransform::TransformLabelStmt(S); 14088 } 14089 14090 // We need to special-case DeclRefExprs referring to FieldDecls which 14091 // are not part of a member pointer formation; normal TreeTransforming 14092 // doesn't catch this case because of the way we represent them in the AST. 14093 // FIXME: This is a bit ugly; is it really the best way to handle this 14094 // case? 14095 // 14096 // Error on DeclRefExprs referring to FieldDecls. 14097 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14098 if (isa<FieldDecl>(E->getDecl()) && 14099 !SemaRef.isUnevaluatedContext()) 14100 return SemaRef.Diag(E->getLocation(), 14101 diag::err_invalid_non_static_member_use) 14102 << E->getDecl() << E->getSourceRange(); 14103 14104 return BaseTransform::TransformDeclRefExpr(E); 14105 } 14106 14107 // Exception: filter out member pointer formation 14108 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14109 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14110 return E; 14111 14112 return BaseTransform::TransformUnaryOperator(E); 14113 } 14114 14115 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14116 // Lambdas never need to be transformed. 14117 return E; 14118 } 14119 }; 14120 } 14121 14122 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14123 assert(isUnevaluatedContext() && 14124 "Should only transform unevaluated expressions"); 14125 ExprEvalContexts.back().Context = 14126 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14127 if (isUnevaluatedContext()) 14128 return E; 14129 return TransformToPE(*this).TransformExpr(E); 14130 } 14131 14132 void 14133 Sema::PushExpressionEvaluationContext( 14134 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14135 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14136 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14137 LambdaContextDecl, ExprContext); 14138 Cleanup.reset(); 14139 if (!MaybeODRUseExprs.empty()) 14140 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14141 } 14142 14143 void 14144 Sema::PushExpressionEvaluationContext( 14145 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14146 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14147 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14148 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14149 } 14150 14151 void Sema::PopExpressionEvaluationContext() { 14152 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14153 unsigned NumTypos = Rec.NumTypos; 14154 14155 if (!Rec.Lambdas.empty()) { 14156 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14157 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14158 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14159 unsigned D; 14160 if (Rec.isUnevaluated()) { 14161 // C++11 [expr.prim.lambda]p2: 14162 // A lambda-expression shall not appear in an unevaluated operand 14163 // (Clause 5). 14164 D = diag::err_lambda_unevaluated_operand; 14165 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14166 // C++1y [expr.const]p2: 14167 // A conditional-expression e is a core constant expression unless the 14168 // evaluation of e, following the rules of the abstract machine, would 14169 // evaluate [...] a lambda-expression. 14170 D = diag::err_lambda_in_constant_expression; 14171 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14172 // C++17 [expr.prim.lamda]p2: 14173 // A lambda-expression shall not appear [...] in a template-argument. 14174 D = diag::err_lambda_in_invalid_context; 14175 } else 14176 llvm_unreachable("Couldn't infer lambda error message."); 14177 14178 for (const auto *L : Rec.Lambdas) 14179 Diag(L->getBeginLoc(), D); 14180 } else { 14181 // Mark the capture expressions odr-used. This was deferred 14182 // during lambda expression creation. 14183 for (auto *Lambda : Rec.Lambdas) { 14184 for (auto *C : Lambda->capture_inits()) 14185 MarkDeclarationsReferencedInExpr(C); 14186 } 14187 } 14188 } 14189 14190 // When are coming out of an unevaluated context, clear out any 14191 // temporaries that we may have created as part of the evaluation of 14192 // the expression in that context: they aren't relevant because they 14193 // will never be constructed. 14194 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14195 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14196 ExprCleanupObjects.end()); 14197 Cleanup = Rec.ParentCleanup; 14198 CleanupVarDeclMarking(); 14199 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14200 // Otherwise, merge the contexts together. 14201 } else { 14202 Cleanup.mergeFrom(Rec.ParentCleanup); 14203 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14204 Rec.SavedMaybeODRUseExprs.end()); 14205 } 14206 14207 // Pop the current expression evaluation context off the stack. 14208 ExprEvalContexts.pop_back(); 14209 14210 if (!ExprEvalContexts.empty()) 14211 ExprEvalContexts.back().NumTypos += NumTypos; 14212 else 14213 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14214 "last ExpressionEvaluationContextRecord"); 14215 } 14216 14217 void Sema::DiscardCleanupsInEvaluationContext() { 14218 ExprCleanupObjects.erase( 14219 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14220 ExprCleanupObjects.end()); 14221 Cleanup.reset(); 14222 MaybeODRUseExprs.clear(); 14223 } 14224 14225 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14226 if (!E->getType()->isVariablyModifiedType()) 14227 return E; 14228 return TransformToPotentiallyEvaluated(E); 14229 } 14230 14231 /// Are we within a context in which some evaluation could be performed (be it 14232 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14233 /// captured by C++'s idea of an "unevaluated context". 14234 static bool isEvaluatableContext(Sema &SemaRef) { 14235 switch (SemaRef.ExprEvalContexts.back().Context) { 14236 case Sema::ExpressionEvaluationContext::Unevaluated: 14237 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14238 // Expressions in this context are never evaluated. 14239 return false; 14240 14241 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14242 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14243 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14244 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14245 // Expressions in this context could be evaluated. 14246 return true; 14247 14248 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14249 // Referenced declarations will only be used if the construct in the 14250 // containing expression is used, at which point we'll be given another 14251 // turn to mark them. 14252 return false; 14253 } 14254 llvm_unreachable("Invalid context"); 14255 } 14256 14257 /// Are we within a context in which references to resolved functions or to 14258 /// variables result in odr-use? 14259 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14260 // An expression in a template is not really an expression until it's been 14261 // instantiated, so it doesn't trigger odr-use. 14262 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14263 return false; 14264 14265 switch (SemaRef.ExprEvalContexts.back().Context) { 14266 case Sema::ExpressionEvaluationContext::Unevaluated: 14267 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14268 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14269 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14270 return false; 14271 14272 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14273 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14274 return true; 14275 14276 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14277 return false; 14278 } 14279 llvm_unreachable("Invalid context"); 14280 } 14281 14282 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14284 return Func->isConstexpr() && 14285 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14286 } 14287 14288 /// Mark a function referenced, and check whether it is odr-used 14289 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14290 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14291 bool MightBeOdrUse) { 14292 assert(Func && "No function?"); 14293 14294 Func->setReferenced(); 14295 14296 // C++11 [basic.def.odr]p3: 14297 // A function whose name appears as a potentially-evaluated expression is 14298 // odr-used if it is the unique lookup result or the selected member of a 14299 // set of overloaded functions [...]. 14300 // 14301 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14302 // can just check that here. 14303 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14304 14305 // Determine whether we require a function definition to exist, per 14306 // C++11 [temp.inst]p3: 14307 // Unless a function template specialization has been explicitly 14308 // instantiated or explicitly specialized, the function template 14309 // specialization is implicitly instantiated when the specialization is 14310 // referenced in a context that requires a function definition to exist. 14311 // 14312 // That is either when this is an odr-use, or when a usage of a constexpr 14313 // function occurs within an evaluatable context. 14314 bool NeedDefinition = 14315 OdrUse || (isEvaluatableContext(*this) && 14316 isImplicitlyDefinableConstexprFunction(Func)); 14317 14318 // C++14 [temp.expl.spec]p6: 14319 // If a template [...] is explicitly specialized then that specialization 14320 // shall be declared before the first use of that specialization that would 14321 // cause an implicit instantiation to take place, in every translation unit 14322 // in which such a use occurs 14323 if (NeedDefinition && 14324 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14325 Func->getMemberSpecializationInfo())) 14326 checkSpecializationVisibility(Loc, Func); 14327 14328 // C++14 [except.spec]p17: 14329 // An exception-specification is considered to be needed when: 14330 // - the function is odr-used or, if it appears in an unevaluated operand, 14331 // would be odr-used if the expression were potentially-evaluated; 14332 // 14333 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14334 // function is a pure virtual function we're calling, and in that case the 14335 // function was selected by overload resolution and we need to resolve its 14336 // exception specification for a different reason. 14337 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14338 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14339 ResolveExceptionSpec(Loc, FPT); 14340 14341 // If we don't need to mark the function as used, and we don't need to 14342 // try to provide a definition, there's nothing more to do. 14343 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14344 (!NeedDefinition || Func->getBody())) 14345 return; 14346 14347 // Note that this declaration has been used. 14348 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14349 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14350 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14351 if (Constructor->isDefaultConstructor()) { 14352 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14353 return; 14354 DefineImplicitDefaultConstructor(Loc, Constructor); 14355 } else if (Constructor->isCopyConstructor()) { 14356 DefineImplicitCopyConstructor(Loc, Constructor); 14357 } else if (Constructor->isMoveConstructor()) { 14358 DefineImplicitMoveConstructor(Loc, Constructor); 14359 } 14360 } else if (Constructor->getInheritedConstructor()) { 14361 DefineInheritingConstructor(Loc, Constructor); 14362 } 14363 } else if (CXXDestructorDecl *Destructor = 14364 dyn_cast<CXXDestructorDecl>(Func)) { 14365 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14366 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14367 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14368 return; 14369 DefineImplicitDestructor(Loc, Destructor); 14370 } 14371 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14372 MarkVTableUsed(Loc, Destructor->getParent()); 14373 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14374 if (MethodDecl->isOverloadedOperator() && 14375 MethodDecl->getOverloadedOperator() == OO_Equal) { 14376 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14377 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14378 if (MethodDecl->isCopyAssignmentOperator()) 14379 DefineImplicitCopyAssignment(Loc, MethodDecl); 14380 else if (MethodDecl->isMoveAssignmentOperator()) 14381 DefineImplicitMoveAssignment(Loc, MethodDecl); 14382 } 14383 } else if (isa<CXXConversionDecl>(MethodDecl) && 14384 MethodDecl->getParent()->isLambda()) { 14385 CXXConversionDecl *Conversion = 14386 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14387 if (Conversion->isLambdaToBlockPointerConversion()) 14388 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14389 else 14390 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14391 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14392 MarkVTableUsed(Loc, MethodDecl->getParent()); 14393 } 14394 14395 // Recursive functions should be marked when used from another function. 14396 // FIXME: Is this really right? 14397 if (CurContext == Func) return; 14398 14399 // Implicit instantiation of function templates and member functions of 14400 // class templates. 14401 if (Func->isImplicitlyInstantiable()) { 14402 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14403 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14404 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14405 if (FirstInstantiation) { 14406 PointOfInstantiation = Loc; 14407 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14408 } else if (TSK != TSK_ImplicitInstantiation) { 14409 // Use the point of use as the point of instantiation, instead of the 14410 // point of explicit instantiation (which we track as the actual point of 14411 // instantiation). This gives better backtraces in diagnostics. 14412 PointOfInstantiation = Loc; 14413 } 14414 14415 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14416 Func->isConstexpr()) { 14417 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14418 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14419 CodeSynthesisContexts.size()) 14420 PendingLocalImplicitInstantiations.push_back( 14421 std::make_pair(Func, PointOfInstantiation)); 14422 else if (Func->isConstexpr()) 14423 // Do not defer instantiations of constexpr functions, to avoid the 14424 // expression evaluator needing to call back into Sema if it sees a 14425 // call to such a function. 14426 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14427 else { 14428 Func->setInstantiationIsPending(true); 14429 PendingInstantiations.push_back(std::make_pair(Func, 14430 PointOfInstantiation)); 14431 // Notify the consumer that a function was implicitly instantiated. 14432 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14433 } 14434 } 14435 } else { 14436 // Walk redefinitions, as some of them may be instantiable. 14437 for (auto i : Func->redecls()) { 14438 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14439 MarkFunctionReferenced(Loc, i, OdrUse); 14440 } 14441 } 14442 14443 if (!OdrUse) return; 14444 14445 // Keep track of used but undefined functions. 14446 if (!Func->isDefined()) { 14447 if (mightHaveNonExternalLinkage(Func)) 14448 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14449 else if (Func->getMostRecentDecl()->isInlined() && 14450 !LangOpts.GNUInline && 14451 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14452 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14453 else if (isExternalWithNoLinkageType(Func)) 14454 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14455 } 14456 14457 Func->markUsed(Context); 14458 } 14459 14460 static void 14461 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14462 ValueDecl *var, DeclContext *DC) { 14463 DeclContext *VarDC = var->getDeclContext(); 14464 14465 // If the parameter still belongs to the translation unit, then 14466 // we're actually just using one parameter in the declaration of 14467 // the next. 14468 if (isa<ParmVarDecl>(var) && 14469 isa<TranslationUnitDecl>(VarDC)) 14470 return; 14471 14472 // For C code, don't diagnose about capture if we're not actually in code 14473 // right now; it's impossible to write a non-constant expression outside of 14474 // function context, so we'll get other (more useful) diagnostics later. 14475 // 14476 // For C++, things get a bit more nasty... it would be nice to suppress this 14477 // diagnostic for certain cases like using a local variable in an array bound 14478 // for a member of a local class, but the correct predicate is not obvious. 14479 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14480 return; 14481 14482 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14483 unsigned ContextKind = 3; // unknown 14484 if (isa<CXXMethodDecl>(VarDC) && 14485 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14486 ContextKind = 2; 14487 } else if (isa<FunctionDecl>(VarDC)) { 14488 ContextKind = 0; 14489 } else if (isa<BlockDecl>(VarDC)) { 14490 ContextKind = 1; 14491 } 14492 14493 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14494 << var << ValueKind << ContextKind << VarDC; 14495 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14496 << var; 14497 14498 // FIXME: Add additional diagnostic info about class etc. which prevents 14499 // capture. 14500 } 14501 14502 14503 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14504 bool &SubCapturesAreNested, 14505 QualType &CaptureType, 14506 QualType &DeclRefType) { 14507 // Check whether we've already captured it. 14508 if (CSI->CaptureMap.count(Var)) { 14509 // If we found a capture, any subcaptures are nested. 14510 SubCapturesAreNested = true; 14511 14512 // Retrieve the capture type for this variable. 14513 CaptureType = CSI->getCapture(Var).getCaptureType(); 14514 14515 // Compute the type of an expression that refers to this variable. 14516 DeclRefType = CaptureType.getNonReferenceType(); 14517 14518 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14519 // are mutable in the sense that user can change their value - they are 14520 // private instances of the captured declarations. 14521 const Capture &Cap = CSI->getCapture(Var); 14522 if (Cap.isCopyCapture() && 14523 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14524 !(isa<CapturedRegionScopeInfo>(CSI) && 14525 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14526 DeclRefType.addConst(); 14527 return true; 14528 } 14529 return false; 14530 } 14531 14532 // Only block literals, captured statements, and lambda expressions can 14533 // capture; other scopes don't work. 14534 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14535 SourceLocation Loc, 14536 const bool Diagnose, Sema &S) { 14537 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14538 return getLambdaAwareParentOfDeclContext(DC); 14539 else if (Var->hasLocalStorage()) { 14540 if (Diagnose) 14541 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14542 } 14543 return nullptr; 14544 } 14545 14546 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14547 // certain types of variables (unnamed, variably modified types etc.) 14548 // so check for eligibility. 14549 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14550 SourceLocation Loc, 14551 const bool Diagnose, Sema &S) { 14552 14553 bool IsBlock = isa<BlockScopeInfo>(CSI); 14554 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14555 14556 // Lambdas are not allowed to capture unnamed variables 14557 // (e.g. anonymous unions). 14558 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14559 // assuming that's the intent. 14560 if (IsLambda && !Var->getDeclName()) { 14561 if (Diagnose) { 14562 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14563 S.Diag(Var->getLocation(), diag::note_declared_at); 14564 } 14565 return false; 14566 } 14567 14568 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14569 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14570 if (Diagnose) { 14571 S.Diag(Loc, diag::err_ref_vm_type); 14572 S.Diag(Var->getLocation(), diag::note_previous_decl) 14573 << Var->getDeclName(); 14574 } 14575 return false; 14576 } 14577 // Prohibit structs with flexible array members too. 14578 // We cannot capture what is in the tail end of the struct. 14579 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14580 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14581 if (Diagnose) { 14582 if (IsBlock) 14583 S.Diag(Loc, diag::err_ref_flexarray_type); 14584 else 14585 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14586 << Var->getDeclName(); 14587 S.Diag(Var->getLocation(), diag::note_previous_decl) 14588 << Var->getDeclName(); 14589 } 14590 return false; 14591 } 14592 } 14593 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14594 // Lambdas and captured statements are not allowed to capture __block 14595 // variables; they don't support the expected semantics. 14596 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14597 if (Diagnose) { 14598 S.Diag(Loc, diag::err_capture_block_variable) 14599 << Var->getDeclName() << !IsLambda; 14600 S.Diag(Var->getLocation(), diag::note_previous_decl) 14601 << Var->getDeclName(); 14602 } 14603 return false; 14604 } 14605 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14606 if (S.getLangOpts().OpenCL && IsBlock && 14607 Var->getType()->isBlockPointerType()) { 14608 if (Diagnose) 14609 S.Diag(Loc, diag::err_opencl_block_ref_block); 14610 return false; 14611 } 14612 14613 return true; 14614 } 14615 14616 // Returns true if the capture by block was successful. 14617 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14618 SourceLocation Loc, 14619 const bool BuildAndDiagnose, 14620 QualType &CaptureType, 14621 QualType &DeclRefType, 14622 const bool Nested, 14623 Sema &S) { 14624 Expr *CopyExpr = nullptr; 14625 bool ByRef = false; 14626 14627 // Blocks are not allowed to capture arrays. 14628 if (CaptureType->isArrayType()) { 14629 if (BuildAndDiagnose) { 14630 S.Diag(Loc, diag::err_ref_array_type); 14631 S.Diag(Var->getLocation(), diag::note_previous_decl) 14632 << Var->getDeclName(); 14633 } 14634 return false; 14635 } 14636 14637 // Forbid the block-capture of autoreleasing variables. 14638 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14639 if (BuildAndDiagnose) { 14640 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14641 << /*block*/ 0; 14642 S.Diag(Var->getLocation(), diag::note_previous_decl) 14643 << Var->getDeclName(); 14644 } 14645 return false; 14646 } 14647 14648 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14649 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14650 // This function finds out whether there is an AttributedType of kind 14651 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14652 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14653 // rather than being added implicitly by the compiler. 14654 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14655 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14656 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14657 return true; 14658 14659 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14660 Ty = AttrTy->getModifiedType(); 14661 } 14662 14663 return false; 14664 }; 14665 14666 QualType PointeeTy = PT->getPointeeType(); 14667 14668 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14669 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14670 !IsObjCOwnershipAttributedType(PointeeTy)) { 14671 if (BuildAndDiagnose) { 14672 SourceLocation VarLoc = Var->getLocation(); 14673 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14674 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14675 } 14676 } 14677 } 14678 14679 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14680 if (HasBlocksAttr || CaptureType->isReferenceType() || 14681 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14682 // Block capture by reference does not change the capture or 14683 // declaration reference types. 14684 ByRef = true; 14685 } else { 14686 // Block capture by copy introduces 'const'. 14687 CaptureType = CaptureType.getNonReferenceType().withConst(); 14688 DeclRefType = CaptureType; 14689 14690 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14691 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14692 // The capture logic needs the destructor, so make sure we mark it. 14693 // Usually this is unnecessary because most local variables have 14694 // their destructors marked at declaration time, but parameters are 14695 // an exception because it's technically only the call site that 14696 // actually requires the destructor. 14697 if (isa<ParmVarDecl>(Var)) 14698 S.FinalizeVarWithDestructor(Var, Record); 14699 14700 // Enter a new evaluation context to insulate the copy 14701 // full-expression. 14702 EnterExpressionEvaluationContext scope( 14703 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14704 14705 // According to the blocks spec, the capture of a variable from 14706 // the stack requires a const copy constructor. This is not true 14707 // of the copy/move done to move a __block variable to the heap. 14708 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14709 DeclRefType.withConst(), 14710 VK_LValue, Loc); 14711 14712 ExprResult Result 14713 = S.PerformCopyInitialization( 14714 InitializedEntity::InitializeBlock(Var->getLocation(), 14715 CaptureType, false), 14716 Loc, DeclRef); 14717 14718 // Build a full-expression copy expression if initialization 14719 // succeeded and used a non-trivial constructor. Recover from 14720 // errors by pretending that the copy isn't necessary. 14721 if (!Result.isInvalid() && 14722 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14723 ->isTrivial()) { 14724 Result = S.MaybeCreateExprWithCleanups(Result); 14725 CopyExpr = Result.get(); 14726 } 14727 } 14728 } 14729 } 14730 14731 // Actually capture the variable. 14732 if (BuildAndDiagnose) 14733 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14734 SourceLocation(), CaptureType, CopyExpr); 14735 14736 return true; 14737 14738 } 14739 14740 14741 /// Capture the given variable in the captured region. 14742 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14743 VarDecl *Var, 14744 SourceLocation Loc, 14745 const bool BuildAndDiagnose, 14746 QualType &CaptureType, 14747 QualType &DeclRefType, 14748 const bool RefersToCapturedVariable, 14749 Sema &S) { 14750 // By default, capture variables by reference. 14751 bool ByRef = true; 14752 // Using an LValue reference type is consistent with Lambdas (see below). 14753 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14754 if (S.isOpenMPCapturedDecl(Var)) { 14755 bool HasConst = DeclRefType.isConstQualified(); 14756 DeclRefType = DeclRefType.getUnqualifiedType(); 14757 // Don't lose diagnostics about assignments to const. 14758 if (HasConst) 14759 DeclRefType.addConst(); 14760 } 14761 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14762 } 14763 14764 if (ByRef) 14765 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14766 else 14767 CaptureType = DeclRefType; 14768 14769 Expr *CopyExpr = nullptr; 14770 if (BuildAndDiagnose) { 14771 // The current implementation assumes that all variables are captured 14772 // by references. Since there is no capture by copy, no expression 14773 // evaluation will be needed. 14774 RecordDecl *RD = RSI->TheRecordDecl; 14775 14776 FieldDecl *Field 14777 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14778 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14779 nullptr, false, ICIS_NoInit); 14780 Field->setImplicit(true); 14781 Field->setAccess(AS_private); 14782 RD->addDecl(Field); 14783 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14784 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14785 14786 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14787 DeclRefType, VK_LValue, Loc); 14788 Var->setReferenced(true); 14789 Var->markUsed(S.Context); 14790 } 14791 14792 // Actually capture the variable. 14793 if (BuildAndDiagnose) 14794 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14795 SourceLocation(), CaptureType, CopyExpr); 14796 14797 14798 return true; 14799 } 14800 14801 /// Create a field within the lambda class for the variable 14802 /// being captured. 14803 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14804 QualType FieldType, QualType DeclRefType, 14805 SourceLocation Loc, 14806 bool RefersToCapturedVariable) { 14807 CXXRecordDecl *Lambda = LSI->Lambda; 14808 14809 // Build the non-static data member. 14810 FieldDecl *Field 14811 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14812 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14813 nullptr, false, ICIS_NoInit); 14814 Field->setImplicit(true); 14815 Field->setAccess(AS_private); 14816 Lambda->addDecl(Field); 14817 } 14818 14819 /// Capture the given variable in the lambda. 14820 static bool captureInLambda(LambdaScopeInfo *LSI, 14821 VarDecl *Var, 14822 SourceLocation Loc, 14823 const bool BuildAndDiagnose, 14824 QualType &CaptureType, 14825 QualType &DeclRefType, 14826 const bool RefersToCapturedVariable, 14827 const Sema::TryCaptureKind Kind, 14828 SourceLocation EllipsisLoc, 14829 const bool IsTopScope, 14830 Sema &S) { 14831 14832 // Determine whether we are capturing by reference or by value. 14833 bool ByRef = false; 14834 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14835 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14836 } else { 14837 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14838 } 14839 14840 // Compute the type of the field that will capture this variable. 14841 if (ByRef) { 14842 // C++11 [expr.prim.lambda]p15: 14843 // An entity is captured by reference if it is implicitly or 14844 // explicitly captured but not captured by copy. It is 14845 // unspecified whether additional unnamed non-static data 14846 // members are declared in the closure type for entities 14847 // captured by reference. 14848 // 14849 // FIXME: It is not clear whether we want to build an lvalue reference 14850 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14851 // to do the former, while EDG does the latter. Core issue 1249 will 14852 // clarify, but for now we follow GCC because it's a more permissive and 14853 // easily defensible position. 14854 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14855 } else { 14856 // C++11 [expr.prim.lambda]p14: 14857 // For each entity captured by copy, an unnamed non-static 14858 // data member is declared in the closure type. The 14859 // declaration order of these members is unspecified. The type 14860 // of such a data member is the type of the corresponding 14861 // captured entity if the entity is not a reference to an 14862 // object, or the referenced type otherwise. [Note: If the 14863 // captured entity is a reference to a function, the 14864 // corresponding data member is also a reference to a 14865 // function. - end note ] 14866 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14867 if (!RefType->getPointeeType()->isFunctionType()) 14868 CaptureType = RefType->getPointeeType(); 14869 } 14870 14871 // Forbid the lambda copy-capture of autoreleasing variables. 14872 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14873 if (BuildAndDiagnose) { 14874 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14875 S.Diag(Var->getLocation(), diag::note_previous_decl) 14876 << Var->getDeclName(); 14877 } 14878 return false; 14879 } 14880 14881 // Make sure that by-copy captures are of a complete and non-abstract type. 14882 if (BuildAndDiagnose) { 14883 if (!CaptureType->isDependentType() && 14884 S.RequireCompleteType(Loc, CaptureType, 14885 diag::err_capture_of_incomplete_type, 14886 Var->getDeclName())) 14887 return false; 14888 14889 if (S.RequireNonAbstractType(Loc, CaptureType, 14890 diag::err_capture_of_abstract_type)) 14891 return false; 14892 } 14893 } 14894 14895 // Capture this variable in the lambda. 14896 if (BuildAndDiagnose) 14897 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14898 RefersToCapturedVariable); 14899 14900 // Compute the type of a reference to this captured variable. 14901 if (ByRef) 14902 DeclRefType = CaptureType.getNonReferenceType(); 14903 else { 14904 // C++ [expr.prim.lambda]p5: 14905 // The closure type for a lambda-expression has a public inline 14906 // function call operator [...]. This function call operator is 14907 // declared const (9.3.1) if and only if the lambda-expression's 14908 // parameter-declaration-clause is not followed by mutable. 14909 DeclRefType = CaptureType.getNonReferenceType(); 14910 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14911 DeclRefType.addConst(); 14912 } 14913 14914 // Add the capture. 14915 if (BuildAndDiagnose) 14916 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14917 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14918 14919 return true; 14920 } 14921 14922 bool Sema::tryCaptureVariable( 14923 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14924 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14925 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14926 // An init-capture is notionally from the context surrounding its 14927 // declaration, but its parent DC is the lambda class. 14928 DeclContext *VarDC = Var->getDeclContext(); 14929 if (Var->isInitCapture()) 14930 VarDC = VarDC->getParent(); 14931 14932 DeclContext *DC = CurContext; 14933 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14934 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14935 // We need to sync up the Declaration Context with the 14936 // FunctionScopeIndexToStopAt 14937 if (FunctionScopeIndexToStopAt) { 14938 unsigned FSIndex = FunctionScopes.size() - 1; 14939 while (FSIndex != MaxFunctionScopesIndex) { 14940 DC = getLambdaAwareParentOfDeclContext(DC); 14941 --FSIndex; 14942 } 14943 } 14944 14945 14946 // If the variable is declared in the current context, there is no need to 14947 // capture it. 14948 if (VarDC == DC) return true; 14949 14950 // Capture global variables if it is required to use private copy of this 14951 // variable. 14952 bool IsGlobal = !Var->hasLocalStorage(); 14953 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 14954 return true; 14955 Var = Var->getCanonicalDecl(); 14956 14957 // Walk up the stack to determine whether we can capture the variable, 14958 // performing the "simple" checks that don't depend on type. We stop when 14959 // we've either hit the declared scope of the variable or find an existing 14960 // capture of that variable. We start from the innermost capturing-entity 14961 // (the DC) and ensure that all intervening capturing-entities 14962 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14963 // declcontext can either capture the variable or have already captured 14964 // the variable. 14965 CaptureType = Var->getType(); 14966 DeclRefType = CaptureType.getNonReferenceType(); 14967 bool Nested = false; 14968 bool Explicit = (Kind != TryCapture_Implicit); 14969 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14970 do { 14971 // Only block literals, captured statements, and lambda expressions can 14972 // capture; other scopes don't work. 14973 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14974 ExprLoc, 14975 BuildAndDiagnose, 14976 *this); 14977 // We need to check for the parent *first* because, if we *have* 14978 // private-captured a global variable, we need to recursively capture it in 14979 // intermediate blocks, lambdas, etc. 14980 if (!ParentDC) { 14981 if (IsGlobal) { 14982 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14983 break; 14984 } 14985 return true; 14986 } 14987 14988 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14989 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14990 14991 14992 // Check whether we've already captured it. 14993 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14994 DeclRefType)) { 14995 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14996 break; 14997 } 14998 // If we are instantiating a generic lambda call operator body, 14999 // we do not want to capture new variables. What was captured 15000 // during either a lambdas transformation or initial parsing 15001 // should be used. 15002 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15003 if (BuildAndDiagnose) { 15004 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15005 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15006 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15007 Diag(Var->getLocation(), diag::note_previous_decl) 15008 << Var->getDeclName(); 15009 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15010 } else 15011 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15012 } 15013 return true; 15014 } 15015 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15016 // certain types of variables (unnamed, variably modified types etc.) 15017 // so check for eligibility. 15018 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15019 return true; 15020 15021 // Try to capture variable-length arrays types. 15022 if (Var->getType()->isVariablyModifiedType()) { 15023 // We're going to walk down into the type and look for VLA 15024 // expressions. 15025 QualType QTy = Var->getType(); 15026 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15027 QTy = PVD->getOriginalType(); 15028 captureVariablyModifiedType(Context, QTy, CSI); 15029 } 15030 15031 if (getLangOpts().OpenMP) { 15032 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15033 // OpenMP private variables should not be captured in outer scope, so 15034 // just break here. Similarly, global variables that are captured in a 15035 // target region should not be captured outside the scope of the region. 15036 if (RSI->CapRegionKind == CR_OpenMP) { 15037 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15038 auto IsTargetCap = !IsOpenMPPrivateDecl && 15039 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15040 // When we detect target captures we are looking from inside the 15041 // target region, therefore we need to propagate the capture from the 15042 // enclosing region. Therefore, the capture is not initially nested. 15043 if (IsTargetCap) 15044 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15045 15046 if (IsTargetCap || IsOpenMPPrivateDecl) { 15047 Nested = !IsTargetCap; 15048 DeclRefType = DeclRefType.getUnqualifiedType(); 15049 CaptureType = Context.getLValueReferenceType(DeclRefType); 15050 break; 15051 } 15052 } 15053 } 15054 } 15055 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15056 // No capture-default, and this is not an explicit capture 15057 // so cannot capture this variable. 15058 if (BuildAndDiagnose) { 15059 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15060 Diag(Var->getLocation(), diag::note_previous_decl) 15061 << Var->getDeclName(); 15062 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15063 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15064 diag::note_lambda_decl); 15065 // FIXME: If we error out because an outer lambda can not implicitly 15066 // capture a variable that an inner lambda explicitly captures, we 15067 // should have the inner lambda do the explicit capture - because 15068 // it makes for cleaner diagnostics later. This would purely be done 15069 // so that the diagnostic does not misleadingly claim that a variable 15070 // can not be captured by a lambda implicitly even though it is captured 15071 // explicitly. Suggestion: 15072 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15073 // at the function head 15074 // - cache the StartingDeclContext - this must be a lambda 15075 // - captureInLambda in the innermost lambda the variable. 15076 } 15077 return true; 15078 } 15079 15080 FunctionScopesIndex--; 15081 DC = ParentDC; 15082 Explicit = false; 15083 } while (!VarDC->Equals(DC)); 15084 15085 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15086 // computing the type of the capture at each step, checking type-specific 15087 // requirements, and adding captures if requested. 15088 // If the variable had already been captured previously, we start capturing 15089 // at the lambda nested within that one. 15090 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15091 ++I) { 15092 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15093 15094 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15095 if (!captureInBlock(BSI, Var, ExprLoc, 15096 BuildAndDiagnose, CaptureType, 15097 DeclRefType, Nested, *this)) 15098 return true; 15099 Nested = true; 15100 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15101 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15102 BuildAndDiagnose, CaptureType, 15103 DeclRefType, Nested, *this)) 15104 return true; 15105 Nested = true; 15106 } else { 15107 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15108 if (!captureInLambda(LSI, Var, ExprLoc, 15109 BuildAndDiagnose, CaptureType, 15110 DeclRefType, Nested, Kind, EllipsisLoc, 15111 /*IsTopScope*/I == N - 1, *this)) 15112 return true; 15113 Nested = true; 15114 } 15115 } 15116 return false; 15117 } 15118 15119 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15120 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15121 QualType CaptureType; 15122 QualType DeclRefType; 15123 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15124 /*BuildAndDiagnose=*/true, CaptureType, 15125 DeclRefType, nullptr); 15126 } 15127 15128 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15129 QualType CaptureType; 15130 QualType DeclRefType; 15131 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15132 /*BuildAndDiagnose=*/false, CaptureType, 15133 DeclRefType, nullptr); 15134 } 15135 15136 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15137 QualType CaptureType; 15138 QualType DeclRefType; 15139 15140 // Determine whether we can capture this variable. 15141 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15142 /*BuildAndDiagnose=*/false, CaptureType, 15143 DeclRefType, nullptr)) 15144 return QualType(); 15145 15146 return DeclRefType; 15147 } 15148 15149 15150 15151 // If either the type of the variable or the initializer is dependent, 15152 // return false. Otherwise, determine whether the variable is a constant 15153 // expression. Use this if you need to know if a variable that might or 15154 // might not be dependent is truly a constant expression. 15155 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15156 ASTContext &Context) { 15157 15158 if (Var->getType()->isDependentType()) 15159 return false; 15160 const VarDecl *DefVD = nullptr; 15161 Var->getAnyInitializer(DefVD); 15162 if (!DefVD) 15163 return false; 15164 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15165 Expr *Init = cast<Expr>(Eval->Value); 15166 if (Init->isValueDependent()) 15167 return false; 15168 return IsVariableAConstantExpression(Var, Context); 15169 } 15170 15171 15172 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15173 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15174 // an object that satisfies the requirements for appearing in a 15175 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15176 // is immediately applied." This function handles the lvalue-to-rvalue 15177 // conversion part. 15178 MaybeODRUseExprs.erase(E->IgnoreParens()); 15179 15180 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15181 // to a variable that is a constant expression, and if so, identify it as 15182 // a reference to a variable that does not involve an odr-use of that 15183 // variable. 15184 if (LambdaScopeInfo *LSI = getCurLambda()) { 15185 Expr *SansParensExpr = E->IgnoreParens(); 15186 VarDecl *Var = nullptr; 15187 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15188 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15189 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15190 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15191 15192 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15193 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15194 } 15195 } 15196 15197 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15198 Res = CorrectDelayedTyposInExpr(Res); 15199 15200 if (!Res.isUsable()) 15201 return Res; 15202 15203 // If a constant-expression is a reference to a variable where we delay 15204 // deciding whether it is an odr-use, just assume we will apply the 15205 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15206 // (a non-type template argument), we have special handling anyway. 15207 UpdateMarkingForLValueToRValue(Res.get()); 15208 return Res; 15209 } 15210 15211 void Sema::CleanupVarDeclMarking() { 15212 for (Expr *E : MaybeODRUseExprs) { 15213 VarDecl *Var; 15214 SourceLocation Loc; 15215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15216 Var = cast<VarDecl>(DRE->getDecl()); 15217 Loc = DRE->getLocation(); 15218 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15219 Var = cast<VarDecl>(ME->getMemberDecl()); 15220 Loc = ME->getMemberLoc(); 15221 } else { 15222 llvm_unreachable("Unexpected expression"); 15223 } 15224 15225 MarkVarDeclODRUsed(Var, Loc, *this, 15226 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15227 } 15228 15229 MaybeODRUseExprs.clear(); 15230 } 15231 15232 15233 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15234 VarDecl *Var, Expr *E) { 15235 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15236 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15237 Var->setReferenced(); 15238 15239 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15240 15241 bool OdrUseContext = isOdrUseContext(SemaRef); 15242 bool UsableInConstantExpr = 15243 Var->isUsableInConstantExpressions(SemaRef.Context); 15244 bool NeedDefinition = 15245 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15246 15247 VarTemplateSpecializationDecl *VarSpec = 15248 dyn_cast<VarTemplateSpecializationDecl>(Var); 15249 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15250 "Can't instantiate a partial template specialization."); 15251 15252 // If this might be a member specialization of a static data member, check 15253 // the specialization is visible. We already did the checks for variable 15254 // template specializations when we created them. 15255 if (NeedDefinition && TSK != TSK_Undeclared && 15256 !isa<VarTemplateSpecializationDecl>(Var)) 15257 SemaRef.checkSpecializationVisibility(Loc, Var); 15258 15259 // Perform implicit instantiation of static data members, static data member 15260 // templates of class templates, and variable template specializations. Delay 15261 // instantiations of variable templates, except for those that could be used 15262 // in a constant expression. 15263 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15264 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15265 // instantiation declaration if a variable is usable in a constant 15266 // expression (among other cases). 15267 bool TryInstantiating = 15268 TSK == TSK_ImplicitInstantiation || 15269 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15270 15271 if (TryInstantiating) { 15272 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15273 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15274 if (FirstInstantiation) { 15275 PointOfInstantiation = Loc; 15276 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15277 } 15278 15279 bool InstantiationDependent = false; 15280 bool IsNonDependent = 15281 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15282 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15283 : true; 15284 15285 // Do not instantiate specializations that are still type-dependent. 15286 if (IsNonDependent) { 15287 if (UsableInConstantExpr) { 15288 // Do not defer instantiations of variables that could be used in a 15289 // constant expression. 15290 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15291 } else if (FirstInstantiation || 15292 isa<VarTemplateSpecializationDecl>(Var)) { 15293 // FIXME: For a specialization of a variable template, we don't 15294 // distinguish between "declaration and type implicitly instantiated" 15295 // and "implicit instantiation of definition requested", so we have 15296 // no direct way to avoid enqueueing the pending instantiation 15297 // multiple times. 15298 SemaRef.PendingInstantiations 15299 .push_back(std::make_pair(Var, PointOfInstantiation)); 15300 } 15301 } 15302 } 15303 } 15304 15305 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15306 // the requirements for appearing in a constant expression (5.19) and, if 15307 // it is an object, the lvalue-to-rvalue conversion (4.1) 15308 // is immediately applied." We check the first part here, and 15309 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15310 // Note that we use the C++11 definition everywhere because nothing in 15311 // C++03 depends on whether we get the C++03 version correct. The second 15312 // part does not apply to references, since they are not objects. 15313 if (OdrUseContext && E && 15314 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15315 // A reference initialized by a constant expression can never be 15316 // odr-used, so simply ignore it. 15317 if (!Var->getType()->isReferenceType() || 15318 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15319 SemaRef.MaybeODRUseExprs.insert(E); 15320 } else if (OdrUseContext) { 15321 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15322 /*MaxFunctionScopeIndex ptr*/ nullptr); 15323 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15324 // If this is a dependent context, we don't need to mark variables as 15325 // odr-used, but we may still need to track them for lambda capture. 15326 // FIXME: Do we also need to do this inside dependent typeid expressions 15327 // (which are modeled as unevaluated at this point)? 15328 const bool RefersToEnclosingScope = 15329 (SemaRef.CurContext != Var->getDeclContext() && 15330 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15331 if (RefersToEnclosingScope) { 15332 LambdaScopeInfo *const LSI = 15333 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15334 if (LSI && (!LSI->CallOperator || 15335 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15336 // If a variable could potentially be odr-used, defer marking it so 15337 // until we finish analyzing the full expression for any 15338 // lvalue-to-rvalue 15339 // or discarded value conversions that would obviate odr-use. 15340 // Add it to the list of potential captures that will be analyzed 15341 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15342 // unless the variable is a reference that was initialized by a constant 15343 // expression (this will never need to be captured or odr-used). 15344 assert(E && "Capture variable should be used in an expression."); 15345 if (!Var->getType()->isReferenceType() || 15346 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15347 LSI->addPotentialCapture(E->IgnoreParens()); 15348 } 15349 } 15350 } 15351 } 15352 15353 /// Mark a variable referenced, and check whether it is odr-used 15354 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15355 /// used directly for normal expressions referring to VarDecl. 15356 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15357 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15358 } 15359 15360 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15361 Decl *D, Expr *E, bool MightBeOdrUse) { 15362 if (SemaRef.isInOpenMPDeclareTargetContext()) 15363 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15364 15365 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15366 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15367 return; 15368 } 15369 15370 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15371 15372 // If this is a call to a method via a cast, also mark the method in the 15373 // derived class used in case codegen can devirtualize the call. 15374 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15375 if (!ME) 15376 return; 15377 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15378 if (!MD) 15379 return; 15380 // Only attempt to devirtualize if this is truly a virtual call. 15381 bool IsVirtualCall = MD->isVirtual() && 15382 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15383 if (!IsVirtualCall) 15384 return; 15385 15386 // If it's possible to devirtualize the call, mark the called function 15387 // referenced. 15388 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15389 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15390 if (DM) 15391 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15392 } 15393 15394 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15395 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15396 // TODO: update this with DR# once a defect report is filed. 15397 // C++11 defect. The address of a pure member should not be an ODR use, even 15398 // if it's a qualified reference. 15399 bool OdrUse = true; 15400 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15401 if (Method->isVirtual() && 15402 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15403 OdrUse = false; 15404 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15405 } 15406 15407 /// Perform reference-marking and odr-use handling for a MemberExpr. 15408 void Sema::MarkMemberReferenced(MemberExpr *E) { 15409 // C++11 [basic.def.odr]p2: 15410 // A non-overloaded function whose name appears as a potentially-evaluated 15411 // expression or a member of a set of candidate functions, if selected by 15412 // overload resolution when referred to from a potentially-evaluated 15413 // expression, is odr-used, unless it is a pure virtual function and its 15414 // name is not explicitly qualified. 15415 bool MightBeOdrUse = true; 15416 if (E->performsVirtualDispatch(getLangOpts())) { 15417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15418 if (Method->isPure()) 15419 MightBeOdrUse = false; 15420 } 15421 SourceLocation Loc = 15422 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15423 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15424 } 15425 15426 /// Perform marking for a reference to an arbitrary declaration. It 15427 /// marks the declaration referenced, and performs odr-use checking for 15428 /// functions and variables. This method should not be used when building a 15429 /// normal expression which refers to a variable. 15430 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15431 bool MightBeOdrUse) { 15432 if (MightBeOdrUse) { 15433 if (auto *VD = dyn_cast<VarDecl>(D)) { 15434 MarkVariableReferenced(Loc, VD); 15435 return; 15436 } 15437 } 15438 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15439 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15440 return; 15441 } 15442 D->setReferenced(); 15443 } 15444 15445 namespace { 15446 // Mark all of the declarations used by a type as referenced. 15447 // FIXME: Not fully implemented yet! We need to have a better understanding 15448 // of when we're entering a context we should not recurse into. 15449 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15450 // TreeTransforms rebuilding the type in a new context. Rather than 15451 // duplicating the TreeTransform logic, we should consider reusing it here. 15452 // Currently that causes problems when rebuilding LambdaExprs. 15453 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15454 Sema &S; 15455 SourceLocation Loc; 15456 15457 public: 15458 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15459 15460 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15461 15462 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15463 }; 15464 } 15465 15466 bool MarkReferencedDecls::TraverseTemplateArgument( 15467 const TemplateArgument &Arg) { 15468 { 15469 // A non-type template argument is a constant-evaluated context. 15470 EnterExpressionEvaluationContext Evaluated( 15471 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15472 if (Arg.getKind() == TemplateArgument::Declaration) { 15473 if (Decl *D = Arg.getAsDecl()) 15474 S.MarkAnyDeclReferenced(Loc, D, true); 15475 } else if (Arg.getKind() == TemplateArgument::Expression) { 15476 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15477 } 15478 } 15479 15480 return Inherited::TraverseTemplateArgument(Arg); 15481 } 15482 15483 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15484 MarkReferencedDecls Marker(*this, Loc); 15485 Marker.TraverseType(T); 15486 } 15487 15488 namespace { 15489 /// Helper class that marks all of the declarations referenced by 15490 /// potentially-evaluated subexpressions as "referenced". 15491 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15492 Sema &S; 15493 bool SkipLocalVariables; 15494 15495 public: 15496 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15497 15498 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15499 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15500 15501 void VisitDeclRefExpr(DeclRefExpr *E) { 15502 // If we were asked not to visit local variables, don't. 15503 if (SkipLocalVariables) { 15504 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15505 if (VD->hasLocalStorage()) 15506 return; 15507 } 15508 15509 S.MarkDeclRefReferenced(E); 15510 } 15511 15512 void VisitMemberExpr(MemberExpr *E) { 15513 S.MarkMemberReferenced(E); 15514 Inherited::VisitMemberExpr(E); 15515 } 15516 15517 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15518 S.MarkFunctionReferenced( 15519 E->getBeginLoc(), 15520 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15521 Visit(E->getSubExpr()); 15522 } 15523 15524 void VisitCXXNewExpr(CXXNewExpr *E) { 15525 if (E->getOperatorNew()) 15526 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15527 if (E->getOperatorDelete()) 15528 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15529 Inherited::VisitCXXNewExpr(E); 15530 } 15531 15532 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15533 if (E->getOperatorDelete()) 15534 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15535 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15536 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15537 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15538 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15539 } 15540 15541 Inherited::VisitCXXDeleteExpr(E); 15542 } 15543 15544 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15545 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15546 Inherited::VisitCXXConstructExpr(E); 15547 } 15548 15549 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15550 Visit(E->getExpr()); 15551 } 15552 15553 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15554 Inherited::VisitImplicitCastExpr(E); 15555 15556 if (E->getCastKind() == CK_LValueToRValue) 15557 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15558 } 15559 }; 15560 } 15561 15562 /// Mark any declarations that appear within this expression or any 15563 /// potentially-evaluated subexpressions as "referenced". 15564 /// 15565 /// \param SkipLocalVariables If true, don't mark local variables as 15566 /// 'referenced'. 15567 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15568 bool SkipLocalVariables) { 15569 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15570 } 15571 15572 /// Emit a diagnostic that describes an effect on the run-time behavior 15573 /// of the program being compiled. 15574 /// 15575 /// This routine emits the given diagnostic when the code currently being 15576 /// type-checked is "potentially evaluated", meaning that there is a 15577 /// possibility that the code will actually be executable. Code in sizeof() 15578 /// expressions, code used only during overload resolution, etc., are not 15579 /// potentially evaluated. This routine will suppress such diagnostics or, 15580 /// in the absolutely nutty case of potentially potentially evaluated 15581 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15582 /// later. 15583 /// 15584 /// This routine should be used for all diagnostics that describe the run-time 15585 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15586 /// Failure to do so will likely result in spurious diagnostics or failures 15587 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15588 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15589 const PartialDiagnostic &PD) { 15590 switch (ExprEvalContexts.back().Context) { 15591 case ExpressionEvaluationContext::Unevaluated: 15592 case ExpressionEvaluationContext::UnevaluatedList: 15593 case ExpressionEvaluationContext::UnevaluatedAbstract: 15594 case ExpressionEvaluationContext::DiscardedStatement: 15595 // The argument will never be evaluated, so don't complain. 15596 break; 15597 15598 case ExpressionEvaluationContext::ConstantEvaluated: 15599 // Relevant diagnostics should be produced by constant evaluation. 15600 break; 15601 15602 case ExpressionEvaluationContext::PotentiallyEvaluated: 15603 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15604 if (Statement && getCurFunctionOrMethodDecl()) { 15605 FunctionScopes.back()->PossiblyUnreachableDiags. 15606 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15607 return true; 15608 } 15609 15610 // The initializer of a constexpr variable or of the first declaration of a 15611 // static data member is not syntactically a constant evaluated constant, 15612 // but nonetheless is always required to be a constant expression, so we 15613 // can skip diagnosing. 15614 // FIXME: Using the mangling context here is a hack. 15615 if (auto *VD = dyn_cast_or_null<VarDecl>( 15616 ExprEvalContexts.back().ManglingContextDecl)) { 15617 if (VD->isConstexpr() || 15618 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15619 break; 15620 // FIXME: For any other kind of variable, we should build a CFG for its 15621 // initializer and check whether the context in question is reachable. 15622 } 15623 15624 Diag(Loc, PD); 15625 return true; 15626 } 15627 15628 return false; 15629 } 15630 15631 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15632 CallExpr *CE, FunctionDecl *FD) { 15633 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15634 return false; 15635 15636 // If we're inside a decltype's expression, don't check for a valid return 15637 // type or construct temporaries until we know whether this is the last call. 15638 if (ExprEvalContexts.back().ExprContext == 15639 ExpressionEvaluationContextRecord::EK_Decltype) { 15640 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15641 return false; 15642 } 15643 15644 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15645 FunctionDecl *FD; 15646 CallExpr *CE; 15647 15648 public: 15649 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15650 : FD(FD), CE(CE) { } 15651 15652 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15653 if (!FD) { 15654 S.Diag(Loc, diag::err_call_incomplete_return) 15655 << T << CE->getSourceRange(); 15656 return; 15657 } 15658 15659 S.Diag(Loc, diag::err_call_function_incomplete_return) 15660 << CE->getSourceRange() << FD->getDeclName() << T; 15661 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15662 << FD->getDeclName(); 15663 } 15664 } Diagnoser(FD, CE); 15665 15666 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15667 return true; 15668 15669 return false; 15670 } 15671 15672 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15673 // will prevent this condition from triggering, which is what we want. 15674 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15675 SourceLocation Loc; 15676 15677 unsigned diagnostic = diag::warn_condition_is_assignment; 15678 bool IsOrAssign = false; 15679 15680 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15681 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15682 return; 15683 15684 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15685 15686 // Greylist some idioms by putting them into a warning subcategory. 15687 if (ObjCMessageExpr *ME 15688 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15689 Selector Sel = ME->getSelector(); 15690 15691 // self = [<foo> init...] 15692 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15693 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15694 15695 // <foo> = [<bar> nextObject] 15696 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15697 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15698 } 15699 15700 Loc = Op->getOperatorLoc(); 15701 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15702 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15703 return; 15704 15705 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15706 Loc = Op->getOperatorLoc(); 15707 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15708 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15709 else { 15710 // Not an assignment. 15711 return; 15712 } 15713 15714 Diag(Loc, diagnostic) << E->getSourceRange(); 15715 15716 SourceLocation Open = E->getBeginLoc(); 15717 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15718 Diag(Loc, diag::note_condition_assign_silence) 15719 << FixItHint::CreateInsertion(Open, "(") 15720 << FixItHint::CreateInsertion(Close, ")"); 15721 15722 if (IsOrAssign) 15723 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15724 << FixItHint::CreateReplacement(Loc, "!="); 15725 else 15726 Diag(Loc, diag::note_condition_assign_to_comparison) 15727 << FixItHint::CreateReplacement(Loc, "=="); 15728 } 15729 15730 /// Redundant parentheses over an equality comparison can indicate 15731 /// that the user intended an assignment used as condition. 15732 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15733 // Don't warn if the parens came from a macro. 15734 SourceLocation parenLoc = ParenE->getBeginLoc(); 15735 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15736 return; 15737 // Don't warn for dependent expressions. 15738 if (ParenE->isTypeDependent()) 15739 return; 15740 15741 Expr *E = ParenE->IgnoreParens(); 15742 15743 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15744 if (opE->getOpcode() == BO_EQ && 15745 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15746 == Expr::MLV_Valid) { 15747 SourceLocation Loc = opE->getOperatorLoc(); 15748 15749 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15750 SourceRange ParenERange = ParenE->getSourceRange(); 15751 Diag(Loc, diag::note_equality_comparison_silence) 15752 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15753 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15754 Diag(Loc, diag::note_equality_comparison_to_assign) 15755 << FixItHint::CreateReplacement(Loc, "="); 15756 } 15757 } 15758 15759 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15760 bool IsConstexpr) { 15761 DiagnoseAssignmentAsCondition(E); 15762 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15763 DiagnoseEqualityWithExtraParens(parenE); 15764 15765 ExprResult result = CheckPlaceholderExpr(E); 15766 if (result.isInvalid()) return ExprError(); 15767 E = result.get(); 15768 15769 if (!E->isTypeDependent()) { 15770 if (getLangOpts().CPlusPlus) 15771 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15772 15773 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15774 if (ERes.isInvalid()) 15775 return ExprError(); 15776 E = ERes.get(); 15777 15778 QualType T = E->getType(); 15779 if (!T->isScalarType()) { // C99 6.8.4.1p1 15780 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15781 << T << E->getSourceRange(); 15782 return ExprError(); 15783 } 15784 CheckBoolLikeConversion(E, Loc); 15785 } 15786 15787 return E; 15788 } 15789 15790 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15791 Expr *SubExpr, ConditionKind CK) { 15792 // Empty conditions are valid in for-statements. 15793 if (!SubExpr) 15794 return ConditionResult(); 15795 15796 ExprResult Cond; 15797 switch (CK) { 15798 case ConditionKind::Boolean: 15799 Cond = CheckBooleanCondition(Loc, SubExpr); 15800 break; 15801 15802 case ConditionKind::ConstexprIf: 15803 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15804 break; 15805 15806 case ConditionKind::Switch: 15807 Cond = CheckSwitchCondition(Loc, SubExpr); 15808 break; 15809 } 15810 if (Cond.isInvalid()) 15811 return ConditionError(); 15812 15813 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15814 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15815 if (!FullExpr.get()) 15816 return ConditionError(); 15817 15818 return ConditionResult(*this, nullptr, FullExpr, 15819 CK == ConditionKind::ConstexprIf); 15820 } 15821 15822 namespace { 15823 /// A visitor for rebuilding a call to an __unknown_any expression 15824 /// to have an appropriate type. 15825 struct RebuildUnknownAnyFunction 15826 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15827 15828 Sema &S; 15829 15830 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15831 15832 ExprResult VisitStmt(Stmt *S) { 15833 llvm_unreachable("unexpected statement!"); 15834 } 15835 15836 ExprResult VisitExpr(Expr *E) { 15837 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15838 << E->getSourceRange(); 15839 return ExprError(); 15840 } 15841 15842 /// Rebuild an expression which simply semantically wraps another 15843 /// expression which it shares the type and value kind of. 15844 template <class T> ExprResult rebuildSugarExpr(T *E) { 15845 ExprResult SubResult = Visit(E->getSubExpr()); 15846 if (SubResult.isInvalid()) return ExprError(); 15847 15848 Expr *SubExpr = SubResult.get(); 15849 E->setSubExpr(SubExpr); 15850 E->setType(SubExpr->getType()); 15851 E->setValueKind(SubExpr->getValueKind()); 15852 assert(E->getObjectKind() == OK_Ordinary); 15853 return E; 15854 } 15855 15856 ExprResult VisitParenExpr(ParenExpr *E) { 15857 return rebuildSugarExpr(E); 15858 } 15859 15860 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15861 return rebuildSugarExpr(E); 15862 } 15863 15864 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15865 ExprResult SubResult = Visit(E->getSubExpr()); 15866 if (SubResult.isInvalid()) return ExprError(); 15867 15868 Expr *SubExpr = SubResult.get(); 15869 E->setSubExpr(SubExpr); 15870 E->setType(S.Context.getPointerType(SubExpr->getType())); 15871 assert(E->getValueKind() == VK_RValue); 15872 assert(E->getObjectKind() == OK_Ordinary); 15873 return E; 15874 } 15875 15876 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15877 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15878 15879 E->setType(VD->getType()); 15880 15881 assert(E->getValueKind() == VK_RValue); 15882 if (S.getLangOpts().CPlusPlus && 15883 !(isa<CXXMethodDecl>(VD) && 15884 cast<CXXMethodDecl>(VD)->isInstance())) 15885 E->setValueKind(VK_LValue); 15886 15887 return E; 15888 } 15889 15890 ExprResult VisitMemberExpr(MemberExpr *E) { 15891 return resolveDecl(E, E->getMemberDecl()); 15892 } 15893 15894 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15895 return resolveDecl(E, E->getDecl()); 15896 } 15897 }; 15898 } 15899 15900 /// Given a function expression of unknown-any type, try to rebuild it 15901 /// to have a function type. 15902 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15903 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15904 if (Result.isInvalid()) return ExprError(); 15905 return S.DefaultFunctionArrayConversion(Result.get()); 15906 } 15907 15908 namespace { 15909 /// A visitor for rebuilding an expression of type __unknown_anytype 15910 /// into one which resolves the type directly on the referring 15911 /// expression. Strict preservation of the original source 15912 /// structure is not a goal. 15913 struct RebuildUnknownAnyExpr 15914 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15915 15916 Sema &S; 15917 15918 /// The current destination type. 15919 QualType DestType; 15920 15921 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15922 : S(S), DestType(CastType) {} 15923 15924 ExprResult VisitStmt(Stmt *S) { 15925 llvm_unreachable("unexpected statement!"); 15926 } 15927 15928 ExprResult VisitExpr(Expr *E) { 15929 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15930 << E->getSourceRange(); 15931 return ExprError(); 15932 } 15933 15934 ExprResult VisitCallExpr(CallExpr *E); 15935 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15936 15937 /// Rebuild an expression which simply semantically wraps another 15938 /// expression which it shares the type and value kind of. 15939 template <class T> ExprResult rebuildSugarExpr(T *E) { 15940 ExprResult SubResult = Visit(E->getSubExpr()); 15941 if (SubResult.isInvalid()) return ExprError(); 15942 Expr *SubExpr = SubResult.get(); 15943 E->setSubExpr(SubExpr); 15944 E->setType(SubExpr->getType()); 15945 E->setValueKind(SubExpr->getValueKind()); 15946 assert(E->getObjectKind() == OK_Ordinary); 15947 return E; 15948 } 15949 15950 ExprResult VisitParenExpr(ParenExpr *E) { 15951 return rebuildSugarExpr(E); 15952 } 15953 15954 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15955 return rebuildSugarExpr(E); 15956 } 15957 15958 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15959 const PointerType *Ptr = DestType->getAs<PointerType>(); 15960 if (!Ptr) { 15961 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15962 << E->getSourceRange(); 15963 return ExprError(); 15964 } 15965 15966 if (isa<CallExpr>(E->getSubExpr())) { 15967 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15968 << E->getSourceRange(); 15969 return ExprError(); 15970 } 15971 15972 assert(E->getValueKind() == VK_RValue); 15973 assert(E->getObjectKind() == OK_Ordinary); 15974 E->setType(DestType); 15975 15976 // Build the sub-expression as if it were an object of the pointee type. 15977 DestType = Ptr->getPointeeType(); 15978 ExprResult SubResult = Visit(E->getSubExpr()); 15979 if (SubResult.isInvalid()) return ExprError(); 15980 E->setSubExpr(SubResult.get()); 15981 return E; 15982 } 15983 15984 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15985 15986 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15987 15988 ExprResult VisitMemberExpr(MemberExpr *E) { 15989 return resolveDecl(E, E->getMemberDecl()); 15990 } 15991 15992 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15993 return resolveDecl(E, E->getDecl()); 15994 } 15995 }; 15996 } 15997 15998 /// Rebuilds a call expression which yielded __unknown_anytype. 15999 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16000 Expr *CalleeExpr = E->getCallee(); 16001 16002 enum FnKind { 16003 FK_MemberFunction, 16004 FK_FunctionPointer, 16005 FK_BlockPointer 16006 }; 16007 16008 FnKind Kind; 16009 QualType CalleeType = CalleeExpr->getType(); 16010 if (CalleeType == S.Context.BoundMemberTy) { 16011 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16012 Kind = FK_MemberFunction; 16013 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16014 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16015 CalleeType = Ptr->getPointeeType(); 16016 Kind = FK_FunctionPointer; 16017 } else { 16018 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16019 Kind = FK_BlockPointer; 16020 } 16021 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16022 16023 // Verify that this is a legal result type of a function. 16024 if (DestType->isArrayType() || DestType->isFunctionType()) { 16025 unsigned diagID = diag::err_func_returning_array_function; 16026 if (Kind == FK_BlockPointer) 16027 diagID = diag::err_block_returning_array_function; 16028 16029 S.Diag(E->getExprLoc(), diagID) 16030 << DestType->isFunctionType() << DestType; 16031 return ExprError(); 16032 } 16033 16034 // Otherwise, go ahead and set DestType as the call's result. 16035 E->setType(DestType.getNonLValueExprType(S.Context)); 16036 E->setValueKind(Expr::getValueKindForType(DestType)); 16037 assert(E->getObjectKind() == OK_Ordinary); 16038 16039 // Rebuild the function type, replacing the result type with DestType. 16040 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16041 if (Proto) { 16042 // __unknown_anytype(...) is a special case used by the debugger when 16043 // it has no idea what a function's signature is. 16044 // 16045 // We want to build this call essentially under the K&R 16046 // unprototyped rules, but making a FunctionNoProtoType in C++ 16047 // would foul up all sorts of assumptions. However, we cannot 16048 // simply pass all arguments as variadic arguments, nor can we 16049 // portably just call the function under a non-variadic type; see 16050 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16051 // However, it turns out that in practice it is generally safe to 16052 // call a function declared as "A foo(B,C,D);" under the prototype 16053 // "A foo(B,C,D,...);". The only known exception is with the 16054 // Windows ABI, where any variadic function is implicitly cdecl 16055 // regardless of its normal CC. Therefore we change the parameter 16056 // types to match the types of the arguments. 16057 // 16058 // This is a hack, but it is far superior to moving the 16059 // corresponding target-specific code from IR-gen to Sema/AST. 16060 16061 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16062 SmallVector<QualType, 8> ArgTypes; 16063 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16064 ArgTypes.reserve(E->getNumArgs()); 16065 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16066 Expr *Arg = E->getArg(i); 16067 QualType ArgType = Arg->getType(); 16068 if (E->isLValue()) { 16069 ArgType = S.Context.getLValueReferenceType(ArgType); 16070 } else if (E->isXValue()) { 16071 ArgType = S.Context.getRValueReferenceType(ArgType); 16072 } 16073 ArgTypes.push_back(ArgType); 16074 } 16075 ParamTypes = ArgTypes; 16076 } 16077 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16078 Proto->getExtProtoInfo()); 16079 } else { 16080 DestType = S.Context.getFunctionNoProtoType(DestType, 16081 FnType->getExtInfo()); 16082 } 16083 16084 // Rebuild the appropriate pointer-to-function type. 16085 switch (Kind) { 16086 case FK_MemberFunction: 16087 // Nothing to do. 16088 break; 16089 16090 case FK_FunctionPointer: 16091 DestType = S.Context.getPointerType(DestType); 16092 break; 16093 16094 case FK_BlockPointer: 16095 DestType = S.Context.getBlockPointerType(DestType); 16096 break; 16097 } 16098 16099 // Finally, we can recurse. 16100 ExprResult CalleeResult = Visit(CalleeExpr); 16101 if (!CalleeResult.isUsable()) return ExprError(); 16102 E->setCallee(CalleeResult.get()); 16103 16104 // Bind a temporary if necessary. 16105 return S.MaybeBindToTemporary(E); 16106 } 16107 16108 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16109 // Verify that this is a legal result type of a call. 16110 if (DestType->isArrayType() || DestType->isFunctionType()) { 16111 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16112 << DestType->isFunctionType() << DestType; 16113 return ExprError(); 16114 } 16115 16116 // Rewrite the method result type if available. 16117 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16118 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16119 Method->setReturnType(DestType); 16120 } 16121 16122 // Change the type of the message. 16123 E->setType(DestType.getNonReferenceType()); 16124 E->setValueKind(Expr::getValueKindForType(DestType)); 16125 16126 return S.MaybeBindToTemporary(E); 16127 } 16128 16129 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16130 // The only case we should ever see here is a function-to-pointer decay. 16131 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16132 assert(E->getValueKind() == VK_RValue); 16133 assert(E->getObjectKind() == OK_Ordinary); 16134 16135 E->setType(DestType); 16136 16137 // Rebuild the sub-expression as the pointee (function) type. 16138 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16139 16140 ExprResult Result = Visit(E->getSubExpr()); 16141 if (!Result.isUsable()) return ExprError(); 16142 16143 E->setSubExpr(Result.get()); 16144 return E; 16145 } else if (E->getCastKind() == CK_LValueToRValue) { 16146 assert(E->getValueKind() == VK_RValue); 16147 assert(E->getObjectKind() == OK_Ordinary); 16148 16149 assert(isa<BlockPointerType>(E->getType())); 16150 16151 E->setType(DestType); 16152 16153 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16154 DestType = S.Context.getLValueReferenceType(DestType); 16155 16156 ExprResult Result = Visit(E->getSubExpr()); 16157 if (!Result.isUsable()) return ExprError(); 16158 16159 E->setSubExpr(Result.get()); 16160 return E; 16161 } else { 16162 llvm_unreachable("Unhandled cast type!"); 16163 } 16164 } 16165 16166 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16167 ExprValueKind ValueKind = VK_LValue; 16168 QualType Type = DestType; 16169 16170 // We know how to make this work for certain kinds of decls: 16171 16172 // - functions 16173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16174 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16175 DestType = Ptr->getPointeeType(); 16176 ExprResult Result = resolveDecl(E, VD); 16177 if (Result.isInvalid()) return ExprError(); 16178 return S.ImpCastExprToType(Result.get(), Type, 16179 CK_FunctionToPointerDecay, VK_RValue); 16180 } 16181 16182 if (!Type->isFunctionType()) { 16183 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16184 << VD << E->getSourceRange(); 16185 return ExprError(); 16186 } 16187 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16188 // We must match the FunctionDecl's type to the hack introduced in 16189 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16190 // type. See the lengthy commentary in that routine. 16191 QualType FDT = FD->getType(); 16192 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16193 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16194 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16195 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16196 SourceLocation Loc = FD->getLocation(); 16197 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16198 FD->getDeclContext(), 16199 Loc, Loc, FD->getNameInfo().getName(), 16200 DestType, FD->getTypeSourceInfo(), 16201 SC_None, false/*isInlineSpecified*/, 16202 FD->hasPrototype(), 16203 false/*isConstexprSpecified*/); 16204 16205 if (FD->getQualifier()) 16206 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16207 16208 SmallVector<ParmVarDecl*, 16> Params; 16209 for (const auto &AI : FT->param_types()) { 16210 ParmVarDecl *Param = 16211 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16212 Param->setScopeInfo(0, Params.size()); 16213 Params.push_back(Param); 16214 } 16215 NewFD->setParams(Params); 16216 DRE->setDecl(NewFD); 16217 VD = DRE->getDecl(); 16218 } 16219 } 16220 16221 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16222 if (MD->isInstance()) { 16223 ValueKind = VK_RValue; 16224 Type = S.Context.BoundMemberTy; 16225 } 16226 16227 // Function references aren't l-values in C. 16228 if (!S.getLangOpts().CPlusPlus) 16229 ValueKind = VK_RValue; 16230 16231 // - variables 16232 } else if (isa<VarDecl>(VD)) { 16233 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16234 Type = RefTy->getPointeeType(); 16235 } else if (Type->isFunctionType()) { 16236 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16237 << VD << E->getSourceRange(); 16238 return ExprError(); 16239 } 16240 16241 // - nothing else 16242 } else { 16243 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16244 << VD << E->getSourceRange(); 16245 return ExprError(); 16246 } 16247 16248 // Modifying the declaration like this is friendly to IR-gen but 16249 // also really dangerous. 16250 VD->setType(DestType); 16251 E->setType(Type); 16252 E->setValueKind(ValueKind); 16253 return E; 16254 } 16255 16256 /// Check a cast of an unknown-any type. We intentionally only 16257 /// trigger this for C-style casts. 16258 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16259 Expr *CastExpr, CastKind &CastKind, 16260 ExprValueKind &VK, CXXCastPath &Path) { 16261 // The type we're casting to must be either void or complete. 16262 if (!CastType->isVoidType() && 16263 RequireCompleteType(TypeRange.getBegin(), CastType, 16264 diag::err_typecheck_cast_to_incomplete)) 16265 return ExprError(); 16266 16267 // Rewrite the casted expression from scratch. 16268 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16269 if (!result.isUsable()) return ExprError(); 16270 16271 CastExpr = result.get(); 16272 VK = CastExpr->getValueKind(); 16273 CastKind = CK_NoOp; 16274 16275 return CastExpr; 16276 } 16277 16278 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16279 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16280 } 16281 16282 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16283 Expr *arg, QualType ¶mType) { 16284 // If the syntactic form of the argument is not an explicit cast of 16285 // any sort, just do default argument promotion. 16286 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16287 if (!castArg) { 16288 ExprResult result = DefaultArgumentPromotion(arg); 16289 if (result.isInvalid()) return ExprError(); 16290 paramType = result.get()->getType(); 16291 return result; 16292 } 16293 16294 // Otherwise, use the type that was written in the explicit cast. 16295 assert(!arg->hasPlaceholderType()); 16296 paramType = castArg->getTypeAsWritten(); 16297 16298 // Copy-initialize a parameter of that type. 16299 InitializedEntity entity = 16300 InitializedEntity::InitializeParameter(Context, paramType, 16301 /*consumed*/ false); 16302 return PerformCopyInitialization(entity, callLoc, arg); 16303 } 16304 16305 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16306 Expr *orig = E; 16307 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16308 while (true) { 16309 E = E->IgnoreParenImpCasts(); 16310 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16311 E = call->getCallee(); 16312 diagID = diag::err_uncasted_call_of_unknown_any; 16313 } else { 16314 break; 16315 } 16316 } 16317 16318 SourceLocation loc; 16319 NamedDecl *d; 16320 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16321 loc = ref->getLocation(); 16322 d = ref->getDecl(); 16323 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16324 loc = mem->getMemberLoc(); 16325 d = mem->getMemberDecl(); 16326 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16327 diagID = diag::err_uncasted_call_of_unknown_any; 16328 loc = msg->getSelectorStartLoc(); 16329 d = msg->getMethodDecl(); 16330 if (!d) { 16331 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16332 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16333 << orig->getSourceRange(); 16334 return ExprError(); 16335 } 16336 } else { 16337 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16338 << E->getSourceRange(); 16339 return ExprError(); 16340 } 16341 16342 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16343 16344 // Never recoverable. 16345 return ExprError(); 16346 } 16347 16348 /// Check for operands with placeholder types and complain if found. 16349 /// Returns ExprError() if there was an error and no recovery was possible. 16350 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16351 if (!getLangOpts().CPlusPlus) { 16352 // C cannot handle TypoExpr nodes on either side of a binop because it 16353 // doesn't handle dependent types properly, so make sure any TypoExprs have 16354 // been dealt with before checking the operands. 16355 ExprResult Result = CorrectDelayedTyposInExpr(E); 16356 if (!Result.isUsable()) return ExprError(); 16357 E = Result.get(); 16358 } 16359 16360 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16361 if (!placeholderType) return E; 16362 16363 switch (placeholderType->getKind()) { 16364 16365 // Overloaded expressions. 16366 case BuiltinType::Overload: { 16367 // Try to resolve a single function template specialization. 16368 // This is obligatory. 16369 ExprResult Result = E; 16370 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16371 return Result; 16372 16373 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16374 // leaves Result unchanged on failure. 16375 Result = E; 16376 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16377 return Result; 16378 16379 // If that failed, try to recover with a call. 16380 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16381 /*complain*/ true); 16382 return Result; 16383 } 16384 16385 // Bound member functions. 16386 case BuiltinType::BoundMember: { 16387 ExprResult result = E; 16388 const Expr *BME = E->IgnoreParens(); 16389 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16390 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16391 if (isa<CXXPseudoDestructorExpr>(BME)) { 16392 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16393 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16394 if (ME->getMemberNameInfo().getName().getNameKind() == 16395 DeclarationName::CXXDestructorName) 16396 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16397 } 16398 tryToRecoverWithCall(result, PD, 16399 /*complain*/ true); 16400 return result; 16401 } 16402 16403 // ARC unbridged casts. 16404 case BuiltinType::ARCUnbridgedCast: { 16405 Expr *realCast = stripARCUnbridgedCast(E); 16406 diagnoseARCUnbridgedCast(realCast); 16407 return realCast; 16408 } 16409 16410 // Expressions of unknown type. 16411 case BuiltinType::UnknownAny: 16412 return diagnoseUnknownAnyExpr(*this, E); 16413 16414 // Pseudo-objects. 16415 case BuiltinType::PseudoObject: 16416 return checkPseudoObjectRValue(E); 16417 16418 case BuiltinType::BuiltinFn: { 16419 // Accept __noop without parens by implicitly converting it to a call expr. 16420 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16421 if (DRE) { 16422 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16423 if (FD->getBuiltinID() == Builtin::BI__noop) { 16424 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16425 CK_BuiltinFnToFnPtr).get(); 16426 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16427 VK_RValue, SourceLocation()); 16428 } 16429 } 16430 16431 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16432 return ExprError(); 16433 } 16434 16435 // Expressions of unknown type. 16436 case BuiltinType::OMPArraySection: 16437 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16438 return ExprError(); 16439 16440 // Everything else should be impossible. 16441 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16442 case BuiltinType::Id: 16443 #include "clang/Basic/OpenCLImageTypes.def" 16444 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16445 #define PLACEHOLDER_TYPE(Id, SingletonId) 16446 #include "clang/AST/BuiltinTypes.def" 16447 break; 16448 } 16449 16450 llvm_unreachable("invalid placeholder type!"); 16451 } 16452 16453 bool Sema::CheckCaseExpression(Expr *E) { 16454 if (E->isTypeDependent()) 16455 return true; 16456 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16457 return E->getType()->isIntegralOrEnumerationType(); 16458 return false; 16459 } 16460 16461 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16462 ExprResult 16463 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16464 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16465 "Unknown Objective-C Boolean value!"); 16466 QualType BoolT = Context.ObjCBuiltinBoolTy; 16467 if (!Context.getBOOLDecl()) { 16468 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16469 Sema::LookupOrdinaryName); 16470 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16471 NamedDecl *ND = Result.getFoundDecl(); 16472 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16473 Context.setBOOLDecl(TD); 16474 } 16475 } 16476 if (Context.getBOOLDecl()) 16477 BoolT = Context.getBOOLType(); 16478 return new (Context) 16479 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16480 } 16481 16482 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16483 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16484 SourceLocation RParen) { 16485 16486 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16487 16488 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16489 [&](const AvailabilitySpec &Spec) { 16490 return Spec.getPlatform() == Platform; 16491 }); 16492 16493 VersionTuple Version; 16494 if (Spec != AvailSpecs.end()) 16495 Version = Spec->getVersion(); 16496 16497 // The use of `@available` in the enclosing function should be analyzed to 16498 // warn when it's used inappropriately (i.e. not if(@available)). 16499 if (getCurFunctionOrMethodDecl()) 16500 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16501 else if (getCurBlock() || getCurLambda()) 16502 getCurFunction()->HasPotentialAvailabilityViolations = true; 16503 16504 return new (Context) 16505 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16506 } 16507