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/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// \brief Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 } 69 70 // See if this function is unavailable. 71 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 72 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 73 return false; 74 75 return true; 76 } 77 78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 79 // Warn if this is used but marked unused. 80 if (const auto *A = D->getAttr<UnusedAttr>()) { 81 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 82 // should diagnose them. 83 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 84 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 85 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 86 if (DC && !DC->hasAttr<UnusedAttr>()) 87 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 88 } 89 } 90 } 91 92 /// \brief Emit a note explaining that this function is deleted. 93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 94 assert(Decl->isDeleted()); 95 96 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 97 98 if (Method && Method->isDeleted() && Method->isDefaulted()) { 99 // If the method was explicitly defaulted, point at that declaration. 100 if (!Method->isImplicit()) 101 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 102 103 // Try to diagnose why this special member function was implicitly 104 // deleted. This might fail, if that reason no longer applies. 105 CXXSpecialMember CSM = getSpecialMember(Method); 106 if (CSM != CXXInvalid) 107 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 108 109 return; 110 } 111 112 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 113 if (Ctor && Ctor->isInheritingConstructor()) 114 return NoteDeletedInheritingConstructor(Ctor); 115 116 Diag(Decl->getLocation(), diag::note_availability_specified_here) 117 << Decl << true; 118 } 119 120 /// \brief Determine whether a FunctionDecl was ever declared with an 121 /// explicit storage class. 122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 123 for (auto I : D->redecls()) { 124 if (I->getStorageClass() != SC_None) 125 return true; 126 } 127 return false; 128 } 129 130 /// \brief Check whether we're in an extern inline function and referring to a 131 /// variable or function with internal linkage (C11 6.7.4p3). 132 /// 133 /// This is only a warning because we used to silently accept this code, but 134 /// in many cases it will not behave correctly. This is not enabled in C++ mode 135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 136 /// and so while there may still be user mistakes, most of the time we can't 137 /// prove that there are errors. 138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 139 const NamedDecl *D, 140 SourceLocation Loc) { 141 // This is disabled under C++; there are too many ways for this to fire in 142 // contexts where the warning is a false positive, or where it is technically 143 // correct but benign. 144 if (S.getLangOpts().CPlusPlus) 145 return; 146 147 // Check if this is an inlined function or method. 148 FunctionDecl *Current = S.getCurFunctionDecl(); 149 if (!Current) 150 return; 151 if (!Current->isInlined()) 152 return; 153 if (!Current->isExternallyVisible()) 154 return; 155 156 // Check if the decl has internal linkage. 157 if (D->getFormalLinkage() != InternalLinkage) 158 return; 159 160 // Downgrade from ExtWarn to Extension if 161 // (1) the supposedly external inline function is in the main file, 162 // and probably won't be included anywhere else. 163 // (2) the thing we're referencing is a pure function. 164 // (3) the thing we're referencing is another inline function. 165 // This last can give us false negatives, but it's better than warning on 166 // wrappers for simple C library functions. 167 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 168 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 169 if (!DowngradeWarning && UsedFn) 170 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 171 172 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 173 : diag::ext_internal_in_extern_inline) 174 << /*IsVar=*/!UsedFn << D; 175 176 S.MaybeSuggestAddingStaticToDecl(Current); 177 178 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 179 << D; 180 } 181 182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 183 const FunctionDecl *First = Cur->getFirstDecl(); 184 185 // Suggest "static" on the function, if possible. 186 if (!hasAnyExplicitStorageClass(First)) { 187 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 188 Diag(DeclBegin, diag::note_convert_inline_to_static) 189 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 190 } 191 } 192 193 /// \brief Determine whether the use of this declaration is valid, and 194 /// emit any corresponding diagnostics. 195 /// 196 /// This routine diagnoses various problems with referencing 197 /// declarations that can occur when using a declaration. For example, 198 /// it might warn if a deprecated or unavailable declaration is being 199 /// used, or produce an error (and return true) if a C++0x deleted 200 /// function is being used. 201 /// 202 /// \returns true if there was an error (this declaration cannot be 203 /// referenced), false otherwise. 204 /// 205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 206 const ObjCInterfaceDecl *UnknownObjCClass, 207 bool ObjCPropertyAccess, 208 bool AvoidPartialAvailabilityChecks) { 209 SourceLocation Loc = Locs.front(); 210 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 211 // If there were any diagnostics suppressed by template argument deduction, 212 // emit them now. 213 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 214 if (Pos != SuppressedDiagnostics.end()) { 215 for (const PartialDiagnosticAt &Suppressed : Pos->second) 216 Diag(Suppressed.first, Suppressed.second); 217 218 // Clear out the list of suppressed diagnostics, so that we don't emit 219 // them again for this specialization. However, we don't obsolete this 220 // entry from the table, because we want to avoid ever emitting these 221 // diagnostics again. 222 Pos->second.clear(); 223 } 224 225 // C++ [basic.start.main]p3: 226 // The function 'main' shall not be used within a program. 227 if (cast<FunctionDecl>(D)->isMain()) 228 Diag(Loc, diag::ext_main_used); 229 } 230 231 // See if this is an auto-typed variable whose initializer we are parsing. 232 if (ParsingInitForAutoVars.count(D)) { 233 if (isa<BindingDecl>(D)) { 234 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 235 << D->getDeclName(); 236 } else { 237 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 238 << D->getDeclName() << cast<VarDecl>(D)->getType(); 239 } 240 return true; 241 } 242 243 // See if this is a deleted function. 244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 245 if (FD->isDeleted()) { 246 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 247 if (Ctor && Ctor->isInheritingConstructor()) 248 Diag(Loc, diag::err_deleted_inherited_ctor_use) 249 << Ctor->getParent() 250 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 251 else 252 Diag(Loc, diag::err_deleted_function_use); 253 NoteDeletedFunction(FD); 254 return true; 255 } 256 257 // If the function has a deduced return type, and we can't deduce it, 258 // then we can't use it either. 259 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 260 DeduceReturnType(FD, Loc)) 261 return true; 262 263 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 264 return true; 265 } 266 267 auto getReferencedObjCProp = [](const NamedDecl *D) -> 268 const ObjCPropertyDecl * { 269 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 270 return MD->findPropertyDecl(); 271 return nullptr; 272 }; 273 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 274 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 275 return true; 276 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 277 return true; 278 } 279 280 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 281 // Only the variables omp_in and omp_out are allowed in the combiner. 282 // Only the variables omp_priv and omp_orig are allowed in the 283 // initializer-clause. 284 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 285 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 286 isa<VarDecl>(D)) { 287 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 288 << getCurFunction()->HasOMPDeclareReductionCombiner; 289 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 290 return true; 291 } 292 293 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 294 AvoidPartialAvailabilityChecks); 295 296 DiagnoseUnusedOfDecl(*this, D, Loc); 297 298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 299 300 return false; 301 } 302 303 /// \brief Retrieve the message suffix that should be added to a 304 /// diagnostic complaining about the given function being deleted or 305 /// unavailable. 306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 307 std::string Message; 308 if (FD->getAvailability(&Message)) 309 return ": " + Message; 310 311 return std::string(); 312 } 313 314 /// DiagnoseSentinelCalls - This routine checks whether a call or 315 /// message-send is to a declaration with the sentinel attribute, and 316 /// if so, it checks that the requirements of the sentinel are 317 /// satisfied. 318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 319 ArrayRef<Expr *> Args) { 320 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 321 if (!attr) 322 return; 323 324 // The number of formal parameters of the declaration. 325 unsigned numFormalParams; 326 327 // The kind of declaration. This is also an index into a %select in 328 // the diagnostic. 329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 330 331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 332 numFormalParams = MD->param_size(); 333 calleeType = CT_Method; 334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 335 numFormalParams = FD->param_size(); 336 calleeType = CT_Function; 337 } else if (isa<VarDecl>(D)) { 338 QualType type = cast<ValueDecl>(D)->getType(); 339 const FunctionType *fn = nullptr; 340 if (const PointerType *ptr = type->getAs<PointerType>()) { 341 fn = ptr->getPointeeType()->getAs<FunctionType>(); 342 if (!fn) return; 343 calleeType = CT_Function; 344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 345 fn = ptr->getPointeeType()->castAs<FunctionType>(); 346 calleeType = CT_Block; 347 } else { 348 return; 349 } 350 351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 352 numFormalParams = proto->getNumParams(); 353 } else { 354 numFormalParams = 0; 355 } 356 } else { 357 return; 358 } 359 360 // "nullPos" is the number of formal parameters at the end which 361 // effectively count as part of the variadic arguments. This is 362 // useful if you would prefer to not have *any* formal parameters, 363 // but the language forces you to have at least one. 364 unsigned nullPos = attr->getNullPos(); 365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 367 368 // The number of arguments which should follow the sentinel. 369 unsigned numArgsAfterSentinel = attr->getSentinel(); 370 371 // If there aren't enough arguments for all the formal parameters, 372 // the sentinel, and the args after the sentinel, complain. 373 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 375 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 376 return; 377 } 378 379 // Otherwise, find the sentinel expression. 380 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 381 if (!sentinelExpr) return; 382 if (sentinelExpr->isValueDependent()) return; 383 if (Context.isSentinelNullExpr(sentinelExpr)) return; 384 385 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 386 // or 'NULL' if those are actually defined in the context. Only use 387 // 'nil' for ObjC methods, where it's much more likely that the 388 // variadic arguments form a list of object pointers. 389 SourceLocation MissingNilLoc 390 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 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->getLocEnd()); 505 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 506 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 507 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 508 AssignLoc), ",") << 509 FixItHint::CreateInsertion(RHSLocEnd, ")"); 510 } 511 else 512 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 513 } else { 514 NamedDecl *ObjectGetClass = 515 S.LookupSingleName(S.TUScope, 516 &S.Context.Idents.get("object_getClass"), 517 SourceLocation(), S.LookupOrdinaryName); 518 if (ObjectGetClass) 519 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 520 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 521 FixItHint::CreateReplacement( 522 SourceRange(OIRE->getOpLoc(), 523 OIRE->getLocEnd()), ")"); 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 526 } 527 S.Diag(IV->getLocation(), diag::note_ivar_decl); 528 } 529 } 530 } 531 532 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 533 // Handle any placeholder expressions which made it here. 534 if (E->getType()->isPlaceholderType()) { 535 ExprResult result = CheckPlaceholderExpr(E); 536 if (result.isInvalid()) return ExprError(); 537 E = result.get(); 538 } 539 540 // C++ [conv.lval]p1: 541 // A glvalue of a non-function, non-array type T can be 542 // converted to a prvalue. 543 if (!E->isGLValue()) return E; 544 545 QualType T = E->getType(); 546 assert(!T.isNull() && "r-value conversion on typeless expression?"); 547 548 // We don't want to throw lvalue-to-rvalue casts on top of 549 // expressions of certain types in C++. 550 if (getLangOpts().CPlusPlus && 551 (E->getType() == Context.OverloadTy || 552 T->isDependentType() || 553 T->isRecordType())) 554 return E; 555 556 // The C standard is actually really unclear on this point, and 557 // DR106 tells us what the result should be but not why. It's 558 // generally best to say that void types just doesn't undergo 559 // lvalue-to-rvalue at all. Note that expressions of unqualified 560 // 'void' type are never l-values, but qualified void can be. 561 if (T->isVoidType()) 562 return E; 563 564 // OpenCL usually rejects direct accesses to values of 'half' type. 565 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 566 T->isHalfType()) { 567 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 568 << 0 << T; 569 return ExprError(); 570 } 571 572 CheckForNullPointerDereference(*this, E); 573 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 574 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 575 &Context.Idents.get("object_getClass"), 576 SourceLocation(), LookupOrdinaryName); 577 if (ObjectGetClass) 578 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 579 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 580 FixItHint::CreateReplacement( 581 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 582 else 583 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 584 } 585 else if (const ObjCIvarRefExpr *OIRE = 586 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 587 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 588 589 // C++ [conv.lval]p1: 590 // [...] If T is a non-class type, the type of the prvalue is the 591 // cv-unqualified version of T. Otherwise, the type of the 592 // rvalue is T. 593 // 594 // C99 6.3.2.1p2: 595 // If the lvalue has qualified type, the value has the unqualified 596 // version of the type of the lvalue; otherwise, the value has the 597 // type of the lvalue. 598 if (T.hasQualifiers()) 599 T = T.getUnqualifiedType(); 600 601 // Under the MS ABI, lock down the inheritance model now. 602 if (T->isMemberPointerType() && 603 Context.getTargetInfo().getCXXABI().isMicrosoft()) 604 (void)isCompleteType(E->getExprLoc(), T); 605 606 UpdateMarkingForLValueToRValue(E); 607 608 // Loading a __weak object implicitly retains the value, so we need a cleanup to 609 // balance that. 610 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 611 Cleanup.setExprNeedsCleanups(true); 612 613 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 614 nullptr, VK_RValue); 615 616 // C11 6.3.2.1p2: 617 // ... if the lvalue has atomic type, the value has the non-atomic version 618 // of the type of the lvalue ... 619 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 620 T = Atomic->getValueType().getUnqualifiedType(); 621 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 622 nullptr, VK_RValue); 623 } 624 625 return Res; 626 } 627 628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 629 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 630 if (Res.isInvalid()) 631 return ExprError(); 632 Res = DefaultLvalueConversion(Res.get()); 633 if (Res.isInvalid()) 634 return ExprError(); 635 return Res; 636 } 637 638 /// CallExprUnaryConversions - a special case of an unary conversion 639 /// performed on a function designator of a call expression. 640 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 641 QualType Ty = E->getType(); 642 ExprResult Res = E; 643 // Only do implicit cast for a function type, but not for a pointer 644 // to function type. 645 if (Ty->isFunctionType()) { 646 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 647 CK_FunctionToPointerDecay).get(); 648 if (Res.isInvalid()) 649 return ExprError(); 650 } 651 Res = DefaultLvalueConversion(Res.get()); 652 if (Res.isInvalid()) 653 return ExprError(); 654 return Res.get(); 655 } 656 657 /// UsualUnaryConversions - Performs various conversions that are common to most 658 /// operators (C99 6.3). The conversions of array and function types are 659 /// sometimes suppressed. For example, the array->pointer conversion doesn't 660 /// apply if the array is an argument to the sizeof or address (&) operators. 661 /// In these instances, this routine should *not* be called. 662 ExprResult Sema::UsualUnaryConversions(Expr *E) { 663 // First, convert to an r-value. 664 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 665 if (Res.isInvalid()) 666 return ExprError(); 667 E = Res.get(); 668 669 QualType Ty = E->getType(); 670 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 671 672 // Half FP have to be promoted to float unless it is natively supported 673 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 674 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 675 676 // Try to perform integral promotions if the object has a theoretically 677 // promotable type. 678 if (Ty->isIntegralOrUnscopedEnumerationType()) { 679 // C99 6.3.1.1p2: 680 // 681 // The following may be used in an expression wherever an int or 682 // unsigned int may be used: 683 // - an object or expression with an integer type whose integer 684 // conversion rank is less than or equal to the rank of int 685 // and unsigned int. 686 // - A bit-field of type _Bool, int, signed int, or unsigned int. 687 // 688 // If an int can represent all values of the original type, the 689 // value is converted to an int; otherwise, it is converted to an 690 // unsigned int. These are called the integer promotions. All 691 // other types are unchanged by the integer promotions. 692 693 QualType PTy = Context.isPromotableBitField(E); 694 if (!PTy.isNull()) { 695 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 696 return E; 697 } 698 if (Ty->isPromotableIntegerType()) { 699 QualType PT = Context.getPromotedIntegerType(Ty); 700 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 701 return E; 702 } 703 } 704 return E; 705 } 706 707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 708 /// do not have a prototype. Arguments that have type float or __fp16 709 /// are promoted to double. All other argument types are converted by 710 /// UsualUnaryConversions(). 711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 712 QualType Ty = E->getType(); 713 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 714 715 ExprResult Res = UsualUnaryConversions(E); 716 if (Res.isInvalid()) 717 return ExprError(); 718 E = Res.get(); 719 720 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 721 // promote to double. 722 // Note that default argument promotion applies only to float (and 723 // half/fp16); it does not apply to _Float16. 724 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 725 if (BTy && (BTy->getKind() == BuiltinType::Half || 726 BTy->getKind() == BuiltinType::Float)) { 727 if (getLangOpts().OpenCL && 728 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 729 if (BTy->getKind() == BuiltinType::Half) { 730 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 731 } 732 } else { 733 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 734 } 735 } 736 737 // C++ performs lvalue-to-rvalue conversion as a default argument 738 // promotion, even on class types, but note: 739 // C++11 [conv.lval]p2: 740 // When an lvalue-to-rvalue conversion occurs in an unevaluated 741 // operand or a subexpression thereof the value contained in the 742 // referenced object is not accessed. Otherwise, if the glvalue 743 // has a class type, the conversion copy-initializes a temporary 744 // of type T from the glvalue and the result of the conversion 745 // is a prvalue for the temporary. 746 // FIXME: add some way to gate this entire thing for correctness in 747 // potentially potentially evaluated contexts. 748 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 749 ExprResult Temp = PerformCopyInitialization( 750 InitializedEntity::InitializeTemporary(E->getType()), 751 E->getExprLoc(), E); 752 if (Temp.isInvalid()) 753 return ExprError(); 754 E = Temp.get(); 755 } 756 757 return E; 758 } 759 760 /// Determine the degree of POD-ness for an expression. 761 /// Incomplete types are considered POD, since this check can be performed 762 /// when we're in an unevaluated context. 763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 764 if (Ty->isIncompleteType()) { 765 // C++11 [expr.call]p7: 766 // After these conversions, if the argument does not have arithmetic, 767 // enumeration, pointer, pointer to member, or class type, the program 768 // is ill-formed. 769 // 770 // Since we've already performed array-to-pointer and function-to-pointer 771 // decay, the only such type in C++ is cv void. This also handles 772 // initializer lists as variadic arguments. 773 if (Ty->isVoidType()) 774 return VAK_Invalid; 775 776 if (Ty->isObjCObjectType()) 777 return VAK_Invalid; 778 return VAK_Valid; 779 } 780 781 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 782 return VAK_Invalid; 783 784 if (Ty.isCXX98PODType(Context)) 785 return VAK_Valid; 786 787 // C++11 [expr.call]p7: 788 // Passing a potentially-evaluated argument of class type (Clause 9) 789 // having a non-trivial copy constructor, a non-trivial move constructor, 790 // or a non-trivial destructor, with no corresponding parameter, 791 // is conditionally-supported with implementation-defined semantics. 792 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 793 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 794 if (!Record->hasNonTrivialCopyConstructor() && 795 !Record->hasNonTrivialMoveConstructor() && 796 !Record->hasNonTrivialDestructor()) 797 return VAK_ValidInCXX11; 798 799 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 800 return VAK_Valid; 801 802 if (Ty->isObjCObjectType()) 803 return VAK_Invalid; 804 805 if (getLangOpts().MSVCCompat) 806 return VAK_MSVCUndefined; 807 808 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 809 // permitted to reject them. We should consider doing so. 810 return VAK_Undefined; 811 } 812 813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 814 // Don't allow one to pass an Objective-C interface to a vararg. 815 const QualType &Ty = E->getType(); 816 VarArgKind VAK = isValidVarArgType(Ty); 817 818 // Complain about passing non-POD types through varargs. 819 switch (VAK) { 820 case VAK_ValidInCXX11: 821 DiagRuntimeBehavior( 822 E->getLocStart(), nullptr, 823 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 824 << 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->getLocStart(), 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( 839 E->getLocStart(), nullptr, 840 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 841 << getLangOpts().CPlusPlus11 << Ty << CT); 842 break; 843 844 case VAK_Invalid: 845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 846 Diag(E->getLocStart(), 847 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT; 848 else if (Ty->isObjCObjectType()) 849 DiagRuntimeBehavior( 850 E->getLocStart(), nullptr, 851 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 852 << Ty << CT); 853 else 854 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 855 << isa<InitListExpr>(E) << Ty << CT; 856 break; 857 } 858 } 859 860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 861 /// will create a trap if the resulting type is not a POD type. 862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 863 FunctionDecl *FDecl) { 864 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 865 // Strip the unbridged-cast placeholder expression off, if applicable. 866 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 867 (CT == VariadicMethod || 868 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 869 E = stripARCUnbridgedCast(E); 870 871 // Otherwise, do normal placeholder checking. 872 } else { 873 ExprResult ExprRes = CheckPlaceholderExpr(E); 874 if (ExprRes.isInvalid()) 875 return ExprError(); 876 E = ExprRes.get(); 877 } 878 } 879 880 ExprResult ExprRes = DefaultArgumentPromotion(E); 881 if (ExprRes.isInvalid()) 882 return ExprError(); 883 E = ExprRes.get(); 884 885 // Diagnostics regarding non-POD argument types are 886 // emitted along with format string checking in Sema::CheckFunctionCall(). 887 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 888 // Turn this into a trap. 889 CXXScopeSpec SS; 890 SourceLocation TemplateKWLoc; 891 UnqualifiedId Name; 892 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 893 E->getLocStart()); 894 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 895 Name, true, false); 896 if (TrapFn.isInvalid()) 897 return ExprError(); 898 899 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 900 E->getLocStart(), None, 901 E->getLocEnd()); 902 if (Call.isInvalid()) 903 return ExprError(); 904 905 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 906 Call.get(), E); 907 if (Comma.isInvalid()) 908 return ExprError(); 909 return Comma.get(); 910 } 911 912 if (!getLangOpts().CPlusPlus && 913 RequireCompleteType(E->getExprLoc(), E->getType(), 914 diag::err_call_incomplete_argument)) 915 return ExprError(); 916 917 return E; 918 } 919 920 /// \brief Converts an integer to complex float type. Helper function of 921 /// UsualArithmeticConversions() 922 /// 923 /// \return false if the integer expression is an integer type and is 924 /// successfully converted to the complex type. 925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 926 ExprResult &ComplexExpr, 927 QualType IntTy, 928 QualType ComplexTy, 929 bool SkipCast) { 930 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 931 if (SkipCast) return false; 932 if (IntTy->isIntegerType()) { 933 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 934 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 935 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 936 CK_FloatingRealToComplex); 937 } else { 938 assert(IntTy->isComplexIntegerType()); 939 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 940 CK_IntegralComplexToFloatingComplex); 941 } 942 return false; 943 } 944 945 /// \brief Handle arithmetic conversion with complex types. Helper function of 946 /// UsualArithmeticConversions() 947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 948 ExprResult &RHS, QualType LHSType, 949 QualType RHSType, 950 bool IsCompAssign) { 951 // if we have an integer operand, the result is the complex type. 952 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 953 /*skipCast*/false)) 954 return LHSType; 955 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 956 /*skipCast*/IsCompAssign)) 957 return RHSType; 958 959 // This handles complex/complex, complex/float, or float/complex. 960 // When both operands are complex, the shorter operand is converted to the 961 // type of the longer, and that is the type of the result. This corresponds 962 // to what is done when combining two real floating-point operands. 963 // The fun begins when size promotion occur across type domains. 964 // From H&S 6.3.4: When one operand is complex and the other is a real 965 // floating-point type, the less precise type is converted, within it's 966 // real or complex domain, to the precision of the other type. For example, 967 // when combining a "long double" with a "double _Complex", the 968 // "double _Complex" is promoted to "long double _Complex". 969 970 // Compute the rank of the two types, regardless of whether they are complex. 971 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 972 973 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 974 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 975 QualType LHSElementType = 976 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 977 QualType RHSElementType = 978 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 979 980 QualType ResultType = S.Context.getComplexType(LHSElementType); 981 if (Order < 0) { 982 // Promote the precision of the LHS if not an assignment. 983 ResultType = S.Context.getComplexType(RHSElementType); 984 if (!IsCompAssign) { 985 if (LHSComplexType) 986 LHS = 987 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 988 else 989 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 990 } 991 } else if (Order > 0) { 992 // Promote the precision of the RHS. 993 if (RHSComplexType) 994 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 995 else 996 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 997 } 998 return ResultType; 999 } 1000 1001 /// \brief Handle arithmetic conversion from integer to float. Helper function 1002 /// of UsualArithmeticConversions() 1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1004 ExprResult &IntExpr, 1005 QualType FloatTy, QualType IntTy, 1006 bool ConvertFloat, bool ConvertInt) { 1007 if (IntTy->isIntegerType()) { 1008 if (ConvertInt) 1009 // Convert intExpr to the lhs floating point type. 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1011 CK_IntegralToFloating); 1012 return FloatTy; 1013 } 1014 1015 // Convert both sides to the appropriate complex float. 1016 assert(IntTy->isComplexIntegerType()); 1017 QualType result = S.Context.getComplexType(FloatTy); 1018 1019 // _Complex int -> _Complex float 1020 if (ConvertInt) 1021 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1022 CK_IntegralComplexToFloatingComplex); 1023 1024 // float -> _Complex float 1025 if (ConvertFloat) 1026 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1027 CK_FloatingRealToComplex); 1028 1029 return result; 1030 } 1031 1032 /// \brief Handle arithmethic conversion with floating point types. Helper 1033 /// function of UsualArithmeticConversions() 1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1035 ExprResult &RHS, QualType LHSType, 1036 QualType RHSType, bool IsCompAssign) { 1037 bool LHSFloat = LHSType->isRealFloatingType(); 1038 bool RHSFloat = RHSType->isRealFloatingType(); 1039 1040 // If we have two real floating types, convert the smaller operand 1041 // to the bigger result. 1042 if (LHSFloat && RHSFloat) { 1043 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1044 if (order > 0) { 1045 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1046 return LHSType; 1047 } 1048 1049 assert(order < 0 && "illegal float comparison"); 1050 if (!IsCompAssign) 1051 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1052 return RHSType; 1053 } 1054 1055 if (LHSFloat) { 1056 // Half FP has to be promoted to float unless it is natively supported 1057 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1058 LHSType = S.Context.FloatTy; 1059 1060 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1061 /*convertFloat=*/!IsCompAssign, 1062 /*convertInt=*/ true); 1063 } 1064 assert(RHSFloat); 1065 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1066 /*convertInt=*/ true, 1067 /*convertFloat=*/!IsCompAssign); 1068 } 1069 1070 /// \brief Diagnose attempts to convert between __float128 and long double if 1071 /// there is no support for such conversion. Helper function of 1072 /// UsualArithmeticConversions(). 1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1074 QualType RHSType) { 1075 /* No issue converting if at least one of the types is not a floating point 1076 type or the two types have the same rank. 1077 */ 1078 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1079 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1080 return false; 1081 1082 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1083 "The remaining types must be floating point types."); 1084 1085 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1086 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1087 1088 QualType LHSElemType = LHSComplex ? 1089 LHSComplex->getElementType() : LHSType; 1090 QualType RHSElemType = RHSComplex ? 1091 RHSComplex->getElementType() : RHSType; 1092 1093 // No issue if the two types have the same representation 1094 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1095 &S.Context.getFloatTypeSemantics(RHSElemType)) 1096 return false; 1097 1098 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1099 RHSElemType == S.Context.LongDoubleTy); 1100 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1101 RHSElemType == S.Context.Float128Ty); 1102 1103 // We've handled the situation where __float128 and long double have the same 1104 // representation. We allow all conversions for all possible long double types 1105 // except PPC's double double. 1106 return Float128AndLongDouble && 1107 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1108 &llvm::APFloat::PPCDoubleDouble()); 1109 } 1110 1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1112 1113 namespace { 1114 /// These helper callbacks are placed in an anonymous namespace to 1115 /// permit their use as function template parameters. 1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1117 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1118 } 1119 1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1121 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1122 CK_IntegralComplexCast); 1123 } 1124 } 1125 1126 /// \brief Handle integer arithmetic conversions. Helper function of 1127 /// UsualArithmeticConversions() 1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1130 ExprResult &RHS, QualType LHSType, 1131 QualType RHSType, bool IsCompAssign) { 1132 // The rules for this case are in C99 6.3.1.8 1133 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1134 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1135 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1136 if (LHSSigned == RHSSigned) { 1137 // Same signedness; use the higher-ranked type 1138 if (order >= 0) { 1139 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1140 return LHSType; 1141 } else if (!IsCompAssign) 1142 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1143 return RHSType; 1144 } else if (order != (LHSSigned ? 1 : -1)) { 1145 // The unsigned type has greater than or equal rank to the 1146 // signed type, so use the unsigned type 1147 if (RHSSigned) { 1148 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1149 return LHSType; 1150 } else if (!IsCompAssign) 1151 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1152 return RHSType; 1153 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1154 // The two types are different widths; if we are here, that 1155 // means the signed type is larger than the unsigned type, so 1156 // use the signed type. 1157 if (LHSSigned) { 1158 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1159 return LHSType; 1160 } else if (!IsCompAssign) 1161 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1162 return RHSType; 1163 } else { 1164 // The signed type is higher-ranked than the unsigned type, 1165 // but isn't actually any bigger (like unsigned int and long 1166 // on most 32-bit systems). Use the unsigned type corresponding 1167 // to the signed type. 1168 QualType result = 1169 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1170 RHS = (*doRHSCast)(S, RHS.get(), result); 1171 if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), result); 1173 return result; 1174 } 1175 } 1176 1177 /// \brief Handle conversions with GCC complex int extension. Helper function 1178 /// of UsualArithmeticConversions() 1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1180 ExprResult &RHS, QualType LHSType, 1181 QualType RHSType, 1182 bool IsCompAssign) { 1183 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1184 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1185 1186 if (LHSComplexInt && RHSComplexInt) { 1187 QualType LHSEltType = LHSComplexInt->getElementType(); 1188 QualType RHSEltType = RHSComplexInt->getElementType(); 1189 QualType ScalarType = 1190 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1191 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1192 1193 return S.Context.getComplexType(ScalarType); 1194 } 1195 1196 if (LHSComplexInt) { 1197 QualType LHSEltType = LHSComplexInt->getElementType(); 1198 QualType ScalarType = 1199 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1200 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1201 QualType ComplexType = S.Context.getComplexType(ScalarType); 1202 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1203 CK_IntegralRealToComplex); 1204 1205 return ComplexType; 1206 } 1207 1208 assert(RHSComplexInt); 1209 1210 QualType RHSEltType = RHSComplexInt->getElementType(); 1211 QualType ScalarType = 1212 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1213 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1214 QualType ComplexType = S.Context.getComplexType(ScalarType); 1215 1216 if (!IsCompAssign) 1217 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1218 CK_IntegralRealToComplex); 1219 return ComplexType; 1220 } 1221 1222 /// UsualArithmeticConversions - Performs various conversions that are common to 1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1224 /// routine returns the first non-arithmetic type found. The client is 1225 /// responsible for emitting appropriate error diagnostics. 1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1227 bool IsCompAssign) { 1228 if (!IsCompAssign) { 1229 LHS = UsualUnaryConversions(LHS.get()); 1230 if (LHS.isInvalid()) 1231 return QualType(); 1232 } 1233 1234 RHS = UsualUnaryConversions(RHS.get()); 1235 if (RHS.isInvalid()) 1236 return QualType(); 1237 1238 // For conversion purposes, we ignore any qualifiers. 1239 // For example, "const float" and "float" are equivalent. 1240 QualType LHSType = 1241 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1242 QualType RHSType = 1243 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1244 1245 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1246 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1247 LHSType = AtomicLHS->getValueType(); 1248 1249 // If both types are identical, no conversion is needed. 1250 if (LHSType == RHSType) 1251 return LHSType; 1252 1253 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1254 // The caller can deal with this (e.g. pointer + int). 1255 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1256 return QualType(); 1257 1258 // Apply unary and bitfield promotions to the LHS's type. 1259 QualType LHSUnpromotedType = LHSType; 1260 if (LHSType->isPromotableIntegerType()) 1261 LHSType = Context.getPromotedIntegerType(LHSType); 1262 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1263 if (!LHSBitfieldPromoteTy.isNull()) 1264 LHSType = LHSBitfieldPromoteTy; 1265 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1266 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1267 1268 // If both types are identical, no conversion is needed. 1269 if (LHSType == RHSType) 1270 return LHSType; 1271 1272 // At this point, we have two different arithmetic types. 1273 1274 // Diagnose attempts to convert between __float128 and long double where 1275 // such conversions currently can't be handled. 1276 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1277 return QualType(); 1278 1279 // Handle complex types first (C99 6.3.1.8p1). 1280 if (LHSType->isComplexType() || RHSType->isComplexType()) 1281 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1282 IsCompAssign); 1283 1284 // Now handle "real" floating types (i.e. float, double, long double). 1285 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1286 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1287 IsCompAssign); 1288 1289 // Handle GCC complex int extension. 1290 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1291 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1292 IsCompAssign); 1293 1294 // Finally, we have two differing integer types. 1295 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1296 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1297 } 1298 1299 1300 //===----------------------------------------------------------------------===// 1301 // Semantic Analysis for various Expression Types 1302 //===----------------------------------------------------------------------===// 1303 1304 1305 ExprResult 1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1307 SourceLocation DefaultLoc, 1308 SourceLocation RParenLoc, 1309 Expr *ControllingExpr, 1310 ArrayRef<ParsedType> ArgTypes, 1311 ArrayRef<Expr *> ArgExprs) { 1312 unsigned NumAssocs = ArgTypes.size(); 1313 assert(NumAssocs == ArgExprs.size()); 1314 1315 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1316 for (unsigned i = 0; i < NumAssocs; ++i) { 1317 if (ArgTypes[i]) 1318 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1319 else 1320 Types[i] = nullptr; 1321 } 1322 1323 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1324 ControllingExpr, 1325 llvm::makeArrayRef(Types, NumAssocs), 1326 ArgExprs); 1327 delete [] Types; 1328 return ER; 1329 } 1330 1331 ExprResult 1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1333 SourceLocation DefaultLoc, 1334 SourceLocation RParenLoc, 1335 Expr *ControllingExpr, 1336 ArrayRef<TypeSourceInfo *> Types, 1337 ArrayRef<Expr *> Exprs) { 1338 unsigned NumAssocs = Types.size(); 1339 assert(NumAssocs == Exprs.size()); 1340 1341 // Decay and strip qualifiers for the controlling expression type, and handle 1342 // placeholder type replacement. See committee discussion from WG14 DR423. 1343 { 1344 EnterExpressionEvaluationContext Unevaluated( 1345 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1346 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1347 if (R.isInvalid()) 1348 return ExprError(); 1349 ControllingExpr = R.get(); 1350 } 1351 1352 // The controlling expression is an unevaluated operand, so side effects are 1353 // likely unintended. 1354 if (!inTemplateInstantiation() && 1355 ControllingExpr->HasSideEffects(Context, false)) 1356 Diag(ControllingExpr->getExprLoc(), 1357 diag::warn_side_effects_unevaluated_context); 1358 1359 bool TypeErrorFound = false, 1360 IsResultDependent = ControllingExpr->isTypeDependent(), 1361 ContainsUnexpandedParameterPack 1362 = ControllingExpr->containsUnexpandedParameterPack(); 1363 1364 for (unsigned i = 0; i < NumAssocs; ++i) { 1365 if (Exprs[i]->containsUnexpandedParameterPack()) 1366 ContainsUnexpandedParameterPack = true; 1367 1368 if (Types[i]) { 1369 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1370 ContainsUnexpandedParameterPack = true; 1371 1372 if (Types[i]->getType()->isDependentType()) { 1373 IsResultDependent = true; 1374 } else { 1375 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1376 // complete object type other than a variably modified type." 1377 unsigned D = 0; 1378 if (Types[i]->getType()->isIncompleteType()) 1379 D = diag::err_assoc_type_incomplete; 1380 else if (!Types[i]->getType()->isObjectType()) 1381 D = diag::err_assoc_type_nonobject; 1382 else if (Types[i]->getType()->isVariablyModifiedType()) 1383 D = diag::err_assoc_type_variably_modified; 1384 1385 if (D != 0) { 1386 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1387 << Types[i]->getTypeLoc().getSourceRange() 1388 << Types[i]->getType(); 1389 TypeErrorFound = true; 1390 } 1391 1392 // C11 6.5.1.1p2 "No two generic associations in the same generic 1393 // selection shall specify compatible types." 1394 for (unsigned j = i+1; j < NumAssocs; ++j) 1395 if (Types[j] && !Types[j]->getType()->isDependentType() && 1396 Context.typesAreCompatible(Types[i]->getType(), 1397 Types[j]->getType())) { 1398 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1399 diag::err_assoc_compatible_types) 1400 << Types[j]->getTypeLoc().getSourceRange() 1401 << Types[j]->getType() 1402 << Types[i]->getType(); 1403 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1404 diag::note_compat_assoc) 1405 << Types[i]->getTypeLoc().getSourceRange() 1406 << Types[i]->getType(); 1407 TypeErrorFound = true; 1408 } 1409 } 1410 } 1411 } 1412 if (TypeErrorFound) 1413 return ExprError(); 1414 1415 // If we determined that the generic selection is result-dependent, don't 1416 // try to compute the result expression. 1417 if (IsResultDependent) 1418 return new (Context) GenericSelectionExpr( 1419 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1420 ContainsUnexpandedParameterPack); 1421 1422 SmallVector<unsigned, 1> CompatIndices; 1423 unsigned DefaultIndex = -1U; 1424 for (unsigned i = 0; i < NumAssocs; ++i) { 1425 if (!Types[i]) 1426 DefaultIndex = i; 1427 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1428 Types[i]->getType())) 1429 CompatIndices.push_back(i); 1430 } 1431 1432 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1433 // type compatible with at most one of the types named in its generic 1434 // association list." 1435 if (CompatIndices.size() > 1) { 1436 // We strip parens here because the controlling expression is typically 1437 // parenthesized in macro definitions. 1438 ControllingExpr = ControllingExpr->IgnoreParens(); 1439 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1441 << (unsigned) CompatIndices.size(); 1442 for (unsigned I : CompatIndices) { 1443 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1444 diag::note_compat_assoc) 1445 << Types[I]->getTypeLoc().getSourceRange() 1446 << Types[I]->getType(); 1447 } 1448 return ExprError(); 1449 } 1450 1451 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1452 // its controlling expression shall have type compatible with exactly one of 1453 // the types named in its generic association list." 1454 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1455 // We strip parens here because the controlling expression is typically 1456 // parenthesized in macro definitions. 1457 ControllingExpr = ControllingExpr->IgnoreParens(); 1458 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1459 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1460 return ExprError(); 1461 } 1462 1463 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1464 // type name that is compatible with the type of the controlling expression, 1465 // then the result expression of the generic selection is the expression 1466 // in that generic association. Otherwise, the result expression of the 1467 // generic selection is the expression in the default generic association." 1468 unsigned ResultIndex = 1469 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1470 1471 return new (Context) GenericSelectionExpr( 1472 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1473 ContainsUnexpandedParameterPack, ResultIndex); 1474 } 1475 1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1477 /// location of the token and the offset of the ud-suffix within it. 1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1479 unsigned Offset) { 1480 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1481 S.getLangOpts()); 1482 } 1483 1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1487 IdentifierInfo *UDSuffix, 1488 SourceLocation UDSuffixLoc, 1489 ArrayRef<Expr*> Args, 1490 SourceLocation LitEndLoc) { 1491 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1492 1493 QualType ArgTy[2]; 1494 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1495 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1496 if (ArgTy[ArgIdx]->isArrayType()) 1497 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1498 } 1499 1500 DeclarationName OpName = 1501 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1502 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1503 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1504 1505 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1506 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1507 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1508 /*AllowStringTemplate*/ false, 1509 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1510 return ExprError(); 1511 1512 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1513 } 1514 1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1516 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1518 /// multiple tokens. However, the common case is that StringToks points to one 1519 /// string. 1520 /// 1521 ExprResult 1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1523 assert(!StringToks.empty() && "Must have at least one string!"); 1524 1525 StringLiteralParser Literal(StringToks, PP); 1526 if (Literal.hadError) 1527 return ExprError(); 1528 1529 SmallVector<SourceLocation, 4> StringTokLocs; 1530 for (const Token &Tok : StringToks) 1531 StringTokLocs.push_back(Tok.getLocation()); 1532 1533 QualType CharTy = Context.CharTy; 1534 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1535 if (Literal.isWide()) { 1536 CharTy = Context.getWideCharType(); 1537 Kind = StringLiteral::Wide; 1538 } else if (Literal.isUTF8()) { 1539 if (getLangOpts().Char8) 1540 CharTy = Context.Char8Ty; 1541 Kind = StringLiteral::UTF8; 1542 } else if (Literal.isUTF16()) { 1543 CharTy = Context.Char16Ty; 1544 Kind = StringLiteral::UTF16; 1545 } else if (Literal.isUTF32()) { 1546 CharTy = Context.Char32Ty; 1547 Kind = StringLiteral::UTF32; 1548 } else if (Literal.isPascal()) { 1549 CharTy = Context.UnsignedCharTy; 1550 } 1551 1552 QualType CharTyConst = CharTy; 1553 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1554 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1555 CharTyConst.addConst(); 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(CharTyConst, 1561 llvm::APInt(32, Literal.GetNumStringChars()+1), 1562 ArrayType::Normal, 0); 1563 1564 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1565 if (getLangOpts().OpenCL) { 1566 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1567 } 1568 1569 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1570 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1571 Kind, Literal.Pascal, StrTy, 1572 &StringTokLocs[0], 1573 StringTokLocs.size()); 1574 if (Literal.getUDSuffix().empty()) 1575 return Lit; 1576 1577 // We're building a user-defined literal. 1578 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1579 SourceLocation UDSuffixLoc = 1580 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1581 Literal.getUDSuffixOffset()); 1582 1583 // Make sure we're allowed user-defined literals here. 1584 if (!UDLScope) 1585 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1586 1587 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1588 // operator "" X (str, len) 1589 QualType SizeType = Context.getSizeType(); 1590 1591 DeclarationName OpName = 1592 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1593 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1594 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1595 1596 QualType ArgTy[] = { 1597 Context.getArrayDecayedType(StrTy), SizeType 1598 }; 1599 1600 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1601 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1602 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1603 /*AllowStringTemplate*/ true, 1604 /*DiagnoseMissing*/ true)) { 1605 1606 case LOLR_Cooked: { 1607 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1608 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1609 StringTokLocs[0]); 1610 Expr *Args[] = { Lit, LenArg }; 1611 1612 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1613 } 1614 1615 case LOLR_StringTemplate: { 1616 TemplateArgumentListInfo ExplicitArgs; 1617 1618 unsigned CharBits = Context.getIntWidth(CharTy); 1619 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1620 llvm::APSInt Value(CharBits, CharIsUnsigned); 1621 1622 TemplateArgument TypeArg(CharTy); 1623 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1624 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1625 1626 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1627 Value = Lit->getCodeUnit(I); 1628 TemplateArgument Arg(Context, Value, CharTy); 1629 TemplateArgumentLocInfo ArgInfo; 1630 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1631 } 1632 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1633 &ExplicitArgs); 1634 } 1635 case LOLR_Raw: 1636 case LOLR_Template: 1637 case LOLR_ErrorNoDiagnostic: 1638 llvm_unreachable("unexpected literal operator lookup result"); 1639 case LOLR_Error: 1640 return ExprError(); 1641 } 1642 llvm_unreachable("unexpected literal operator lookup result"); 1643 } 1644 1645 ExprResult 1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1647 SourceLocation Loc, 1648 const CXXScopeSpec *SS) { 1649 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1650 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1651 } 1652 1653 /// BuildDeclRefExpr - Build an expression that references a 1654 /// declaration that does not require a closure capture. 1655 ExprResult 1656 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1657 const DeclarationNameInfo &NameInfo, 1658 const CXXScopeSpec *SS, NamedDecl *FoundD, 1659 const TemplateArgumentListInfo *TemplateArgs) { 1660 bool RefersToCapturedVariable = 1661 isa<VarDecl>(D) && 1662 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1663 1664 DeclRefExpr *E; 1665 if (isa<VarTemplateSpecializationDecl>(D)) { 1666 VarTemplateSpecializationDecl *VarSpec = 1667 cast<VarTemplateSpecializationDecl>(D); 1668 1669 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1670 : NestedNameSpecifierLoc(), 1671 VarSpec->getTemplateKeywordLoc(), D, 1672 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1673 FoundD, TemplateArgs); 1674 } else { 1675 assert(!TemplateArgs && "No template arguments for non-variable" 1676 " template specialization references"); 1677 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1678 : NestedNameSpecifierLoc(), 1679 SourceLocation(), D, RefersToCapturedVariable, 1680 NameInfo, Ty, VK, FoundD); 1681 } 1682 1683 MarkDeclRefReferenced(E); 1684 1685 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1686 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1687 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1688 getCurFunction()->recordUseOfWeak(E); 1689 1690 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1691 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1692 FD = IFD->getAnonField(); 1693 if (FD) { 1694 UnusedPrivateFields.remove(FD); 1695 // Just in case we're building an illegal pointer-to-member. 1696 if (FD->isBitField()) 1697 E->setObjectKind(OK_BitField); 1698 } 1699 1700 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1701 // designates a bit-field. 1702 if (auto *BD = dyn_cast<BindingDecl>(D)) 1703 if (auto *BE = BD->getBinding()) 1704 E->setObjectKind(BE->getObjectKind()); 1705 1706 return E; 1707 } 1708 1709 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1710 /// possibly a list of template arguments. 1711 /// 1712 /// If this produces template arguments, it is permitted to call 1713 /// DecomposeTemplateName. 1714 /// 1715 /// This actually loses a lot of source location information for 1716 /// non-standard name kinds; we should consider preserving that in 1717 /// some way. 1718 void 1719 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1720 TemplateArgumentListInfo &Buffer, 1721 DeclarationNameInfo &NameInfo, 1722 const TemplateArgumentListInfo *&TemplateArgs) { 1723 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1724 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1725 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1726 1727 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1728 Id.TemplateId->NumArgs); 1729 translateTemplateArguments(TemplateArgsPtr, Buffer); 1730 1731 TemplateName TName = Id.TemplateId->Template.get(); 1732 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1733 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1734 TemplateArgs = &Buffer; 1735 } else { 1736 NameInfo = GetNameFromUnqualifiedId(Id); 1737 TemplateArgs = nullptr; 1738 } 1739 } 1740 1741 static void emitEmptyLookupTypoDiagnostic( 1742 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1743 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1744 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1745 DeclContext *Ctx = 1746 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1747 if (!TC) { 1748 // Emit a special diagnostic for failed member lookups. 1749 // FIXME: computing the declaration context might fail here (?) 1750 if (Ctx) 1751 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1752 << SS.getRange(); 1753 else 1754 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1755 return; 1756 } 1757 1758 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1759 bool DroppedSpecifier = 1760 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1761 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1762 ? diag::note_implicit_param_decl 1763 : diag::note_previous_decl; 1764 if (!Ctx) 1765 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1766 SemaRef.PDiag(NoteID)); 1767 else 1768 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1769 << Typo << Ctx << DroppedSpecifier 1770 << SS.getRange(), 1771 SemaRef.PDiag(NoteID)); 1772 } 1773 1774 /// Diagnose an empty lookup. 1775 /// 1776 /// \return false if new lookup candidates were found 1777 bool 1778 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1779 std::unique_ptr<CorrectionCandidateCallback> CCC, 1780 TemplateArgumentListInfo *ExplicitTemplateArgs, 1781 ArrayRef<Expr *> Args, TypoExpr **Out) { 1782 DeclarationName Name = R.getLookupName(); 1783 1784 unsigned diagnostic = diag::err_undeclared_var_use; 1785 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1786 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1787 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1788 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1789 diagnostic = diag::err_undeclared_use; 1790 diagnostic_suggest = diag::err_undeclared_use_suggest; 1791 } 1792 1793 // If the original lookup was an unqualified lookup, fake an 1794 // unqualified lookup. This is useful when (for example) the 1795 // original lookup would not have found something because it was a 1796 // dependent name. 1797 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1798 while (DC) { 1799 if (isa<CXXRecordDecl>(DC)) { 1800 LookupQualifiedName(R, DC); 1801 1802 if (!R.empty()) { 1803 // Don't give errors about ambiguities in this lookup. 1804 R.suppressDiagnostics(); 1805 1806 // During a default argument instantiation the CurContext points 1807 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1808 // function parameter list, hence add an explicit check. 1809 bool isDefaultArgument = 1810 !CodeSynthesisContexts.empty() && 1811 CodeSynthesisContexts.back().Kind == 1812 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1813 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1814 bool isInstance = CurMethod && 1815 CurMethod->isInstance() && 1816 DC == CurMethod->getParent() && !isDefaultArgument; 1817 1818 // Give a code modification hint to insert 'this->'. 1819 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1820 // Actually quite difficult! 1821 if (getLangOpts().MSVCCompat) 1822 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1823 if (isInstance) { 1824 Diag(R.getNameLoc(), diagnostic) << Name 1825 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1826 CheckCXXThisCapture(R.getNameLoc()); 1827 } else { 1828 Diag(R.getNameLoc(), diagnostic) << Name; 1829 } 1830 1831 // Do we really want to note all of these? 1832 for (NamedDecl *D : R) 1833 Diag(D->getLocation(), diag::note_dependent_var_use); 1834 1835 // Return true if we are inside a default argument instantiation 1836 // and the found name refers to an instance member function, otherwise 1837 // the function calling DiagnoseEmptyLookup will try to create an 1838 // implicit member call and this is wrong for default argument. 1839 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1840 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1841 return true; 1842 } 1843 1844 // Tell the callee to try to recover. 1845 return false; 1846 } 1847 1848 R.clear(); 1849 } 1850 1851 // In Microsoft mode, if we are performing lookup from within a friend 1852 // function definition declared at class scope then we must set 1853 // DC to the lexical parent to be able to search into the parent 1854 // class. 1855 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1856 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1857 DC->getLexicalParent()->isRecord()) 1858 DC = DC->getLexicalParent(); 1859 else 1860 DC = DC->getParent(); 1861 } 1862 1863 // We didn't find anything, so try to correct for a typo. 1864 TypoCorrection Corrected; 1865 if (S && Out) { 1866 SourceLocation TypoLoc = R.getNameLoc(); 1867 assert(!ExplicitTemplateArgs && 1868 "Diagnosing an empty lookup with explicit template args!"); 1869 *Out = CorrectTypoDelayed( 1870 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1871 [=](const TypoCorrection &TC) { 1872 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1873 diagnostic, diagnostic_suggest); 1874 }, 1875 nullptr, CTK_ErrorRecovery); 1876 if (*Out) 1877 return true; 1878 } else if (S && (Corrected = 1879 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1880 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1881 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1882 bool DroppedSpecifier = 1883 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1884 R.setLookupName(Corrected.getCorrection()); 1885 1886 bool AcceptableWithRecovery = false; 1887 bool AcceptableWithoutRecovery = false; 1888 NamedDecl *ND = Corrected.getFoundDecl(); 1889 if (ND) { 1890 if (Corrected.isOverloaded()) { 1891 OverloadCandidateSet OCS(R.getNameLoc(), 1892 OverloadCandidateSet::CSK_Normal); 1893 OverloadCandidateSet::iterator Best; 1894 for (NamedDecl *CD : Corrected) { 1895 if (FunctionTemplateDecl *FTD = 1896 dyn_cast<FunctionTemplateDecl>(CD)) 1897 AddTemplateOverloadCandidate( 1898 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1899 Args, OCS); 1900 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1901 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1902 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1903 Args, OCS); 1904 } 1905 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1906 case OR_Success: 1907 ND = Best->FoundDecl; 1908 Corrected.setCorrectionDecl(ND); 1909 break; 1910 default: 1911 // FIXME: Arbitrarily pick the first declaration for the note. 1912 Corrected.setCorrectionDecl(ND); 1913 break; 1914 } 1915 } 1916 R.addDecl(ND); 1917 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1918 CXXRecordDecl *Record = nullptr; 1919 if (Corrected.getCorrectionSpecifier()) { 1920 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1921 Record = Ty->getAsCXXRecordDecl(); 1922 } 1923 if (!Record) 1924 Record = cast<CXXRecordDecl>( 1925 ND->getDeclContext()->getRedeclContext()); 1926 R.setNamingClass(Record); 1927 } 1928 1929 auto *UnderlyingND = ND->getUnderlyingDecl(); 1930 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1931 isa<FunctionTemplateDecl>(UnderlyingND); 1932 // FIXME: If we ended up with a typo for a type name or 1933 // Objective-C class name, we're in trouble because the parser 1934 // is in the wrong place to recover. Suggest the typo 1935 // correction, but don't make it a fix-it since we're not going 1936 // to recover well anyway. 1937 AcceptableWithoutRecovery = 1938 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1939 } else { 1940 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1941 // because we aren't able to recover. 1942 AcceptableWithoutRecovery = true; 1943 } 1944 1945 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1946 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1947 ? diag::note_implicit_param_decl 1948 : diag::note_previous_decl; 1949 if (SS.isEmpty()) 1950 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1951 PDiag(NoteID), AcceptableWithRecovery); 1952 else 1953 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1954 << Name << computeDeclContext(SS, false) 1955 << DroppedSpecifier << SS.getRange(), 1956 PDiag(NoteID), AcceptableWithRecovery); 1957 1958 // Tell the callee whether to try to recover. 1959 return !AcceptableWithRecovery; 1960 } 1961 } 1962 R.clear(); 1963 1964 // Emit a special diagnostic for failed member lookups. 1965 // FIXME: computing the declaration context might fail here (?) 1966 if (!SS.isEmpty()) { 1967 Diag(R.getNameLoc(), diag::err_no_member) 1968 << Name << computeDeclContext(SS, false) 1969 << SS.getRange(); 1970 return true; 1971 } 1972 1973 // Give up, we can't recover. 1974 Diag(R.getNameLoc(), diagnostic) << Name; 1975 return true; 1976 } 1977 1978 /// In Microsoft mode, if we are inside a template class whose parent class has 1979 /// dependent base classes, and we can't resolve an unqualified identifier, then 1980 /// assume the identifier is a member of a dependent base class. We can only 1981 /// recover successfully in static methods, instance methods, and other contexts 1982 /// where 'this' is available. This doesn't precisely match MSVC's 1983 /// instantiation model, but it's close enough. 1984 static Expr * 1985 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1986 DeclarationNameInfo &NameInfo, 1987 SourceLocation TemplateKWLoc, 1988 const TemplateArgumentListInfo *TemplateArgs) { 1989 // Only try to recover from lookup into dependent bases in static methods or 1990 // contexts where 'this' is available. 1991 QualType ThisType = S.getCurrentThisType(); 1992 const CXXRecordDecl *RD = nullptr; 1993 if (!ThisType.isNull()) 1994 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1995 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1996 RD = MD->getParent(); 1997 if (!RD || !RD->hasAnyDependentBases()) 1998 return nullptr; 1999 2000 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2001 // is available, suggest inserting 'this->' as a fixit. 2002 SourceLocation Loc = NameInfo.getLoc(); 2003 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2004 DB << NameInfo.getName() << RD; 2005 2006 if (!ThisType.isNull()) { 2007 DB << FixItHint::CreateInsertion(Loc, "this->"); 2008 return CXXDependentScopeMemberExpr::Create( 2009 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2010 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2011 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2012 } 2013 2014 // Synthesize a fake NNS that points to the derived class. This will 2015 // perform name lookup during template instantiation. 2016 CXXScopeSpec SS; 2017 auto *NNS = 2018 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2019 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2020 return DependentScopeDeclRefExpr::Create( 2021 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2022 TemplateArgs); 2023 } 2024 2025 ExprResult 2026 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2027 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2028 bool HasTrailingLParen, bool IsAddressOfOperand, 2029 std::unique_ptr<CorrectionCandidateCallback> CCC, 2030 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2031 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2032 "cannot be direct & operand and have a trailing lparen"); 2033 if (SS.isInvalid()) 2034 return ExprError(); 2035 2036 TemplateArgumentListInfo TemplateArgsBuffer; 2037 2038 // Decompose the UnqualifiedId into the following data. 2039 DeclarationNameInfo NameInfo; 2040 const TemplateArgumentListInfo *TemplateArgs; 2041 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2042 2043 DeclarationName Name = NameInfo.getName(); 2044 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2045 SourceLocation NameLoc = NameInfo.getLoc(); 2046 2047 if (II && II->isEditorPlaceholder()) { 2048 // FIXME: When typed placeholders are supported we can create a typed 2049 // placeholder expression node. 2050 return ExprError(); 2051 } 2052 2053 // C++ [temp.dep.expr]p3: 2054 // An id-expression is type-dependent if it contains: 2055 // -- an identifier that was declared with a dependent type, 2056 // (note: handled after lookup) 2057 // -- a template-id that is dependent, 2058 // (note: handled in BuildTemplateIdExpr) 2059 // -- a conversion-function-id that specifies a dependent type, 2060 // -- a nested-name-specifier that contains a class-name that 2061 // names a dependent type. 2062 // Determine whether this is a member of an unknown specialization; 2063 // we need to handle these differently. 2064 bool DependentID = false; 2065 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2066 Name.getCXXNameType()->isDependentType()) { 2067 DependentID = true; 2068 } else if (SS.isSet()) { 2069 if (DeclContext *DC = computeDeclContext(SS, false)) { 2070 if (RequireCompleteDeclContext(SS, DC)) 2071 return ExprError(); 2072 } else { 2073 DependentID = true; 2074 } 2075 } 2076 2077 if (DependentID) 2078 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2079 IsAddressOfOperand, TemplateArgs); 2080 2081 // Perform the required lookup. 2082 LookupResult R(*this, NameInfo, 2083 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2084 ? LookupObjCImplicitSelfParam 2085 : LookupOrdinaryName); 2086 if (TemplateKWLoc.isValid() || TemplateArgs) { 2087 // Lookup the template name again to correctly establish the context in 2088 // which it was found. This is really unfortunate as we already did the 2089 // lookup to determine that it was a template name in the first place. If 2090 // this becomes a performance hit, we can work harder to preserve those 2091 // results until we get here but it's likely not worth it. 2092 bool MemberOfUnknownSpecialization; 2093 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2094 MemberOfUnknownSpecialization); 2095 2096 if (MemberOfUnknownSpecialization || 2097 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2098 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2099 IsAddressOfOperand, TemplateArgs); 2100 } else { 2101 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2102 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2103 2104 // If the result might be in a dependent base class, this is a dependent 2105 // id-expression. 2106 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2107 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2108 IsAddressOfOperand, TemplateArgs); 2109 2110 // If this reference is in an Objective-C method, then we need to do 2111 // some special Objective-C lookup, too. 2112 if (IvarLookupFollowUp) { 2113 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2114 if (E.isInvalid()) 2115 return ExprError(); 2116 2117 if (Expr *Ex = E.getAs<Expr>()) 2118 return Ex; 2119 } 2120 } 2121 2122 if (R.isAmbiguous()) 2123 return ExprError(); 2124 2125 // This could be an implicitly declared function reference (legal in C90, 2126 // extension in C99, forbidden in C++). 2127 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2128 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2129 if (D) R.addDecl(D); 2130 } 2131 2132 // Determine whether this name might be a candidate for 2133 // argument-dependent lookup. 2134 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2135 2136 if (R.empty() && !ADL) { 2137 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2138 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2139 TemplateKWLoc, TemplateArgs)) 2140 return E; 2141 } 2142 2143 // Don't diagnose an empty lookup for inline assembly. 2144 if (IsInlineAsmIdentifier) 2145 return ExprError(); 2146 2147 // If this name wasn't predeclared and if this is not a function 2148 // call, diagnose the problem. 2149 TypoExpr *TE = nullptr; 2150 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2151 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2152 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2153 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2154 "Typo correction callback misconfigured"); 2155 if (CCC) { 2156 // Make sure the callback knows what the typo being diagnosed is. 2157 CCC->setTypoName(II); 2158 if (SS.isValid()) 2159 CCC->setTypoNNS(SS.getScopeRep()); 2160 } 2161 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2162 // a template name, but we happen to have always already looked up the name 2163 // before we get here if it must be a template name. 2164 if (DiagnoseEmptyLookup(S, SS, R, 2165 CCC ? std::move(CCC) : std::move(DefaultValidator), 2166 nullptr, None, &TE)) { 2167 if (TE && KeywordReplacement) { 2168 auto &State = getTypoExprState(TE); 2169 auto BestTC = State.Consumer->getNextCorrection(); 2170 if (BestTC.isKeyword()) { 2171 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2172 if (State.DiagHandler) 2173 State.DiagHandler(BestTC); 2174 KeywordReplacement->startToken(); 2175 KeywordReplacement->setKind(II->getTokenID()); 2176 KeywordReplacement->setIdentifierInfo(II); 2177 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2178 // Clean up the state associated with the TypoExpr, since it has 2179 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2180 clearDelayedTypo(TE); 2181 // Signal that a correction to a keyword was performed by returning a 2182 // valid-but-null ExprResult. 2183 return (Expr*)nullptr; 2184 } 2185 State.Consumer->resetCorrectionStream(); 2186 } 2187 return TE ? TE : ExprError(); 2188 } 2189 2190 assert(!R.empty() && 2191 "DiagnoseEmptyLookup returned false but added no results"); 2192 2193 // If we found an Objective-C instance variable, let 2194 // LookupInObjCMethod build the appropriate expression to 2195 // reference the ivar. 2196 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2197 R.clear(); 2198 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2199 // In a hopelessly buggy code, Objective-C instance variable 2200 // lookup fails and no expression will be built to reference it. 2201 if (!E.isInvalid() && !E.get()) 2202 return ExprError(); 2203 return E; 2204 } 2205 } 2206 2207 // This is guaranteed from this point on. 2208 assert(!R.empty() || ADL); 2209 2210 // Check whether this might be a C++ implicit instance member access. 2211 // C++ [class.mfct.non-static]p3: 2212 // When an id-expression that is not part of a class member access 2213 // syntax and not used to form a pointer to member is used in the 2214 // body of a non-static member function of class X, if name lookup 2215 // resolves the name in the id-expression to a non-static non-type 2216 // member of some class C, the id-expression is transformed into a 2217 // class member access expression using (*this) as the 2218 // postfix-expression to the left of the . operator. 2219 // 2220 // But we don't actually need to do this for '&' operands if R 2221 // resolved to a function or overloaded function set, because the 2222 // expression is ill-formed if it actually works out to be a 2223 // non-static member function: 2224 // 2225 // C++ [expr.ref]p4: 2226 // Otherwise, if E1.E2 refers to a non-static member function. . . 2227 // [t]he expression can be used only as the left-hand operand of a 2228 // member function call. 2229 // 2230 // There are other safeguards against such uses, but it's important 2231 // to get this right here so that we don't end up making a 2232 // spuriously dependent expression if we're inside a dependent 2233 // instance method. 2234 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2235 bool MightBeImplicitMember; 2236 if (!IsAddressOfOperand) 2237 MightBeImplicitMember = true; 2238 else if (!SS.isEmpty()) 2239 MightBeImplicitMember = false; 2240 else if (R.isOverloadedResult()) 2241 MightBeImplicitMember = false; 2242 else if (R.isUnresolvableResult()) 2243 MightBeImplicitMember = true; 2244 else 2245 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2246 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2247 isa<MSPropertyDecl>(R.getFoundDecl()); 2248 2249 if (MightBeImplicitMember) 2250 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2251 R, TemplateArgs, S); 2252 } 2253 2254 if (TemplateArgs || TemplateKWLoc.isValid()) { 2255 2256 // In C++1y, if this is a variable template id, then check it 2257 // in BuildTemplateIdExpr(). 2258 // The single lookup result must be a variable template declaration. 2259 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2260 Id.TemplateId->Kind == TNK_Var_template) { 2261 assert(R.getAsSingle<VarTemplateDecl>() && 2262 "There should only be one declaration found."); 2263 } 2264 2265 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2266 } 2267 2268 return BuildDeclarationNameExpr(SS, R, ADL); 2269 } 2270 2271 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2272 /// declaration name, generally during template instantiation. 2273 /// There's a large number of things which don't need to be done along 2274 /// this path. 2275 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2276 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2277 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2278 DeclContext *DC = computeDeclContext(SS, false); 2279 if (!DC) 2280 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2281 NameInfo, /*TemplateArgs=*/nullptr); 2282 2283 if (RequireCompleteDeclContext(SS, DC)) 2284 return ExprError(); 2285 2286 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2287 LookupQualifiedName(R, DC); 2288 2289 if (R.isAmbiguous()) 2290 return ExprError(); 2291 2292 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2293 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2294 NameInfo, /*TemplateArgs=*/nullptr); 2295 2296 if (R.empty()) { 2297 Diag(NameInfo.getLoc(), diag::err_no_member) 2298 << NameInfo.getName() << DC << SS.getRange(); 2299 return ExprError(); 2300 } 2301 2302 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2303 // Diagnose a missing typename if this resolved unambiguously to a type in 2304 // a dependent context. If we can recover with a type, downgrade this to 2305 // a warning in Microsoft compatibility mode. 2306 unsigned DiagID = diag::err_typename_missing; 2307 if (RecoveryTSI && getLangOpts().MSVCCompat) 2308 DiagID = diag::ext_typename_missing; 2309 SourceLocation Loc = SS.getBeginLoc(); 2310 auto D = Diag(Loc, DiagID); 2311 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2312 << SourceRange(Loc, NameInfo.getEndLoc()); 2313 2314 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2315 // context. 2316 if (!RecoveryTSI) 2317 return ExprError(); 2318 2319 // Only issue the fixit if we're prepared to recover. 2320 D << FixItHint::CreateInsertion(Loc, "typename "); 2321 2322 // Recover by pretending this was an elaborated type. 2323 QualType Ty = Context.getTypeDeclType(TD); 2324 TypeLocBuilder TLB; 2325 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2326 2327 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2328 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2329 QTL.setElaboratedKeywordLoc(SourceLocation()); 2330 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2331 2332 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2333 2334 return ExprEmpty(); 2335 } 2336 2337 // Defend against this resolving to an implicit member access. We usually 2338 // won't get here if this might be a legitimate a class member (we end up in 2339 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2340 // a pointer-to-member or in an unevaluated context in C++11. 2341 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2342 return BuildPossibleImplicitMemberExpr(SS, 2343 /*TemplateKWLoc=*/SourceLocation(), 2344 R, /*TemplateArgs=*/nullptr, S); 2345 2346 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2347 } 2348 2349 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2350 /// detected that we're currently inside an ObjC method. Perform some 2351 /// additional lookup. 2352 /// 2353 /// Ideally, most of this would be done by lookup, but there's 2354 /// actually quite a lot of extra work involved. 2355 /// 2356 /// Returns a null sentinel to indicate trivial success. 2357 ExprResult 2358 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2359 IdentifierInfo *II, bool AllowBuiltinCreation) { 2360 SourceLocation Loc = Lookup.getNameLoc(); 2361 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2362 2363 // Check for error condition which is already reported. 2364 if (!CurMethod) 2365 return ExprError(); 2366 2367 // There are two cases to handle here. 1) scoped lookup could have failed, 2368 // in which case we should look for an ivar. 2) scoped lookup could have 2369 // found a decl, but that decl is outside the current instance method (i.e. 2370 // a global variable). In these two cases, we do a lookup for an ivar with 2371 // this name, if the lookup sucedes, we replace it our current decl. 2372 2373 // If we're in a class method, we don't normally want to look for 2374 // ivars. But if we don't find anything else, and there's an 2375 // ivar, that's an error. 2376 bool IsClassMethod = CurMethod->isClassMethod(); 2377 2378 bool LookForIvars; 2379 if (Lookup.empty()) 2380 LookForIvars = true; 2381 else if (IsClassMethod) 2382 LookForIvars = false; 2383 else 2384 LookForIvars = (Lookup.isSingleResult() && 2385 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2386 ObjCInterfaceDecl *IFace = nullptr; 2387 if (LookForIvars) { 2388 IFace = CurMethod->getClassInterface(); 2389 ObjCInterfaceDecl *ClassDeclared; 2390 ObjCIvarDecl *IV = nullptr; 2391 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2392 // Diagnose using an ivar in a class method. 2393 if (IsClassMethod) 2394 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2395 << IV->getDeclName()); 2396 2397 // If we're referencing an invalid decl, just return this as a silent 2398 // error node. The error diagnostic was already emitted on the decl. 2399 if (IV->isInvalidDecl()) 2400 return ExprError(); 2401 2402 // Check if referencing a field with __attribute__((deprecated)). 2403 if (DiagnoseUseOfDecl(IV, Loc)) 2404 return ExprError(); 2405 2406 // Diagnose the use of an ivar outside of the declaring class. 2407 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2408 !declaresSameEntity(ClassDeclared, IFace) && 2409 !getLangOpts().DebuggerSupport) 2410 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2411 2412 // FIXME: This should use a new expr for a direct reference, don't 2413 // turn this into Self->ivar, just return a BareIVarExpr or something. 2414 IdentifierInfo &II = Context.Idents.get("self"); 2415 UnqualifiedId SelfName; 2416 SelfName.setIdentifier(&II, SourceLocation()); 2417 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2418 CXXScopeSpec SelfScopeSpec; 2419 SourceLocation TemplateKWLoc; 2420 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2421 SelfName, false, false); 2422 if (SelfExpr.isInvalid()) 2423 return ExprError(); 2424 2425 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2426 if (SelfExpr.isInvalid()) 2427 return ExprError(); 2428 2429 MarkAnyDeclReferenced(Loc, IV, true); 2430 2431 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2432 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2433 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2434 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2435 2436 ObjCIvarRefExpr *Result = new (Context) 2437 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2438 IV->getLocation(), SelfExpr.get(), true, true); 2439 2440 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2441 if (!isUnevaluatedContext() && 2442 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2443 getCurFunction()->recordUseOfWeak(Result); 2444 } 2445 if (getLangOpts().ObjCAutoRefCount) { 2446 if (CurContext->isClosure()) 2447 Diag(Loc, diag::warn_implicitly_retains_self) 2448 << FixItHint::CreateInsertion(Loc, "self->"); 2449 } 2450 2451 return Result; 2452 } 2453 } else if (CurMethod->isInstanceMethod()) { 2454 // We should warn if a local variable hides an ivar. 2455 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2456 ObjCInterfaceDecl *ClassDeclared; 2457 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2458 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2459 declaresSameEntity(IFace, ClassDeclared)) 2460 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2461 } 2462 } 2463 } else if (Lookup.isSingleResult() && 2464 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2465 // If accessing a stand-alone ivar in a class method, this is an error. 2466 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2467 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2468 << IV->getDeclName()); 2469 } 2470 2471 if (Lookup.empty() && II && AllowBuiltinCreation) { 2472 // FIXME. Consolidate this with similar code in LookupName. 2473 if (unsigned BuiltinID = II->getBuiltinID()) { 2474 if (!(getLangOpts().CPlusPlus && 2475 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2476 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2477 S, Lookup.isForRedeclaration(), 2478 Lookup.getNameLoc()); 2479 if (D) Lookup.addDecl(D); 2480 } 2481 } 2482 } 2483 // Sentinel value saying that we didn't do anything special. 2484 return ExprResult((Expr *)nullptr); 2485 } 2486 2487 /// \brief Cast a base object to a member's actual type. 2488 /// 2489 /// Logically this happens in three phases: 2490 /// 2491 /// * First we cast from the base type to the naming class. 2492 /// The naming class is the class into which we were looking 2493 /// when we found the member; it's the qualifier type if a 2494 /// qualifier was provided, and otherwise it's the base type. 2495 /// 2496 /// * Next we cast from the naming class to the declaring class. 2497 /// If the member we found was brought into a class's scope by 2498 /// a using declaration, this is that class; otherwise it's 2499 /// the class declaring the member. 2500 /// 2501 /// * Finally we cast from the declaring class to the "true" 2502 /// declaring class of the member. This conversion does not 2503 /// obey access control. 2504 ExprResult 2505 Sema::PerformObjectMemberConversion(Expr *From, 2506 NestedNameSpecifier *Qualifier, 2507 NamedDecl *FoundDecl, 2508 NamedDecl *Member) { 2509 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2510 if (!RD) 2511 return From; 2512 2513 QualType DestRecordType; 2514 QualType DestType; 2515 QualType FromRecordType; 2516 QualType FromType = From->getType(); 2517 bool PointerConversions = false; 2518 if (isa<FieldDecl>(Member)) { 2519 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2520 2521 if (FromType->getAs<PointerType>()) { 2522 DestType = Context.getPointerType(DestRecordType); 2523 FromRecordType = FromType->getPointeeType(); 2524 PointerConversions = true; 2525 } else { 2526 DestType = DestRecordType; 2527 FromRecordType = FromType; 2528 } 2529 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2530 if (Method->isStatic()) 2531 return From; 2532 2533 DestType = Method->getThisType(Context); 2534 DestRecordType = DestType->getPointeeType(); 2535 2536 if (FromType->getAs<PointerType>()) { 2537 FromRecordType = FromType->getPointeeType(); 2538 PointerConversions = true; 2539 } else { 2540 FromRecordType = FromType; 2541 DestType = DestRecordType; 2542 } 2543 } else { 2544 // No conversion necessary. 2545 return From; 2546 } 2547 2548 if (DestType->isDependentType() || FromType->isDependentType()) 2549 return From; 2550 2551 // If the unqualified types are the same, no conversion is necessary. 2552 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2553 return From; 2554 2555 SourceRange FromRange = From->getSourceRange(); 2556 SourceLocation FromLoc = FromRange.getBegin(); 2557 2558 ExprValueKind VK = From->getValueKind(); 2559 2560 // C++ [class.member.lookup]p8: 2561 // [...] Ambiguities can often be resolved by qualifying a name with its 2562 // class name. 2563 // 2564 // If the member was a qualified name and the qualified referred to a 2565 // specific base subobject type, we'll cast to that intermediate type 2566 // first and then to the object in which the member is declared. That allows 2567 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2568 // 2569 // class Base { public: int x; }; 2570 // class Derived1 : public Base { }; 2571 // class Derived2 : public Base { }; 2572 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2573 // 2574 // void VeryDerived::f() { 2575 // x = 17; // error: ambiguous base subobjects 2576 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2577 // } 2578 if (Qualifier && Qualifier->getAsType()) { 2579 QualType QType = QualType(Qualifier->getAsType(), 0); 2580 assert(QType->isRecordType() && "lookup done with non-record type"); 2581 2582 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2583 2584 // In C++98, the qualifier type doesn't actually have to be a base 2585 // type of the object type, in which case we just ignore it. 2586 // Otherwise build the appropriate casts. 2587 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2588 CXXCastPath BasePath; 2589 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2590 FromLoc, FromRange, &BasePath)) 2591 return ExprError(); 2592 2593 if (PointerConversions) 2594 QType = Context.getPointerType(QType); 2595 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2596 VK, &BasePath).get(); 2597 2598 FromType = QType; 2599 FromRecordType = QRecordType; 2600 2601 // If the qualifier type was the same as the destination type, 2602 // we're done. 2603 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2604 return From; 2605 } 2606 } 2607 2608 bool IgnoreAccess = false; 2609 2610 // If we actually found the member through a using declaration, cast 2611 // down to the using declaration's type. 2612 // 2613 // Pointer equality is fine here because only one declaration of a 2614 // class ever has member declarations. 2615 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2616 assert(isa<UsingShadowDecl>(FoundDecl)); 2617 QualType URecordType = Context.getTypeDeclType( 2618 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2619 2620 // We only need to do this if the naming-class to declaring-class 2621 // conversion is non-trivial. 2622 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2623 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2624 CXXCastPath BasePath; 2625 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2626 FromLoc, FromRange, &BasePath)) 2627 return ExprError(); 2628 2629 QualType UType = URecordType; 2630 if (PointerConversions) 2631 UType = Context.getPointerType(UType); 2632 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2633 VK, &BasePath).get(); 2634 FromType = UType; 2635 FromRecordType = URecordType; 2636 } 2637 2638 // We don't do access control for the conversion from the 2639 // declaring class to the true declaring class. 2640 IgnoreAccess = true; 2641 } 2642 2643 CXXCastPath BasePath; 2644 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2645 FromLoc, FromRange, &BasePath, 2646 IgnoreAccess)) 2647 return ExprError(); 2648 2649 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2650 VK, &BasePath); 2651 } 2652 2653 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2654 const LookupResult &R, 2655 bool HasTrailingLParen) { 2656 // Only when used directly as the postfix-expression of a call. 2657 if (!HasTrailingLParen) 2658 return false; 2659 2660 // Never if a scope specifier was provided. 2661 if (SS.isSet()) 2662 return false; 2663 2664 // Only in C++ or ObjC++. 2665 if (!getLangOpts().CPlusPlus) 2666 return false; 2667 2668 // Turn off ADL when we find certain kinds of declarations during 2669 // normal lookup: 2670 for (NamedDecl *D : R) { 2671 // C++0x [basic.lookup.argdep]p3: 2672 // -- a declaration of a class member 2673 // Since using decls preserve this property, we check this on the 2674 // original decl. 2675 if (D->isCXXClassMember()) 2676 return false; 2677 2678 // C++0x [basic.lookup.argdep]p3: 2679 // -- a block-scope function declaration that is not a 2680 // using-declaration 2681 // NOTE: we also trigger this for function templates (in fact, we 2682 // don't check the decl type at all, since all other decl types 2683 // turn off ADL anyway). 2684 if (isa<UsingShadowDecl>(D)) 2685 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2686 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2687 return false; 2688 2689 // C++0x [basic.lookup.argdep]p3: 2690 // -- a declaration that is neither a function or a function 2691 // template 2692 // And also for builtin functions. 2693 if (isa<FunctionDecl>(D)) { 2694 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2695 2696 // But also builtin functions. 2697 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2698 return false; 2699 } else if (!isa<FunctionTemplateDecl>(D)) 2700 return false; 2701 } 2702 2703 return true; 2704 } 2705 2706 2707 /// Diagnoses obvious problems with the use of the given declaration 2708 /// as an expression. This is only actually called for lookups that 2709 /// were not overloaded, and it doesn't promise that the declaration 2710 /// will in fact be used. 2711 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2712 if (D->isInvalidDecl()) 2713 return true; 2714 2715 if (isa<TypedefNameDecl>(D)) { 2716 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2717 return true; 2718 } 2719 2720 if (isa<ObjCInterfaceDecl>(D)) { 2721 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2722 return true; 2723 } 2724 2725 if (isa<NamespaceDecl>(D)) { 2726 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2727 return true; 2728 } 2729 2730 return false; 2731 } 2732 2733 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2734 LookupResult &R, bool NeedsADL, 2735 bool AcceptInvalidDecl) { 2736 // If this is a single, fully-resolved result and we don't need ADL, 2737 // just build an ordinary singleton decl ref. 2738 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2739 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2740 R.getRepresentativeDecl(), nullptr, 2741 AcceptInvalidDecl); 2742 2743 // We only need to check the declaration if there's exactly one 2744 // result, because in the overloaded case the results can only be 2745 // functions and function templates. 2746 if (R.isSingleResult() && 2747 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2748 return ExprError(); 2749 2750 // Otherwise, just build an unresolved lookup expression. Suppress 2751 // any lookup-related diagnostics; we'll hash these out later, when 2752 // we've picked a target. 2753 R.suppressDiagnostics(); 2754 2755 UnresolvedLookupExpr *ULE 2756 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2757 SS.getWithLocInContext(Context), 2758 R.getLookupNameInfo(), 2759 NeedsADL, R.isOverloadedResult(), 2760 R.begin(), R.end()); 2761 2762 return ULE; 2763 } 2764 2765 static void 2766 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2767 ValueDecl *var, DeclContext *DC); 2768 2769 /// \brief Complete semantic analysis for a reference to the given declaration. 2770 ExprResult Sema::BuildDeclarationNameExpr( 2771 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2772 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2773 bool AcceptInvalidDecl) { 2774 assert(D && "Cannot refer to a NULL declaration"); 2775 assert(!isa<FunctionTemplateDecl>(D) && 2776 "Cannot refer unambiguously to a function template"); 2777 2778 SourceLocation Loc = NameInfo.getLoc(); 2779 if (CheckDeclInExpr(*this, Loc, D)) 2780 return ExprError(); 2781 2782 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2783 // Specifically diagnose references to class templates that are missing 2784 // a template argument list. 2785 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2786 return ExprError(); 2787 } 2788 2789 // Make sure that we're referring to a value. 2790 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2791 if (!VD) { 2792 Diag(Loc, diag::err_ref_non_value) 2793 << D << SS.getRange(); 2794 Diag(D->getLocation(), diag::note_declared_at); 2795 return ExprError(); 2796 } 2797 2798 // Check whether this declaration can be used. Note that we suppress 2799 // this check when we're going to perform argument-dependent lookup 2800 // on this function name, because this might not be the function 2801 // that overload resolution actually selects. 2802 if (DiagnoseUseOfDecl(VD, Loc)) 2803 return ExprError(); 2804 2805 // Only create DeclRefExpr's for valid Decl's. 2806 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2807 return ExprError(); 2808 2809 // Handle members of anonymous structs and unions. If we got here, 2810 // and the reference is to a class member indirect field, then this 2811 // must be the subject of a pointer-to-member expression. 2812 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2813 if (!indirectField->isCXXClassMember()) 2814 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2815 indirectField); 2816 2817 { 2818 QualType type = VD->getType(); 2819 if (type.isNull()) 2820 return ExprError(); 2821 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2822 // C++ [except.spec]p17: 2823 // An exception-specification is considered to be needed when: 2824 // - in an expression, the function is the unique lookup result or 2825 // the selected member of a set of overloaded functions. 2826 ResolveExceptionSpec(Loc, FPT); 2827 type = VD->getType(); 2828 } 2829 ExprValueKind valueKind = VK_RValue; 2830 2831 switch (D->getKind()) { 2832 // Ignore all the non-ValueDecl kinds. 2833 #define ABSTRACT_DECL(kind) 2834 #define VALUE(type, base) 2835 #define DECL(type, base) \ 2836 case Decl::type: 2837 #include "clang/AST/DeclNodes.inc" 2838 llvm_unreachable("invalid value decl kind"); 2839 2840 // These shouldn't make it here. 2841 case Decl::ObjCAtDefsField: 2842 case Decl::ObjCIvar: 2843 llvm_unreachable("forming non-member reference to ivar?"); 2844 2845 // Enum constants are always r-values and never references. 2846 // Unresolved using declarations are dependent. 2847 case Decl::EnumConstant: 2848 case Decl::UnresolvedUsingValue: 2849 case Decl::OMPDeclareReduction: 2850 valueKind = VK_RValue; 2851 break; 2852 2853 // Fields and indirect fields that got here must be for 2854 // pointer-to-member expressions; we just call them l-values for 2855 // internal consistency, because this subexpression doesn't really 2856 // exist in the high-level semantics. 2857 case Decl::Field: 2858 case Decl::IndirectField: 2859 assert(getLangOpts().CPlusPlus && 2860 "building reference to field in C?"); 2861 2862 // These can't have reference type in well-formed programs, but 2863 // for internal consistency we do this anyway. 2864 type = type.getNonReferenceType(); 2865 valueKind = VK_LValue; 2866 break; 2867 2868 // Non-type template parameters are either l-values or r-values 2869 // depending on the type. 2870 case Decl::NonTypeTemplateParm: { 2871 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2872 type = reftype->getPointeeType(); 2873 valueKind = VK_LValue; // even if the parameter is an r-value reference 2874 break; 2875 } 2876 2877 // For non-references, we need to strip qualifiers just in case 2878 // the template parameter was declared as 'const int' or whatever. 2879 valueKind = VK_RValue; 2880 type = type.getUnqualifiedType(); 2881 break; 2882 } 2883 2884 case Decl::Var: 2885 case Decl::VarTemplateSpecialization: 2886 case Decl::VarTemplatePartialSpecialization: 2887 case Decl::Decomposition: 2888 case Decl::OMPCapturedExpr: 2889 // In C, "extern void blah;" is valid and is an r-value. 2890 if (!getLangOpts().CPlusPlus && 2891 !type.hasQualifiers() && 2892 type->isVoidType()) { 2893 valueKind = VK_RValue; 2894 break; 2895 } 2896 LLVM_FALLTHROUGH; 2897 2898 case Decl::ImplicitParam: 2899 case Decl::ParmVar: { 2900 // These are always l-values. 2901 valueKind = VK_LValue; 2902 type = type.getNonReferenceType(); 2903 2904 // FIXME: Does the addition of const really only apply in 2905 // potentially-evaluated contexts? Since the variable isn't actually 2906 // captured in an unevaluated context, it seems that the answer is no. 2907 if (!isUnevaluatedContext()) { 2908 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2909 if (!CapturedType.isNull()) 2910 type = CapturedType; 2911 } 2912 2913 break; 2914 } 2915 2916 case Decl::Binding: { 2917 // These are always lvalues. 2918 valueKind = VK_LValue; 2919 type = type.getNonReferenceType(); 2920 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2921 // decides how that's supposed to work. 2922 auto *BD = cast<BindingDecl>(VD); 2923 if (BD->getDeclContext()->isFunctionOrMethod() && 2924 BD->getDeclContext() != CurContext) 2925 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2926 break; 2927 } 2928 2929 case Decl::Function: { 2930 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2931 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2932 type = Context.BuiltinFnTy; 2933 valueKind = VK_RValue; 2934 break; 2935 } 2936 } 2937 2938 const FunctionType *fty = type->castAs<FunctionType>(); 2939 2940 // If we're referring to a function with an __unknown_anytype 2941 // result type, make the entire expression __unknown_anytype. 2942 if (fty->getReturnType() == Context.UnknownAnyTy) { 2943 type = Context.UnknownAnyTy; 2944 valueKind = VK_RValue; 2945 break; 2946 } 2947 2948 // Functions are l-values in C++. 2949 if (getLangOpts().CPlusPlus) { 2950 valueKind = VK_LValue; 2951 break; 2952 } 2953 2954 // C99 DR 316 says that, if a function type comes from a 2955 // function definition (without a prototype), that type is only 2956 // used for checking compatibility. Therefore, when referencing 2957 // the function, we pretend that we don't have the full function 2958 // type. 2959 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2960 isa<FunctionProtoType>(fty)) 2961 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2962 fty->getExtInfo()); 2963 2964 // Functions are r-values in C. 2965 valueKind = VK_RValue; 2966 break; 2967 } 2968 2969 case Decl::CXXDeductionGuide: 2970 llvm_unreachable("building reference to deduction guide"); 2971 2972 case Decl::MSProperty: 2973 valueKind = VK_LValue; 2974 break; 2975 2976 case Decl::CXXMethod: 2977 // If we're referring to a method with an __unknown_anytype 2978 // result type, make the entire expression __unknown_anytype. 2979 // This should only be possible with a type written directly. 2980 if (const FunctionProtoType *proto 2981 = dyn_cast<FunctionProtoType>(VD->getType())) 2982 if (proto->getReturnType() == Context.UnknownAnyTy) { 2983 type = Context.UnknownAnyTy; 2984 valueKind = VK_RValue; 2985 break; 2986 } 2987 2988 // C++ methods are l-values if static, r-values if non-static. 2989 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2990 valueKind = VK_LValue; 2991 break; 2992 } 2993 LLVM_FALLTHROUGH; 2994 2995 case Decl::CXXConversion: 2996 case Decl::CXXDestructor: 2997 case Decl::CXXConstructor: 2998 valueKind = VK_RValue; 2999 break; 3000 } 3001 3002 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3003 TemplateArgs); 3004 } 3005 } 3006 3007 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3008 SmallString<32> &Target) { 3009 Target.resize(CharByteWidth * (Source.size() + 1)); 3010 char *ResultPtr = &Target[0]; 3011 const llvm::UTF8 *ErrorPtr; 3012 bool success = 3013 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3014 (void)success; 3015 assert(success); 3016 Target.resize(ResultPtr - &Target[0]); 3017 } 3018 3019 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3020 PredefinedExpr::IdentType IT) { 3021 // Pick the current block, lambda, captured statement or function. 3022 Decl *currentDecl = nullptr; 3023 if (const BlockScopeInfo *BSI = getCurBlock()) 3024 currentDecl = BSI->TheDecl; 3025 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3026 currentDecl = LSI->CallOperator; 3027 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3028 currentDecl = CSI->TheCapturedDecl; 3029 else 3030 currentDecl = getCurFunctionOrMethodDecl(); 3031 3032 if (!currentDecl) { 3033 Diag(Loc, diag::ext_predef_outside_function); 3034 currentDecl = Context.getTranslationUnitDecl(); 3035 } 3036 3037 QualType ResTy; 3038 StringLiteral *SL = nullptr; 3039 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3040 ResTy = Context.DependentTy; 3041 else { 3042 // Pre-defined identifiers are of type char[x], where x is the length of 3043 // the string. 3044 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3045 unsigned Length = Str.length(); 3046 3047 llvm::APInt LengthI(32, Length + 1); 3048 if (IT == PredefinedExpr::LFunction) { 3049 ResTy = Context.WideCharTy.withConst(); 3050 SmallString<32> RawChars; 3051 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3052 Str, RawChars); 3053 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3054 /*IndexTypeQuals*/ 0); 3055 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3056 /*Pascal*/ false, ResTy, Loc); 3057 } else { 3058 ResTy = Context.CharTy.withConst(); 3059 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3060 /*IndexTypeQuals*/ 0); 3061 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3062 /*Pascal*/ false, ResTy, Loc); 3063 } 3064 } 3065 3066 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3067 } 3068 3069 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3070 PredefinedExpr::IdentType IT; 3071 3072 switch (Kind) { 3073 default: llvm_unreachable("Unknown simple primary expr!"); 3074 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3075 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3076 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3077 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3078 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3079 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3080 } 3081 3082 return BuildPredefinedExpr(Loc, IT); 3083 } 3084 3085 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3086 SmallString<16> CharBuffer; 3087 bool Invalid = false; 3088 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3089 if (Invalid) 3090 return ExprError(); 3091 3092 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3093 PP, Tok.getKind()); 3094 if (Literal.hadError()) 3095 return ExprError(); 3096 3097 QualType Ty; 3098 if (Literal.isWide()) 3099 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3100 else if (Literal.isUTF8() && getLangOpts().Char8) 3101 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3102 else if (Literal.isUTF16()) 3103 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3104 else if (Literal.isUTF32()) 3105 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3106 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3107 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3108 else 3109 Ty = Context.CharTy; // 'x' -> char in C++ 3110 3111 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3112 if (Literal.isWide()) 3113 Kind = CharacterLiteral::Wide; 3114 else if (Literal.isUTF16()) 3115 Kind = CharacterLiteral::UTF16; 3116 else if (Literal.isUTF32()) 3117 Kind = CharacterLiteral::UTF32; 3118 else if (Literal.isUTF8()) 3119 Kind = CharacterLiteral::UTF8; 3120 3121 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3122 Tok.getLocation()); 3123 3124 if (Literal.getUDSuffix().empty()) 3125 return Lit; 3126 3127 // We're building a user-defined literal. 3128 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3129 SourceLocation UDSuffixLoc = 3130 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3131 3132 // Make sure we're allowed user-defined literals here. 3133 if (!UDLScope) 3134 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3135 3136 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3137 // operator "" X (ch) 3138 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3139 Lit, Tok.getLocation()); 3140 } 3141 3142 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3143 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3144 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3145 Context.IntTy, Loc); 3146 } 3147 3148 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3149 QualType Ty, SourceLocation Loc) { 3150 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3151 3152 using llvm::APFloat; 3153 APFloat Val(Format); 3154 3155 APFloat::opStatus result = Literal.GetFloatValue(Val); 3156 3157 // Overflow is always an error, but underflow is only an error if 3158 // we underflowed to zero (APFloat reports denormals as underflow). 3159 if ((result & APFloat::opOverflow) || 3160 ((result & APFloat::opUnderflow) && Val.isZero())) { 3161 unsigned diagnostic; 3162 SmallString<20> buffer; 3163 if (result & APFloat::opOverflow) { 3164 diagnostic = diag::warn_float_overflow; 3165 APFloat::getLargest(Format).toString(buffer); 3166 } else { 3167 diagnostic = diag::warn_float_underflow; 3168 APFloat::getSmallest(Format).toString(buffer); 3169 } 3170 3171 S.Diag(Loc, diagnostic) 3172 << Ty 3173 << StringRef(buffer.data(), buffer.size()); 3174 } 3175 3176 bool isExact = (result == APFloat::opOK); 3177 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3178 } 3179 3180 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3181 assert(E && "Invalid expression"); 3182 3183 if (E->isValueDependent()) 3184 return false; 3185 3186 QualType QT = E->getType(); 3187 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3188 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3189 return true; 3190 } 3191 3192 llvm::APSInt ValueAPS; 3193 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3194 3195 if (R.isInvalid()) 3196 return true; 3197 3198 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3199 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3200 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3201 << ValueAPS.toString(10) << ValueIsPositive; 3202 return true; 3203 } 3204 3205 return false; 3206 } 3207 3208 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3209 // Fast path for a single digit (which is quite common). A single digit 3210 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3211 if (Tok.getLength() == 1) { 3212 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3213 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3214 } 3215 3216 SmallString<128> SpellingBuffer; 3217 // NumericLiteralParser wants to overread by one character. Add padding to 3218 // the buffer in case the token is copied to the buffer. If getSpelling() 3219 // returns a StringRef to the memory buffer, it should have a null char at 3220 // the EOF, so it is also safe. 3221 SpellingBuffer.resize(Tok.getLength() + 1); 3222 3223 // Get the spelling of the token, which eliminates trigraphs, etc. 3224 bool Invalid = false; 3225 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3226 if (Invalid) 3227 return ExprError(); 3228 3229 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3230 if (Literal.hadError) 3231 return ExprError(); 3232 3233 if (Literal.hasUDSuffix()) { 3234 // We're building a user-defined literal. 3235 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3236 SourceLocation UDSuffixLoc = 3237 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3238 3239 // Make sure we're allowed user-defined literals here. 3240 if (!UDLScope) 3241 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3242 3243 QualType CookedTy; 3244 if (Literal.isFloatingLiteral()) { 3245 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3246 // long double, the literal is treated as a call of the form 3247 // operator "" X (f L) 3248 CookedTy = Context.LongDoubleTy; 3249 } else { 3250 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3251 // unsigned long long, the literal is treated as a call of the form 3252 // operator "" X (n ULL) 3253 CookedTy = Context.UnsignedLongLongTy; 3254 } 3255 3256 DeclarationName OpName = 3257 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3258 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3259 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3260 3261 SourceLocation TokLoc = Tok.getLocation(); 3262 3263 // Perform literal operator lookup to determine if we're building a raw 3264 // literal or a cooked one. 3265 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3266 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3267 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3268 /*AllowStringTemplate*/ false, 3269 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3270 case LOLR_ErrorNoDiagnostic: 3271 // Lookup failure for imaginary constants isn't fatal, there's still the 3272 // GNU extension producing _Complex types. 3273 break; 3274 case LOLR_Error: 3275 return ExprError(); 3276 case LOLR_Cooked: { 3277 Expr *Lit; 3278 if (Literal.isFloatingLiteral()) { 3279 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3280 } else { 3281 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3282 if (Literal.GetIntegerValue(ResultVal)) 3283 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3284 << /* Unsigned */ 1; 3285 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3286 Tok.getLocation()); 3287 } 3288 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3289 } 3290 3291 case LOLR_Raw: { 3292 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3293 // literal is treated as a call of the form 3294 // operator "" X ("n") 3295 unsigned Length = Literal.getUDSuffixOffset(); 3296 QualType StrTy = Context.getConstantArrayType( 3297 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3298 ArrayType::Normal, 0); 3299 Expr *Lit = StringLiteral::Create( 3300 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3301 /*Pascal*/false, StrTy, &TokLoc, 1); 3302 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3303 } 3304 3305 case LOLR_Template: { 3306 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3307 // template), L is treated as a call fo the form 3308 // operator "" X <'c1', 'c2', ... 'ck'>() 3309 // where n is the source character sequence c1 c2 ... ck. 3310 TemplateArgumentListInfo ExplicitArgs; 3311 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3312 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3313 llvm::APSInt Value(CharBits, CharIsUnsigned); 3314 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3315 Value = TokSpelling[I]; 3316 TemplateArgument Arg(Context, Value, Context.CharTy); 3317 TemplateArgumentLocInfo ArgInfo; 3318 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3319 } 3320 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3321 &ExplicitArgs); 3322 } 3323 case LOLR_StringTemplate: 3324 llvm_unreachable("unexpected literal operator lookup result"); 3325 } 3326 } 3327 3328 Expr *Res; 3329 3330 if (Literal.isFloatingLiteral()) { 3331 QualType Ty; 3332 if (Literal.isHalf){ 3333 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3334 Ty = Context.HalfTy; 3335 else { 3336 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3337 return ExprError(); 3338 } 3339 } else if (Literal.isFloat) 3340 Ty = Context.FloatTy; 3341 else if (Literal.isLong) 3342 Ty = Context.LongDoubleTy; 3343 else if (Literal.isFloat16) 3344 Ty = Context.Float16Ty; 3345 else if (Literal.isFloat128) 3346 Ty = Context.Float128Ty; 3347 else 3348 Ty = Context.DoubleTy; 3349 3350 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3351 3352 if (Ty == Context.DoubleTy) { 3353 if (getLangOpts().SinglePrecisionConstants) { 3354 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3355 if (BTy->getKind() != BuiltinType::Float) { 3356 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3357 } 3358 } else if (getLangOpts().OpenCL && 3359 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3360 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3361 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3362 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3363 } 3364 } 3365 } else if (!Literal.isIntegerLiteral()) { 3366 return ExprError(); 3367 } else { 3368 QualType Ty; 3369 3370 // 'long long' is a C99 or C++11 feature. 3371 if (!getLangOpts().C99 && Literal.isLongLong) { 3372 if (getLangOpts().CPlusPlus) 3373 Diag(Tok.getLocation(), 3374 getLangOpts().CPlusPlus11 ? 3375 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3376 else 3377 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3378 } 3379 3380 // Get the value in the widest-possible width. 3381 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3382 llvm::APInt ResultVal(MaxWidth, 0); 3383 3384 if (Literal.GetIntegerValue(ResultVal)) { 3385 // If this value didn't fit into uintmax_t, error and force to ull. 3386 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3387 << /* Unsigned */ 1; 3388 Ty = Context.UnsignedLongLongTy; 3389 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3390 "long long is not intmax_t?"); 3391 } else { 3392 // If this value fits into a ULL, try to figure out what else it fits into 3393 // according to the rules of C99 6.4.4.1p5. 3394 3395 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3396 // be an unsigned int. 3397 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3398 3399 // Check from smallest to largest, picking the smallest type we can. 3400 unsigned Width = 0; 3401 3402 // Microsoft specific integer suffixes are explicitly sized. 3403 if (Literal.MicrosoftInteger) { 3404 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3405 Width = 8; 3406 Ty = Context.CharTy; 3407 } else { 3408 Width = Literal.MicrosoftInteger; 3409 Ty = Context.getIntTypeForBitwidth(Width, 3410 /*Signed=*/!Literal.isUnsigned); 3411 } 3412 } 3413 3414 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3415 // Are int/unsigned possibilities? 3416 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3417 3418 // Does it fit in a unsigned int? 3419 if (ResultVal.isIntN(IntSize)) { 3420 // Does it fit in a signed int? 3421 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3422 Ty = Context.IntTy; 3423 else if (AllowUnsigned) 3424 Ty = Context.UnsignedIntTy; 3425 Width = IntSize; 3426 } 3427 } 3428 3429 // Are long/unsigned long possibilities? 3430 if (Ty.isNull() && !Literal.isLongLong) { 3431 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3432 3433 // Does it fit in a unsigned long? 3434 if (ResultVal.isIntN(LongSize)) { 3435 // Does it fit in a signed long? 3436 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3437 Ty = Context.LongTy; 3438 else if (AllowUnsigned) 3439 Ty = Context.UnsignedLongTy; 3440 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3441 // is compatible. 3442 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3443 const unsigned LongLongSize = 3444 Context.getTargetInfo().getLongLongWidth(); 3445 Diag(Tok.getLocation(), 3446 getLangOpts().CPlusPlus 3447 ? Literal.isLong 3448 ? diag::warn_old_implicitly_unsigned_long_cxx 3449 : /*C++98 UB*/ diag:: 3450 ext_old_implicitly_unsigned_long_cxx 3451 : diag::warn_old_implicitly_unsigned_long) 3452 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3453 : /*will be ill-formed*/ 1); 3454 Ty = Context.UnsignedLongTy; 3455 } 3456 Width = LongSize; 3457 } 3458 } 3459 3460 // Check long long if needed. 3461 if (Ty.isNull()) { 3462 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3463 3464 // Does it fit in a unsigned long long? 3465 if (ResultVal.isIntN(LongLongSize)) { 3466 // Does it fit in a signed long long? 3467 // To be compatible with MSVC, hex integer literals ending with the 3468 // LL or i64 suffix are always signed in Microsoft mode. 3469 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3470 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3471 Ty = Context.LongLongTy; 3472 else if (AllowUnsigned) 3473 Ty = Context.UnsignedLongLongTy; 3474 Width = LongLongSize; 3475 } 3476 } 3477 3478 // If we still couldn't decide a type, we probably have something that 3479 // does not fit in a signed long long, but has no U suffix. 3480 if (Ty.isNull()) { 3481 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3482 Ty = Context.UnsignedLongLongTy; 3483 Width = Context.getTargetInfo().getLongLongWidth(); 3484 } 3485 3486 if (ResultVal.getBitWidth() != Width) 3487 ResultVal = ResultVal.trunc(Width); 3488 } 3489 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3490 } 3491 3492 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3493 if (Literal.isImaginary) { 3494 Res = new (Context) ImaginaryLiteral(Res, 3495 Context.getComplexType(Res->getType())); 3496 3497 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3498 } 3499 return Res; 3500 } 3501 3502 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3503 assert(E && "ActOnParenExpr() missing expr"); 3504 return new (Context) ParenExpr(L, R, E); 3505 } 3506 3507 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3508 SourceLocation Loc, 3509 SourceRange ArgRange) { 3510 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3511 // scalar or vector data type argument..." 3512 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3513 // type (C99 6.2.5p18) or void. 3514 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3515 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3516 << T << ArgRange; 3517 return true; 3518 } 3519 3520 assert((T->isVoidType() || !T->isIncompleteType()) && 3521 "Scalar types should always be complete"); 3522 return false; 3523 } 3524 3525 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3526 SourceLocation Loc, 3527 SourceRange ArgRange, 3528 UnaryExprOrTypeTrait TraitKind) { 3529 // Invalid types must be hard errors for SFINAE in C++. 3530 if (S.LangOpts.CPlusPlus) 3531 return true; 3532 3533 // C99 6.5.3.4p1: 3534 if (T->isFunctionType() && 3535 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3536 // sizeof(function)/alignof(function) is allowed as an extension. 3537 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3538 << TraitKind << ArgRange; 3539 return false; 3540 } 3541 3542 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3543 // this is an error (OpenCL v1.1 s6.3.k) 3544 if (T->isVoidType()) { 3545 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3546 : diag::ext_sizeof_alignof_void_type; 3547 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3548 return false; 3549 } 3550 3551 return true; 3552 } 3553 3554 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3555 SourceLocation Loc, 3556 SourceRange ArgRange, 3557 UnaryExprOrTypeTrait TraitKind) { 3558 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3559 // runtime doesn't allow it. 3560 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3561 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3562 << T << (TraitKind == UETT_SizeOf) 3563 << ArgRange; 3564 return true; 3565 } 3566 3567 return false; 3568 } 3569 3570 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3571 /// pointer type is equal to T) and emit a warning if it is. 3572 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3573 Expr *E) { 3574 // Don't warn if the operation changed the type. 3575 if (T != E->getType()) 3576 return; 3577 3578 // Now look for array decays. 3579 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3580 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3581 return; 3582 3583 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3584 << ICE->getType() 3585 << ICE->getSubExpr()->getType(); 3586 } 3587 3588 /// \brief Check the constraints on expression operands to unary type expression 3589 /// and type traits. 3590 /// 3591 /// Completes any types necessary and validates the constraints on the operand 3592 /// expression. The logic mostly mirrors the type-based overload, but may modify 3593 /// the expression as it completes the type for that expression through template 3594 /// instantiation, etc. 3595 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3596 UnaryExprOrTypeTrait ExprKind) { 3597 QualType ExprTy = E->getType(); 3598 assert(!ExprTy->isReferenceType()); 3599 3600 if (ExprKind == UETT_VecStep) 3601 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3602 E->getSourceRange()); 3603 3604 // Whitelist some types as extensions 3605 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3606 E->getSourceRange(), ExprKind)) 3607 return false; 3608 3609 // 'alignof' applied to an expression only requires the base element type of 3610 // the expression to be complete. 'sizeof' requires the expression's type to 3611 // be complete (and will attempt to complete it if it's an array of unknown 3612 // bound). 3613 if (ExprKind == UETT_AlignOf) { 3614 if (RequireCompleteType(E->getExprLoc(), 3615 Context.getBaseElementType(E->getType()), 3616 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3617 E->getSourceRange())) 3618 return true; 3619 } else { 3620 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3621 ExprKind, E->getSourceRange())) 3622 return true; 3623 } 3624 3625 // Completing the expression's type may have changed it. 3626 ExprTy = E->getType(); 3627 assert(!ExprTy->isReferenceType()); 3628 3629 if (ExprTy->isFunctionType()) { 3630 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3631 << ExprKind << E->getSourceRange(); 3632 return true; 3633 } 3634 3635 // The operand for sizeof and alignof is in an unevaluated expression context, 3636 // so side effects could result in unintended consequences. 3637 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3638 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3639 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3640 3641 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3642 E->getSourceRange(), ExprKind)) 3643 return true; 3644 3645 if (ExprKind == UETT_SizeOf) { 3646 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3647 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3648 QualType OType = PVD->getOriginalType(); 3649 QualType Type = PVD->getType(); 3650 if (Type->isPointerType() && OType->isArrayType()) { 3651 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3652 << Type << OType; 3653 Diag(PVD->getLocation(), diag::note_declared_at); 3654 } 3655 } 3656 } 3657 3658 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3659 // decays into a pointer and returns an unintended result. This is most 3660 // likely a typo for "sizeof(array) op x". 3661 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3662 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3663 BO->getLHS()); 3664 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3665 BO->getRHS()); 3666 } 3667 } 3668 3669 return false; 3670 } 3671 3672 /// \brief Check the constraints on operands to unary expression and type 3673 /// traits. 3674 /// 3675 /// This will complete any types necessary, and validate the various constraints 3676 /// on those operands. 3677 /// 3678 /// The UsualUnaryConversions() function is *not* called by this routine. 3679 /// C99 6.3.2.1p[2-4] all state: 3680 /// Except when it is the operand of the sizeof operator ... 3681 /// 3682 /// C++ [expr.sizeof]p4 3683 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3684 /// standard conversions are not applied to the operand of sizeof. 3685 /// 3686 /// This policy is followed for all of the unary trait expressions. 3687 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3688 SourceLocation OpLoc, 3689 SourceRange ExprRange, 3690 UnaryExprOrTypeTrait ExprKind) { 3691 if (ExprType->isDependentType()) 3692 return false; 3693 3694 // C++ [expr.sizeof]p2: 3695 // When applied to a reference or a reference type, the result 3696 // is the size of the referenced type. 3697 // C++11 [expr.alignof]p3: 3698 // When alignof is applied to a reference type, the result 3699 // shall be the alignment of the referenced type. 3700 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3701 ExprType = Ref->getPointeeType(); 3702 3703 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3704 // When alignof or _Alignof is applied to an array type, the result 3705 // is the alignment of the element type. 3706 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3707 ExprType = Context.getBaseElementType(ExprType); 3708 3709 if (ExprKind == UETT_VecStep) 3710 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3711 3712 // Whitelist some types as extensions 3713 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3714 ExprKind)) 3715 return false; 3716 3717 if (RequireCompleteType(OpLoc, ExprType, 3718 diag::err_sizeof_alignof_incomplete_type, 3719 ExprKind, ExprRange)) 3720 return true; 3721 3722 if (ExprType->isFunctionType()) { 3723 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3724 << ExprKind << ExprRange; 3725 return true; 3726 } 3727 3728 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3729 ExprKind)) 3730 return true; 3731 3732 return false; 3733 } 3734 3735 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3736 E = E->IgnoreParens(); 3737 3738 // Cannot know anything else if the expression is dependent. 3739 if (E->isTypeDependent()) 3740 return false; 3741 3742 if (E->getObjectKind() == OK_BitField) { 3743 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3744 << 1 << E->getSourceRange(); 3745 return true; 3746 } 3747 3748 ValueDecl *D = nullptr; 3749 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3750 D = DRE->getDecl(); 3751 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3752 D = ME->getMemberDecl(); 3753 } 3754 3755 // If it's a field, require the containing struct to have a 3756 // complete definition so that we can compute the layout. 3757 // 3758 // This can happen in C++11 onwards, either by naming the member 3759 // in a way that is not transformed into a member access expression 3760 // (in an unevaluated operand, for instance), or by naming the member 3761 // in a trailing-return-type. 3762 // 3763 // For the record, since __alignof__ on expressions is a GCC 3764 // extension, GCC seems to permit this but always gives the 3765 // nonsensical answer 0. 3766 // 3767 // We don't really need the layout here --- we could instead just 3768 // directly check for all the appropriate alignment-lowing 3769 // attributes --- but that would require duplicating a lot of 3770 // logic that just isn't worth duplicating for such a marginal 3771 // use-case. 3772 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3773 // Fast path this check, since we at least know the record has a 3774 // definition if we can find a member of it. 3775 if (!FD->getParent()->isCompleteDefinition()) { 3776 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3777 << E->getSourceRange(); 3778 return true; 3779 } 3780 3781 // Otherwise, if it's a field, and the field doesn't have 3782 // reference type, then it must have a complete type (or be a 3783 // flexible array member, which we explicitly want to 3784 // white-list anyway), which makes the following checks trivial. 3785 if (!FD->getType()->isReferenceType()) 3786 return false; 3787 } 3788 3789 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3790 } 3791 3792 bool Sema::CheckVecStepExpr(Expr *E) { 3793 E = E->IgnoreParens(); 3794 3795 // Cannot know anything else if the expression is dependent. 3796 if (E->isTypeDependent()) 3797 return false; 3798 3799 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3800 } 3801 3802 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3803 CapturingScopeInfo *CSI) { 3804 assert(T->isVariablyModifiedType()); 3805 assert(CSI != nullptr); 3806 3807 // We're going to walk down into the type and look for VLA expressions. 3808 do { 3809 const Type *Ty = T.getTypePtr(); 3810 switch (Ty->getTypeClass()) { 3811 #define TYPE(Class, Base) 3812 #define ABSTRACT_TYPE(Class, Base) 3813 #define NON_CANONICAL_TYPE(Class, Base) 3814 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3815 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3816 #include "clang/AST/TypeNodes.def" 3817 T = QualType(); 3818 break; 3819 // These types are never variably-modified. 3820 case Type::Builtin: 3821 case Type::Complex: 3822 case Type::Vector: 3823 case Type::ExtVector: 3824 case Type::Record: 3825 case Type::Enum: 3826 case Type::Elaborated: 3827 case Type::TemplateSpecialization: 3828 case Type::ObjCObject: 3829 case Type::ObjCInterface: 3830 case Type::ObjCObjectPointer: 3831 case Type::ObjCTypeParam: 3832 case Type::Pipe: 3833 llvm_unreachable("type class is never variably-modified!"); 3834 case Type::Adjusted: 3835 T = cast<AdjustedType>(Ty)->getOriginalType(); 3836 break; 3837 case Type::Decayed: 3838 T = cast<DecayedType>(Ty)->getPointeeType(); 3839 break; 3840 case Type::Pointer: 3841 T = cast<PointerType>(Ty)->getPointeeType(); 3842 break; 3843 case Type::BlockPointer: 3844 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3845 break; 3846 case Type::LValueReference: 3847 case Type::RValueReference: 3848 T = cast<ReferenceType>(Ty)->getPointeeType(); 3849 break; 3850 case Type::MemberPointer: 3851 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3852 break; 3853 case Type::ConstantArray: 3854 case Type::IncompleteArray: 3855 // Losing element qualification here is fine. 3856 T = cast<ArrayType>(Ty)->getElementType(); 3857 break; 3858 case Type::VariableArray: { 3859 // Losing element qualification here is fine. 3860 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3861 3862 // Unknown size indication requires no size computation. 3863 // Otherwise, evaluate and record it. 3864 if (auto Size = VAT->getSizeExpr()) { 3865 if (!CSI->isVLATypeCaptured(VAT)) { 3866 RecordDecl *CapRecord = nullptr; 3867 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3868 CapRecord = LSI->Lambda; 3869 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3870 CapRecord = CRSI->TheRecordDecl; 3871 } 3872 if (CapRecord) { 3873 auto ExprLoc = Size->getExprLoc(); 3874 auto SizeType = Context.getSizeType(); 3875 // Build the non-static data member. 3876 auto Field = 3877 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3878 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3879 /*BW*/ nullptr, /*Mutable*/ false, 3880 /*InitStyle*/ ICIS_NoInit); 3881 Field->setImplicit(true); 3882 Field->setAccess(AS_private); 3883 Field->setCapturedVLAType(VAT); 3884 CapRecord->addDecl(Field); 3885 3886 CSI->addVLATypeCapture(ExprLoc, SizeType); 3887 } 3888 } 3889 } 3890 T = VAT->getElementType(); 3891 break; 3892 } 3893 case Type::FunctionProto: 3894 case Type::FunctionNoProto: 3895 T = cast<FunctionType>(Ty)->getReturnType(); 3896 break; 3897 case Type::Paren: 3898 case Type::TypeOf: 3899 case Type::UnaryTransform: 3900 case Type::Attributed: 3901 case Type::SubstTemplateTypeParm: 3902 case Type::PackExpansion: 3903 // Keep walking after single level desugaring. 3904 T = T.getSingleStepDesugaredType(Context); 3905 break; 3906 case Type::Typedef: 3907 T = cast<TypedefType>(Ty)->desugar(); 3908 break; 3909 case Type::Decltype: 3910 T = cast<DecltypeType>(Ty)->desugar(); 3911 break; 3912 case Type::Auto: 3913 case Type::DeducedTemplateSpecialization: 3914 T = cast<DeducedType>(Ty)->getDeducedType(); 3915 break; 3916 case Type::TypeOfExpr: 3917 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3918 break; 3919 case Type::Atomic: 3920 T = cast<AtomicType>(Ty)->getValueType(); 3921 break; 3922 } 3923 } while (!T.isNull() && T->isVariablyModifiedType()); 3924 } 3925 3926 /// \brief Build a sizeof or alignof expression given a type operand. 3927 ExprResult 3928 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3929 SourceLocation OpLoc, 3930 UnaryExprOrTypeTrait ExprKind, 3931 SourceRange R) { 3932 if (!TInfo) 3933 return ExprError(); 3934 3935 QualType T = TInfo->getType(); 3936 3937 if (!T->isDependentType() && 3938 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3939 return ExprError(); 3940 3941 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3942 if (auto *TT = T->getAs<TypedefType>()) { 3943 for (auto I = FunctionScopes.rbegin(), 3944 E = std::prev(FunctionScopes.rend()); 3945 I != E; ++I) { 3946 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3947 if (CSI == nullptr) 3948 break; 3949 DeclContext *DC = nullptr; 3950 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3951 DC = LSI->CallOperator; 3952 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3953 DC = CRSI->TheCapturedDecl; 3954 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3955 DC = BSI->TheDecl; 3956 if (DC) { 3957 if (DC->containsDecl(TT->getDecl())) 3958 break; 3959 captureVariablyModifiedType(Context, T, CSI); 3960 } 3961 } 3962 } 3963 } 3964 3965 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3966 return new (Context) UnaryExprOrTypeTraitExpr( 3967 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3968 } 3969 3970 /// \brief Build a sizeof or alignof expression given an expression 3971 /// operand. 3972 ExprResult 3973 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3974 UnaryExprOrTypeTrait ExprKind) { 3975 ExprResult PE = CheckPlaceholderExpr(E); 3976 if (PE.isInvalid()) 3977 return ExprError(); 3978 3979 E = PE.get(); 3980 3981 // Verify that the operand is valid. 3982 bool isInvalid = false; 3983 if (E->isTypeDependent()) { 3984 // Delay type-checking for type-dependent expressions. 3985 } else if (ExprKind == UETT_AlignOf) { 3986 isInvalid = CheckAlignOfExpr(*this, E); 3987 } else if (ExprKind == UETT_VecStep) { 3988 isInvalid = CheckVecStepExpr(E); 3989 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3990 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3991 isInvalid = true; 3992 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3993 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3994 isInvalid = true; 3995 } else { 3996 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3997 } 3998 3999 if (isInvalid) 4000 return ExprError(); 4001 4002 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4003 PE = TransformToPotentiallyEvaluated(E); 4004 if (PE.isInvalid()) return ExprError(); 4005 E = PE.get(); 4006 } 4007 4008 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4009 return new (Context) UnaryExprOrTypeTraitExpr( 4010 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4011 } 4012 4013 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4014 /// expr and the same for @c alignof and @c __alignof 4015 /// Note that the ArgRange is invalid if isType is false. 4016 ExprResult 4017 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4018 UnaryExprOrTypeTrait ExprKind, bool IsType, 4019 void *TyOrEx, SourceRange ArgRange) { 4020 // If error parsing type, ignore. 4021 if (!TyOrEx) return ExprError(); 4022 4023 if (IsType) { 4024 TypeSourceInfo *TInfo; 4025 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4026 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4027 } 4028 4029 Expr *ArgEx = (Expr *)TyOrEx; 4030 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4031 return Result; 4032 } 4033 4034 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4035 bool IsReal) { 4036 if (V.get()->isTypeDependent()) 4037 return S.Context.DependentTy; 4038 4039 // _Real and _Imag are only l-values for normal l-values. 4040 if (V.get()->getObjectKind() != OK_Ordinary) { 4041 V = S.DefaultLvalueConversion(V.get()); 4042 if (V.isInvalid()) 4043 return QualType(); 4044 } 4045 4046 // These operators return the element type of a complex type. 4047 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4048 return CT->getElementType(); 4049 4050 // Otherwise they pass through real integer and floating point types here. 4051 if (V.get()->getType()->isArithmeticType()) 4052 return V.get()->getType(); 4053 4054 // Test for placeholders. 4055 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4056 if (PR.isInvalid()) return QualType(); 4057 if (PR.get() != V.get()) { 4058 V = PR; 4059 return CheckRealImagOperand(S, V, Loc, IsReal); 4060 } 4061 4062 // Reject anything else. 4063 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4064 << (IsReal ? "__real" : "__imag"); 4065 return QualType(); 4066 } 4067 4068 4069 4070 ExprResult 4071 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4072 tok::TokenKind Kind, Expr *Input) { 4073 UnaryOperatorKind Opc; 4074 switch (Kind) { 4075 default: llvm_unreachable("Unknown unary op!"); 4076 case tok::plusplus: Opc = UO_PostInc; break; 4077 case tok::minusminus: Opc = UO_PostDec; break; 4078 } 4079 4080 // Since this might is a postfix expression, get rid of ParenListExprs. 4081 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4082 if (Result.isInvalid()) return ExprError(); 4083 Input = Result.get(); 4084 4085 return BuildUnaryOp(S, OpLoc, Opc, Input); 4086 } 4087 4088 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4089 /// 4090 /// \return true on error 4091 static bool checkArithmeticOnObjCPointer(Sema &S, 4092 SourceLocation opLoc, 4093 Expr *op) { 4094 assert(op->getType()->isObjCObjectPointerType()); 4095 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4096 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4097 return false; 4098 4099 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4100 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4101 << op->getSourceRange(); 4102 return true; 4103 } 4104 4105 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4106 auto *BaseNoParens = Base->IgnoreParens(); 4107 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4108 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4109 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4110 } 4111 4112 ExprResult 4113 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4114 Expr *idx, SourceLocation rbLoc) { 4115 if (base && !base->getType().isNull() && 4116 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4117 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4118 /*Length=*/nullptr, rbLoc); 4119 4120 // Since this might be a postfix expression, get rid of ParenListExprs. 4121 if (isa<ParenListExpr>(base)) { 4122 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4123 if (result.isInvalid()) return ExprError(); 4124 base = result.get(); 4125 } 4126 4127 // Handle any non-overload placeholder types in the base and index 4128 // expressions. We can't handle overloads here because the other 4129 // operand might be an overloadable type, in which case the overload 4130 // resolution for the operator overload should get the first crack 4131 // at the overload. 4132 bool IsMSPropertySubscript = false; 4133 if (base->getType()->isNonOverloadPlaceholderType()) { 4134 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4135 if (!IsMSPropertySubscript) { 4136 ExprResult result = CheckPlaceholderExpr(base); 4137 if (result.isInvalid()) 4138 return ExprError(); 4139 base = result.get(); 4140 } 4141 } 4142 if (idx->getType()->isNonOverloadPlaceholderType()) { 4143 ExprResult result = CheckPlaceholderExpr(idx); 4144 if (result.isInvalid()) return ExprError(); 4145 idx = result.get(); 4146 } 4147 4148 // Build an unanalyzed expression if either operand is type-dependent. 4149 if (getLangOpts().CPlusPlus && 4150 (base->isTypeDependent() || idx->isTypeDependent())) { 4151 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4152 VK_LValue, OK_Ordinary, rbLoc); 4153 } 4154 4155 // MSDN, property (C++) 4156 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4157 // This attribute can also be used in the declaration of an empty array in a 4158 // class or structure definition. For example: 4159 // __declspec(property(get=GetX, put=PutX)) int x[]; 4160 // The above statement indicates that x[] can be used with one or more array 4161 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4162 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4163 if (IsMSPropertySubscript) { 4164 // Build MS property subscript expression if base is MS property reference 4165 // or MS property subscript. 4166 return new (Context) MSPropertySubscriptExpr( 4167 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4168 } 4169 4170 // Use C++ overloaded-operator rules if either operand has record 4171 // type. The spec says to do this if either type is *overloadable*, 4172 // but enum types can't declare subscript operators or conversion 4173 // operators, so there's nothing interesting for overload resolution 4174 // to do if there aren't any record types involved. 4175 // 4176 // ObjC pointers have their own subscripting logic that is not tied 4177 // to overload resolution and so should not take this path. 4178 if (getLangOpts().CPlusPlus && 4179 (base->getType()->isRecordType() || 4180 (!base->getType()->isObjCObjectPointerType() && 4181 idx->getType()->isRecordType()))) { 4182 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4183 } 4184 4185 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4186 } 4187 4188 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4189 Expr *LowerBound, 4190 SourceLocation ColonLoc, Expr *Length, 4191 SourceLocation RBLoc) { 4192 if (Base->getType()->isPlaceholderType() && 4193 !Base->getType()->isSpecificPlaceholderType( 4194 BuiltinType::OMPArraySection)) { 4195 ExprResult Result = CheckPlaceholderExpr(Base); 4196 if (Result.isInvalid()) 4197 return ExprError(); 4198 Base = Result.get(); 4199 } 4200 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4201 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4202 if (Result.isInvalid()) 4203 return ExprError(); 4204 Result = DefaultLvalueConversion(Result.get()); 4205 if (Result.isInvalid()) 4206 return ExprError(); 4207 LowerBound = Result.get(); 4208 } 4209 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4210 ExprResult Result = CheckPlaceholderExpr(Length); 4211 if (Result.isInvalid()) 4212 return ExprError(); 4213 Result = DefaultLvalueConversion(Result.get()); 4214 if (Result.isInvalid()) 4215 return ExprError(); 4216 Length = Result.get(); 4217 } 4218 4219 // Build an unanalyzed expression if either operand is type-dependent. 4220 if (Base->isTypeDependent() || 4221 (LowerBound && 4222 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4223 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4224 return new (Context) 4225 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4226 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4227 } 4228 4229 // Perform default conversions. 4230 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4231 QualType ResultTy; 4232 if (OriginalTy->isAnyPointerType()) { 4233 ResultTy = OriginalTy->getPointeeType(); 4234 } else if (OriginalTy->isArrayType()) { 4235 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4236 } else { 4237 return ExprError( 4238 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4239 << Base->getSourceRange()); 4240 } 4241 // C99 6.5.2.1p1 4242 if (LowerBound) { 4243 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4244 LowerBound); 4245 if (Res.isInvalid()) 4246 return ExprError(Diag(LowerBound->getExprLoc(), 4247 diag::err_omp_typecheck_section_not_integer) 4248 << 0 << LowerBound->getSourceRange()); 4249 LowerBound = Res.get(); 4250 4251 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4252 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4253 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4254 << 0 << LowerBound->getSourceRange(); 4255 } 4256 if (Length) { 4257 auto Res = 4258 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4259 if (Res.isInvalid()) 4260 return ExprError(Diag(Length->getExprLoc(), 4261 diag::err_omp_typecheck_section_not_integer) 4262 << 1 << Length->getSourceRange()); 4263 Length = Res.get(); 4264 4265 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4266 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4267 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4268 << 1 << Length->getSourceRange(); 4269 } 4270 4271 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4272 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4273 // type. Note that functions are not objects, and that (in C99 parlance) 4274 // incomplete types are not object types. 4275 if (ResultTy->isFunctionType()) { 4276 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4277 << ResultTy << Base->getSourceRange(); 4278 return ExprError(); 4279 } 4280 4281 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4282 diag::err_omp_section_incomplete_type, Base)) 4283 return ExprError(); 4284 4285 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4286 llvm::APSInt LowerBoundValue; 4287 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4288 // OpenMP 4.5, [2.4 Array Sections] 4289 // The array section must be a subset of the original array. 4290 if (LowerBoundValue.isNegative()) { 4291 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4292 << LowerBound->getSourceRange(); 4293 return ExprError(); 4294 } 4295 } 4296 } 4297 4298 if (Length) { 4299 llvm::APSInt LengthValue; 4300 if (Length->EvaluateAsInt(LengthValue, Context)) { 4301 // OpenMP 4.5, [2.4 Array Sections] 4302 // The length must evaluate to non-negative integers. 4303 if (LengthValue.isNegative()) { 4304 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4305 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4306 << Length->getSourceRange(); 4307 return ExprError(); 4308 } 4309 } 4310 } else if (ColonLoc.isValid() && 4311 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4312 !OriginalTy->isVariableArrayType()))) { 4313 // OpenMP 4.5, [2.4 Array Sections] 4314 // When the size of the array dimension is not known, the length must be 4315 // specified explicitly. 4316 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4317 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4318 return ExprError(); 4319 } 4320 4321 if (!Base->getType()->isSpecificPlaceholderType( 4322 BuiltinType::OMPArraySection)) { 4323 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4324 if (Result.isInvalid()) 4325 return ExprError(); 4326 Base = Result.get(); 4327 } 4328 return new (Context) 4329 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4330 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4331 } 4332 4333 ExprResult 4334 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4335 Expr *Idx, SourceLocation RLoc) { 4336 Expr *LHSExp = Base; 4337 Expr *RHSExp = Idx; 4338 4339 ExprValueKind VK = VK_LValue; 4340 ExprObjectKind OK = OK_Ordinary; 4341 4342 // Per C++ core issue 1213, the result is an xvalue if either operand is 4343 // a non-lvalue array, and an lvalue otherwise. 4344 if (getLangOpts().CPlusPlus11 && 4345 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4346 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4347 VK = VK_XValue; 4348 4349 // Perform default conversions. 4350 if (!LHSExp->getType()->getAs<VectorType>()) { 4351 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4352 if (Result.isInvalid()) 4353 return ExprError(); 4354 LHSExp = Result.get(); 4355 } 4356 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4357 if (Result.isInvalid()) 4358 return ExprError(); 4359 RHSExp = Result.get(); 4360 4361 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4362 4363 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4364 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4365 // in the subscript position. As a result, we need to derive the array base 4366 // and index from the expression types. 4367 Expr *BaseExpr, *IndexExpr; 4368 QualType ResultType; 4369 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4370 BaseExpr = LHSExp; 4371 IndexExpr = RHSExp; 4372 ResultType = Context.DependentTy; 4373 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4374 BaseExpr = LHSExp; 4375 IndexExpr = RHSExp; 4376 ResultType = PTy->getPointeeType(); 4377 } else if (const ObjCObjectPointerType *PTy = 4378 LHSTy->getAs<ObjCObjectPointerType>()) { 4379 BaseExpr = LHSExp; 4380 IndexExpr = RHSExp; 4381 4382 // Use custom logic if this should be the pseudo-object subscript 4383 // expression. 4384 if (!LangOpts.isSubscriptPointerArithmetic()) 4385 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4386 nullptr); 4387 4388 ResultType = PTy->getPointeeType(); 4389 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4390 // Handle the uncommon case of "123[Ptr]". 4391 BaseExpr = RHSExp; 4392 IndexExpr = LHSExp; 4393 ResultType = PTy->getPointeeType(); 4394 } else if (const ObjCObjectPointerType *PTy = 4395 RHSTy->getAs<ObjCObjectPointerType>()) { 4396 // Handle the uncommon case of "123[Ptr]". 4397 BaseExpr = RHSExp; 4398 IndexExpr = LHSExp; 4399 ResultType = PTy->getPointeeType(); 4400 if (!LangOpts.isSubscriptPointerArithmetic()) { 4401 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4402 << ResultType << BaseExpr->getSourceRange(); 4403 return ExprError(); 4404 } 4405 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4406 BaseExpr = LHSExp; // vectors: V[123] 4407 IndexExpr = RHSExp; 4408 VK = LHSExp->getValueKind(); 4409 if (VK != VK_RValue) 4410 OK = OK_VectorComponent; 4411 4412 ResultType = VTy->getElementType(); 4413 QualType BaseType = BaseExpr->getType(); 4414 Qualifiers BaseQuals = BaseType.getQualifiers(); 4415 Qualifiers MemberQuals = ResultType.getQualifiers(); 4416 Qualifiers Combined = BaseQuals + MemberQuals; 4417 if (Combined != MemberQuals) 4418 ResultType = Context.getQualifiedType(ResultType, Combined); 4419 } else if (LHSTy->isArrayType()) { 4420 // If we see an array that wasn't promoted by 4421 // DefaultFunctionArrayLvalueConversion, it must be an array that 4422 // wasn't promoted because of the C90 rule that doesn't 4423 // allow promoting non-lvalue arrays. Warn, then 4424 // force the promotion here. 4425 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4426 LHSExp->getSourceRange(); 4427 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4428 CK_ArrayToPointerDecay).get(); 4429 LHSTy = LHSExp->getType(); 4430 4431 BaseExpr = LHSExp; 4432 IndexExpr = RHSExp; 4433 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4434 } else if (RHSTy->isArrayType()) { 4435 // Same as previous, except for 123[f().a] case 4436 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4437 RHSExp->getSourceRange(); 4438 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4439 CK_ArrayToPointerDecay).get(); 4440 RHSTy = RHSExp->getType(); 4441 4442 BaseExpr = RHSExp; 4443 IndexExpr = LHSExp; 4444 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4445 } else { 4446 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4447 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4448 } 4449 // C99 6.5.2.1p1 4450 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4451 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4452 << IndexExpr->getSourceRange()); 4453 4454 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4455 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4456 && !IndexExpr->isTypeDependent()) 4457 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4458 4459 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4460 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4461 // type. Note that Functions are not objects, and that (in C99 parlance) 4462 // incomplete types are not object types. 4463 if (ResultType->isFunctionType()) { 4464 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4465 << ResultType << BaseExpr->getSourceRange(); 4466 return ExprError(); 4467 } 4468 4469 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4470 // GNU extension: subscripting on pointer to void 4471 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4472 << BaseExpr->getSourceRange(); 4473 4474 // C forbids expressions of unqualified void type from being l-values. 4475 // See IsCForbiddenLValueType. 4476 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4477 } else if (!ResultType->isDependentType() && 4478 RequireCompleteType(LLoc, ResultType, 4479 diag::err_subscript_incomplete_type, BaseExpr)) 4480 return ExprError(); 4481 4482 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4483 !ResultType.isCForbiddenLValueType()); 4484 4485 return new (Context) 4486 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4487 } 4488 4489 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4490 ParmVarDecl *Param) { 4491 if (Param->hasUnparsedDefaultArg()) { 4492 Diag(CallLoc, 4493 diag::err_use_of_default_argument_to_function_declared_later) << 4494 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4495 Diag(UnparsedDefaultArgLocs[Param], 4496 diag::note_default_argument_declared_here); 4497 return true; 4498 } 4499 4500 if (Param->hasUninstantiatedDefaultArg()) { 4501 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4502 4503 EnterExpressionEvaluationContext EvalContext( 4504 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4505 4506 // Instantiate the expression. 4507 // 4508 // FIXME: Pass in a correct Pattern argument, otherwise 4509 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4510 // 4511 // template<typename T> 4512 // struct A { 4513 // static int FooImpl(); 4514 // 4515 // template<typename Tp> 4516 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4517 // // template argument list [[T], [Tp]], should be [[Tp]]. 4518 // friend A<Tp> Foo(int a); 4519 // }; 4520 // 4521 // template<typename T> 4522 // A<T> Foo(int a = A<T>::FooImpl()); 4523 MultiLevelTemplateArgumentList MutiLevelArgList 4524 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4525 4526 InstantiatingTemplate Inst(*this, CallLoc, Param, 4527 MutiLevelArgList.getInnermost()); 4528 if (Inst.isInvalid()) 4529 return true; 4530 if (Inst.isAlreadyInstantiating()) { 4531 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4532 Param->setInvalidDecl(); 4533 return true; 4534 } 4535 4536 ExprResult Result; 4537 { 4538 // C++ [dcl.fct.default]p5: 4539 // The names in the [default argument] expression are bound, and 4540 // the semantic constraints are checked, at the point where the 4541 // default argument expression appears. 4542 ContextRAII SavedContext(*this, FD); 4543 LocalInstantiationScope Local(*this); 4544 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4545 /*DirectInit*/false); 4546 } 4547 if (Result.isInvalid()) 4548 return true; 4549 4550 // Check the expression as an initializer for the parameter. 4551 InitializedEntity Entity 4552 = InitializedEntity::InitializeParameter(Context, Param); 4553 InitializationKind Kind 4554 = InitializationKind::CreateCopy(Param->getLocation(), 4555 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4556 Expr *ResultE = Result.getAs<Expr>(); 4557 4558 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4559 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4560 if (Result.isInvalid()) 4561 return true; 4562 4563 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4564 Param->getOuterLocStart()); 4565 if (Result.isInvalid()) 4566 return true; 4567 4568 // Remember the instantiated default argument. 4569 Param->setDefaultArg(Result.getAs<Expr>()); 4570 if (ASTMutationListener *L = getASTMutationListener()) { 4571 L->DefaultArgumentInstantiated(Param); 4572 } 4573 } 4574 4575 // If the default argument expression is not set yet, we are building it now. 4576 if (!Param->hasInit()) { 4577 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4578 Param->setInvalidDecl(); 4579 return true; 4580 } 4581 4582 // If the default expression creates temporaries, we need to 4583 // push them to the current stack of expression temporaries so they'll 4584 // be properly destroyed. 4585 // FIXME: We should really be rebuilding the default argument with new 4586 // bound temporaries; see the comment in PR5810. 4587 // We don't need to do that with block decls, though, because 4588 // blocks in default argument expression can never capture anything. 4589 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4590 // Set the "needs cleanups" bit regardless of whether there are 4591 // any explicit objects. 4592 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4593 4594 // Append all the objects to the cleanup list. Right now, this 4595 // should always be a no-op, because blocks in default argument 4596 // expressions should never be able to capture anything. 4597 assert(!Init->getNumObjects() && 4598 "default argument expression has capturing blocks?"); 4599 } 4600 4601 // We already type-checked the argument, so we know it works. 4602 // Just mark all of the declarations in this potentially-evaluated expression 4603 // as being "referenced". 4604 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4605 /*SkipLocalVariables=*/true); 4606 return false; 4607 } 4608 4609 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4610 FunctionDecl *FD, ParmVarDecl *Param) { 4611 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4612 return ExprError(); 4613 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4614 } 4615 4616 Sema::VariadicCallType 4617 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4618 Expr *Fn) { 4619 if (Proto && Proto->isVariadic()) { 4620 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4621 return VariadicConstructor; 4622 else if (Fn && Fn->getType()->isBlockPointerType()) 4623 return VariadicBlock; 4624 else if (FDecl) { 4625 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4626 if (Method->isInstance()) 4627 return VariadicMethod; 4628 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4629 return VariadicMethod; 4630 return VariadicFunction; 4631 } 4632 return VariadicDoesNotApply; 4633 } 4634 4635 namespace { 4636 class FunctionCallCCC : public FunctionCallFilterCCC { 4637 public: 4638 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4639 unsigned NumArgs, MemberExpr *ME) 4640 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4641 FunctionName(FuncName) {} 4642 4643 bool ValidateCandidate(const TypoCorrection &candidate) override { 4644 if (!candidate.getCorrectionSpecifier() || 4645 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4646 return false; 4647 } 4648 4649 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4650 } 4651 4652 private: 4653 const IdentifierInfo *const FunctionName; 4654 }; 4655 } 4656 4657 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4658 FunctionDecl *FDecl, 4659 ArrayRef<Expr *> Args) { 4660 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4661 DeclarationName FuncName = FDecl->getDeclName(); 4662 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4663 4664 if (TypoCorrection Corrected = S.CorrectTypo( 4665 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4666 S.getScopeForContext(S.CurContext), nullptr, 4667 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4668 Args.size(), ME), 4669 Sema::CTK_ErrorRecovery)) { 4670 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4671 if (Corrected.isOverloaded()) { 4672 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4673 OverloadCandidateSet::iterator Best; 4674 for (NamedDecl *CD : Corrected) { 4675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4676 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4677 OCS); 4678 } 4679 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4680 case OR_Success: 4681 ND = Best->FoundDecl; 4682 Corrected.setCorrectionDecl(ND); 4683 break; 4684 default: 4685 break; 4686 } 4687 } 4688 ND = ND->getUnderlyingDecl(); 4689 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4690 return Corrected; 4691 } 4692 } 4693 return TypoCorrection(); 4694 } 4695 4696 /// ConvertArgumentsForCall - Converts the arguments specified in 4697 /// Args/NumArgs to the parameter types of the function FDecl with 4698 /// function prototype Proto. Call is the call expression itself, and 4699 /// Fn is the function expression. For a C++ member function, this 4700 /// routine does not attempt to convert the object argument. Returns 4701 /// true if the call is ill-formed. 4702 bool 4703 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4704 FunctionDecl *FDecl, 4705 const FunctionProtoType *Proto, 4706 ArrayRef<Expr *> Args, 4707 SourceLocation RParenLoc, 4708 bool IsExecConfig) { 4709 // Bail out early if calling a builtin with custom typechecking. 4710 if (FDecl) 4711 if (unsigned ID = FDecl->getBuiltinID()) 4712 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4713 return false; 4714 4715 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4716 // assignment, to the types of the corresponding parameter, ... 4717 unsigned NumParams = Proto->getNumParams(); 4718 bool Invalid = false; 4719 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4720 unsigned FnKind = Fn->getType()->isBlockPointerType() 4721 ? 1 /* block */ 4722 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4723 : 0 /* function */); 4724 4725 // If too few arguments are available (and we don't have default 4726 // arguments for the remaining parameters), don't make the call. 4727 if (Args.size() < NumParams) { 4728 if (Args.size() < MinArgs) { 4729 TypoCorrection TC; 4730 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4731 unsigned diag_id = 4732 MinArgs == NumParams && !Proto->isVariadic() 4733 ? diag::err_typecheck_call_too_few_args_suggest 4734 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4735 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4736 << static_cast<unsigned>(Args.size()) 4737 << TC.getCorrectionRange()); 4738 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4739 Diag(RParenLoc, 4740 MinArgs == NumParams && !Proto->isVariadic() 4741 ? diag::err_typecheck_call_too_few_args_one 4742 : diag::err_typecheck_call_too_few_args_at_least_one) 4743 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4744 else 4745 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4746 ? diag::err_typecheck_call_too_few_args 4747 : diag::err_typecheck_call_too_few_args_at_least) 4748 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4749 << Fn->getSourceRange(); 4750 4751 // Emit the location of the prototype. 4752 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4753 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4754 << FDecl; 4755 4756 return true; 4757 } 4758 Call->setNumArgs(Context, NumParams); 4759 } 4760 4761 // If too many are passed and not variadic, error on the extras and drop 4762 // them. 4763 if (Args.size() > NumParams) { 4764 if (!Proto->isVariadic()) { 4765 TypoCorrection TC; 4766 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4767 unsigned diag_id = 4768 MinArgs == NumParams && !Proto->isVariadic() 4769 ? diag::err_typecheck_call_too_many_args_suggest 4770 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4771 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4772 << static_cast<unsigned>(Args.size()) 4773 << TC.getCorrectionRange()); 4774 } else if (NumParams == 1 && FDecl && 4775 FDecl->getParamDecl(0)->getDeclName()) 4776 Diag(Args[NumParams]->getLocStart(), 4777 MinArgs == NumParams 4778 ? diag::err_typecheck_call_too_many_args_one 4779 : diag::err_typecheck_call_too_many_args_at_most_one) 4780 << FnKind << FDecl->getParamDecl(0) 4781 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4782 << SourceRange(Args[NumParams]->getLocStart(), 4783 Args.back()->getLocEnd()); 4784 else 4785 Diag(Args[NumParams]->getLocStart(), 4786 MinArgs == NumParams 4787 ? diag::err_typecheck_call_too_many_args 4788 : diag::err_typecheck_call_too_many_args_at_most) 4789 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4790 << Fn->getSourceRange() 4791 << SourceRange(Args[NumParams]->getLocStart(), 4792 Args.back()->getLocEnd()); 4793 4794 // Emit the location of the prototype. 4795 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4796 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4797 << FDecl; 4798 4799 // This deletes the extra arguments. 4800 Call->setNumArgs(Context, NumParams); 4801 return true; 4802 } 4803 } 4804 SmallVector<Expr *, 8> AllArgs; 4805 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4806 4807 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4808 Proto, 0, Args, AllArgs, CallType); 4809 if (Invalid) 4810 return true; 4811 unsigned TotalNumArgs = AllArgs.size(); 4812 for (unsigned i = 0; i < TotalNumArgs; ++i) 4813 Call->setArg(i, AllArgs[i]); 4814 4815 return false; 4816 } 4817 4818 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4819 const FunctionProtoType *Proto, 4820 unsigned FirstParam, ArrayRef<Expr *> Args, 4821 SmallVectorImpl<Expr *> &AllArgs, 4822 VariadicCallType CallType, bool AllowExplicit, 4823 bool IsListInitialization) { 4824 unsigned NumParams = Proto->getNumParams(); 4825 bool Invalid = false; 4826 size_t ArgIx = 0; 4827 // Continue to check argument types (even if we have too few/many args). 4828 for (unsigned i = FirstParam; i < NumParams; i++) { 4829 QualType ProtoArgType = Proto->getParamType(i); 4830 4831 Expr *Arg; 4832 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4833 if (ArgIx < Args.size()) { 4834 Arg = Args[ArgIx++]; 4835 4836 if (RequireCompleteType(Arg->getLocStart(), 4837 ProtoArgType, 4838 diag::err_call_incomplete_argument, Arg)) 4839 return true; 4840 4841 // Strip the unbridged-cast placeholder expression off, if applicable. 4842 bool CFAudited = false; 4843 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4844 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4845 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4846 Arg = stripARCUnbridgedCast(Arg); 4847 else if (getLangOpts().ObjCAutoRefCount && 4848 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4849 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4850 CFAudited = true; 4851 4852 if (Proto->getExtParameterInfo(i).isNoEscape()) 4853 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4854 BE->getBlockDecl()->setDoesNotEscape(); 4855 4856 InitializedEntity Entity = 4857 Param ? InitializedEntity::InitializeParameter(Context, Param, 4858 ProtoArgType) 4859 : InitializedEntity::InitializeParameter( 4860 Context, ProtoArgType, Proto->isParamConsumed(i)); 4861 4862 // Remember that parameter belongs to a CF audited API. 4863 if (CFAudited) 4864 Entity.setParameterCFAudited(); 4865 4866 ExprResult ArgE = PerformCopyInitialization( 4867 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4868 if (ArgE.isInvalid()) 4869 return true; 4870 4871 Arg = ArgE.getAs<Expr>(); 4872 } else { 4873 assert(Param && "can't use default arguments without a known callee"); 4874 4875 ExprResult ArgExpr = 4876 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4877 if (ArgExpr.isInvalid()) 4878 return true; 4879 4880 Arg = ArgExpr.getAs<Expr>(); 4881 } 4882 4883 // Check for array bounds violations for each argument to the call. This 4884 // check only triggers warnings when the argument isn't a more complex Expr 4885 // with its own checking, such as a BinaryOperator. 4886 CheckArrayAccess(Arg); 4887 4888 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4889 CheckStaticArrayArgument(CallLoc, Param, Arg); 4890 4891 AllArgs.push_back(Arg); 4892 } 4893 4894 // If this is a variadic call, handle args passed through "...". 4895 if (CallType != VariadicDoesNotApply) { 4896 // Assume that extern "C" functions with variadic arguments that 4897 // return __unknown_anytype aren't *really* variadic. 4898 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4899 FDecl->isExternC()) { 4900 for (Expr *A : Args.slice(ArgIx)) { 4901 QualType paramType; // ignored 4902 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4903 Invalid |= arg.isInvalid(); 4904 AllArgs.push_back(arg.get()); 4905 } 4906 4907 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4908 } else { 4909 for (Expr *A : Args.slice(ArgIx)) { 4910 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4911 Invalid |= Arg.isInvalid(); 4912 AllArgs.push_back(Arg.get()); 4913 } 4914 } 4915 4916 // Check for array bounds violations. 4917 for (Expr *A : Args.slice(ArgIx)) 4918 CheckArrayAccess(A); 4919 } 4920 return Invalid; 4921 } 4922 4923 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4924 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4925 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4926 TL = DTL.getOriginalLoc(); 4927 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4928 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4929 << ATL.getLocalSourceRange(); 4930 } 4931 4932 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4933 /// array parameter, check that it is non-null, and that if it is formed by 4934 /// array-to-pointer decay, the underlying array is sufficiently large. 4935 /// 4936 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4937 /// array type derivation, then for each call to the function, the value of the 4938 /// corresponding actual argument shall provide access to the first element of 4939 /// an array with at least as many elements as specified by the size expression. 4940 void 4941 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4942 ParmVarDecl *Param, 4943 const Expr *ArgExpr) { 4944 // Static array parameters are not supported in C++. 4945 if (!Param || getLangOpts().CPlusPlus) 4946 return; 4947 4948 QualType OrigTy = Param->getOriginalType(); 4949 4950 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4951 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4952 return; 4953 4954 if (ArgExpr->isNullPointerConstant(Context, 4955 Expr::NPC_NeverValueDependent)) { 4956 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4957 DiagnoseCalleeStaticArrayParam(*this, Param); 4958 return; 4959 } 4960 4961 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4962 if (!CAT) 4963 return; 4964 4965 const ConstantArrayType *ArgCAT = 4966 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4967 if (!ArgCAT) 4968 return; 4969 4970 if (ArgCAT->getSize().ult(CAT->getSize())) { 4971 Diag(CallLoc, diag::warn_static_array_too_small) 4972 << ArgExpr->getSourceRange() 4973 << (unsigned) ArgCAT->getSize().getZExtValue() 4974 << (unsigned) CAT->getSize().getZExtValue(); 4975 DiagnoseCalleeStaticArrayParam(*this, Param); 4976 } 4977 } 4978 4979 /// Given a function expression of unknown-any type, try to rebuild it 4980 /// to have a function type. 4981 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4982 4983 /// Is the given type a placeholder that we need to lower out 4984 /// immediately during argument processing? 4985 static bool isPlaceholderToRemoveAsArg(QualType type) { 4986 // Placeholders are never sugared. 4987 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4988 if (!placeholder) return false; 4989 4990 switch (placeholder->getKind()) { 4991 // Ignore all the non-placeholder types. 4992 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4993 case BuiltinType::Id: 4994 #include "clang/Basic/OpenCLImageTypes.def" 4995 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4996 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4997 #include "clang/AST/BuiltinTypes.def" 4998 return false; 4999 5000 // We cannot lower out overload sets; they might validly be resolved 5001 // by the call machinery. 5002 case BuiltinType::Overload: 5003 return false; 5004 5005 // Unbridged casts in ARC can be handled in some call positions and 5006 // should be left in place. 5007 case BuiltinType::ARCUnbridgedCast: 5008 return false; 5009 5010 // Pseudo-objects should be converted as soon as possible. 5011 case BuiltinType::PseudoObject: 5012 return true; 5013 5014 // The debugger mode could theoretically but currently does not try 5015 // to resolve unknown-typed arguments based on known parameter types. 5016 case BuiltinType::UnknownAny: 5017 return true; 5018 5019 // These are always invalid as call arguments and should be reported. 5020 case BuiltinType::BoundMember: 5021 case BuiltinType::BuiltinFn: 5022 case BuiltinType::OMPArraySection: 5023 return true; 5024 5025 } 5026 llvm_unreachable("bad builtin type kind"); 5027 } 5028 5029 /// Check an argument list for placeholders that we won't try to 5030 /// handle later. 5031 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5032 // Apply this processing to all the arguments at once instead of 5033 // dying at the first failure. 5034 bool hasInvalid = false; 5035 for (size_t i = 0, e = args.size(); i != e; i++) { 5036 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5037 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5038 if (result.isInvalid()) hasInvalid = true; 5039 else args[i] = result.get(); 5040 } else if (hasInvalid) { 5041 (void)S.CorrectDelayedTyposInExpr(args[i]); 5042 } 5043 } 5044 return hasInvalid; 5045 } 5046 5047 /// If a builtin function has a pointer argument with no explicit address 5048 /// space, then it should be able to accept a pointer to any address 5049 /// space as input. In order to do this, we need to replace the 5050 /// standard builtin declaration with one that uses the same address space 5051 /// as the call. 5052 /// 5053 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5054 /// it does not contain any pointer arguments without 5055 /// an address space qualifer. Otherwise the rewritten 5056 /// FunctionDecl is returned. 5057 /// TODO: Handle pointer return types. 5058 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5059 const FunctionDecl *FDecl, 5060 MultiExprArg ArgExprs) { 5061 5062 QualType DeclType = FDecl->getType(); 5063 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5064 5065 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5066 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5067 return nullptr; 5068 5069 bool NeedsNewDecl = false; 5070 unsigned i = 0; 5071 SmallVector<QualType, 8> OverloadParams; 5072 5073 for (QualType ParamType : FT->param_types()) { 5074 5075 // Convert array arguments to pointer to simplify type lookup. 5076 ExprResult ArgRes = 5077 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5078 if (ArgRes.isInvalid()) 5079 return nullptr; 5080 Expr *Arg = ArgRes.get(); 5081 QualType ArgType = Arg->getType(); 5082 if (!ParamType->isPointerType() || 5083 ParamType.getQualifiers().hasAddressSpace() || 5084 !ArgType->isPointerType() || 5085 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5086 OverloadParams.push_back(ParamType); 5087 continue; 5088 } 5089 5090 NeedsNewDecl = true; 5091 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5092 5093 QualType PointeeType = ParamType->getPointeeType(); 5094 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5095 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5096 } 5097 5098 if (!NeedsNewDecl) 5099 return nullptr; 5100 5101 FunctionProtoType::ExtProtoInfo EPI; 5102 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5103 OverloadParams, EPI); 5104 DeclContext *Parent = Context.getTranslationUnitDecl(); 5105 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5106 FDecl->getLocation(), 5107 FDecl->getLocation(), 5108 FDecl->getIdentifier(), 5109 OverloadTy, 5110 /*TInfo=*/nullptr, 5111 SC_Extern, false, 5112 /*hasPrototype=*/true); 5113 SmallVector<ParmVarDecl*, 16> Params; 5114 FT = cast<FunctionProtoType>(OverloadTy); 5115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5116 QualType ParamType = FT->getParamType(i); 5117 ParmVarDecl *Parm = 5118 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5119 SourceLocation(), nullptr, ParamType, 5120 /*TInfo=*/nullptr, SC_None, nullptr); 5121 Parm->setScopeInfo(0, i); 5122 Params.push_back(Parm); 5123 } 5124 OverloadDecl->setParams(Params); 5125 return OverloadDecl; 5126 } 5127 5128 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5129 FunctionDecl *Callee, 5130 MultiExprArg ArgExprs) { 5131 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5132 // similar attributes) really don't like it when functions are called with an 5133 // invalid number of args. 5134 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5135 /*PartialOverloading=*/false) && 5136 !Callee->isVariadic()) 5137 return; 5138 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5139 return; 5140 5141 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5142 S.Diag(Fn->getLocStart(), 5143 isa<CXXMethodDecl>(Callee) 5144 ? diag::err_ovl_no_viable_member_function_in_call 5145 : diag::err_ovl_no_viable_function_in_call) 5146 << Callee << Callee->getSourceRange(); 5147 S.Diag(Callee->getLocation(), 5148 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5149 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5150 return; 5151 } 5152 } 5153 5154 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5155 const UnresolvedMemberExpr *const UME, Sema &S) { 5156 5157 const auto GetFunctionLevelDCIfCXXClass = 5158 [](Sema &S) -> const CXXRecordDecl * { 5159 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5160 if (!DC || !DC->getParent()) 5161 return nullptr; 5162 5163 // If the call to some member function was made from within a member 5164 // function body 'M' return return 'M's parent. 5165 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5166 return MD->getParent()->getCanonicalDecl(); 5167 // else the call was made from within a default member initializer of a 5168 // class, so return the class. 5169 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5170 return RD->getCanonicalDecl(); 5171 return nullptr; 5172 }; 5173 // If our DeclContext is neither a member function nor a class (in the 5174 // case of a lambda in a default member initializer), we can't have an 5175 // enclosing 'this'. 5176 5177 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5178 if (!CurParentClass) 5179 return false; 5180 5181 // The naming class for implicit member functions call is the class in which 5182 // name lookup starts. 5183 const CXXRecordDecl *const NamingClass = 5184 UME->getNamingClass()->getCanonicalDecl(); 5185 assert(NamingClass && "Must have naming class even for implicit access"); 5186 5187 // If the unresolved member functions were found in a 'naming class' that is 5188 // related (either the same or derived from) to the class that contains the 5189 // member function that itself contained the implicit member access. 5190 5191 return CurParentClass == NamingClass || 5192 CurParentClass->isDerivedFrom(NamingClass); 5193 } 5194 5195 static void 5196 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5197 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5198 5199 if (!UME) 5200 return; 5201 5202 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5203 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5204 // already been captured, or if this is an implicit member function call (if 5205 // it isn't, an attempt to capture 'this' should already have been made). 5206 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5207 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5208 return; 5209 5210 // Check if the naming class in which the unresolved members were found is 5211 // related (same as or is a base of) to the enclosing class. 5212 5213 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5214 return; 5215 5216 5217 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5218 // If the enclosing function is not dependent, then this lambda is 5219 // capture ready, so if we can capture this, do so. 5220 if (!EnclosingFunctionCtx->isDependentContext()) { 5221 // If the current lambda and all enclosing lambdas can capture 'this' - 5222 // then go ahead and capture 'this' (since our unresolved overload set 5223 // contains at least one non-static member function). 5224 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5225 S.CheckCXXThisCapture(CallLoc); 5226 } else if (S.CurContext->isDependentContext()) { 5227 // ... since this is an implicit member reference, that might potentially 5228 // involve a 'this' capture, mark 'this' for potential capture in 5229 // enclosing lambdas. 5230 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5231 CurLSI->addPotentialThisCapture(CallLoc); 5232 } 5233 } 5234 5235 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5236 /// This provides the location of the left/right parens and a list of comma 5237 /// locations. 5238 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5239 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5240 Expr *ExecConfig, bool IsExecConfig) { 5241 // Since this might be a postfix expression, get rid of ParenListExprs. 5242 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5243 if (Result.isInvalid()) return ExprError(); 5244 Fn = Result.get(); 5245 5246 if (checkArgsForPlaceholders(*this, ArgExprs)) 5247 return ExprError(); 5248 5249 if (getLangOpts().CPlusPlus) { 5250 // If this is a pseudo-destructor expression, build the call immediately. 5251 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5252 if (!ArgExprs.empty()) { 5253 // Pseudo-destructor calls should not have any arguments. 5254 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5255 << FixItHint::CreateRemoval( 5256 SourceRange(ArgExprs.front()->getLocStart(), 5257 ArgExprs.back()->getLocEnd())); 5258 } 5259 5260 return new (Context) 5261 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5262 } 5263 if (Fn->getType() == Context.PseudoObjectTy) { 5264 ExprResult result = CheckPlaceholderExpr(Fn); 5265 if (result.isInvalid()) return ExprError(); 5266 Fn = result.get(); 5267 } 5268 5269 // Determine whether this is a dependent call inside a C++ template, 5270 // in which case we won't do any semantic analysis now. 5271 bool Dependent = false; 5272 if (Fn->isTypeDependent()) 5273 Dependent = true; 5274 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5275 Dependent = true; 5276 5277 if (Dependent) { 5278 if (ExecConfig) { 5279 return new (Context) CUDAKernelCallExpr( 5280 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5281 Context.DependentTy, VK_RValue, RParenLoc); 5282 } else { 5283 5284 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5285 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5286 Fn->getLocStart()); 5287 5288 return new (Context) CallExpr( 5289 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5290 } 5291 } 5292 5293 // Determine whether this is a call to an object (C++ [over.call.object]). 5294 if (Fn->getType()->isRecordType()) 5295 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5296 RParenLoc); 5297 5298 if (Fn->getType() == Context.UnknownAnyTy) { 5299 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5300 if (result.isInvalid()) return ExprError(); 5301 Fn = result.get(); 5302 } 5303 5304 if (Fn->getType() == Context.BoundMemberTy) { 5305 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5306 RParenLoc); 5307 } 5308 } 5309 5310 // Check for overloaded calls. This can happen even in C due to extensions. 5311 if (Fn->getType() == Context.OverloadTy) { 5312 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5313 5314 // We aren't supposed to apply this logic if there's an '&' involved. 5315 if (!find.HasFormOfMemberPointer) { 5316 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5317 return new (Context) CallExpr( 5318 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5319 OverloadExpr *ovl = find.Expression; 5320 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5321 return BuildOverloadedCallExpr( 5322 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5323 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5324 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5325 RParenLoc); 5326 } 5327 } 5328 5329 // If we're directly calling a function, get the appropriate declaration. 5330 if (Fn->getType() == Context.UnknownAnyTy) { 5331 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5332 if (result.isInvalid()) return ExprError(); 5333 Fn = result.get(); 5334 } 5335 5336 Expr *NakedFn = Fn->IgnoreParens(); 5337 5338 bool CallingNDeclIndirectly = false; 5339 NamedDecl *NDecl = nullptr; 5340 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5341 if (UnOp->getOpcode() == UO_AddrOf) { 5342 CallingNDeclIndirectly = true; 5343 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5344 } 5345 } 5346 5347 if (isa<DeclRefExpr>(NakedFn)) { 5348 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5349 5350 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5351 if (FDecl && FDecl->getBuiltinID()) { 5352 // Rewrite the function decl for this builtin by replacing parameters 5353 // with no explicit address space with the address space of the arguments 5354 // in ArgExprs. 5355 if ((FDecl = 5356 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5357 NDecl = FDecl; 5358 Fn = DeclRefExpr::Create( 5359 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5360 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5361 } 5362 } 5363 } else if (isa<MemberExpr>(NakedFn)) 5364 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5365 5366 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5367 if (CallingNDeclIndirectly && 5368 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5369 Fn->getLocStart())) 5370 return ExprError(); 5371 5372 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5373 return ExprError(); 5374 5375 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5376 } 5377 5378 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5379 ExecConfig, IsExecConfig); 5380 } 5381 5382 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5383 /// 5384 /// __builtin_astype( value, dst type ) 5385 /// 5386 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5387 SourceLocation BuiltinLoc, 5388 SourceLocation RParenLoc) { 5389 ExprValueKind VK = VK_RValue; 5390 ExprObjectKind OK = OK_Ordinary; 5391 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5392 QualType SrcTy = E->getType(); 5393 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5394 return ExprError(Diag(BuiltinLoc, 5395 diag::err_invalid_astype_of_different_size) 5396 << DstTy 5397 << SrcTy 5398 << E->getSourceRange()); 5399 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5400 } 5401 5402 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5403 /// provided arguments. 5404 /// 5405 /// __builtin_convertvector( value, dst type ) 5406 /// 5407 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5408 SourceLocation BuiltinLoc, 5409 SourceLocation RParenLoc) { 5410 TypeSourceInfo *TInfo; 5411 GetTypeFromParser(ParsedDestTy, &TInfo); 5412 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5413 } 5414 5415 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5416 /// i.e. an expression not of \p OverloadTy. The expression should 5417 /// unary-convert to an expression of function-pointer or 5418 /// block-pointer type. 5419 /// 5420 /// \param NDecl the declaration being called, if available 5421 ExprResult 5422 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5423 SourceLocation LParenLoc, 5424 ArrayRef<Expr *> Args, 5425 SourceLocation RParenLoc, 5426 Expr *Config, bool IsExecConfig) { 5427 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5428 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5429 5430 // Functions with 'interrupt' attribute cannot be called directly. 5431 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5432 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5433 return ExprError(); 5434 } 5435 5436 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5437 // so there's some risk when calling out to non-interrupt handler functions 5438 // that the callee might not preserve them. This is easy to diagnose here, 5439 // but can be very challenging to debug. 5440 if (auto *Caller = getCurFunctionDecl()) 5441 if (Caller->hasAttr<ARMInterruptAttr>()) { 5442 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5443 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5444 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5445 } 5446 5447 // Promote the function operand. 5448 // We special-case function promotion here because we only allow promoting 5449 // builtin functions to function pointers in the callee of a call. 5450 ExprResult Result; 5451 if (BuiltinID && 5452 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5453 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5454 CK_BuiltinFnToFnPtr).get(); 5455 } else { 5456 Result = CallExprUnaryConversions(Fn); 5457 } 5458 if (Result.isInvalid()) 5459 return ExprError(); 5460 Fn = Result.get(); 5461 5462 // Make the call expr early, before semantic checks. This guarantees cleanup 5463 // of arguments and function on error. 5464 CallExpr *TheCall; 5465 if (Config) 5466 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5467 cast<CallExpr>(Config), Args, 5468 Context.BoolTy, VK_RValue, 5469 RParenLoc); 5470 else 5471 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5472 VK_RValue, RParenLoc); 5473 5474 if (!getLangOpts().CPlusPlus) { 5475 // C cannot always handle TypoExpr nodes in builtin calls and direct 5476 // function calls as their argument checking don't necessarily handle 5477 // dependent types properly, so make sure any TypoExprs have been 5478 // dealt with. 5479 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5480 if (!Result.isUsable()) return ExprError(); 5481 TheCall = dyn_cast<CallExpr>(Result.get()); 5482 if (!TheCall) return Result; 5483 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5484 } 5485 5486 // Bail out early if calling a builtin with custom typechecking. 5487 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5488 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5489 5490 retry: 5491 const FunctionType *FuncT; 5492 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5493 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5494 // have type pointer to function". 5495 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5496 if (!FuncT) 5497 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5498 << Fn->getType() << Fn->getSourceRange()); 5499 } else if (const BlockPointerType *BPT = 5500 Fn->getType()->getAs<BlockPointerType>()) { 5501 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5502 } else { 5503 // Handle calls to expressions of unknown-any type. 5504 if (Fn->getType() == Context.UnknownAnyTy) { 5505 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5506 if (rewrite.isInvalid()) return ExprError(); 5507 Fn = rewrite.get(); 5508 TheCall->setCallee(Fn); 5509 goto retry; 5510 } 5511 5512 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5513 << Fn->getType() << Fn->getSourceRange()); 5514 } 5515 5516 if (getLangOpts().CUDA) { 5517 if (Config) { 5518 // CUDA: Kernel calls must be to global functions 5519 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5520 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5521 << FDecl << Fn->getSourceRange()); 5522 5523 // CUDA: Kernel function must have 'void' return type 5524 if (!FuncT->getReturnType()->isVoidType()) 5525 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5526 << Fn->getType() << Fn->getSourceRange()); 5527 } else { 5528 // CUDA: Calls to global functions must be configured 5529 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5530 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5531 << FDecl << Fn->getSourceRange()); 5532 } 5533 } 5534 5535 // Check for a valid return type 5536 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5537 FDecl)) 5538 return ExprError(); 5539 5540 // We know the result type of the call, set it. 5541 TheCall->setType(FuncT->getCallResultType(Context)); 5542 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5543 5544 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5545 if (Proto) { 5546 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5547 IsExecConfig)) 5548 return ExprError(); 5549 } else { 5550 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5551 5552 if (FDecl) { 5553 // Check if we have too few/too many template arguments, based 5554 // on our knowledge of the function definition. 5555 const FunctionDecl *Def = nullptr; 5556 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5557 Proto = Def->getType()->getAs<FunctionProtoType>(); 5558 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5559 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5560 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5561 } 5562 5563 // If the function we're calling isn't a function prototype, but we have 5564 // a function prototype from a prior declaratiom, use that prototype. 5565 if (!FDecl->hasPrototype()) 5566 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5567 } 5568 5569 // Promote the arguments (C99 6.5.2.2p6). 5570 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5571 Expr *Arg = Args[i]; 5572 5573 if (Proto && i < Proto->getNumParams()) { 5574 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5575 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5576 ExprResult ArgE = 5577 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5578 if (ArgE.isInvalid()) 5579 return true; 5580 5581 Arg = ArgE.getAs<Expr>(); 5582 5583 } else { 5584 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5585 5586 if (ArgE.isInvalid()) 5587 return true; 5588 5589 Arg = ArgE.getAs<Expr>(); 5590 } 5591 5592 if (RequireCompleteType(Arg->getLocStart(), 5593 Arg->getType(), 5594 diag::err_call_incomplete_argument, Arg)) 5595 return ExprError(); 5596 5597 TheCall->setArg(i, Arg); 5598 } 5599 } 5600 5601 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5602 if (!Method->isStatic()) 5603 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5604 << Fn->getSourceRange()); 5605 5606 // Check for sentinels 5607 if (NDecl) 5608 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5609 5610 // Do special checking on direct calls to functions. 5611 if (FDecl) { 5612 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5613 return ExprError(); 5614 5615 if (BuiltinID) 5616 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5617 } else if (NDecl) { 5618 if (CheckPointerCall(NDecl, TheCall, Proto)) 5619 return ExprError(); 5620 } else { 5621 if (CheckOtherCall(TheCall, Proto)) 5622 return ExprError(); 5623 } 5624 5625 return MaybeBindToTemporary(TheCall); 5626 } 5627 5628 ExprResult 5629 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5630 SourceLocation RParenLoc, Expr *InitExpr) { 5631 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5632 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5633 5634 TypeSourceInfo *TInfo; 5635 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5636 if (!TInfo) 5637 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5638 5639 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5640 } 5641 5642 ExprResult 5643 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5644 SourceLocation RParenLoc, Expr *LiteralExpr) { 5645 QualType literalType = TInfo->getType(); 5646 5647 if (literalType->isArrayType()) { 5648 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5649 diag::err_illegal_decl_array_incomplete_type, 5650 SourceRange(LParenLoc, 5651 LiteralExpr->getSourceRange().getEnd()))) 5652 return ExprError(); 5653 if (literalType->isVariableArrayType()) 5654 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5655 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5656 } else if (!literalType->isDependentType() && 5657 RequireCompleteType(LParenLoc, literalType, 5658 diag::err_typecheck_decl_incomplete_type, 5659 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5660 return ExprError(); 5661 5662 InitializedEntity Entity 5663 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5664 InitializationKind Kind 5665 = InitializationKind::CreateCStyleCast(LParenLoc, 5666 SourceRange(LParenLoc, RParenLoc), 5667 /*InitList=*/true); 5668 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5669 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5670 &literalType); 5671 if (Result.isInvalid()) 5672 return ExprError(); 5673 LiteralExpr = Result.get(); 5674 5675 bool isFileScope = !CurContext->isFunctionOrMethod(); 5676 if (isFileScope && 5677 !LiteralExpr->isTypeDependent() && 5678 !LiteralExpr->isValueDependent() && 5679 !literalType->isDependentType()) { // 6.5.2.5p3 5680 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5681 return ExprError(); 5682 } 5683 5684 // In C, compound literals are l-values for some reason. 5685 // For GCC compatibility, in C++, file-scope array compound literals with 5686 // constant initializers are also l-values, and compound literals are 5687 // otherwise prvalues. 5688 // 5689 // (GCC also treats C++ list-initialized file-scope array prvalues with 5690 // constant initializers as l-values, but that's non-conforming, so we don't 5691 // follow it there.) 5692 // 5693 // FIXME: It would be better to handle the lvalue cases as materializing and 5694 // lifetime-extending a temporary object, but our materialized temporaries 5695 // representation only supports lifetime extension from a variable, not "out 5696 // of thin air". 5697 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5698 // is bound to the result of applying array-to-pointer decay to the compound 5699 // literal. 5700 // FIXME: GCC supports compound literals of reference type, which should 5701 // obviously have a value kind derived from the kind of reference involved. 5702 ExprValueKind VK = 5703 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5704 ? VK_RValue 5705 : VK_LValue; 5706 5707 return MaybeBindToTemporary( 5708 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5709 VK, LiteralExpr, isFileScope)); 5710 } 5711 5712 ExprResult 5713 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5714 SourceLocation RBraceLoc) { 5715 // Immediately handle non-overload placeholders. Overloads can be 5716 // resolved contextually, but everything else here can't. 5717 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5718 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5719 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5720 5721 // Ignore failures; dropping the entire initializer list because 5722 // of one failure would be terrible for indexing/etc. 5723 if (result.isInvalid()) continue; 5724 5725 InitArgList[I] = result.get(); 5726 } 5727 } 5728 5729 // Semantic analysis for initializers is done by ActOnDeclarator() and 5730 // CheckInitializer() - it requires knowledge of the object being initialized. 5731 5732 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5733 RBraceLoc); 5734 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5735 return E; 5736 } 5737 5738 /// Do an explicit extend of the given block pointer if we're in ARC. 5739 void Sema::maybeExtendBlockObject(ExprResult &E) { 5740 assert(E.get()->getType()->isBlockPointerType()); 5741 assert(E.get()->isRValue()); 5742 5743 // Only do this in an r-value context. 5744 if (!getLangOpts().ObjCAutoRefCount) return; 5745 5746 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5747 CK_ARCExtendBlockObject, E.get(), 5748 /*base path*/ nullptr, VK_RValue); 5749 Cleanup.setExprNeedsCleanups(true); 5750 } 5751 5752 /// Prepare a conversion of the given expression to an ObjC object 5753 /// pointer type. 5754 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5755 QualType type = E.get()->getType(); 5756 if (type->isObjCObjectPointerType()) { 5757 return CK_BitCast; 5758 } else if (type->isBlockPointerType()) { 5759 maybeExtendBlockObject(E); 5760 return CK_BlockPointerToObjCPointerCast; 5761 } else { 5762 assert(type->isPointerType()); 5763 return CK_CPointerToObjCPointerCast; 5764 } 5765 } 5766 5767 /// Prepares for a scalar cast, performing all the necessary stages 5768 /// except the final cast and returning the kind required. 5769 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5770 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5771 // Also, callers should have filtered out the invalid cases with 5772 // pointers. Everything else should be possible. 5773 5774 QualType SrcTy = Src.get()->getType(); 5775 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5776 return CK_NoOp; 5777 5778 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5779 case Type::STK_MemberPointer: 5780 llvm_unreachable("member pointer type in C"); 5781 5782 case Type::STK_CPointer: 5783 case Type::STK_BlockPointer: 5784 case Type::STK_ObjCObjectPointer: 5785 switch (DestTy->getScalarTypeKind()) { 5786 case Type::STK_CPointer: { 5787 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5788 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5789 if (SrcAS != DestAS) 5790 return CK_AddressSpaceConversion; 5791 return CK_BitCast; 5792 } 5793 case Type::STK_BlockPointer: 5794 return (SrcKind == Type::STK_BlockPointer 5795 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5796 case Type::STK_ObjCObjectPointer: 5797 if (SrcKind == Type::STK_ObjCObjectPointer) 5798 return CK_BitCast; 5799 if (SrcKind == Type::STK_CPointer) 5800 return CK_CPointerToObjCPointerCast; 5801 maybeExtendBlockObject(Src); 5802 return CK_BlockPointerToObjCPointerCast; 5803 case Type::STK_Bool: 5804 return CK_PointerToBoolean; 5805 case Type::STK_Integral: 5806 return CK_PointerToIntegral; 5807 case Type::STK_Floating: 5808 case Type::STK_FloatingComplex: 5809 case Type::STK_IntegralComplex: 5810 case Type::STK_MemberPointer: 5811 llvm_unreachable("illegal cast from pointer"); 5812 } 5813 llvm_unreachable("Should have returned before this"); 5814 5815 case Type::STK_Bool: // casting from bool is like casting from an integer 5816 case Type::STK_Integral: 5817 switch (DestTy->getScalarTypeKind()) { 5818 case Type::STK_CPointer: 5819 case Type::STK_ObjCObjectPointer: 5820 case Type::STK_BlockPointer: 5821 if (Src.get()->isNullPointerConstant(Context, 5822 Expr::NPC_ValueDependentIsNull)) 5823 return CK_NullToPointer; 5824 return CK_IntegralToPointer; 5825 case Type::STK_Bool: 5826 return CK_IntegralToBoolean; 5827 case Type::STK_Integral: 5828 return CK_IntegralCast; 5829 case Type::STK_Floating: 5830 return CK_IntegralToFloating; 5831 case Type::STK_IntegralComplex: 5832 Src = ImpCastExprToType(Src.get(), 5833 DestTy->castAs<ComplexType>()->getElementType(), 5834 CK_IntegralCast); 5835 return CK_IntegralRealToComplex; 5836 case Type::STK_FloatingComplex: 5837 Src = ImpCastExprToType(Src.get(), 5838 DestTy->castAs<ComplexType>()->getElementType(), 5839 CK_IntegralToFloating); 5840 return CK_FloatingRealToComplex; 5841 case Type::STK_MemberPointer: 5842 llvm_unreachable("member pointer type in C"); 5843 } 5844 llvm_unreachable("Should have returned before this"); 5845 5846 case Type::STK_Floating: 5847 switch (DestTy->getScalarTypeKind()) { 5848 case Type::STK_Floating: 5849 return CK_FloatingCast; 5850 case Type::STK_Bool: 5851 return CK_FloatingToBoolean; 5852 case Type::STK_Integral: 5853 return CK_FloatingToIntegral; 5854 case Type::STK_FloatingComplex: 5855 Src = ImpCastExprToType(Src.get(), 5856 DestTy->castAs<ComplexType>()->getElementType(), 5857 CK_FloatingCast); 5858 return CK_FloatingRealToComplex; 5859 case Type::STK_IntegralComplex: 5860 Src = ImpCastExprToType(Src.get(), 5861 DestTy->castAs<ComplexType>()->getElementType(), 5862 CK_FloatingToIntegral); 5863 return CK_IntegralRealToComplex; 5864 case Type::STK_CPointer: 5865 case Type::STK_ObjCObjectPointer: 5866 case Type::STK_BlockPointer: 5867 llvm_unreachable("valid float->pointer cast?"); 5868 case Type::STK_MemberPointer: 5869 llvm_unreachable("member pointer type in C"); 5870 } 5871 llvm_unreachable("Should have returned before this"); 5872 5873 case Type::STK_FloatingComplex: 5874 switch (DestTy->getScalarTypeKind()) { 5875 case Type::STK_FloatingComplex: 5876 return CK_FloatingComplexCast; 5877 case Type::STK_IntegralComplex: 5878 return CK_FloatingComplexToIntegralComplex; 5879 case Type::STK_Floating: { 5880 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5881 if (Context.hasSameType(ET, DestTy)) 5882 return CK_FloatingComplexToReal; 5883 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5884 return CK_FloatingCast; 5885 } 5886 case Type::STK_Bool: 5887 return CK_FloatingComplexToBoolean; 5888 case Type::STK_Integral: 5889 Src = ImpCastExprToType(Src.get(), 5890 SrcTy->castAs<ComplexType>()->getElementType(), 5891 CK_FloatingComplexToReal); 5892 return CK_FloatingToIntegral; 5893 case Type::STK_CPointer: 5894 case Type::STK_ObjCObjectPointer: 5895 case Type::STK_BlockPointer: 5896 llvm_unreachable("valid complex float->pointer cast?"); 5897 case Type::STK_MemberPointer: 5898 llvm_unreachable("member pointer type in C"); 5899 } 5900 llvm_unreachable("Should have returned before this"); 5901 5902 case Type::STK_IntegralComplex: 5903 switch (DestTy->getScalarTypeKind()) { 5904 case Type::STK_FloatingComplex: 5905 return CK_IntegralComplexToFloatingComplex; 5906 case Type::STK_IntegralComplex: 5907 return CK_IntegralComplexCast; 5908 case Type::STK_Integral: { 5909 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5910 if (Context.hasSameType(ET, DestTy)) 5911 return CK_IntegralComplexToReal; 5912 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5913 return CK_IntegralCast; 5914 } 5915 case Type::STK_Bool: 5916 return CK_IntegralComplexToBoolean; 5917 case Type::STK_Floating: 5918 Src = ImpCastExprToType(Src.get(), 5919 SrcTy->castAs<ComplexType>()->getElementType(), 5920 CK_IntegralComplexToReal); 5921 return CK_IntegralToFloating; 5922 case Type::STK_CPointer: 5923 case Type::STK_ObjCObjectPointer: 5924 case Type::STK_BlockPointer: 5925 llvm_unreachable("valid complex int->pointer cast?"); 5926 case Type::STK_MemberPointer: 5927 llvm_unreachable("member pointer type in C"); 5928 } 5929 llvm_unreachable("Should have returned before this"); 5930 } 5931 5932 llvm_unreachable("Unhandled scalar cast"); 5933 } 5934 5935 static bool breakDownVectorType(QualType type, uint64_t &len, 5936 QualType &eltType) { 5937 // Vectors are simple. 5938 if (const VectorType *vecType = type->getAs<VectorType>()) { 5939 len = vecType->getNumElements(); 5940 eltType = vecType->getElementType(); 5941 assert(eltType->isScalarType()); 5942 return true; 5943 } 5944 5945 // We allow lax conversion to and from non-vector types, but only if 5946 // they're real types (i.e. non-complex, non-pointer scalar types). 5947 if (!type->isRealType()) return false; 5948 5949 len = 1; 5950 eltType = type; 5951 return true; 5952 } 5953 5954 /// Are the two types lax-compatible vector types? That is, given 5955 /// that one of them is a vector, do they have equal storage sizes, 5956 /// where the storage size is the number of elements times the element 5957 /// size? 5958 /// 5959 /// This will also return false if either of the types is neither a 5960 /// vector nor a real type. 5961 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5962 assert(destTy->isVectorType() || srcTy->isVectorType()); 5963 5964 // Disallow lax conversions between scalars and ExtVectors (these 5965 // conversions are allowed for other vector types because common headers 5966 // depend on them). Most scalar OP ExtVector cases are handled by the 5967 // splat path anyway, which does what we want (convert, not bitcast). 5968 // What this rules out for ExtVectors is crazy things like char4*float. 5969 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5970 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5971 5972 uint64_t srcLen, destLen; 5973 QualType srcEltTy, destEltTy; 5974 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5975 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5976 5977 // ASTContext::getTypeSize will return the size rounded up to a 5978 // power of 2, so instead of using that, we need to use the raw 5979 // element size multiplied by the element count. 5980 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5981 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5982 5983 return (srcLen * srcEltSize == destLen * destEltSize); 5984 } 5985 5986 /// Is this a legal conversion between two types, one of which is 5987 /// known to be a vector type? 5988 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5989 assert(destTy->isVectorType() || srcTy->isVectorType()); 5990 5991 if (!Context.getLangOpts().LaxVectorConversions) 5992 return false; 5993 return areLaxCompatibleVectorTypes(srcTy, destTy); 5994 } 5995 5996 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5997 CastKind &Kind) { 5998 assert(VectorTy->isVectorType() && "Not a vector type!"); 5999 6000 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6001 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6002 return Diag(R.getBegin(), 6003 Ty->isVectorType() ? 6004 diag::err_invalid_conversion_between_vectors : 6005 diag::err_invalid_conversion_between_vector_and_integer) 6006 << VectorTy << Ty << R; 6007 } else 6008 return Diag(R.getBegin(), 6009 diag::err_invalid_conversion_between_vector_and_scalar) 6010 << VectorTy << Ty << R; 6011 6012 Kind = CK_BitCast; 6013 return false; 6014 } 6015 6016 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6017 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6018 6019 if (DestElemTy == SplattedExpr->getType()) 6020 return SplattedExpr; 6021 6022 assert(DestElemTy->isFloatingType() || 6023 DestElemTy->isIntegralOrEnumerationType()); 6024 6025 CastKind CK; 6026 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6027 // OpenCL requires that we convert `true` boolean expressions to -1, but 6028 // only when splatting vectors. 6029 if (DestElemTy->isFloatingType()) { 6030 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6031 // in two steps: boolean to signed integral, then to floating. 6032 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6033 CK_BooleanToSignedIntegral); 6034 SplattedExpr = CastExprRes.get(); 6035 CK = CK_IntegralToFloating; 6036 } else { 6037 CK = CK_BooleanToSignedIntegral; 6038 } 6039 } else { 6040 ExprResult CastExprRes = SplattedExpr; 6041 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6042 if (CastExprRes.isInvalid()) 6043 return ExprError(); 6044 SplattedExpr = CastExprRes.get(); 6045 } 6046 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6047 } 6048 6049 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6050 Expr *CastExpr, CastKind &Kind) { 6051 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6052 6053 QualType SrcTy = CastExpr->getType(); 6054 6055 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6056 // an ExtVectorType. 6057 // In OpenCL, casts between vectors of different types are not allowed. 6058 // (See OpenCL 6.2). 6059 if (SrcTy->isVectorType()) { 6060 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6061 (getLangOpts().OpenCL && 6062 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6063 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6064 << DestTy << SrcTy << R; 6065 return ExprError(); 6066 } 6067 Kind = CK_BitCast; 6068 return CastExpr; 6069 } 6070 6071 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6072 // conversion will take place first from scalar to elt type, and then 6073 // splat from elt type to vector. 6074 if (SrcTy->isPointerType()) 6075 return Diag(R.getBegin(), 6076 diag::err_invalid_conversion_between_vector_and_scalar) 6077 << DestTy << SrcTy << R; 6078 6079 Kind = CK_VectorSplat; 6080 return prepareVectorSplat(DestTy, CastExpr); 6081 } 6082 6083 ExprResult 6084 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6085 Declarator &D, ParsedType &Ty, 6086 SourceLocation RParenLoc, Expr *CastExpr) { 6087 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6088 "ActOnCastExpr(): missing type or expr"); 6089 6090 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6091 if (D.isInvalidType()) 6092 return ExprError(); 6093 6094 if (getLangOpts().CPlusPlus) { 6095 // Check that there are no default arguments (C++ only). 6096 CheckExtraCXXDefaultArguments(D); 6097 } else { 6098 // Make sure any TypoExprs have been dealt with. 6099 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6100 if (!Res.isUsable()) 6101 return ExprError(); 6102 CastExpr = Res.get(); 6103 } 6104 6105 checkUnusedDeclAttributes(D); 6106 6107 QualType castType = castTInfo->getType(); 6108 Ty = CreateParsedType(castType, castTInfo); 6109 6110 bool isVectorLiteral = false; 6111 6112 // Check for an altivec or OpenCL literal, 6113 // i.e. all the elements are integer constants. 6114 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6115 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6116 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6117 && castType->isVectorType() && (PE || PLE)) { 6118 if (PLE && PLE->getNumExprs() == 0) { 6119 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6120 return ExprError(); 6121 } 6122 if (PE || PLE->getNumExprs() == 1) { 6123 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6124 if (!E->getType()->isVectorType()) 6125 isVectorLiteral = true; 6126 } 6127 else 6128 isVectorLiteral = true; 6129 } 6130 6131 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6132 // then handle it as such. 6133 if (isVectorLiteral) 6134 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6135 6136 // If the Expr being casted is a ParenListExpr, handle it specially. 6137 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6138 // sequence of BinOp comma operators. 6139 if (isa<ParenListExpr>(CastExpr)) { 6140 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6141 if (Result.isInvalid()) return ExprError(); 6142 CastExpr = Result.get(); 6143 } 6144 6145 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6146 !getSourceManager().isInSystemMacro(LParenLoc)) 6147 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6148 6149 CheckTollFreeBridgeCast(castType, CastExpr); 6150 6151 CheckObjCBridgeRelatedCast(castType, CastExpr); 6152 6153 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6154 6155 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6156 } 6157 6158 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6159 SourceLocation RParenLoc, Expr *E, 6160 TypeSourceInfo *TInfo) { 6161 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6162 "Expected paren or paren list expression"); 6163 6164 Expr **exprs; 6165 unsigned numExprs; 6166 Expr *subExpr; 6167 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6168 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6169 LiteralLParenLoc = PE->getLParenLoc(); 6170 LiteralRParenLoc = PE->getRParenLoc(); 6171 exprs = PE->getExprs(); 6172 numExprs = PE->getNumExprs(); 6173 } else { // isa<ParenExpr> by assertion at function entrance 6174 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6175 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6176 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6177 exprs = &subExpr; 6178 numExprs = 1; 6179 } 6180 6181 QualType Ty = TInfo->getType(); 6182 assert(Ty->isVectorType() && "Expected vector type"); 6183 6184 SmallVector<Expr *, 8> initExprs; 6185 const VectorType *VTy = Ty->getAs<VectorType>(); 6186 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6187 6188 // '(...)' form of vector initialization in AltiVec: the number of 6189 // initializers must be one or must match the size of the vector. 6190 // If a single value is specified in the initializer then it will be 6191 // replicated to all the components of the vector 6192 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6193 // The number of initializers must be one or must match the size of the 6194 // vector. If a single value is specified in the initializer then it will 6195 // be replicated to all the components of the vector 6196 if (numExprs == 1) { 6197 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6198 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6199 if (Literal.isInvalid()) 6200 return ExprError(); 6201 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6202 PrepareScalarCast(Literal, ElemTy)); 6203 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6204 } 6205 else if (numExprs < numElems) { 6206 Diag(E->getExprLoc(), 6207 diag::err_incorrect_number_of_vector_initializers); 6208 return ExprError(); 6209 } 6210 else 6211 initExprs.append(exprs, exprs + numExprs); 6212 } 6213 else { 6214 // For OpenCL, when the number of initializers is a single value, 6215 // it will be replicated to all components of the vector. 6216 if (getLangOpts().OpenCL && 6217 VTy->getVectorKind() == VectorType::GenericVector && 6218 numExprs == 1) { 6219 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6220 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6221 if (Literal.isInvalid()) 6222 return ExprError(); 6223 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6224 PrepareScalarCast(Literal, ElemTy)); 6225 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6226 } 6227 6228 initExprs.append(exprs, exprs + numExprs); 6229 } 6230 // FIXME: This means that pretty-printing the final AST will produce curly 6231 // braces instead of the original commas. 6232 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6233 initExprs, LiteralRParenLoc); 6234 initE->setType(Ty); 6235 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6236 } 6237 6238 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6239 /// the ParenListExpr into a sequence of comma binary operators. 6240 ExprResult 6241 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6242 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6243 if (!E) 6244 return OrigExpr; 6245 6246 ExprResult Result(E->getExpr(0)); 6247 6248 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6249 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6250 E->getExpr(i)); 6251 6252 if (Result.isInvalid()) return ExprError(); 6253 6254 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6255 } 6256 6257 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6258 SourceLocation R, 6259 MultiExprArg Val) { 6260 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6261 return expr; 6262 } 6263 6264 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6265 /// constant and the other is not a pointer. Returns true if a diagnostic is 6266 /// emitted. 6267 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6268 SourceLocation QuestionLoc) { 6269 Expr *NullExpr = LHSExpr; 6270 Expr *NonPointerExpr = RHSExpr; 6271 Expr::NullPointerConstantKind NullKind = 6272 NullExpr->isNullPointerConstant(Context, 6273 Expr::NPC_ValueDependentIsNotNull); 6274 6275 if (NullKind == Expr::NPCK_NotNull) { 6276 NullExpr = RHSExpr; 6277 NonPointerExpr = LHSExpr; 6278 NullKind = 6279 NullExpr->isNullPointerConstant(Context, 6280 Expr::NPC_ValueDependentIsNotNull); 6281 } 6282 6283 if (NullKind == Expr::NPCK_NotNull) 6284 return false; 6285 6286 if (NullKind == Expr::NPCK_ZeroExpression) 6287 return false; 6288 6289 if (NullKind == Expr::NPCK_ZeroLiteral) { 6290 // In this case, check to make sure that we got here from a "NULL" 6291 // string in the source code. 6292 NullExpr = NullExpr->IgnoreParenImpCasts(); 6293 SourceLocation loc = NullExpr->getExprLoc(); 6294 if (!findMacroSpelling(loc, "NULL")) 6295 return false; 6296 } 6297 6298 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6299 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6300 << NonPointerExpr->getType() << DiagType 6301 << NonPointerExpr->getSourceRange(); 6302 return true; 6303 } 6304 6305 /// \brief Return false if the condition expression is valid, true otherwise. 6306 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6307 QualType CondTy = Cond->getType(); 6308 6309 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6310 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6311 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6312 << CondTy << Cond->getSourceRange(); 6313 return true; 6314 } 6315 6316 // C99 6.5.15p2 6317 if (CondTy->isScalarType()) return false; 6318 6319 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6320 << CondTy << Cond->getSourceRange(); 6321 return true; 6322 } 6323 6324 /// \brief Handle when one or both operands are void type. 6325 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6326 ExprResult &RHS) { 6327 Expr *LHSExpr = LHS.get(); 6328 Expr *RHSExpr = RHS.get(); 6329 6330 if (!LHSExpr->getType()->isVoidType()) 6331 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6332 << RHSExpr->getSourceRange(); 6333 if (!RHSExpr->getType()->isVoidType()) 6334 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6335 << LHSExpr->getSourceRange(); 6336 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6337 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6338 return S.Context.VoidTy; 6339 } 6340 6341 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6342 /// true otherwise. 6343 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6344 QualType PointerTy) { 6345 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6346 !NullExpr.get()->isNullPointerConstant(S.Context, 6347 Expr::NPC_ValueDependentIsNull)) 6348 return true; 6349 6350 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6351 return false; 6352 } 6353 6354 /// \brief Checks compatibility between two pointers and return the resulting 6355 /// type. 6356 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6357 ExprResult &RHS, 6358 SourceLocation Loc) { 6359 QualType LHSTy = LHS.get()->getType(); 6360 QualType RHSTy = RHS.get()->getType(); 6361 6362 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6363 // Two identical pointers types are always compatible. 6364 return LHSTy; 6365 } 6366 6367 QualType lhptee, rhptee; 6368 6369 // Get the pointee types. 6370 bool IsBlockPointer = false; 6371 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6372 lhptee = LHSBTy->getPointeeType(); 6373 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6374 IsBlockPointer = true; 6375 } else { 6376 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6377 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6378 } 6379 6380 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6381 // differently qualified versions of compatible types, the result type is 6382 // a pointer to an appropriately qualified version of the composite 6383 // type. 6384 6385 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6386 // clause doesn't make sense for our extensions. E.g. address space 2 should 6387 // be incompatible with address space 3: they may live on different devices or 6388 // anything. 6389 Qualifiers lhQual = lhptee.getQualifiers(); 6390 Qualifiers rhQual = rhptee.getQualifiers(); 6391 6392 LangAS ResultAddrSpace = LangAS::Default; 6393 LangAS LAddrSpace = lhQual.getAddressSpace(); 6394 LangAS RAddrSpace = rhQual.getAddressSpace(); 6395 if (S.getLangOpts().OpenCL) { 6396 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6397 // spaces is disallowed. 6398 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6399 ResultAddrSpace = LAddrSpace; 6400 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6401 ResultAddrSpace = RAddrSpace; 6402 else { 6403 S.Diag(Loc, 6404 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6405 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6406 << RHS.get()->getSourceRange(); 6407 return QualType(); 6408 } 6409 } 6410 6411 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6412 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6413 lhQual.removeCVRQualifiers(); 6414 rhQual.removeCVRQualifiers(); 6415 6416 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6417 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6418 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6419 // qual types are compatible iff 6420 // * corresponded types are compatible 6421 // * CVR qualifiers are equal 6422 // * address spaces are equal 6423 // Thus for conditional operator we merge CVR and address space unqualified 6424 // pointees and if there is a composite type we return a pointer to it with 6425 // merged qualifiers. 6426 if (S.getLangOpts().OpenCL) { 6427 LHSCastKind = LAddrSpace == ResultAddrSpace 6428 ? CK_BitCast 6429 : CK_AddressSpaceConversion; 6430 RHSCastKind = RAddrSpace == ResultAddrSpace 6431 ? CK_BitCast 6432 : CK_AddressSpaceConversion; 6433 lhQual.removeAddressSpace(); 6434 rhQual.removeAddressSpace(); 6435 } 6436 6437 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6438 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6439 6440 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6441 6442 if (CompositeTy.isNull()) { 6443 // In this situation, we assume void* type. No especially good 6444 // reason, but this is what gcc does, and we do have to pick 6445 // to get a consistent AST. 6446 QualType incompatTy; 6447 incompatTy = S.Context.getPointerType( 6448 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6449 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6450 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6451 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6452 // for casts between types with incompatible address space qualifiers. 6453 // For the following code the compiler produces casts between global and 6454 // local address spaces of the corresponded innermost pointees: 6455 // local int *global *a; 6456 // global int *global *b; 6457 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6458 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6459 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6460 << RHS.get()->getSourceRange(); 6461 return incompatTy; 6462 } 6463 6464 // The pointer types are compatible. 6465 // In case of OpenCL ResultTy should have the address space qualifier 6466 // which is a superset of address spaces of both the 2nd and the 3rd 6467 // operands of the conditional operator. 6468 QualType ResultTy = [&, ResultAddrSpace]() { 6469 if (S.getLangOpts().OpenCL) { 6470 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6471 CompositeQuals.setAddressSpace(ResultAddrSpace); 6472 return S.Context 6473 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6474 .withCVRQualifiers(MergedCVRQual); 6475 } 6476 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6477 }(); 6478 if (IsBlockPointer) 6479 ResultTy = S.Context.getBlockPointerType(ResultTy); 6480 else 6481 ResultTy = S.Context.getPointerType(ResultTy); 6482 6483 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6484 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6485 return ResultTy; 6486 } 6487 6488 /// \brief Return the resulting type when the operands are both block pointers. 6489 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6490 ExprResult &LHS, 6491 ExprResult &RHS, 6492 SourceLocation Loc) { 6493 QualType LHSTy = LHS.get()->getType(); 6494 QualType RHSTy = RHS.get()->getType(); 6495 6496 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6497 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6498 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6499 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6500 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6501 return destType; 6502 } 6503 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6504 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6505 << RHS.get()->getSourceRange(); 6506 return QualType(); 6507 } 6508 6509 // We have 2 block pointer types. 6510 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6511 } 6512 6513 /// \brief Return the resulting type when the operands are both pointers. 6514 static QualType 6515 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6516 ExprResult &RHS, 6517 SourceLocation Loc) { 6518 // get the pointer types 6519 QualType LHSTy = LHS.get()->getType(); 6520 QualType RHSTy = RHS.get()->getType(); 6521 6522 // get the "pointed to" types 6523 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6524 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6525 6526 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6527 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6528 // Figure out necessary qualifiers (C99 6.5.15p6) 6529 QualType destPointee 6530 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6531 QualType destType = S.Context.getPointerType(destPointee); 6532 // Add qualifiers if necessary. 6533 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6534 // Promote to void*. 6535 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6536 return destType; 6537 } 6538 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6539 QualType destPointee 6540 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6541 QualType destType = S.Context.getPointerType(destPointee); 6542 // Add qualifiers if necessary. 6543 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6544 // Promote to void*. 6545 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6546 return destType; 6547 } 6548 6549 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6550 } 6551 6552 /// \brief Return false if the first expression is not an integer and the second 6553 /// expression is not a pointer, true otherwise. 6554 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6555 Expr* PointerExpr, SourceLocation Loc, 6556 bool IsIntFirstExpr) { 6557 if (!PointerExpr->getType()->isPointerType() || 6558 !Int.get()->getType()->isIntegerType()) 6559 return false; 6560 6561 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6562 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6563 6564 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6565 << Expr1->getType() << Expr2->getType() 6566 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6567 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6568 CK_IntegralToPointer); 6569 return true; 6570 } 6571 6572 /// \brief Simple conversion between integer and floating point types. 6573 /// 6574 /// Used when handling the OpenCL conditional operator where the 6575 /// condition is a vector while the other operands are scalar. 6576 /// 6577 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6578 /// types are either integer or floating type. Between the two 6579 /// operands, the type with the higher rank is defined as the "result 6580 /// type". The other operand needs to be promoted to the same type. No 6581 /// other type promotion is allowed. We cannot use 6582 /// UsualArithmeticConversions() for this purpose, since it always 6583 /// promotes promotable types. 6584 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6585 ExprResult &RHS, 6586 SourceLocation QuestionLoc) { 6587 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6588 if (LHS.isInvalid()) 6589 return QualType(); 6590 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6591 if (RHS.isInvalid()) 6592 return QualType(); 6593 6594 // For conversion purposes, we ignore any qualifiers. 6595 // For example, "const float" and "float" are equivalent. 6596 QualType LHSType = 6597 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6598 QualType RHSType = 6599 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6600 6601 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6602 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6603 << LHSType << LHS.get()->getSourceRange(); 6604 return QualType(); 6605 } 6606 6607 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6608 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6609 << RHSType << RHS.get()->getSourceRange(); 6610 return QualType(); 6611 } 6612 6613 // If both types are identical, no conversion is needed. 6614 if (LHSType == RHSType) 6615 return LHSType; 6616 6617 // Now handle "real" floating types (i.e. float, double, long double). 6618 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6619 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6620 /*IsCompAssign = */ false); 6621 6622 // Finally, we have two differing integer types. 6623 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6624 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6625 } 6626 6627 /// \brief Convert scalar operands to a vector that matches the 6628 /// condition in length. 6629 /// 6630 /// Used when handling the OpenCL conditional operator where the 6631 /// condition is a vector while the other operands are scalar. 6632 /// 6633 /// We first compute the "result type" for the scalar operands 6634 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6635 /// into a vector of that type where the length matches the condition 6636 /// vector type. s6.11.6 requires that the element types of the result 6637 /// and the condition must have the same number of bits. 6638 static QualType 6639 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6640 QualType CondTy, SourceLocation QuestionLoc) { 6641 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6642 if (ResTy.isNull()) return QualType(); 6643 6644 const VectorType *CV = CondTy->getAs<VectorType>(); 6645 assert(CV); 6646 6647 // Determine the vector result type 6648 unsigned NumElements = CV->getNumElements(); 6649 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6650 6651 // Ensure that all types have the same number of bits 6652 if (S.Context.getTypeSize(CV->getElementType()) 6653 != S.Context.getTypeSize(ResTy)) { 6654 // Since VectorTy is created internally, it does not pretty print 6655 // with an OpenCL name. Instead, we just print a description. 6656 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6657 SmallString<64> Str; 6658 llvm::raw_svector_ostream OS(Str); 6659 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6660 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6661 << CondTy << OS.str(); 6662 return QualType(); 6663 } 6664 6665 // Convert operands to the vector result type 6666 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6667 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6668 6669 return VectorTy; 6670 } 6671 6672 /// \brief Return false if this is a valid OpenCL condition vector 6673 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6674 SourceLocation QuestionLoc) { 6675 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6676 // integral type. 6677 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6678 assert(CondTy); 6679 QualType EleTy = CondTy->getElementType(); 6680 if (EleTy->isIntegerType()) return false; 6681 6682 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6683 << Cond->getType() << Cond->getSourceRange(); 6684 return true; 6685 } 6686 6687 /// \brief Return false if the vector condition type and the vector 6688 /// result type are compatible. 6689 /// 6690 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6691 /// number of elements, and their element types have the same number 6692 /// of bits. 6693 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6694 SourceLocation QuestionLoc) { 6695 const VectorType *CV = CondTy->getAs<VectorType>(); 6696 const VectorType *RV = VecResTy->getAs<VectorType>(); 6697 assert(CV && RV); 6698 6699 if (CV->getNumElements() != RV->getNumElements()) { 6700 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6701 << CondTy << VecResTy; 6702 return true; 6703 } 6704 6705 QualType CVE = CV->getElementType(); 6706 QualType RVE = RV->getElementType(); 6707 6708 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6709 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6710 << CondTy << VecResTy; 6711 return true; 6712 } 6713 6714 return false; 6715 } 6716 6717 /// \brief Return the resulting type for the conditional operator in 6718 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6719 /// s6.3.i) when the condition is a vector type. 6720 static QualType 6721 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6722 ExprResult &LHS, ExprResult &RHS, 6723 SourceLocation QuestionLoc) { 6724 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6725 if (Cond.isInvalid()) 6726 return QualType(); 6727 QualType CondTy = Cond.get()->getType(); 6728 6729 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6730 return QualType(); 6731 6732 // If either operand is a vector then find the vector type of the 6733 // result as specified in OpenCL v1.1 s6.3.i. 6734 if (LHS.get()->getType()->isVectorType() || 6735 RHS.get()->getType()->isVectorType()) { 6736 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6737 /*isCompAssign*/false, 6738 /*AllowBothBool*/true, 6739 /*AllowBoolConversions*/false); 6740 if (VecResTy.isNull()) return QualType(); 6741 // The result type must match the condition type as specified in 6742 // OpenCL v1.1 s6.11.6. 6743 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6744 return QualType(); 6745 return VecResTy; 6746 } 6747 6748 // Both operands are scalar. 6749 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6750 } 6751 6752 /// \brief Return true if the Expr is block type 6753 static bool checkBlockType(Sema &S, const Expr *E) { 6754 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6755 QualType Ty = CE->getCallee()->getType(); 6756 if (Ty->isBlockPointerType()) { 6757 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6758 return true; 6759 } 6760 } 6761 return false; 6762 } 6763 6764 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6765 /// In that case, LHS = cond. 6766 /// C99 6.5.15 6767 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6768 ExprResult &RHS, ExprValueKind &VK, 6769 ExprObjectKind &OK, 6770 SourceLocation QuestionLoc) { 6771 6772 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6773 if (!LHSResult.isUsable()) return QualType(); 6774 LHS = LHSResult; 6775 6776 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6777 if (!RHSResult.isUsable()) return QualType(); 6778 RHS = RHSResult; 6779 6780 // C++ is sufficiently different to merit its own checker. 6781 if (getLangOpts().CPlusPlus) 6782 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6783 6784 VK = VK_RValue; 6785 OK = OK_Ordinary; 6786 6787 // The OpenCL operator with a vector condition is sufficiently 6788 // different to merit its own checker. 6789 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6790 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6791 6792 // First, check the condition. 6793 Cond = UsualUnaryConversions(Cond.get()); 6794 if (Cond.isInvalid()) 6795 return QualType(); 6796 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6797 return QualType(); 6798 6799 // Now check the two expressions. 6800 if (LHS.get()->getType()->isVectorType() || 6801 RHS.get()->getType()->isVectorType()) 6802 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6803 /*AllowBothBool*/true, 6804 /*AllowBoolConversions*/false); 6805 6806 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6807 if (LHS.isInvalid() || RHS.isInvalid()) 6808 return QualType(); 6809 6810 QualType LHSTy = LHS.get()->getType(); 6811 QualType RHSTy = RHS.get()->getType(); 6812 6813 // Diagnose attempts to convert between __float128 and long double where 6814 // such conversions currently can't be handled. 6815 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6816 Diag(QuestionLoc, 6817 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6819 return QualType(); 6820 } 6821 6822 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6823 // selection operator (?:). 6824 if (getLangOpts().OpenCL && 6825 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6826 return QualType(); 6827 } 6828 6829 // If both operands have arithmetic type, do the usual arithmetic conversions 6830 // to find a common type: C99 6.5.15p3,5. 6831 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6832 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6833 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6834 6835 return ResTy; 6836 } 6837 6838 // If both operands are the same structure or union type, the result is that 6839 // type. 6840 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6841 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6842 if (LHSRT->getDecl() == RHSRT->getDecl()) 6843 // "If both the operands have structure or union type, the result has 6844 // that type." This implies that CV qualifiers are dropped. 6845 return LHSTy.getUnqualifiedType(); 6846 // FIXME: Type of conditional expression must be complete in C mode. 6847 } 6848 6849 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6850 // The following || allows only one side to be void (a GCC-ism). 6851 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6852 return checkConditionalVoidType(*this, LHS, RHS); 6853 } 6854 6855 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6856 // the type of the other operand." 6857 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6858 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6859 6860 // All objective-c pointer type analysis is done here. 6861 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6862 QuestionLoc); 6863 if (LHS.isInvalid() || RHS.isInvalid()) 6864 return QualType(); 6865 if (!compositeType.isNull()) 6866 return compositeType; 6867 6868 6869 // Handle block pointer types. 6870 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6871 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6872 QuestionLoc); 6873 6874 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6875 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6876 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6877 QuestionLoc); 6878 6879 // GCC compatibility: soften pointer/integer mismatch. Note that 6880 // null pointers have been filtered out by this point. 6881 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6882 /*isIntFirstExpr=*/true)) 6883 return RHSTy; 6884 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6885 /*isIntFirstExpr=*/false)) 6886 return LHSTy; 6887 6888 // Emit a better diagnostic if one of the expressions is a null pointer 6889 // constant and the other is not a pointer type. In this case, the user most 6890 // likely forgot to take the address of the other expression. 6891 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6892 return QualType(); 6893 6894 // Otherwise, the operands are not compatible. 6895 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6896 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6897 << RHS.get()->getSourceRange(); 6898 return QualType(); 6899 } 6900 6901 /// FindCompositeObjCPointerType - Helper method to find composite type of 6902 /// two objective-c pointer types of the two input expressions. 6903 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6904 SourceLocation QuestionLoc) { 6905 QualType LHSTy = LHS.get()->getType(); 6906 QualType RHSTy = RHS.get()->getType(); 6907 6908 // Handle things like Class and struct objc_class*. Here we case the result 6909 // to the pseudo-builtin, because that will be implicitly cast back to the 6910 // redefinition type if an attempt is made to access its fields. 6911 if (LHSTy->isObjCClassType() && 6912 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6913 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6914 return LHSTy; 6915 } 6916 if (RHSTy->isObjCClassType() && 6917 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6918 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6919 return RHSTy; 6920 } 6921 // And the same for struct objc_object* / id 6922 if (LHSTy->isObjCIdType() && 6923 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6924 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6925 return LHSTy; 6926 } 6927 if (RHSTy->isObjCIdType() && 6928 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6929 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6930 return RHSTy; 6931 } 6932 // And the same for struct objc_selector* / SEL 6933 if (Context.isObjCSelType(LHSTy) && 6934 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6935 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6936 return LHSTy; 6937 } 6938 if (Context.isObjCSelType(RHSTy) && 6939 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6940 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6941 return RHSTy; 6942 } 6943 // Check constraints for Objective-C object pointers types. 6944 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6945 6946 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6947 // Two identical object pointer types are always compatible. 6948 return LHSTy; 6949 } 6950 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6951 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6952 QualType compositeType = LHSTy; 6953 6954 // If both operands are interfaces and either operand can be 6955 // assigned to the other, use that type as the composite 6956 // type. This allows 6957 // xxx ? (A*) a : (B*) b 6958 // where B is a subclass of A. 6959 // 6960 // Additionally, as for assignment, if either type is 'id' 6961 // allow silent coercion. Finally, if the types are 6962 // incompatible then make sure to use 'id' as the composite 6963 // type so the result is acceptable for sending messages to. 6964 6965 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6966 // It could return the composite type. 6967 if (!(compositeType = 6968 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6969 // Nothing more to do. 6970 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6971 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6972 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6973 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6974 } else if ((LHSTy->isObjCQualifiedIdType() || 6975 RHSTy->isObjCQualifiedIdType()) && 6976 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6977 // Need to handle "id<xx>" explicitly. 6978 // GCC allows qualified id and any Objective-C type to devolve to 6979 // id. Currently localizing to here until clear this should be 6980 // part of ObjCQualifiedIdTypesAreCompatible. 6981 compositeType = Context.getObjCIdType(); 6982 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6983 compositeType = Context.getObjCIdType(); 6984 } else { 6985 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6986 << LHSTy << RHSTy 6987 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6988 QualType incompatTy = Context.getObjCIdType(); 6989 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6990 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6991 return incompatTy; 6992 } 6993 // The object pointer types are compatible. 6994 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6995 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6996 return compositeType; 6997 } 6998 // Check Objective-C object pointer types and 'void *' 6999 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7000 if (getLangOpts().ObjCAutoRefCount) { 7001 // ARC forbids the implicit conversion of object pointers to 'void *', 7002 // so these types are not compatible. 7003 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7004 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7005 LHS = RHS = true; 7006 return QualType(); 7007 } 7008 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7009 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7010 QualType destPointee 7011 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7012 QualType destType = Context.getPointerType(destPointee); 7013 // Add qualifiers if necessary. 7014 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7015 // Promote to void*. 7016 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7017 return destType; 7018 } 7019 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7020 if (getLangOpts().ObjCAutoRefCount) { 7021 // ARC forbids the implicit conversion of object pointers to 'void *', 7022 // so these types are not compatible. 7023 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7024 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7025 LHS = RHS = true; 7026 return QualType(); 7027 } 7028 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7029 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7030 QualType destPointee 7031 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7032 QualType destType = Context.getPointerType(destPointee); 7033 // Add qualifiers if necessary. 7034 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7035 // Promote to void*. 7036 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7037 return destType; 7038 } 7039 return QualType(); 7040 } 7041 7042 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7043 /// ParenRange in parentheses. 7044 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7045 const PartialDiagnostic &Note, 7046 SourceRange ParenRange) { 7047 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7048 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7049 EndLoc.isValid()) { 7050 Self.Diag(Loc, Note) 7051 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7052 << FixItHint::CreateInsertion(EndLoc, ")"); 7053 } else { 7054 // We can't display the parentheses, so just show the bare note. 7055 Self.Diag(Loc, Note) << ParenRange; 7056 } 7057 } 7058 7059 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7060 return BinaryOperator::isAdditiveOp(Opc) || 7061 BinaryOperator::isMultiplicativeOp(Opc) || 7062 BinaryOperator::isShiftOp(Opc); 7063 } 7064 7065 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7066 /// expression, either using a built-in or overloaded operator, 7067 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7068 /// expression. 7069 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7070 Expr **RHSExprs) { 7071 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7072 E = E->IgnoreImpCasts(); 7073 E = E->IgnoreConversionOperator(); 7074 E = E->IgnoreImpCasts(); 7075 7076 // Built-in binary operator. 7077 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7078 if (IsArithmeticOp(OP->getOpcode())) { 7079 *Opcode = OP->getOpcode(); 7080 *RHSExprs = OP->getRHS(); 7081 return true; 7082 } 7083 } 7084 7085 // Overloaded operator. 7086 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7087 if (Call->getNumArgs() != 2) 7088 return false; 7089 7090 // Make sure this is really a binary operator that is safe to pass into 7091 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7092 OverloadedOperatorKind OO = Call->getOperator(); 7093 if (OO < OO_Plus || OO > OO_Arrow || 7094 OO == OO_PlusPlus || OO == OO_MinusMinus) 7095 return false; 7096 7097 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7098 if (IsArithmeticOp(OpKind)) { 7099 *Opcode = OpKind; 7100 *RHSExprs = Call->getArg(1); 7101 return true; 7102 } 7103 } 7104 7105 return false; 7106 } 7107 7108 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7109 /// or is a logical expression such as (x==y) which has int type, but is 7110 /// commonly interpreted as boolean. 7111 static bool ExprLooksBoolean(Expr *E) { 7112 E = E->IgnoreParenImpCasts(); 7113 7114 if (E->getType()->isBooleanType()) 7115 return true; 7116 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7117 return OP->isComparisonOp() || OP->isLogicalOp(); 7118 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7119 return OP->getOpcode() == UO_LNot; 7120 if (E->getType()->isPointerType()) 7121 return true; 7122 7123 return false; 7124 } 7125 7126 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7127 /// and binary operator are mixed in a way that suggests the programmer assumed 7128 /// the conditional operator has higher precedence, for example: 7129 /// "int x = a + someBinaryCondition ? 1 : 2". 7130 static void DiagnoseConditionalPrecedence(Sema &Self, 7131 SourceLocation OpLoc, 7132 Expr *Condition, 7133 Expr *LHSExpr, 7134 Expr *RHSExpr) { 7135 BinaryOperatorKind CondOpcode; 7136 Expr *CondRHS; 7137 7138 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7139 return; 7140 if (!ExprLooksBoolean(CondRHS)) 7141 return; 7142 7143 // The condition is an arithmetic binary expression, with a right- 7144 // hand side that looks boolean, so warn. 7145 7146 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7147 << Condition->getSourceRange() 7148 << BinaryOperator::getOpcodeStr(CondOpcode); 7149 7150 SuggestParentheses(Self, OpLoc, 7151 Self.PDiag(diag::note_precedence_silence) 7152 << BinaryOperator::getOpcodeStr(CondOpcode), 7153 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7154 7155 SuggestParentheses(Self, OpLoc, 7156 Self.PDiag(diag::note_precedence_conditional_first), 7157 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7158 } 7159 7160 /// Compute the nullability of a conditional expression. 7161 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7162 QualType LHSTy, QualType RHSTy, 7163 ASTContext &Ctx) { 7164 if (!ResTy->isAnyPointerType()) 7165 return ResTy; 7166 7167 auto GetNullability = [&Ctx](QualType Ty) { 7168 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7169 if (Kind) 7170 return *Kind; 7171 return NullabilityKind::Unspecified; 7172 }; 7173 7174 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7175 NullabilityKind MergedKind; 7176 7177 // Compute nullability of a binary conditional expression. 7178 if (IsBin) { 7179 if (LHSKind == NullabilityKind::NonNull) 7180 MergedKind = NullabilityKind::NonNull; 7181 else 7182 MergedKind = RHSKind; 7183 // Compute nullability of a normal conditional expression. 7184 } else { 7185 if (LHSKind == NullabilityKind::Nullable || 7186 RHSKind == NullabilityKind::Nullable) 7187 MergedKind = NullabilityKind::Nullable; 7188 else if (LHSKind == NullabilityKind::NonNull) 7189 MergedKind = RHSKind; 7190 else if (RHSKind == NullabilityKind::NonNull) 7191 MergedKind = LHSKind; 7192 else 7193 MergedKind = NullabilityKind::Unspecified; 7194 } 7195 7196 // Return if ResTy already has the correct nullability. 7197 if (GetNullability(ResTy) == MergedKind) 7198 return ResTy; 7199 7200 // Strip all nullability from ResTy. 7201 while (ResTy->getNullability(Ctx)) 7202 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7203 7204 // Create a new AttributedType with the new nullability kind. 7205 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7206 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7207 } 7208 7209 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7210 /// in the case of a the GNU conditional expr extension. 7211 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7212 SourceLocation ColonLoc, 7213 Expr *CondExpr, Expr *LHSExpr, 7214 Expr *RHSExpr) { 7215 if (!getLangOpts().CPlusPlus) { 7216 // C cannot handle TypoExpr nodes in the condition because it 7217 // doesn't handle dependent types properly, so make sure any TypoExprs have 7218 // been dealt with before checking the operands. 7219 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7220 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7221 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7222 7223 if (!CondResult.isUsable()) 7224 return ExprError(); 7225 7226 if (LHSExpr) { 7227 if (!LHSResult.isUsable()) 7228 return ExprError(); 7229 } 7230 7231 if (!RHSResult.isUsable()) 7232 return ExprError(); 7233 7234 CondExpr = CondResult.get(); 7235 LHSExpr = LHSResult.get(); 7236 RHSExpr = RHSResult.get(); 7237 } 7238 7239 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7240 // was the condition. 7241 OpaqueValueExpr *opaqueValue = nullptr; 7242 Expr *commonExpr = nullptr; 7243 if (!LHSExpr) { 7244 commonExpr = CondExpr; 7245 // Lower out placeholder types first. This is important so that we don't 7246 // try to capture a placeholder. This happens in few cases in C++; such 7247 // as Objective-C++'s dictionary subscripting syntax. 7248 if (commonExpr->hasPlaceholderType()) { 7249 ExprResult result = CheckPlaceholderExpr(commonExpr); 7250 if (!result.isUsable()) return ExprError(); 7251 commonExpr = result.get(); 7252 } 7253 // We usually want to apply unary conversions *before* saving, except 7254 // in the special case of a C++ l-value conditional. 7255 if (!(getLangOpts().CPlusPlus 7256 && !commonExpr->isTypeDependent() 7257 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7258 && commonExpr->isGLValue() 7259 && commonExpr->isOrdinaryOrBitFieldObject() 7260 && RHSExpr->isOrdinaryOrBitFieldObject() 7261 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7262 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7263 if (commonRes.isInvalid()) 7264 return ExprError(); 7265 commonExpr = commonRes.get(); 7266 } 7267 7268 // If the common expression is a class or array prvalue, materialize it 7269 // so that we can safely refer to it multiple times. 7270 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7271 commonExpr->getType()->isArrayType())) { 7272 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7273 if (MatExpr.isInvalid()) 7274 return ExprError(); 7275 commonExpr = MatExpr.get(); 7276 } 7277 7278 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7279 commonExpr->getType(), 7280 commonExpr->getValueKind(), 7281 commonExpr->getObjectKind(), 7282 commonExpr); 7283 LHSExpr = CondExpr = opaqueValue; 7284 } 7285 7286 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7287 ExprValueKind VK = VK_RValue; 7288 ExprObjectKind OK = OK_Ordinary; 7289 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7290 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7291 VK, OK, QuestionLoc); 7292 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7293 RHS.isInvalid()) 7294 return ExprError(); 7295 7296 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7297 RHS.get()); 7298 7299 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7300 7301 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7302 Context); 7303 7304 if (!commonExpr) 7305 return new (Context) 7306 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7307 RHS.get(), result, VK, OK); 7308 7309 return new (Context) BinaryConditionalOperator( 7310 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7311 ColonLoc, result, VK, OK); 7312 } 7313 7314 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7315 // being closely modeled after the C99 spec:-). The odd characteristic of this 7316 // routine is it effectively iqnores the qualifiers on the top level pointee. 7317 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7318 // FIXME: add a couple examples in this comment. 7319 static Sema::AssignConvertType 7320 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7321 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7322 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7323 7324 // get the "pointed to" type (ignoring qualifiers at the top level) 7325 const Type *lhptee, *rhptee; 7326 Qualifiers lhq, rhq; 7327 std::tie(lhptee, lhq) = 7328 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7329 std::tie(rhptee, rhq) = 7330 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7331 7332 Sema::AssignConvertType ConvTy = Sema::Compatible; 7333 7334 // C99 6.5.16.1p1: This following citation is common to constraints 7335 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7336 // qualifiers of the type *pointed to* by the right; 7337 7338 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7339 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7340 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7341 // Ignore lifetime for further calculation. 7342 lhq.removeObjCLifetime(); 7343 rhq.removeObjCLifetime(); 7344 } 7345 7346 if (!lhq.compatiblyIncludes(rhq)) { 7347 // Treat address-space mismatches as fatal. TODO: address subspaces 7348 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7349 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7350 7351 // It's okay to add or remove GC or lifetime qualifiers when converting to 7352 // and from void*. 7353 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7354 .compatiblyIncludes( 7355 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7356 && (lhptee->isVoidType() || rhptee->isVoidType())) 7357 ; // keep old 7358 7359 // Treat lifetime mismatches as fatal. 7360 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7361 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7362 7363 // For GCC/MS compatibility, other qualifier mismatches are treated 7364 // as still compatible in C. 7365 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7366 } 7367 7368 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7369 // incomplete type and the other is a pointer to a qualified or unqualified 7370 // version of void... 7371 if (lhptee->isVoidType()) { 7372 if (rhptee->isIncompleteOrObjectType()) 7373 return ConvTy; 7374 7375 // As an extension, we allow cast to/from void* to function pointer. 7376 assert(rhptee->isFunctionType()); 7377 return Sema::FunctionVoidPointer; 7378 } 7379 7380 if (rhptee->isVoidType()) { 7381 if (lhptee->isIncompleteOrObjectType()) 7382 return ConvTy; 7383 7384 // As an extension, we allow cast to/from void* to function pointer. 7385 assert(lhptee->isFunctionType()); 7386 return Sema::FunctionVoidPointer; 7387 } 7388 7389 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7390 // unqualified versions of compatible types, ... 7391 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7392 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7393 // Check if the pointee types are compatible ignoring the sign. 7394 // We explicitly check for char so that we catch "char" vs 7395 // "unsigned char" on systems where "char" is unsigned. 7396 if (lhptee->isCharType()) 7397 ltrans = S.Context.UnsignedCharTy; 7398 else if (lhptee->hasSignedIntegerRepresentation()) 7399 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7400 7401 if (rhptee->isCharType()) 7402 rtrans = S.Context.UnsignedCharTy; 7403 else if (rhptee->hasSignedIntegerRepresentation()) 7404 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7405 7406 if (ltrans == rtrans) { 7407 // Types are compatible ignoring the sign. Qualifier incompatibility 7408 // takes priority over sign incompatibility because the sign 7409 // warning can be disabled. 7410 if (ConvTy != Sema::Compatible) 7411 return ConvTy; 7412 7413 return Sema::IncompatiblePointerSign; 7414 } 7415 7416 // If we are a multi-level pointer, it's possible that our issue is simply 7417 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7418 // the eventual target type is the same and the pointers have the same 7419 // level of indirection, this must be the issue. 7420 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7421 do { 7422 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7423 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7424 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7425 7426 if (lhptee == rhptee) 7427 return Sema::IncompatibleNestedPointerQualifiers; 7428 } 7429 7430 // General pointer incompatibility takes priority over qualifiers. 7431 return Sema::IncompatiblePointer; 7432 } 7433 if (!S.getLangOpts().CPlusPlus && 7434 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7435 return Sema::IncompatiblePointer; 7436 return ConvTy; 7437 } 7438 7439 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7440 /// block pointer types are compatible or whether a block and normal pointer 7441 /// are compatible. It is more restrict than comparing two function pointer 7442 // types. 7443 static Sema::AssignConvertType 7444 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7445 QualType RHSType) { 7446 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7447 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7448 7449 QualType lhptee, rhptee; 7450 7451 // get the "pointed to" type (ignoring qualifiers at the top level) 7452 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7453 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7454 7455 // In C++, the types have to match exactly. 7456 if (S.getLangOpts().CPlusPlus) 7457 return Sema::IncompatibleBlockPointer; 7458 7459 Sema::AssignConvertType ConvTy = Sema::Compatible; 7460 7461 // For blocks we enforce that qualifiers are identical. 7462 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7463 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7464 if (S.getLangOpts().OpenCL) { 7465 LQuals.removeAddressSpace(); 7466 RQuals.removeAddressSpace(); 7467 } 7468 if (LQuals != RQuals) 7469 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7470 7471 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7472 // assignment. 7473 // The current behavior is similar to C++ lambdas. A block might be 7474 // assigned to a variable iff its return type and parameters are compatible 7475 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7476 // an assignment. Presumably it should behave in way that a function pointer 7477 // assignment does in C, so for each parameter and return type: 7478 // * CVR and address space of LHS should be a superset of CVR and address 7479 // space of RHS. 7480 // * unqualified types should be compatible. 7481 if (S.getLangOpts().OpenCL) { 7482 if (!S.Context.typesAreBlockPointerCompatible( 7483 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7484 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7485 return Sema::IncompatibleBlockPointer; 7486 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7487 return Sema::IncompatibleBlockPointer; 7488 7489 return ConvTy; 7490 } 7491 7492 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7493 /// for assignment compatibility. 7494 static Sema::AssignConvertType 7495 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7496 QualType RHSType) { 7497 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7498 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7499 7500 if (LHSType->isObjCBuiltinType()) { 7501 // Class is not compatible with ObjC object pointers. 7502 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7503 !RHSType->isObjCQualifiedClassType()) 7504 return Sema::IncompatiblePointer; 7505 return Sema::Compatible; 7506 } 7507 if (RHSType->isObjCBuiltinType()) { 7508 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7509 !LHSType->isObjCQualifiedClassType()) 7510 return Sema::IncompatiblePointer; 7511 return Sema::Compatible; 7512 } 7513 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7514 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7515 7516 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7517 // make an exception for id<P> 7518 !LHSType->isObjCQualifiedIdType()) 7519 return Sema::CompatiblePointerDiscardsQualifiers; 7520 7521 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7522 return Sema::Compatible; 7523 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7524 return Sema::IncompatibleObjCQualifiedId; 7525 return Sema::IncompatiblePointer; 7526 } 7527 7528 Sema::AssignConvertType 7529 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7530 QualType LHSType, QualType RHSType) { 7531 // Fake up an opaque expression. We don't actually care about what 7532 // cast operations are required, so if CheckAssignmentConstraints 7533 // adds casts to this they'll be wasted, but fortunately that doesn't 7534 // usually happen on valid code. 7535 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7536 ExprResult RHSPtr = &RHSExpr; 7537 CastKind K; 7538 7539 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7540 } 7541 7542 /// This helper function returns true if QT is a vector type that has element 7543 /// type ElementType. 7544 static bool isVector(QualType QT, QualType ElementType) { 7545 if (const VectorType *VT = QT->getAs<VectorType>()) 7546 return VT->getElementType() == ElementType; 7547 return false; 7548 } 7549 7550 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7551 /// has code to accommodate several GCC extensions when type checking 7552 /// pointers. Here are some objectionable examples that GCC considers warnings: 7553 /// 7554 /// int a, *pint; 7555 /// short *pshort; 7556 /// struct foo *pfoo; 7557 /// 7558 /// pint = pshort; // warning: assignment from incompatible pointer type 7559 /// a = pint; // warning: assignment makes integer from pointer without a cast 7560 /// pint = a; // warning: assignment makes pointer from integer without a cast 7561 /// pint = pfoo; // warning: assignment from incompatible pointer type 7562 /// 7563 /// As a result, the code for dealing with pointers is more complex than the 7564 /// C99 spec dictates. 7565 /// 7566 /// Sets 'Kind' for any result kind except Incompatible. 7567 Sema::AssignConvertType 7568 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7569 CastKind &Kind, bool ConvertRHS) { 7570 QualType RHSType = RHS.get()->getType(); 7571 QualType OrigLHSType = LHSType; 7572 7573 // Get canonical types. We're not formatting these types, just comparing 7574 // them. 7575 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7576 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7577 7578 // Common case: no conversion required. 7579 if (LHSType == RHSType) { 7580 Kind = CK_NoOp; 7581 return Compatible; 7582 } 7583 7584 // If we have an atomic type, try a non-atomic assignment, then just add an 7585 // atomic qualification step. 7586 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7587 Sema::AssignConvertType result = 7588 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7589 if (result != Compatible) 7590 return result; 7591 if (Kind != CK_NoOp && ConvertRHS) 7592 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7593 Kind = CK_NonAtomicToAtomic; 7594 return Compatible; 7595 } 7596 7597 // If the left-hand side is a reference type, then we are in a 7598 // (rare!) case where we've allowed the use of references in C, 7599 // e.g., as a parameter type in a built-in function. In this case, 7600 // just make sure that the type referenced is compatible with the 7601 // right-hand side type. The caller is responsible for adjusting 7602 // LHSType so that the resulting expression does not have reference 7603 // type. 7604 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7605 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7606 Kind = CK_LValueBitCast; 7607 return Compatible; 7608 } 7609 return Incompatible; 7610 } 7611 7612 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7613 // to the same ExtVector type. 7614 if (LHSType->isExtVectorType()) { 7615 if (RHSType->isExtVectorType()) 7616 return Incompatible; 7617 if (RHSType->isArithmeticType()) { 7618 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7619 if (ConvertRHS) 7620 RHS = prepareVectorSplat(LHSType, RHS.get()); 7621 Kind = CK_VectorSplat; 7622 return Compatible; 7623 } 7624 } 7625 7626 // Conversions to or from vector type. 7627 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7628 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7629 // Allow assignments of an AltiVec vector type to an equivalent GCC 7630 // vector type and vice versa 7631 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7632 Kind = CK_BitCast; 7633 return Compatible; 7634 } 7635 7636 // If we are allowing lax vector conversions, and LHS and RHS are both 7637 // vectors, the total size only needs to be the same. This is a bitcast; 7638 // no bits are changed but the result type is different. 7639 if (isLaxVectorConversion(RHSType, LHSType)) { 7640 Kind = CK_BitCast; 7641 return IncompatibleVectors; 7642 } 7643 } 7644 7645 // When the RHS comes from another lax conversion (e.g. binops between 7646 // scalars and vectors) the result is canonicalized as a vector. When the 7647 // LHS is also a vector, the lax is allowed by the condition above. Handle 7648 // the case where LHS is a scalar. 7649 if (LHSType->isScalarType()) { 7650 const VectorType *VecType = RHSType->getAs<VectorType>(); 7651 if (VecType && VecType->getNumElements() == 1 && 7652 isLaxVectorConversion(RHSType, LHSType)) { 7653 ExprResult *VecExpr = &RHS; 7654 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7655 Kind = CK_BitCast; 7656 return Compatible; 7657 } 7658 } 7659 7660 return Incompatible; 7661 } 7662 7663 // Diagnose attempts to convert between __float128 and long double where 7664 // such conversions currently can't be handled. 7665 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7666 return Incompatible; 7667 7668 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7669 // discards the imaginary part. 7670 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7671 !LHSType->getAs<ComplexType>()) 7672 return Incompatible; 7673 7674 // Arithmetic conversions. 7675 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7676 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7677 if (ConvertRHS) 7678 Kind = PrepareScalarCast(RHS, LHSType); 7679 return Compatible; 7680 } 7681 7682 // Conversions to normal pointers. 7683 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7684 // U* -> T* 7685 if (isa<PointerType>(RHSType)) { 7686 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7687 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7688 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7689 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7690 } 7691 7692 // int -> T* 7693 if (RHSType->isIntegerType()) { 7694 Kind = CK_IntegralToPointer; // FIXME: null? 7695 return IntToPointer; 7696 } 7697 7698 // C pointers are not compatible with ObjC object pointers, 7699 // with two exceptions: 7700 if (isa<ObjCObjectPointerType>(RHSType)) { 7701 // - conversions to void* 7702 if (LHSPointer->getPointeeType()->isVoidType()) { 7703 Kind = CK_BitCast; 7704 return Compatible; 7705 } 7706 7707 // - conversions from 'Class' to the redefinition type 7708 if (RHSType->isObjCClassType() && 7709 Context.hasSameType(LHSType, 7710 Context.getObjCClassRedefinitionType())) { 7711 Kind = CK_BitCast; 7712 return Compatible; 7713 } 7714 7715 Kind = CK_BitCast; 7716 return IncompatiblePointer; 7717 } 7718 7719 // U^ -> void* 7720 if (RHSType->getAs<BlockPointerType>()) { 7721 if (LHSPointer->getPointeeType()->isVoidType()) { 7722 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7723 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7724 ->getPointeeType() 7725 .getAddressSpace(); 7726 Kind = 7727 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7728 return Compatible; 7729 } 7730 } 7731 7732 return Incompatible; 7733 } 7734 7735 // Conversions to block pointers. 7736 if (isa<BlockPointerType>(LHSType)) { 7737 // U^ -> T^ 7738 if (RHSType->isBlockPointerType()) { 7739 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7740 ->getPointeeType() 7741 .getAddressSpace(); 7742 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7743 ->getPointeeType() 7744 .getAddressSpace(); 7745 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7746 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7747 } 7748 7749 // int or null -> T^ 7750 if (RHSType->isIntegerType()) { 7751 Kind = CK_IntegralToPointer; // FIXME: null 7752 return IntToBlockPointer; 7753 } 7754 7755 // id -> T^ 7756 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7757 Kind = CK_AnyPointerToBlockPointerCast; 7758 return Compatible; 7759 } 7760 7761 // void* -> T^ 7762 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7763 if (RHSPT->getPointeeType()->isVoidType()) { 7764 Kind = CK_AnyPointerToBlockPointerCast; 7765 return Compatible; 7766 } 7767 7768 return Incompatible; 7769 } 7770 7771 // Conversions to Objective-C pointers. 7772 if (isa<ObjCObjectPointerType>(LHSType)) { 7773 // A* -> B* 7774 if (RHSType->isObjCObjectPointerType()) { 7775 Kind = CK_BitCast; 7776 Sema::AssignConvertType result = 7777 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7778 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7779 result == Compatible && 7780 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7781 result = IncompatibleObjCWeakRef; 7782 return result; 7783 } 7784 7785 // int or null -> A* 7786 if (RHSType->isIntegerType()) { 7787 Kind = CK_IntegralToPointer; // FIXME: null 7788 return IntToPointer; 7789 } 7790 7791 // In general, C pointers are not compatible with ObjC object pointers, 7792 // with two exceptions: 7793 if (isa<PointerType>(RHSType)) { 7794 Kind = CK_CPointerToObjCPointerCast; 7795 7796 // - conversions from 'void*' 7797 if (RHSType->isVoidPointerType()) { 7798 return Compatible; 7799 } 7800 7801 // - conversions to 'Class' from its redefinition type 7802 if (LHSType->isObjCClassType() && 7803 Context.hasSameType(RHSType, 7804 Context.getObjCClassRedefinitionType())) { 7805 return Compatible; 7806 } 7807 7808 return IncompatiblePointer; 7809 } 7810 7811 // Only under strict condition T^ is compatible with an Objective-C pointer. 7812 if (RHSType->isBlockPointerType() && 7813 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7814 if (ConvertRHS) 7815 maybeExtendBlockObject(RHS); 7816 Kind = CK_BlockPointerToObjCPointerCast; 7817 return Compatible; 7818 } 7819 7820 return Incompatible; 7821 } 7822 7823 // Conversions from pointers that are not covered by the above. 7824 if (isa<PointerType>(RHSType)) { 7825 // T* -> _Bool 7826 if (LHSType == Context.BoolTy) { 7827 Kind = CK_PointerToBoolean; 7828 return Compatible; 7829 } 7830 7831 // T* -> int 7832 if (LHSType->isIntegerType()) { 7833 Kind = CK_PointerToIntegral; 7834 return PointerToInt; 7835 } 7836 7837 return Incompatible; 7838 } 7839 7840 // Conversions from Objective-C pointers that are not covered by the above. 7841 if (isa<ObjCObjectPointerType>(RHSType)) { 7842 // T* -> _Bool 7843 if (LHSType == Context.BoolTy) { 7844 Kind = CK_PointerToBoolean; 7845 return Compatible; 7846 } 7847 7848 // T* -> int 7849 if (LHSType->isIntegerType()) { 7850 Kind = CK_PointerToIntegral; 7851 return PointerToInt; 7852 } 7853 7854 return Incompatible; 7855 } 7856 7857 // struct A -> struct B 7858 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7859 if (Context.typesAreCompatible(LHSType, RHSType)) { 7860 Kind = CK_NoOp; 7861 return Compatible; 7862 } 7863 } 7864 7865 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7866 Kind = CK_IntToOCLSampler; 7867 return Compatible; 7868 } 7869 7870 return Incompatible; 7871 } 7872 7873 /// \brief Constructs a transparent union from an expression that is 7874 /// used to initialize the transparent union. 7875 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7876 ExprResult &EResult, QualType UnionType, 7877 FieldDecl *Field) { 7878 // Build an initializer list that designates the appropriate member 7879 // of the transparent union. 7880 Expr *E = EResult.get(); 7881 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7882 E, SourceLocation()); 7883 Initializer->setType(UnionType); 7884 Initializer->setInitializedFieldInUnion(Field); 7885 7886 // Build a compound literal constructing a value of the transparent 7887 // union type from this initializer list. 7888 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7889 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7890 VK_RValue, Initializer, false); 7891 } 7892 7893 Sema::AssignConvertType 7894 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7895 ExprResult &RHS) { 7896 QualType RHSType = RHS.get()->getType(); 7897 7898 // If the ArgType is a Union type, we want to handle a potential 7899 // transparent_union GCC extension. 7900 const RecordType *UT = ArgType->getAsUnionType(); 7901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7902 return Incompatible; 7903 7904 // The field to initialize within the transparent union. 7905 RecordDecl *UD = UT->getDecl(); 7906 FieldDecl *InitField = nullptr; 7907 // It's compatible if the expression matches any of the fields. 7908 for (auto *it : UD->fields()) { 7909 if (it->getType()->isPointerType()) { 7910 // If the transparent union contains a pointer type, we allow: 7911 // 1) void pointer 7912 // 2) null pointer constant 7913 if (RHSType->isPointerType()) 7914 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7915 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7916 InitField = it; 7917 break; 7918 } 7919 7920 if (RHS.get()->isNullPointerConstant(Context, 7921 Expr::NPC_ValueDependentIsNull)) { 7922 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7923 CK_NullToPointer); 7924 InitField = it; 7925 break; 7926 } 7927 } 7928 7929 CastKind Kind; 7930 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7931 == Compatible) { 7932 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7933 InitField = it; 7934 break; 7935 } 7936 } 7937 7938 if (!InitField) 7939 return Incompatible; 7940 7941 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7942 return Compatible; 7943 } 7944 7945 Sema::AssignConvertType 7946 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7947 bool Diagnose, 7948 bool DiagnoseCFAudited, 7949 bool ConvertRHS) { 7950 // We need to be able to tell the caller whether we diagnosed a problem, if 7951 // they ask us to issue diagnostics. 7952 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7953 7954 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7955 // we can't avoid *all* modifications at the moment, so we need some somewhere 7956 // to put the updated value. 7957 ExprResult LocalRHS = CallerRHS; 7958 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7959 7960 if (getLangOpts().CPlusPlus) { 7961 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7962 // C++ 5.17p3: If the left operand is not of class type, the 7963 // expression is implicitly converted (C++ 4) to the 7964 // cv-unqualified type of the left operand. 7965 QualType RHSType = RHS.get()->getType(); 7966 if (Diagnose) { 7967 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7968 AA_Assigning); 7969 } else { 7970 ImplicitConversionSequence ICS = 7971 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7972 /*SuppressUserConversions=*/false, 7973 /*AllowExplicit=*/false, 7974 /*InOverloadResolution=*/false, 7975 /*CStyle=*/false, 7976 /*AllowObjCWritebackConversion=*/false); 7977 if (ICS.isFailure()) 7978 return Incompatible; 7979 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7980 ICS, AA_Assigning); 7981 } 7982 if (RHS.isInvalid()) 7983 return Incompatible; 7984 Sema::AssignConvertType result = Compatible; 7985 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7986 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7987 result = IncompatibleObjCWeakRef; 7988 return result; 7989 } 7990 7991 // FIXME: Currently, we fall through and treat C++ classes like C 7992 // structures. 7993 // FIXME: We also fall through for atomics; not sure what should 7994 // happen there, though. 7995 } else if (RHS.get()->getType() == Context.OverloadTy) { 7996 // As a set of extensions to C, we support overloading on functions. These 7997 // functions need to be resolved here. 7998 DeclAccessPair DAP; 7999 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8000 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8001 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8002 else 8003 return Incompatible; 8004 } 8005 8006 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8007 // a null pointer constant. 8008 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8009 LHSType->isBlockPointerType()) && 8010 RHS.get()->isNullPointerConstant(Context, 8011 Expr::NPC_ValueDependentIsNull)) { 8012 if (Diagnose || ConvertRHS) { 8013 CastKind Kind; 8014 CXXCastPath Path; 8015 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8016 /*IgnoreBaseAccess=*/false, Diagnose); 8017 if (ConvertRHS) 8018 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8019 } 8020 return Compatible; 8021 } 8022 8023 // This check seems unnatural, however it is necessary to ensure the proper 8024 // conversion of functions/arrays. If the conversion were done for all 8025 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8026 // expressions that suppress this implicit conversion (&, sizeof). 8027 // 8028 // Suppress this for references: C++ 8.5.3p5. 8029 if (!LHSType->isReferenceType()) { 8030 // FIXME: We potentially allocate here even if ConvertRHS is false. 8031 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8032 if (RHS.isInvalid()) 8033 return Incompatible; 8034 } 8035 8036 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8037 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8038 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8039 if (PDecl && !PDecl->hasDefinition()) { 8040 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl; 8041 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8042 } 8043 } 8044 8045 CastKind Kind; 8046 Sema::AssignConvertType result = 8047 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8048 8049 // C99 6.5.16.1p2: The value of the right operand is converted to the 8050 // type of the assignment expression. 8051 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8052 // so that we can use references in built-in functions even in C. 8053 // The getNonReferenceType() call makes sure that the resulting expression 8054 // does not have reference type. 8055 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8056 QualType Ty = LHSType.getNonLValueExprType(Context); 8057 Expr *E = RHS.get(); 8058 8059 // Check for various Objective-C errors. If we are not reporting 8060 // diagnostics and just checking for errors, e.g., during overload 8061 // resolution, return Incompatible to indicate the failure. 8062 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8063 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8064 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8065 if (!Diagnose) 8066 return Incompatible; 8067 } 8068 if (getLangOpts().ObjC1 && 8069 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8070 E->getType(), E, Diagnose) || 8071 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8072 if (!Diagnose) 8073 return Incompatible; 8074 // Replace the expression with a corrected version and continue so we 8075 // can find further errors. 8076 RHS = E; 8077 return Compatible; 8078 } 8079 8080 if (ConvertRHS) 8081 RHS = ImpCastExprToType(E, Ty, Kind); 8082 } 8083 return result; 8084 } 8085 8086 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8087 ExprResult &RHS) { 8088 Diag(Loc, diag::err_typecheck_invalid_operands) 8089 << LHS.get()->getType() << RHS.get()->getType() 8090 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8091 return QualType(); 8092 } 8093 8094 // Diagnose cases where a scalar was implicitly converted to a vector and 8095 // diagnose the underlying types. Otherwise, diagnose the error 8096 // as invalid vector logical operands for non-C++ cases. 8097 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8098 ExprResult &RHS) { 8099 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8100 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8101 8102 bool LHSNatVec = LHSType->isVectorType(); 8103 bool RHSNatVec = RHSType->isVectorType(); 8104 8105 if (!(LHSNatVec && RHSNatVec)) { 8106 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8107 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8108 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8109 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8110 << Vector->getSourceRange(); 8111 return QualType(); 8112 } 8113 8114 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8115 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8116 << RHS.get()->getSourceRange(); 8117 8118 return QualType(); 8119 } 8120 8121 /// Try to convert a value of non-vector type to a vector type by converting 8122 /// the type to the element type of the vector and then performing a splat. 8123 /// If the language is OpenCL, we only use conversions that promote scalar 8124 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8125 /// for float->int. 8126 /// 8127 /// OpenCL V2.0 6.2.6.p2: 8128 /// An error shall occur if any scalar operand type has greater rank 8129 /// than the type of the vector element. 8130 /// 8131 /// \param scalar - if non-null, actually perform the conversions 8132 /// \return true if the operation fails (but without diagnosing the failure) 8133 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8134 QualType scalarTy, 8135 QualType vectorEltTy, 8136 QualType vectorTy, 8137 unsigned &DiagID) { 8138 // The conversion to apply to the scalar before splatting it, 8139 // if necessary. 8140 CastKind scalarCast = CK_NoOp; 8141 8142 if (vectorEltTy->isIntegralType(S.Context)) { 8143 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8144 (scalarTy->isIntegerType() && 8145 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8146 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8147 return true; 8148 } 8149 if (!scalarTy->isIntegralType(S.Context)) 8150 return true; 8151 scalarCast = CK_IntegralCast; 8152 } else if (vectorEltTy->isRealFloatingType()) { 8153 if (scalarTy->isRealFloatingType()) { 8154 if (S.getLangOpts().OpenCL && 8155 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8156 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8157 return true; 8158 } 8159 scalarCast = CK_FloatingCast; 8160 } 8161 else if (scalarTy->isIntegralType(S.Context)) 8162 scalarCast = CK_IntegralToFloating; 8163 else 8164 return true; 8165 } else { 8166 return true; 8167 } 8168 8169 // Adjust scalar if desired. 8170 if (scalar) { 8171 if (scalarCast != CK_NoOp) 8172 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8173 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8174 } 8175 return false; 8176 } 8177 8178 /// Convert vector E to a vector with the same number of elements but different 8179 /// element type. 8180 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8181 const auto *VecTy = E->getType()->getAs<VectorType>(); 8182 assert(VecTy && "Expression E must be a vector"); 8183 QualType NewVecTy = S.Context.getVectorType(ElementType, 8184 VecTy->getNumElements(), 8185 VecTy->getVectorKind()); 8186 8187 // Look through the implicit cast. Return the subexpression if its type is 8188 // NewVecTy. 8189 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8190 if (ICE->getSubExpr()->getType() == NewVecTy) 8191 return ICE->getSubExpr(); 8192 8193 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8194 return S.ImpCastExprToType(E, NewVecTy, Cast); 8195 } 8196 8197 /// Test if a (constant) integer Int can be casted to another integer type 8198 /// IntTy without losing precision. 8199 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8200 QualType OtherIntTy) { 8201 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8202 8203 // Reject cases where the value of the Int is unknown as that would 8204 // possibly cause truncation, but accept cases where the scalar can be 8205 // demoted without loss of precision. 8206 llvm::APSInt Result; 8207 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8208 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8209 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8210 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8211 8212 if (CstInt) { 8213 // If the scalar is constant and is of a higher order and has more active 8214 // bits that the vector element type, reject it. 8215 unsigned NumBits = IntSigned 8216 ? (Result.isNegative() ? Result.getMinSignedBits() 8217 : Result.getActiveBits()) 8218 : Result.getActiveBits(); 8219 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8220 return true; 8221 8222 // If the signedness of the scalar type and the vector element type 8223 // differs and the number of bits is greater than that of the vector 8224 // element reject it. 8225 return (IntSigned != OtherIntSigned && 8226 NumBits > S.Context.getIntWidth(OtherIntTy)); 8227 } 8228 8229 // Reject cases where the value of the scalar is not constant and it's 8230 // order is greater than that of the vector element type. 8231 return (Order < 0); 8232 } 8233 8234 /// Test if a (constant) integer Int can be casted to floating point type 8235 /// FloatTy without losing precision. 8236 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8237 QualType FloatTy) { 8238 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8239 8240 // Determine if the integer constant can be expressed as a floating point 8241 // number of the appropriate type. 8242 llvm::APSInt Result; 8243 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8244 uint64_t Bits = 0; 8245 if (CstInt) { 8246 // Reject constants that would be truncated if they were converted to 8247 // the floating point type. Test by simple to/from conversion. 8248 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8249 // could be avoided if there was a convertFromAPInt method 8250 // which could signal back if implicit truncation occurred. 8251 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8252 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8253 llvm::APFloat::rmTowardZero); 8254 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8255 !IntTy->hasSignedIntegerRepresentation()); 8256 bool Ignored = false; 8257 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8258 &Ignored); 8259 if (Result != ConvertBack) 8260 return true; 8261 } else { 8262 // Reject types that cannot be fully encoded into the mantissa of 8263 // the float. 8264 Bits = S.Context.getTypeSize(IntTy); 8265 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8266 S.Context.getFloatTypeSemantics(FloatTy)); 8267 if (Bits > FloatPrec) 8268 return true; 8269 } 8270 8271 return false; 8272 } 8273 8274 /// Attempt to convert and splat Scalar into a vector whose types matches 8275 /// Vector following GCC conversion rules. The rule is that implicit 8276 /// conversion can occur when Scalar can be casted to match Vector's element 8277 /// type without causing truncation of Scalar. 8278 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8279 ExprResult *Vector) { 8280 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8281 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8282 const VectorType *VT = VectorTy->getAs<VectorType>(); 8283 8284 assert(!isa<ExtVectorType>(VT) && 8285 "ExtVectorTypes should not be handled here!"); 8286 8287 QualType VectorEltTy = VT->getElementType(); 8288 8289 // Reject cases where the vector element type or the scalar element type are 8290 // not integral or floating point types. 8291 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8292 return true; 8293 8294 // The conversion to apply to the scalar before splatting it, 8295 // if necessary. 8296 CastKind ScalarCast = CK_NoOp; 8297 8298 // Accept cases where the vector elements are integers and the scalar is 8299 // an integer. 8300 // FIXME: Notionally if the scalar was a floating point value with a precise 8301 // integral representation, we could cast it to an appropriate integer 8302 // type and then perform the rest of the checks here. GCC will perform 8303 // this conversion in some cases as determined by the input language. 8304 // We should accept it on a language independent basis. 8305 if (VectorEltTy->isIntegralType(S.Context) && 8306 ScalarTy->isIntegralType(S.Context) && 8307 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8308 8309 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8310 return true; 8311 8312 ScalarCast = CK_IntegralCast; 8313 } else if (VectorEltTy->isRealFloatingType()) { 8314 if (ScalarTy->isRealFloatingType()) { 8315 8316 // Reject cases where the scalar type is not a constant and has a higher 8317 // Order than the vector element type. 8318 llvm::APFloat Result(0.0); 8319 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8320 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8321 if (!CstScalar && Order < 0) 8322 return true; 8323 8324 // If the scalar cannot be safely casted to the vector element type, 8325 // reject it. 8326 if (CstScalar) { 8327 bool Truncated = false; 8328 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8329 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8330 if (Truncated) 8331 return true; 8332 } 8333 8334 ScalarCast = CK_FloatingCast; 8335 } else if (ScalarTy->isIntegralType(S.Context)) { 8336 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8337 return true; 8338 8339 ScalarCast = CK_IntegralToFloating; 8340 } else 8341 return true; 8342 } 8343 8344 // Adjust scalar if desired. 8345 if (Scalar) { 8346 if (ScalarCast != CK_NoOp) 8347 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8348 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8349 } 8350 return false; 8351 } 8352 8353 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8354 SourceLocation Loc, bool IsCompAssign, 8355 bool AllowBothBool, 8356 bool AllowBoolConversions) { 8357 if (!IsCompAssign) { 8358 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8359 if (LHS.isInvalid()) 8360 return QualType(); 8361 } 8362 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8363 if (RHS.isInvalid()) 8364 return QualType(); 8365 8366 // For conversion purposes, we ignore any qualifiers. 8367 // For example, "const float" and "float" are equivalent. 8368 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8369 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8370 8371 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8372 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8373 assert(LHSVecType || RHSVecType); 8374 8375 // AltiVec-style "vector bool op vector bool" combinations are allowed 8376 // for some operators but not others. 8377 if (!AllowBothBool && 8378 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8379 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8380 return InvalidOperands(Loc, LHS, RHS); 8381 8382 // If the vector types are identical, return. 8383 if (Context.hasSameType(LHSType, RHSType)) 8384 return LHSType; 8385 8386 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8387 if (LHSVecType && RHSVecType && 8388 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8389 if (isa<ExtVectorType>(LHSVecType)) { 8390 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8391 return LHSType; 8392 } 8393 8394 if (!IsCompAssign) 8395 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8396 return RHSType; 8397 } 8398 8399 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8400 // can be mixed, with the result being the non-bool type. The non-bool 8401 // operand must have integer element type. 8402 if (AllowBoolConversions && LHSVecType && RHSVecType && 8403 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8404 (Context.getTypeSize(LHSVecType->getElementType()) == 8405 Context.getTypeSize(RHSVecType->getElementType()))) { 8406 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8407 LHSVecType->getElementType()->isIntegerType() && 8408 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8409 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8410 return LHSType; 8411 } 8412 if (!IsCompAssign && 8413 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8414 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8415 RHSVecType->getElementType()->isIntegerType()) { 8416 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8417 return RHSType; 8418 } 8419 } 8420 8421 // If there's a vector type and a scalar, try to convert the scalar to 8422 // the vector element type and splat. 8423 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8424 if (!RHSVecType) { 8425 if (isa<ExtVectorType>(LHSVecType)) { 8426 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8427 LHSVecType->getElementType(), LHSType, 8428 DiagID)) 8429 return LHSType; 8430 } else { 8431 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8432 return LHSType; 8433 } 8434 } 8435 if (!LHSVecType) { 8436 if (isa<ExtVectorType>(RHSVecType)) { 8437 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8438 LHSType, RHSVecType->getElementType(), 8439 RHSType, DiagID)) 8440 return RHSType; 8441 } else { 8442 if (LHS.get()->getValueKind() == VK_LValue || 8443 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8444 return RHSType; 8445 } 8446 } 8447 8448 // FIXME: The code below also handles conversion between vectors and 8449 // non-scalars, we should break this down into fine grained specific checks 8450 // and emit proper diagnostics. 8451 QualType VecType = LHSVecType ? LHSType : RHSType; 8452 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8453 QualType OtherType = LHSVecType ? RHSType : LHSType; 8454 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8455 if (isLaxVectorConversion(OtherType, VecType)) { 8456 // If we're allowing lax vector conversions, only the total (data) size 8457 // needs to be the same. For non compound assignment, if one of the types is 8458 // scalar, the result is always the vector type. 8459 if (!IsCompAssign) { 8460 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8461 return VecType; 8462 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8463 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8464 // type. Note that this is already done by non-compound assignments in 8465 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8466 // <1 x T> -> T. The result is also a vector type. 8467 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8468 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8469 ExprResult *RHSExpr = &RHS; 8470 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8471 return VecType; 8472 } 8473 } 8474 8475 // Okay, the expression is invalid. 8476 8477 // If there's a non-vector, non-real operand, diagnose that. 8478 if ((!RHSVecType && !RHSType->isRealType()) || 8479 (!LHSVecType && !LHSType->isRealType())) { 8480 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8481 << LHSType << RHSType 8482 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8483 return QualType(); 8484 } 8485 8486 // OpenCL V1.1 6.2.6.p1: 8487 // If the operands are of more than one vector type, then an error shall 8488 // occur. Implicit conversions between vector types are not permitted, per 8489 // section 6.2.1. 8490 if (getLangOpts().OpenCL && 8491 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8492 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8493 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8494 << RHSType; 8495 return QualType(); 8496 } 8497 8498 8499 // If there is a vector type that is not a ExtVector and a scalar, we reach 8500 // this point if scalar could not be converted to the vector's element type 8501 // without truncation. 8502 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8503 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8504 QualType Scalar = LHSVecType ? RHSType : LHSType; 8505 QualType Vector = LHSVecType ? LHSType : RHSType; 8506 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8507 Diag(Loc, 8508 diag::err_typecheck_vector_not_convertable_implict_truncation) 8509 << ScalarOrVector << Scalar << Vector; 8510 8511 return QualType(); 8512 } 8513 8514 // Otherwise, use the generic diagnostic. 8515 Diag(Loc, DiagID) 8516 << LHSType << RHSType 8517 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8518 return QualType(); 8519 } 8520 8521 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8522 // expression. These are mainly cases where the null pointer is used as an 8523 // integer instead of a pointer. 8524 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8525 SourceLocation Loc, bool IsCompare) { 8526 // The canonical way to check for a GNU null is with isNullPointerConstant, 8527 // but we use a bit of a hack here for speed; this is a relatively 8528 // hot path, and isNullPointerConstant is slow. 8529 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8530 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8531 8532 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8533 8534 // Avoid analyzing cases where the result will either be invalid (and 8535 // diagnosed as such) or entirely valid and not something to warn about. 8536 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8537 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8538 return; 8539 8540 // Comparison operations would not make sense with a null pointer no matter 8541 // what the other expression is. 8542 if (!IsCompare) { 8543 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8544 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8545 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8546 return; 8547 } 8548 8549 // The rest of the operations only make sense with a null pointer 8550 // if the other expression is a pointer. 8551 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8552 NonNullType->canDecayToPointerType()) 8553 return; 8554 8555 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8556 << LHSNull /* LHS is NULL */ << NonNullType 8557 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8558 } 8559 8560 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8561 ExprResult &RHS, 8562 SourceLocation Loc, bool IsDiv) { 8563 // Check for division/remainder by zero. 8564 llvm::APSInt RHSValue; 8565 if (!RHS.get()->isValueDependent() && 8566 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8567 S.DiagRuntimeBehavior(Loc, RHS.get(), 8568 S.PDiag(diag::warn_remainder_division_by_zero) 8569 << IsDiv << RHS.get()->getSourceRange()); 8570 } 8571 8572 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8573 SourceLocation Loc, 8574 bool IsCompAssign, bool IsDiv) { 8575 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8576 8577 if (LHS.get()->getType()->isVectorType() || 8578 RHS.get()->getType()->isVectorType()) 8579 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8580 /*AllowBothBool*/getLangOpts().AltiVec, 8581 /*AllowBoolConversions*/false); 8582 8583 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8584 if (LHS.isInvalid() || RHS.isInvalid()) 8585 return QualType(); 8586 8587 8588 if (compType.isNull() || !compType->isArithmeticType()) 8589 return InvalidOperands(Loc, LHS, RHS); 8590 if (IsDiv) 8591 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8592 return compType; 8593 } 8594 8595 QualType Sema::CheckRemainderOperands( 8596 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8597 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8598 8599 if (LHS.get()->getType()->isVectorType() || 8600 RHS.get()->getType()->isVectorType()) { 8601 if (LHS.get()->getType()->hasIntegerRepresentation() && 8602 RHS.get()->getType()->hasIntegerRepresentation()) 8603 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8604 /*AllowBothBool*/getLangOpts().AltiVec, 8605 /*AllowBoolConversions*/false); 8606 return InvalidOperands(Loc, LHS, RHS); 8607 } 8608 8609 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8610 if (LHS.isInvalid() || RHS.isInvalid()) 8611 return QualType(); 8612 8613 if (compType.isNull() || !compType->isIntegerType()) 8614 return InvalidOperands(Loc, LHS, RHS); 8615 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8616 return compType; 8617 } 8618 8619 /// \brief Diagnose invalid arithmetic on two void pointers. 8620 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8621 Expr *LHSExpr, Expr *RHSExpr) { 8622 S.Diag(Loc, S.getLangOpts().CPlusPlus 8623 ? diag::err_typecheck_pointer_arith_void_type 8624 : diag::ext_gnu_void_ptr) 8625 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8626 << RHSExpr->getSourceRange(); 8627 } 8628 8629 /// \brief Diagnose invalid arithmetic on a void pointer. 8630 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8631 Expr *Pointer) { 8632 S.Diag(Loc, S.getLangOpts().CPlusPlus 8633 ? diag::err_typecheck_pointer_arith_void_type 8634 : diag::ext_gnu_void_ptr) 8635 << 0 /* one pointer */ << Pointer->getSourceRange(); 8636 } 8637 8638 /// \brief Diagnose invalid arithmetic on a null pointer. 8639 /// 8640 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8641 /// idiom, which we recognize as a GNU extension. 8642 /// 8643 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8644 Expr *Pointer, bool IsGNUIdiom) { 8645 if (IsGNUIdiom) 8646 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8647 << Pointer->getSourceRange(); 8648 else 8649 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8650 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8651 } 8652 8653 /// \brief Diagnose invalid arithmetic on two function pointers. 8654 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8655 Expr *LHS, Expr *RHS) { 8656 assert(LHS->getType()->isAnyPointerType()); 8657 assert(RHS->getType()->isAnyPointerType()); 8658 S.Diag(Loc, S.getLangOpts().CPlusPlus 8659 ? diag::err_typecheck_pointer_arith_function_type 8660 : diag::ext_gnu_ptr_func_arith) 8661 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8662 // We only show the second type if it differs from the first. 8663 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8664 RHS->getType()) 8665 << RHS->getType()->getPointeeType() 8666 << LHS->getSourceRange() << RHS->getSourceRange(); 8667 } 8668 8669 /// \brief Diagnose invalid arithmetic on a function pointer. 8670 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8671 Expr *Pointer) { 8672 assert(Pointer->getType()->isAnyPointerType()); 8673 S.Diag(Loc, S.getLangOpts().CPlusPlus 8674 ? diag::err_typecheck_pointer_arith_function_type 8675 : diag::ext_gnu_ptr_func_arith) 8676 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8677 << 0 /* one pointer, so only one type */ 8678 << Pointer->getSourceRange(); 8679 } 8680 8681 /// \brief Emit error if Operand is incomplete pointer type 8682 /// 8683 /// \returns True if pointer has incomplete type 8684 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8685 Expr *Operand) { 8686 QualType ResType = Operand->getType(); 8687 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8688 ResType = ResAtomicType->getValueType(); 8689 8690 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8691 QualType PointeeTy = ResType->getPointeeType(); 8692 return S.RequireCompleteType(Loc, PointeeTy, 8693 diag::err_typecheck_arithmetic_incomplete_type, 8694 PointeeTy, Operand->getSourceRange()); 8695 } 8696 8697 /// \brief Check the validity of an arithmetic pointer operand. 8698 /// 8699 /// If the operand has pointer type, this code will check for pointer types 8700 /// which are invalid in arithmetic operations. These will be diagnosed 8701 /// appropriately, including whether or not the use is supported as an 8702 /// extension. 8703 /// 8704 /// \returns True when the operand is valid to use (even if as an extension). 8705 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8706 Expr *Operand) { 8707 QualType ResType = Operand->getType(); 8708 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8709 ResType = ResAtomicType->getValueType(); 8710 8711 if (!ResType->isAnyPointerType()) return true; 8712 8713 QualType PointeeTy = ResType->getPointeeType(); 8714 if (PointeeTy->isVoidType()) { 8715 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8716 return !S.getLangOpts().CPlusPlus; 8717 } 8718 if (PointeeTy->isFunctionType()) { 8719 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8720 return !S.getLangOpts().CPlusPlus; 8721 } 8722 8723 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8724 8725 return true; 8726 } 8727 8728 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8729 /// operands. 8730 /// 8731 /// This routine will diagnose any invalid arithmetic on pointer operands much 8732 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8733 /// for emitting a single diagnostic even for operations where both LHS and RHS 8734 /// are (potentially problematic) pointers. 8735 /// 8736 /// \returns True when the operand is valid to use (even if as an extension). 8737 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8738 Expr *LHSExpr, Expr *RHSExpr) { 8739 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8740 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8741 if (!isLHSPointer && !isRHSPointer) return true; 8742 8743 QualType LHSPointeeTy, RHSPointeeTy; 8744 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8745 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8746 8747 // if both are pointers check if operation is valid wrt address spaces 8748 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8749 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8750 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8751 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8752 S.Diag(Loc, 8753 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8754 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8755 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8756 return false; 8757 } 8758 } 8759 8760 // Check for arithmetic on pointers to incomplete types. 8761 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8762 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8763 if (isLHSVoidPtr || isRHSVoidPtr) { 8764 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8765 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8766 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8767 8768 return !S.getLangOpts().CPlusPlus; 8769 } 8770 8771 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8772 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8773 if (isLHSFuncPtr || isRHSFuncPtr) { 8774 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8775 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8776 RHSExpr); 8777 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8778 8779 return !S.getLangOpts().CPlusPlus; 8780 } 8781 8782 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8783 return false; 8784 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8785 return false; 8786 8787 return true; 8788 } 8789 8790 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8791 /// literal. 8792 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8793 Expr *LHSExpr, Expr *RHSExpr) { 8794 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8795 Expr* IndexExpr = RHSExpr; 8796 if (!StrExpr) { 8797 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8798 IndexExpr = LHSExpr; 8799 } 8800 8801 bool IsStringPlusInt = StrExpr && 8802 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8803 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8804 return; 8805 8806 llvm::APSInt index; 8807 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8808 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8809 if (index.isNonNegative() && 8810 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8811 index.isUnsigned())) 8812 return; 8813 } 8814 8815 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8816 Self.Diag(OpLoc, diag::warn_string_plus_int) 8817 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8818 8819 // Only print a fixit for "str" + int, not for int + "str". 8820 if (IndexExpr == RHSExpr) { 8821 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8822 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8823 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8824 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8825 << FixItHint::CreateInsertion(EndLoc, "]"); 8826 } else 8827 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8828 } 8829 8830 /// \brief Emit a warning when adding a char literal to a string. 8831 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8832 Expr *LHSExpr, Expr *RHSExpr) { 8833 const Expr *StringRefExpr = LHSExpr; 8834 const CharacterLiteral *CharExpr = 8835 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8836 8837 if (!CharExpr) { 8838 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8839 StringRefExpr = RHSExpr; 8840 } 8841 8842 if (!CharExpr || !StringRefExpr) 8843 return; 8844 8845 const QualType StringType = StringRefExpr->getType(); 8846 8847 // Return if not a PointerType. 8848 if (!StringType->isAnyPointerType()) 8849 return; 8850 8851 // Return if not a CharacterType. 8852 if (!StringType->getPointeeType()->isAnyCharacterType()) 8853 return; 8854 8855 ASTContext &Ctx = Self.getASTContext(); 8856 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8857 8858 const QualType CharType = CharExpr->getType(); 8859 if (!CharType->isAnyCharacterType() && 8860 CharType->isIntegerType() && 8861 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8862 Self.Diag(OpLoc, diag::warn_string_plus_char) 8863 << DiagRange << Ctx.CharTy; 8864 } else { 8865 Self.Diag(OpLoc, diag::warn_string_plus_char) 8866 << DiagRange << CharExpr->getType(); 8867 } 8868 8869 // Only print a fixit for str + char, not for char + str. 8870 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8871 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8872 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8873 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8874 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8875 << FixItHint::CreateInsertion(EndLoc, "]"); 8876 } else { 8877 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8878 } 8879 } 8880 8881 /// \brief Emit error when two pointers are incompatible. 8882 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8883 Expr *LHSExpr, Expr *RHSExpr) { 8884 assert(LHSExpr->getType()->isAnyPointerType()); 8885 assert(RHSExpr->getType()->isAnyPointerType()); 8886 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8887 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8888 << RHSExpr->getSourceRange(); 8889 } 8890 8891 // C99 6.5.6 8892 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8893 SourceLocation Loc, BinaryOperatorKind Opc, 8894 QualType* CompLHSTy) { 8895 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8896 8897 if (LHS.get()->getType()->isVectorType() || 8898 RHS.get()->getType()->isVectorType()) { 8899 QualType compType = CheckVectorOperands( 8900 LHS, RHS, Loc, CompLHSTy, 8901 /*AllowBothBool*/getLangOpts().AltiVec, 8902 /*AllowBoolConversions*/getLangOpts().ZVector); 8903 if (CompLHSTy) *CompLHSTy = compType; 8904 return compType; 8905 } 8906 8907 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8908 if (LHS.isInvalid() || RHS.isInvalid()) 8909 return QualType(); 8910 8911 // Diagnose "string literal" '+' int and string '+' "char literal". 8912 if (Opc == BO_Add) { 8913 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8914 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8915 } 8916 8917 // handle the common case first (both operands are arithmetic). 8918 if (!compType.isNull() && compType->isArithmeticType()) { 8919 if (CompLHSTy) *CompLHSTy = compType; 8920 return compType; 8921 } 8922 8923 // Type-checking. Ultimately the pointer's going to be in PExp; 8924 // note that we bias towards the LHS being the pointer. 8925 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8926 8927 bool isObjCPointer; 8928 if (PExp->getType()->isPointerType()) { 8929 isObjCPointer = false; 8930 } else if (PExp->getType()->isObjCObjectPointerType()) { 8931 isObjCPointer = true; 8932 } else { 8933 std::swap(PExp, IExp); 8934 if (PExp->getType()->isPointerType()) { 8935 isObjCPointer = false; 8936 } else if (PExp->getType()->isObjCObjectPointerType()) { 8937 isObjCPointer = true; 8938 } else { 8939 return InvalidOperands(Loc, LHS, RHS); 8940 } 8941 } 8942 assert(PExp->getType()->isAnyPointerType()); 8943 8944 if (!IExp->getType()->isIntegerType()) 8945 return InvalidOperands(Loc, LHS, RHS); 8946 8947 // Adding to a null pointer results in undefined behavior. 8948 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8949 Context, Expr::NPC_ValueDependentIsNotNull)) { 8950 // In C++ adding zero to a null pointer is defined. 8951 llvm::APSInt KnownVal; 8952 if (!getLangOpts().CPlusPlus || 8953 (!IExp->isValueDependent() && 8954 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8955 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8956 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8957 Context, BO_Add, PExp, IExp); 8958 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8959 } 8960 } 8961 8962 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8963 return QualType(); 8964 8965 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8966 return QualType(); 8967 8968 // Check array bounds for pointer arithemtic 8969 CheckArrayAccess(PExp, IExp); 8970 8971 if (CompLHSTy) { 8972 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8973 if (LHSTy.isNull()) { 8974 LHSTy = LHS.get()->getType(); 8975 if (LHSTy->isPromotableIntegerType()) 8976 LHSTy = Context.getPromotedIntegerType(LHSTy); 8977 } 8978 *CompLHSTy = LHSTy; 8979 } 8980 8981 return PExp->getType(); 8982 } 8983 8984 // C99 6.5.6 8985 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8986 SourceLocation Loc, 8987 QualType* CompLHSTy) { 8988 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8989 8990 if (LHS.get()->getType()->isVectorType() || 8991 RHS.get()->getType()->isVectorType()) { 8992 QualType compType = CheckVectorOperands( 8993 LHS, RHS, Loc, CompLHSTy, 8994 /*AllowBothBool*/getLangOpts().AltiVec, 8995 /*AllowBoolConversions*/getLangOpts().ZVector); 8996 if (CompLHSTy) *CompLHSTy = compType; 8997 return compType; 8998 } 8999 9000 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9001 if (LHS.isInvalid() || RHS.isInvalid()) 9002 return QualType(); 9003 9004 // Enforce type constraints: C99 6.5.6p3. 9005 9006 // Handle the common case first (both operands are arithmetic). 9007 if (!compType.isNull() && compType->isArithmeticType()) { 9008 if (CompLHSTy) *CompLHSTy = compType; 9009 return compType; 9010 } 9011 9012 // Either ptr - int or ptr - ptr. 9013 if (LHS.get()->getType()->isAnyPointerType()) { 9014 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9015 9016 // Diagnose bad cases where we step over interface counts. 9017 if (LHS.get()->getType()->isObjCObjectPointerType() && 9018 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9019 return QualType(); 9020 9021 // The result type of a pointer-int computation is the pointer type. 9022 if (RHS.get()->getType()->isIntegerType()) { 9023 // Subtracting from a null pointer should produce a warning. 9024 // The last argument to the diagnose call says this doesn't match the 9025 // GNU int-to-pointer idiom. 9026 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9027 Expr::NPC_ValueDependentIsNotNull)) { 9028 // In C++ adding zero to a null pointer is defined. 9029 llvm::APSInt KnownVal; 9030 if (!getLangOpts().CPlusPlus || 9031 (!RHS.get()->isValueDependent() && 9032 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9033 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9034 } 9035 } 9036 9037 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9038 return QualType(); 9039 9040 // Check array bounds for pointer arithemtic 9041 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9042 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9043 9044 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9045 return LHS.get()->getType(); 9046 } 9047 9048 // Handle pointer-pointer subtractions. 9049 if (const PointerType *RHSPTy 9050 = RHS.get()->getType()->getAs<PointerType>()) { 9051 QualType rpointee = RHSPTy->getPointeeType(); 9052 9053 if (getLangOpts().CPlusPlus) { 9054 // Pointee types must be the same: C++ [expr.add] 9055 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9056 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9057 } 9058 } else { 9059 // Pointee types must be compatible C99 6.5.6p3 9060 if (!Context.typesAreCompatible( 9061 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9062 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9063 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9064 return QualType(); 9065 } 9066 } 9067 9068 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9069 LHS.get(), RHS.get())) 9070 return QualType(); 9071 9072 // FIXME: Add warnings for nullptr - ptr. 9073 9074 // The pointee type may have zero size. As an extension, a structure or 9075 // union may have zero size or an array may have zero length. In this 9076 // case subtraction does not make sense. 9077 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9078 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9079 if (ElementSize.isZero()) { 9080 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9081 << rpointee.getUnqualifiedType() 9082 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9083 } 9084 } 9085 9086 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9087 return Context.getPointerDiffType(); 9088 } 9089 } 9090 9091 return InvalidOperands(Loc, LHS, RHS); 9092 } 9093 9094 static bool isScopedEnumerationType(QualType T) { 9095 if (const EnumType *ET = T->getAs<EnumType>()) 9096 return ET->getDecl()->isScoped(); 9097 return false; 9098 } 9099 9100 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9101 SourceLocation Loc, BinaryOperatorKind Opc, 9102 QualType LHSType) { 9103 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9104 // so skip remaining warnings as we don't want to modify values within Sema. 9105 if (S.getLangOpts().OpenCL) 9106 return; 9107 9108 llvm::APSInt Right; 9109 // Check right/shifter operand 9110 if (RHS.get()->isValueDependent() || 9111 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9112 return; 9113 9114 if (Right.isNegative()) { 9115 S.DiagRuntimeBehavior(Loc, RHS.get(), 9116 S.PDiag(diag::warn_shift_negative) 9117 << RHS.get()->getSourceRange()); 9118 return; 9119 } 9120 llvm::APInt LeftBits(Right.getBitWidth(), 9121 S.Context.getTypeSize(LHS.get()->getType())); 9122 if (Right.uge(LeftBits)) { 9123 S.DiagRuntimeBehavior(Loc, RHS.get(), 9124 S.PDiag(diag::warn_shift_gt_typewidth) 9125 << RHS.get()->getSourceRange()); 9126 return; 9127 } 9128 if (Opc != BO_Shl) 9129 return; 9130 9131 // When left shifting an ICE which is signed, we can check for overflow which 9132 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9133 // integers have defined behavior modulo one more than the maximum value 9134 // representable in the result type, so never warn for those. 9135 llvm::APSInt Left; 9136 if (LHS.get()->isValueDependent() || 9137 LHSType->hasUnsignedIntegerRepresentation() || 9138 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9139 return; 9140 9141 // If LHS does not have a signed type and non-negative value 9142 // then, the behavior is undefined. Warn about it. 9143 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9144 S.DiagRuntimeBehavior(Loc, LHS.get(), 9145 S.PDiag(diag::warn_shift_lhs_negative) 9146 << LHS.get()->getSourceRange()); 9147 return; 9148 } 9149 9150 llvm::APInt ResultBits = 9151 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9152 if (LeftBits.uge(ResultBits)) 9153 return; 9154 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9155 Result = Result.shl(Right); 9156 9157 // Print the bit representation of the signed integer as an unsigned 9158 // hexadecimal number. 9159 SmallString<40> HexResult; 9160 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9161 9162 // If we are only missing a sign bit, this is less likely to result in actual 9163 // bugs -- if the result is cast back to an unsigned type, it will have the 9164 // expected value. Thus we place this behind a different warning that can be 9165 // turned off separately if needed. 9166 if (LeftBits == ResultBits - 1) { 9167 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9168 << HexResult << LHSType 9169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9170 return; 9171 } 9172 9173 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9174 << HexResult.str() << Result.getMinSignedBits() << LHSType 9175 << Left.getBitWidth() << LHS.get()->getSourceRange() 9176 << RHS.get()->getSourceRange(); 9177 } 9178 9179 /// \brief Return the resulting type when a vector is shifted 9180 /// by a scalar or vector shift amount. 9181 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9182 SourceLocation Loc, bool IsCompAssign) { 9183 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9184 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9185 !LHS.get()->getType()->isVectorType()) { 9186 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9187 << RHS.get()->getType() << LHS.get()->getType() 9188 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9189 return QualType(); 9190 } 9191 9192 if (!IsCompAssign) { 9193 LHS = S.UsualUnaryConversions(LHS.get()); 9194 if (LHS.isInvalid()) return QualType(); 9195 } 9196 9197 RHS = S.UsualUnaryConversions(RHS.get()); 9198 if (RHS.isInvalid()) return QualType(); 9199 9200 QualType LHSType = LHS.get()->getType(); 9201 // Note that LHS might be a scalar because the routine calls not only in 9202 // OpenCL case. 9203 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9204 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9205 9206 // Note that RHS might not be a vector. 9207 QualType RHSType = RHS.get()->getType(); 9208 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9209 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9210 9211 // The operands need to be integers. 9212 if (!LHSEleType->isIntegerType()) { 9213 S.Diag(Loc, diag::err_typecheck_expect_int) 9214 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9215 return QualType(); 9216 } 9217 9218 if (!RHSEleType->isIntegerType()) { 9219 S.Diag(Loc, diag::err_typecheck_expect_int) 9220 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9221 return QualType(); 9222 } 9223 9224 if (!LHSVecTy) { 9225 assert(RHSVecTy); 9226 if (IsCompAssign) 9227 return RHSType; 9228 if (LHSEleType != RHSEleType) { 9229 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9230 LHSEleType = RHSEleType; 9231 } 9232 QualType VecTy = 9233 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9234 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9235 LHSType = VecTy; 9236 } else if (RHSVecTy) { 9237 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9238 // are applied component-wise. So if RHS is a vector, then ensure 9239 // that the number of elements is the same as LHS... 9240 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9241 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9242 << LHS.get()->getType() << RHS.get()->getType() 9243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9244 return QualType(); 9245 } 9246 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9247 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9248 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9249 if (LHSBT != RHSBT && 9250 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9251 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9252 << LHS.get()->getType() << RHS.get()->getType() 9253 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9254 } 9255 } 9256 } else { 9257 // ...else expand RHS to match the number of elements in LHS. 9258 QualType VecTy = 9259 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9260 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9261 } 9262 9263 return LHSType; 9264 } 9265 9266 // C99 6.5.7 9267 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9268 SourceLocation Loc, BinaryOperatorKind Opc, 9269 bool IsCompAssign) { 9270 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9271 9272 // Vector shifts promote their scalar inputs to vector type. 9273 if (LHS.get()->getType()->isVectorType() || 9274 RHS.get()->getType()->isVectorType()) { 9275 if (LangOpts.ZVector) { 9276 // The shift operators for the z vector extensions work basically 9277 // like general shifts, except that neither the LHS nor the RHS is 9278 // allowed to be a "vector bool". 9279 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9280 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9281 return InvalidOperands(Loc, LHS, RHS); 9282 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9283 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9284 return InvalidOperands(Loc, LHS, RHS); 9285 } 9286 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9287 } 9288 9289 // Shifts don't perform usual arithmetic conversions, they just do integer 9290 // promotions on each operand. C99 6.5.7p3 9291 9292 // For the LHS, do usual unary conversions, but then reset them away 9293 // if this is a compound assignment. 9294 ExprResult OldLHS = LHS; 9295 LHS = UsualUnaryConversions(LHS.get()); 9296 if (LHS.isInvalid()) 9297 return QualType(); 9298 QualType LHSType = LHS.get()->getType(); 9299 if (IsCompAssign) LHS = OldLHS; 9300 9301 // The RHS is simpler. 9302 RHS = UsualUnaryConversions(RHS.get()); 9303 if (RHS.isInvalid()) 9304 return QualType(); 9305 QualType RHSType = RHS.get()->getType(); 9306 9307 // C99 6.5.7p2: Each of the operands shall have integer type. 9308 if (!LHSType->hasIntegerRepresentation() || 9309 !RHSType->hasIntegerRepresentation()) 9310 return InvalidOperands(Loc, LHS, RHS); 9311 9312 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9313 // hasIntegerRepresentation() above instead of this. 9314 if (isScopedEnumerationType(LHSType) || 9315 isScopedEnumerationType(RHSType)) { 9316 return InvalidOperands(Loc, LHS, RHS); 9317 } 9318 // Sanity-check shift operands 9319 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9320 9321 // "The type of the result is that of the promoted left operand." 9322 return LHSType; 9323 } 9324 9325 /// If two different enums are compared, raise a warning. 9326 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9327 Expr *RHS) { 9328 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9329 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9330 9331 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9332 if (!LHSEnumType) 9333 return; 9334 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9335 if (!RHSEnumType) 9336 return; 9337 9338 // Ignore anonymous enums. 9339 if (!LHSEnumType->getDecl()->getIdentifier() && 9340 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9341 return; 9342 if (!RHSEnumType->getDecl()->getIdentifier() && 9343 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9344 return; 9345 9346 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9347 return; 9348 9349 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9350 << LHSStrippedType << RHSStrippedType 9351 << LHS->getSourceRange() << RHS->getSourceRange(); 9352 } 9353 9354 /// \brief Diagnose bad pointer comparisons. 9355 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9356 ExprResult &LHS, ExprResult &RHS, 9357 bool IsError) { 9358 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9359 : diag::ext_typecheck_comparison_of_distinct_pointers) 9360 << LHS.get()->getType() << RHS.get()->getType() 9361 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9362 } 9363 9364 /// \brief Returns false if the pointers are converted to a composite type, 9365 /// true otherwise. 9366 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9367 ExprResult &LHS, ExprResult &RHS) { 9368 // C++ [expr.rel]p2: 9369 // [...] Pointer conversions (4.10) and qualification 9370 // conversions (4.4) are performed on pointer operands (or on 9371 // a pointer operand and a null pointer constant) to bring 9372 // them to their composite pointer type. [...] 9373 // 9374 // C++ [expr.eq]p1 uses the same notion for (in)equality 9375 // comparisons of pointers. 9376 9377 QualType LHSType = LHS.get()->getType(); 9378 QualType RHSType = RHS.get()->getType(); 9379 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9380 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9381 9382 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9383 if (T.isNull()) { 9384 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9385 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9386 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9387 else 9388 S.InvalidOperands(Loc, LHS, RHS); 9389 return true; 9390 } 9391 9392 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9393 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9394 return false; 9395 } 9396 9397 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9398 ExprResult &LHS, 9399 ExprResult &RHS, 9400 bool IsError) { 9401 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9402 : diag::ext_typecheck_comparison_of_fptr_to_void) 9403 << LHS.get()->getType() << RHS.get()->getType() 9404 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9405 } 9406 9407 static bool isObjCObjectLiteral(ExprResult &E) { 9408 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9409 case Stmt::ObjCArrayLiteralClass: 9410 case Stmt::ObjCDictionaryLiteralClass: 9411 case Stmt::ObjCStringLiteralClass: 9412 case Stmt::ObjCBoxedExprClass: 9413 return true; 9414 default: 9415 // Note that ObjCBoolLiteral is NOT an object literal! 9416 return false; 9417 } 9418 } 9419 9420 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9421 const ObjCObjectPointerType *Type = 9422 LHS->getType()->getAs<ObjCObjectPointerType>(); 9423 9424 // If this is not actually an Objective-C object, bail out. 9425 if (!Type) 9426 return false; 9427 9428 // Get the LHS object's interface type. 9429 QualType InterfaceType = Type->getPointeeType(); 9430 9431 // If the RHS isn't an Objective-C object, bail out. 9432 if (!RHS->getType()->isObjCObjectPointerType()) 9433 return false; 9434 9435 // Try to find the -isEqual: method. 9436 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9437 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9438 InterfaceType, 9439 /*instance=*/true); 9440 if (!Method) { 9441 if (Type->isObjCIdType()) { 9442 // For 'id', just check the global pool. 9443 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9444 /*receiverId=*/true); 9445 } else { 9446 // Check protocols. 9447 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9448 /*instance=*/true); 9449 } 9450 } 9451 9452 if (!Method) 9453 return false; 9454 9455 QualType T = Method->parameters()[0]->getType(); 9456 if (!T->isObjCObjectPointerType()) 9457 return false; 9458 9459 QualType R = Method->getReturnType(); 9460 if (!R->isScalarType()) 9461 return false; 9462 9463 return true; 9464 } 9465 9466 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9467 FromE = FromE->IgnoreParenImpCasts(); 9468 switch (FromE->getStmtClass()) { 9469 default: 9470 break; 9471 case Stmt::ObjCStringLiteralClass: 9472 // "string literal" 9473 return LK_String; 9474 case Stmt::ObjCArrayLiteralClass: 9475 // "array literal" 9476 return LK_Array; 9477 case Stmt::ObjCDictionaryLiteralClass: 9478 // "dictionary literal" 9479 return LK_Dictionary; 9480 case Stmt::BlockExprClass: 9481 return LK_Block; 9482 case Stmt::ObjCBoxedExprClass: { 9483 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9484 switch (Inner->getStmtClass()) { 9485 case Stmt::IntegerLiteralClass: 9486 case Stmt::FloatingLiteralClass: 9487 case Stmt::CharacterLiteralClass: 9488 case Stmt::ObjCBoolLiteralExprClass: 9489 case Stmt::CXXBoolLiteralExprClass: 9490 // "numeric literal" 9491 return LK_Numeric; 9492 case Stmt::ImplicitCastExprClass: { 9493 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9494 // Boolean literals can be represented by implicit casts. 9495 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9496 return LK_Numeric; 9497 break; 9498 } 9499 default: 9500 break; 9501 } 9502 return LK_Boxed; 9503 } 9504 } 9505 return LK_None; 9506 } 9507 9508 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9509 ExprResult &LHS, ExprResult &RHS, 9510 BinaryOperator::Opcode Opc){ 9511 Expr *Literal; 9512 Expr *Other; 9513 if (isObjCObjectLiteral(LHS)) { 9514 Literal = LHS.get(); 9515 Other = RHS.get(); 9516 } else { 9517 Literal = RHS.get(); 9518 Other = LHS.get(); 9519 } 9520 9521 // Don't warn on comparisons against nil. 9522 Other = Other->IgnoreParenCasts(); 9523 if (Other->isNullPointerConstant(S.getASTContext(), 9524 Expr::NPC_ValueDependentIsNotNull)) 9525 return; 9526 9527 // This should be kept in sync with warn_objc_literal_comparison. 9528 // LK_String should always be after the other literals, since it has its own 9529 // warning flag. 9530 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9531 assert(LiteralKind != Sema::LK_Block); 9532 if (LiteralKind == Sema::LK_None) { 9533 llvm_unreachable("Unknown Objective-C object literal kind"); 9534 } 9535 9536 if (LiteralKind == Sema::LK_String) 9537 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9538 << Literal->getSourceRange(); 9539 else 9540 S.Diag(Loc, diag::warn_objc_literal_comparison) 9541 << LiteralKind << Literal->getSourceRange(); 9542 9543 if (BinaryOperator::isEqualityOp(Opc) && 9544 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9545 SourceLocation Start = LHS.get()->getLocStart(); 9546 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9547 CharSourceRange OpRange = 9548 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9549 9550 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9551 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9552 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9553 << FixItHint::CreateInsertion(End, "]"); 9554 } 9555 } 9556 9557 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9558 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9559 ExprResult &RHS, SourceLocation Loc, 9560 BinaryOperatorKind Opc) { 9561 // Check that left hand side is !something. 9562 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9563 if (!UO || UO->getOpcode() != UO_LNot) return; 9564 9565 // Only check if the right hand side is non-bool arithmetic type. 9566 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9567 9568 // Make sure that the something in !something is not bool. 9569 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9570 if (SubExpr->isKnownToHaveBooleanValue()) return; 9571 9572 // Emit warning. 9573 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9574 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9575 << Loc << IsBitwiseOp; 9576 9577 // First note suggest !(x < y) 9578 SourceLocation FirstOpen = SubExpr->getLocStart(); 9579 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9580 FirstClose = S.getLocForEndOfToken(FirstClose); 9581 if (FirstClose.isInvalid()) 9582 FirstOpen = SourceLocation(); 9583 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9584 << IsBitwiseOp 9585 << FixItHint::CreateInsertion(FirstOpen, "(") 9586 << FixItHint::CreateInsertion(FirstClose, ")"); 9587 9588 // Second note suggests (!x) < y 9589 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9590 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9591 SecondClose = S.getLocForEndOfToken(SecondClose); 9592 if (SecondClose.isInvalid()) 9593 SecondOpen = SourceLocation(); 9594 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9595 << FixItHint::CreateInsertion(SecondOpen, "(") 9596 << FixItHint::CreateInsertion(SecondClose, ")"); 9597 } 9598 9599 // Get the decl for a simple expression: a reference to a variable, 9600 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9601 static ValueDecl *getCompareDecl(Expr *E) { 9602 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9603 return DR->getDecl(); 9604 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9605 if (Ivar->isFreeIvar()) 9606 return Ivar->getDecl(); 9607 } 9608 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9609 if (Mem->isImplicitAccess()) 9610 return Mem->getMemberDecl(); 9611 } 9612 return nullptr; 9613 } 9614 9615 /// Diagnose some forms of syntactically-obvious tautological comparison. 9616 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9617 Expr *LHS, Expr *RHS, 9618 BinaryOperatorKind Opc) { 9619 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9620 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9621 9622 QualType LHSType = LHS->getType(); 9623 QualType RHSType = RHS->getType(); 9624 if (LHSType->hasFloatingRepresentation() || 9625 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9626 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9627 S.inTemplateInstantiation()) 9628 return; 9629 9630 // Comparisons between two array types are ill-formed for operator<=>, so 9631 // we shouldn't emit any additional warnings about it. 9632 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9633 return; 9634 9635 // For non-floating point types, check for self-comparisons of the form 9636 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9637 // often indicate logic errors in the program. 9638 // 9639 // NOTE: Don't warn about comparison expressions resulting from macro 9640 // expansion. Also don't warn about comparisons which are only self 9641 // comparisons within a template instantiation. The warnings should catch 9642 // obvious cases in the definition of the template anyways. The idea is to 9643 // warn when the typed comparison operator will always evaluate to the same 9644 // result. 9645 ValueDecl *DL = getCompareDecl(LHSStripped); 9646 ValueDecl *DR = getCompareDecl(RHSStripped); 9647 if (DL && DR && declaresSameEntity(DL, DR)) { 9648 StringRef Result; 9649 switch (Opc) { 9650 case BO_EQ: case BO_LE: case BO_GE: 9651 Result = "true"; 9652 break; 9653 case BO_NE: case BO_LT: case BO_GT: 9654 Result = "false"; 9655 break; 9656 case BO_Cmp: 9657 Result = "'std::strong_ordering::equal'"; 9658 break; 9659 default: 9660 break; 9661 } 9662 S.DiagRuntimeBehavior(Loc, nullptr, 9663 S.PDiag(diag::warn_comparison_always) 9664 << 0 /*self-comparison*/ << !Result.empty() 9665 << Result); 9666 } else if (DL && DR && 9667 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9668 !DL->isWeak() && !DR->isWeak()) { 9669 // What is it always going to evaluate to? 9670 StringRef Result; 9671 switch(Opc) { 9672 case BO_EQ: // e.g. array1 == array2 9673 Result = "false"; 9674 break; 9675 case BO_NE: // e.g. array1 != array2 9676 Result = "true"; 9677 break; 9678 default: // e.g. array1 <= array2 9679 // The best we can say is 'a constant' 9680 break; 9681 } 9682 S.DiagRuntimeBehavior(Loc, nullptr, 9683 S.PDiag(diag::warn_comparison_always) 9684 << 1 /*array comparison*/ 9685 << !Result.empty() << Result); 9686 } 9687 9688 if (isa<CastExpr>(LHSStripped)) 9689 LHSStripped = LHSStripped->IgnoreParenCasts(); 9690 if (isa<CastExpr>(RHSStripped)) 9691 RHSStripped = RHSStripped->IgnoreParenCasts(); 9692 9693 // Warn about comparisons against a string constant (unless the other 9694 // operand is null); the user probably wants strcmp. 9695 Expr *LiteralString = nullptr; 9696 Expr *LiteralStringStripped = nullptr; 9697 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9698 !RHSStripped->isNullPointerConstant(S.Context, 9699 Expr::NPC_ValueDependentIsNull)) { 9700 LiteralString = LHS; 9701 LiteralStringStripped = LHSStripped; 9702 } else if ((isa<StringLiteral>(RHSStripped) || 9703 isa<ObjCEncodeExpr>(RHSStripped)) && 9704 !LHSStripped->isNullPointerConstant(S.Context, 9705 Expr::NPC_ValueDependentIsNull)) { 9706 LiteralString = RHS; 9707 LiteralStringStripped = RHSStripped; 9708 } 9709 9710 if (LiteralString) { 9711 S.DiagRuntimeBehavior(Loc, nullptr, 9712 S.PDiag(diag::warn_stringcompare) 9713 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9714 << LiteralString->getSourceRange()); 9715 } 9716 } 9717 9718 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9719 switch (CK) { 9720 default: { 9721 #ifndef NDEBUG 9722 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9723 << "\n"; 9724 #endif 9725 llvm_unreachable("unhandled cast kind"); 9726 } 9727 case CK_UserDefinedConversion: 9728 return ICK_Identity; 9729 case CK_LValueToRValue: 9730 return ICK_Lvalue_To_Rvalue; 9731 case CK_ArrayToPointerDecay: 9732 return ICK_Array_To_Pointer; 9733 case CK_FunctionToPointerDecay: 9734 return ICK_Function_To_Pointer; 9735 case CK_IntegralCast: 9736 return ICK_Integral_Conversion; 9737 case CK_FloatingCast: 9738 return ICK_Floating_Conversion; 9739 case CK_IntegralToFloating: 9740 case CK_FloatingToIntegral: 9741 return ICK_Floating_Integral; 9742 case CK_IntegralComplexCast: 9743 case CK_FloatingComplexCast: 9744 case CK_FloatingComplexToIntegralComplex: 9745 case CK_IntegralComplexToFloatingComplex: 9746 return ICK_Complex_Conversion; 9747 case CK_FloatingComplexToReal: 9748 case CK_FloatingRealToComplex: 9749 case CK_IntegralComplexToReal: 9750 case CK_IntegralRealToComplex: 9751 return ICK_Complex_Real; 9752 } 9753 } 9754 9755 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9756 QualType FromType, 9757 SourceLocation Loc) { 9758 // Check for a narrowing implicit conversion. 9759 StandardConversionSequence SCS; 9760 SCS.setAsIdentityConversion(); 9761 SCS.setToType(0, FromType); 9762 SCS.setToType(1, ToType); 9763 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9764 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9765 9766 APValue PreNarrowingValue; 9767 QualType PreNarrowingType; 9768 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9769 PreNarrowingType, 9770 /*IgnoreFloatToIntegralConversion*/ true)) { 9771 case NK_Dependent_Narrowing: 9772 // Implicit conversion to a narrower type, but the expression is 9773 // value-dependent so we can't tell whether it's actually narrowing. 9774 case NK_Not_Narrowing: 9775 return false; 9776 9777 case NK_Constant_Narrowing: 9778 // Implicit conversion to a narrower type, and the value is not a constant 9779 // expression. 9780 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing) 9781 << /*Constant*/ 1 9782 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9783 return true; 9784 9785 case NK_Variable_Narrowing: 9786 // Implicit conversion to a narrower type, and the value is not a constant 9787 // expression. 9788 case NK_Type_Narrowing: 9789 S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing) 9790 << /*Constant*/ 0 << FromType << ToType; 9791 // TODO: It's not a constant expression, but what if the user intended it 9792 // to be? Can we produce notes to help them figure out why it isn't? 9793 return true; 9794 } 9795 llvm_unreachable("unhandled case in switch"); 9796 } 9797 9798 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9799 ExprResult &LHS, 9800 ExprResult &RHS, 9801 SourceLocation Loc) { 9802 using CCT = ComparisonCategoryType; 9803 9804 QualType LHSType = LHS.get()->getType(); 9805 QualType RHSType = RHS.get()->getType(); 9806 // Dig out the original argument type and expression before implicit casts 9807 // were applied. These are the types/expressions we need to check the 9808 // [expr.spaceship] requirements against. 9809 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9810 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9811 QualType LHSStrippedType = LHSStripped.get()->getType(); 9812 QualType RHSStrippedType = RHSStripped.get()->getType(); 9813 9814 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9815 // other is not, the program is ill-formed. 9816 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9817 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9818 return QualType(); 9819 } 9820 9821 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9822 RHSStrippedType->isEnumeralType(); 9823 if (NumEnumArgs == 1) { 9824 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9825 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9826 if (OtherTy->hasFloatingRepresentation()) { 9827 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9828 return QualType(); 9829 } 9830 } 9831 if (NumEnumArgs == 2) { 9832 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9833 // type E, the operator yields the result of converting the operands 9834 // to the underlying type of E and applying <=> to the converted operands. 9835 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 9836 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9837 return QualType(); 9838 } 9839 QualType IntType = 9840 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 9841 assert(IntType->isArithmeticType()); 9842 9843 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 9844 // promote the boolean type, and all other promotable integer types, to 9845 // avoid this. 9846 if (IntType->isPromotableIntegerType()) 9847 IntType = S.Context.getPromotedIntegerType(IntType); 9848 9849 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 9850 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 9851 LHSType = RHSType = IntType; 9852 } 9853 9854 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 9855 // usual arithmetic conversions are applied to the operands. 9856 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9857 if (LHS.isInvalid() || RHS.isInvalid()) 9858 return QualType(); 9859 if (Type.isNull()) 9860 return S.InvalidOperands(Loc, LHS, RHS); 9861 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9862 9863 bool HasNarrowing = checkThreeWayNarrowingConversion( 9864 S, Type, LHS.get(), LHSType, LHS.get()->getLocStart()); 9865 HasNarrowing |= checkThreeWayNarrowingConversion( 9866 S, Type, RHS.get(), RHSType, RHS.get()->getLocStart()); 9867 if (HasNarrowing) 9868 return QualType(); 9869 9870 assert(!Type.isNull() && "composite type for <=> has not been set"); 9871 9872 auto TypeKind = [&]() { 9873 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 9874 if (CT->getElementType()->hasFloatingRepresentation()) 9875 return CCT::WeakEquality; 9876 return CCT::StrongEquality; 9877 } 9878 if (Type->isIntegralOrEnumerationType()) 9879 return CCT::StrongOrdering; 9880 if (Type->hasFloatingRepresentation()) 9881 return CCT::PartialOrdering; 9882 llvm_unreachable("other types are unimplemented"); 9883 }(); 9884 9885 return S.CheckComparisonCategoryType(TypeKind, Loc); 9886 } 9887 9888 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9889 ExprResult &RHS, 9890 SourceLocation Loc, 9891 BinaryOperatorKind Opc) { 9892 if (Opc == BO_Cmp) 9893 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 9894 9895 // C99 6.5.8p3 / C99 6.5.9p4 9896 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9897 if (LHS.isInvalid() || RHS.isInvalid()) 9898 return QualType(); 9899 if (Type.isNull()) 9900 return S.InvalidOperands(Loc, LHS, RHS); 9901 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9902 9903 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9904 9905 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 9906 return S.InvalidOperands(Loc, LHS, RHS); 9907 9908 // Check for comparisons of floating point operands using != and ==. 9909 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 9910 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9911 9912 // The result of comparisons is 'bool' in C++, 'int' in C. 9913 return S.Context.getLogicalOperationType(); 9914 } 9915 9916 // C99 6.5.8, C++ [expr.rel] 9917 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9918 SourceLocation Loc, 9919 BinaryOperatorKind Opc) { 9920 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 9921 bool IsThreeWay = Opc == BO_Cmp; 9922 auto IsAnyPointerType = [](ExprResult E) { 9923 QualType Ty = E.get()->getType(); 9924 return Ty->isPointerType() || Ty->isMemberPointerType(); 9925 }; 9926 9927 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 9928 // type, array-to-pointer, ..., conversions are performed on both operands to 9929 // bring them to their composite type. 9930 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 9931 // any type-related checks. 9932 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 9933 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9934 if (LHS.isInvalid()) 9935 return QualType(); 9936 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9937 if (RHS.isInvalid()) 9938 return QualType(); 9939 } else { 9940 LHS = DefaultLvalueConversion(LHS.get()); 9941 if (LHS.isInvalid()) 9942 return QualType(); 9943 RHS = DefaultLvalueConversion(RHS.get()); 9944 if (RHS.isInvalid()) 9945 return QualType(); 9946 } 9947 9948 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9949 9950 // Handle vector comparisons separately. 9951 if (LHS.get()->getType()->isVectorType() || 9952 RHS.get()->getType()->isVectorType()) 9953 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 9954 9955 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9956 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 9957 9958 QualType LHSType = LHS.get()->getType(); 9959 QualType RHSType = RHS.get()->getType(); 9960 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 9961 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 9962 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 9963 9964 const Expr::NullPointerConstantKind LHSNullKind = 9965 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9966 const Expr::NullPointerConstantKind RHSNullKind = 9967 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9968 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9969 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9970 9971 auto computeResultTy = [&]() { 9972 if (Opc != BO_Cmp) 9973 return Context.getLogicalOperationType(); 9974 assert(getLangOpts().CPlusPlus); 9975 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 9976 9977 QualType CompositeTy = LHS.get()->getType(); 9978 assert(!CompositeTy->isReferenceType()); 9979 9980 auto buildResultTy = [&](ComparisonCategoryType Kind) { 9981 return CheckComparisonCategoryType(Kind, Loc); 9982 }; 9983 9984 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 9985 // pointer type, a pointer-to-member type, or std::nullptr_t, the 9986 // result is of type std::strong_equality 9987 if (CompositeTy->isFunctionPointerType() || 9988 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 9989 // FIXME: consider making the function pointer case produce 9990 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 9991 // and direction polls 9992 return buildResultTy(ComparisonCategoryType::StrongEquality); 9993 9994 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 9995 // pointer type, p <=> q is of type std::strong_ordering. 9996 if (CompositeTy->isPointerType()) { 9997 // P0946R0: Comparisons between a null pointer constant and an object 9998 // pointer result in std::strong_equality 9999 if (LHSIsNull != RHSIsNull) 10000 return buildResultTy(ComparisonCategoryType::StrongEquality); 10001 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10002 } 10003 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10004 // TODO: Extend support for operator<=> to ObjC types. 10005 return InvalidOperands(Loc, LHS, RHS); 10006 }; 10007 10008 10009 if (!IsRelational && LHSIsNull != RHSIsNull) { 10010 bool IsEquality = Opc == BO_EQ; 10011 if (RHSIsNull) 10012 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10013 RHS.get()->getSourceRange()); 10014 else 10015 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10016 LHS.get()->getSourceRange()); 10017 } 10018 10019 if ((LHSType->isIntegerType() && !LHSIsNull) || 10020 (RHSType->isIntegerType() && !RHSIsNull)) { 10021 // Skip normal pointer conversion checks in this case; we have better 10022 // diagnostics for this below. 10023 } else if (getLangOpts().CPlusPlus) { 10024 // Equality comparison of a function pointer to a void pointer is invalid, 10025 // but we allow it as an extension. 10026 // FIXME: If we really want to allow this, should it be part of composite 10027 // pointer type computation so it works in conditionals too? 10028 if (!IsRelational && 10029 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10030 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10031 // This is a gcc extension compatibility comparison. 10032 // In a SFINAE context, we treat this as a hard error to maintain 10033 // conformance with the C++ standard. 10034 diagnoseFunctionPointerToVoidComparison( 10035 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10036 10037 if (isSFINAEContext()) 10038 return QualType(); 10039 10040 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10041 return computeResultTy(); 10042 } 10043 10044 // C++ [expr.eq]p2: 10045 // If at least one operand is a pointer [...] bring them to their 10046 // composite pointer type. 10047 // C++ [expr.spaceship]p6 10048 // If at least one of the operands is of pointer type, [...] bring them 10049 // to their composite pointer type. 10050 // C++ [expr.rel]p2: 10051 // If both operands are pointers, [...] bring them to their composite 10052 // pointer type. 10053 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10054 (IsRelational ? 2 : 1) && 10055 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10056 RHSType->isObjCObjectPointerType()))) { 10057 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10058 return QualType(); 10059 return computeResultTy(); 10060 } 10061 } else if (LHSType->isPointerType() && 10062 RHSType->isPointerType()) { // C99 6.5.8p2 10063 // All of the following pointer-related warnings are GCC extensions, except 10064 // when handling null pointer constants. 10065 QualType LCanPointeeTy = 10066 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10067 QualType RCanPointeeTy = 10068 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10069 10070 // C99 6.5.9p2 and C99 6.5.8p2 10071 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10072 RCanPointeeTy.getUnqualifiedType())) { 10073 // Valid unless a relational comparison of function pointers 10074 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10075 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10076 << LHSType << RHSType << LHS.get()->getSourceRange() 10077 << RHS.get()->getSourceRange(); 10078 } 10079 } else if (!IsRelational && 10080 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10081 // Valid unless comparison between non-null pointer and function pointer 10082 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10083 && !LHSIsNull && !RHSIsNull) 10084 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10085 /*isError*/false); 10086 } else { 10087 // Invalid 10088 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10089 } 10090 if (LCanPointeeTy != RCanPointeeTy) { 10091 // Treat NULL constant as a special case in OpenCL. 10092 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10093 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10094 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10095 Diag(Loc, 10096 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10097 << LHSType << RHSType << 0 /* comparison */ 10098 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10099 } 10100 } 10101 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10102 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10103 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10104 : CK_BitCast; 10105 if (LHSIsNull && !RHSIsNull) 10106 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10107 else 10108 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10109 } 10110 return computeResultTy(); 10111 } 10112 10113 if (getLangOpts().CPlusPlus) { 10114 // C++ [expr.eq]p4: 10115 // Two operands of type std::nullptr_t or one operand of type 10116 // std::nullptr_t and the other a null pointer constant compare equal. 10117 if (!IsRelational && LHSIsNull && RHSIsNull) { 10118 if (LHSType->isNullPtrType()) { 10119 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10120 return computeResultTy(); 10121 } 10122 if (RHSType->isNullPtrType()) { 10123 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10124 return computeResultTy(); 10125 } 10126 } 10127 10128 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10129 // These aren't covered by the composite pointer type rules. 10130 if (!IsRelational && RHSType->isNullPtrType() && 10131 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10132 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10133 return computeResultTy(); 10134 } 10135 if (!IsRelational && LHSType->isNullPtrType() && 10136 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10137 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10138 return computeResultTy(); 10139 } 10140 10141 if (IsRelational && 10142 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10143 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10144 // HACK: Relational comparison of nullptr_t against a pointer type is 10145 // invalid per DR583, but we allow it within std::less<> and friends, 10146 // since otherwise common uses of it break. 10147 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10148 // friends to have std::nullptr_t overload candidates. 10149 DeclContext *DC = CurContext; 10150 if (isa<FunctionDecl>(DC)) 10151 DC = DC->getParent(); 10152 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10153 if (CTSD->isInStdNamespace() && 10154 llvm::StringSwitch<bool>(CTSD->getName()) 10155 .Cases("less", "less_equal", "greater", "greater_equal", true) 10156 .Default(false)) { 10157 if (RHSType->isNullPtrType()) 10158 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10159 else 10160 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10161 return computeResultTy(); 10162 } 10163 } 10164 } 10165 10166 // C++ [expr.eq]p2: 10167 // If at least one operand is a pointer to member, [...] bring them to 10168 // their composite pointer type. 10169 if (!IsRelational && 10170 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10171 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10172 return QualType(); 10173 else 10174 return computeResultTy(); 10175 } 10176 } 10177 10178 // Handle block pointer types. 10179 if (!IsRelational && LHSType->isBlockPointerType() && 10180 RHSType->isBlockPointerType()) { 10181 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10182 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10183 10184 if (!LHSIsNull && !RHSIsNull && 10185 !Context.typesAreCompatible(lpointee, rpointee)) { 10186 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10187 << LHSType << RHSType << LHS.get()->getSourceRange() 10188 << RHS.get()->getSourceRange(); 10189 } 10190 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10191 return computeResultTy(); 10192 } 10193 10194 // Allow block pointers to be compared with null pointer constants. 10195 if (!IsRelational 10196 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10197 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10198 if (!LHSIsNull && !RHSIsNull) { 10199 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10200 ->getPointeeType()->isVoidType()) 10201 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10202 ->getPointeeType()->isVoidType()))) 10203 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10204 << LHSType << RHSType << LHS.get()->getSourceRange() 10205 << RHS.get()->getSourceRange(); 10206 } 10207 if (LHSIsNull && !RHSIsNull) 10208 LHS = ImpCastExprToType(LHS.get(), RHSType, 10209 RHSType->isPointerType() ? CK_BitCast 10210 : CK_AnyPointerToBlockPointerCast); 10211 else 10212 RHS = ImpCastExprToType(RHS.get(), LHSType, 10213 LHSType->isPointerType() ? CK_BitCast 10214 : CK_AnyPointerToBlockPointerCast); 10215 return computeResultTy(); 10216 } 10217 10218 if (LHSType->isObjCObjectPointerType() || 10219 RHSType->isObjCObjectPointerType()) { 10220 const PointerType *LPT = LHSType->getAs<PointerType>(); 10221 const PointerType *RPT = RHSType->getAs<PointerType>(); 10222 if (LPT || RPT) { 10223 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10224 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10225 10226 if (!LPtrToVoid && !RPtrToVoid && 10227 !Context.typesAreCompatible(LHSType, RHSType)) { 10228 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10229 /*isError*/false); 10230 } 10231 if (LHSIsNull && !RHSIsNull) { 10232 Expr *E = LHS.get(); 10233 if (getLangOpts().ObjCAutoRefCount) 10234 CheckObjCConversion(SourceRange(), RHSType, E, 10235 CCK_ImplicitConversion); 10236 LHS = ImpCastExprToType(E, RHSType, 10237 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10238 } 10239 else { 10240 Expr *E = RHS.get(); 10241 if (getLangOpts().ObjCAutoRefCount) 10242 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10243 /*Diagnose=*/true, 10244 /*DiagnoseCFAudited=*/false, Opc); 10245 RHS = ImpCastExprToType(E, LHSType, 10246 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10247 } 10248 return computeResultTy(); 10249 } 10250 if (LHSType->isObjCObjectPointerType() && 10251 RHSType->isObjCObjectPointerType()) { 10252 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10253 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10254 /*isError*/false); 10255 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10256 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10257 10258 if (LHSIsNull && !RHSIsNull) 10259 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10260 else 10261 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10262 return computeResultTy(); 10263 } 10264 10265 if (!IsRelational && LHSType->isBlockPointerType() && 10266 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10267 LHS = ImpCastExprToType(LHS.get(), RHSType, 10268 CK_BlockPointerToObjCPointerCast); 10269 return computeResultTy(); 10270 } else if (!IsRelational && 10271 LHSType->isBlockCompatibleObjCPointerType(Context) && 10272 RHSType->isBlockPointerType()) { 10273 RHS = ImpCastExprToType(RHS.get(), LHSType, 10274 CK_BlockPointerToObjCPointerCast); 10275 return computeResultTy(); 10276 } 10277 } 10278 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10279 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10280 unsigned DiagID = 0; 10281 bool isError = false; 10282 if (LangOpts.DebuggerSupport) { 10283 // Under a debugger, allow the comparison of pointers to integers, 10284 // since users tend to want to compare addresses. 10285 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10286 (RHSIsNull && RHSType->isIntegerType())) { 10287 if (IsRelational) { 10288 isError = getLangOpts().CPlusPlus; 10289 DiagID = 10290 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10291 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10292 } 10293 } else if (getLangOpts().CPlusPlus) { 10294 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10295 isError = true; 10296 } else if (IsRelational) 10297 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10298 else 10299 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10300 10301 if (DiagID) { 10302 Diag(Loc, DiagID) 10303 << LHSType << RHSType << LHS.get()->getSourceRange() 10304 << RHS.get()->getSourceRange(); 10305 if (isError) 10306 return QualType(); 10307 } 10308 10309 if (LHSType->isIntegerType()) 10310 LHS = ImpCastExprToType(LHS.get(), RHSType, 10311 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10312 else 10313 RHS = ImpCastExprToType(RHS.get(), LHSType, 10314 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10315 return computeResultTy(); 10316 } 10317 10318 // Handle block pointers. 10319 if (!IsRelational && RHSIsNull 10320 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10321 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10322 return computeResultTy(); 10323 } 10324 if (!IsRelational && LHSIsNull 10325 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10326 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10327 return computeResultTy(); 10328 } 10329 10330 if (getLangOpts().OpenCLVersion >= 200) { 10331 if (LHSIsNull && RHSType->isQueueT()) { 10332 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10333 return computeResultTy(); 10334 } 10335 10336 if (LHSType->isQueueT() && RHSIsNull) { 10337 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10338 return computeResultTy(); 10339 } 10340 } 10341 10342 return InvalidOperands(Loc, LHS, RHS); 10343 } 10344 10345 // Return a signed ext_vector_type that is of identical size and number of 10346 // elements. For floating point vectors, return an integer type of identical 10347 // size and number of elements. In the non ext_vector_type case, search from 10348 // the largest type to the smallest type to avoid cases where long long == long, 10349 // where long gets picked over long long. 10350 QualType Sema::GetSignedVectorType(QualType V) { 10351 const VectorType *VTy = V->getAs<VectorType>(); 10352 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10353 10354 if (isa<ExtVectorType>(VTy)) { 10355 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10356 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10357 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10358 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10359 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10360 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10361 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10362 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10363 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10364 "Unhandled vector element size in vector compare"); 10365 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10366 } 10367 10368 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10369 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10370 VectorType::GenericVector); 10371 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10372 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10373 VectorType::GenericVector); 10374 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10375 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10376 VectorType::GenericVector); 10377 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10378 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10379 VectorType::GenericVector); 10380 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10381 "Unhandled vector element size in vector compare"); 10382 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10383 VectorType::GenericVector); 10384 } 10385 10386 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10387 /// operates on extended vector types. Instead of producing an IntTy result, 10388 /// like a scalar comparison, a vector comparison produces a vector of integer 10389 /// types. 10390 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10391 SourceLocation Loc, 10392 BinaryOperatorKind Opc) { 10393 // Check to make sure we're operating on vectors of the same type and width, 10394 // Allowing one side to be a scalar of element type. 10395 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10396 /*AllowBothBool*/true, 10397 /*AllowBoolConversions*/getLangOpts().ZVector); 10398 if (vType.isNull()) 10399 return vType; 10400 10401 QualType LHSType = LHS.get()->getType(); 10402 10403 // If AltiVec, the comparison results in a numeric type, i.e. 10404 // bool for C++, int for C 10405 if (getLangOpts().AltiVec && 10406 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10407 return Context.getLogicalOperationType(); 10408 10409 // For non-floating point types, check for self-comparisons of the form 10410 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10411 // often indicate logic errors in the program. 10412 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10413 10414 // Check for comparisons of floating point operands using != and ==. 10415 if (BinaryOperator::isEqualityOp(Opc) && 10416 LHSType->hasFloatingRepresentation()) { 10417 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10418 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10419 } 10420 10421 // Return a signed type for the vector. 10422 return GetSignedVectorType(vType); 10423 } 10424 10425 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10426 SourceLocation Loc) { 10427 // Ensure that either both operands are of the same vector type, or 10428 // one operand is of a vector type and the other is of its element type. 10429 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10430 /*AllowBothBool*/true, 10431 /*AllowBoolConversions*/false); 10432 if (vType.isNull()) 10433 return InvalidOperands(Loc, LHS, RHS); 10434 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10435 vType->hasFloatingRepresentation()) 10436 return InvalidOperands(Loc, LHS, RHS); 10437 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10438 // usage of the logical operators && and || with vectors in C. This 10439 // check could be notionally dropped. 10440 if (!getLangOpts().CPlusPlus && 10441 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10442 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10443 10444 return GetSignedVectorType(LHS.get()->getType()); 10445 } 10446 10447 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10448 SourceLocation Loc, 10449 BinaryOperatorKind Opc) { 10450 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10451 10452 bool IsCompAssign = 10453 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10454 10455 if (LHS.get()->getType()->isVectorType() || 10456 RHS.get()->getType()->isVectorType()) { 10457 if (LHS.get()->getType()->hasIntegerRepresentation() && 10458 RHS.get()->getType()->hasIntegerRepresentation()) 10459 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10460 /*AllowBothBool*/true, 10461 /*AllowBoolConversions*/getLangOpts().ZVector); 10462 return InvalidOperands(Loc, LHS, RHS); 10463 } 10464 10465 if (Opc == BO_And) 10466 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10467 10468 ExprResult LHSResult = LHS, RHSResult = RHS; 10469 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10470 IsCompAssign); 10471 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10472 return QualType(); 10473 LHS = LHSResult.get(); 10474 RHS = RHSResult.get(); 10475 10476 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10477 return compType; 10478 return InvalidOperands(Loc, LHS, RHS); 10479 } 10480 10481 // C99 6.5.[13,14] 10482 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10483 SourceLocation Loc, 10484 BinaryOperatorKind Opc) { 10485 // Check vector operands differently. 10486 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10487 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10488 10489 // Diagnose cases where the user write a logical and/or but probably meant a 10490 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10491 // is a constant. 10492 if (LHS.get()->getType()->isIntegerType() && 10493 !LHS.get()->getType()->isBooleanType() && 10494 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10495 // Don't warn in macros or template instantiations. 10496 !Loc.isMacroID() && !inTemplateInstantiation()) { 10497 // If the RHS can be constant folded, and if it constant folds to something 10498 // that isn't 0 or 1 (which indicate a potential logical operation that 10499 // happened to fold to true/false) then warn. 10500 // Parens on the RHS are ignored. 10501 llvm::APSInt Result; 10502 if (RHS.get()->EvaluateAsInt(Result, Context)) 10503 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10504 !RHS.get()->getExprLoc().isMacroID()) || 10505 (Result != 0 && Result != 1)) { 10506 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10507 << RHS.get()->getSourceRange() 10508 << (Opc == BO_LAnd ? "&&" : "||"); 10509 // Suggest replacing the logical operator with the bitwise version 10510 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10511 << (Opc == BO_LAnd ? "&" : "|") 10512 << FixItHint::CreateReplacement(SourceRange( 10513 Loc, getLocForEndOfToken(Loc)), 10514 Opc == BO_LAnd ? "&" : "|"); 10515 if (Opc == BO_LAnd) 10516 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10517 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10518 << FixItHint::CreateRemoval( 10519 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10520 RHS.get()->getLocEnd())); 10521 } 10522 } 10523 10524 if (!Context.getLangOpts().CPlusPlus) { 10525 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10526 // not operate on the built-in scalar and vector float types. 10527 if (Context.getLangOpts().OpenCL && 10528 Context.getLangOpts().OpenCLVersion < 120) { 10529 if (LHS.get()->getType()->isFloatingType() || 10530 RHS.get()->getType()->isFloatingType()) 10531 return InvalidOperands(Loc, LHS, RHS); 10532 } 10533 10534 LHS = UsualUnaryConversions(LHS.get()); 10535 if (LHS.isInvalid()) 10536 return QualType(); 10537 10538 RHS = UsualUnaryConversions(RHS.get()); 10539 if (RHS.isInvalid()) 10540 return QualType(); 10541 10542 if (!LHS.get()->getType()->isScalarType() || 10543 !RHS.get()->getType()->isScalarType()) 10544 return InvalidOperands(Loc, LHS, RHS); 10545 10546 return Context.IntTy; 10547 } 10548 10549 // The following is safe because we only use this method for 10550 // non-overloadable operands. 10551 10552 // C++ [expr.log.and]p1 10553 // C++ [expr.log.or]p1 10554 // The operands are both contextually converted to type bool. 10555 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10556 if (LHSRes.isInvalid()) 10557 return InvalidOperands(Loc, LHS, RHS); 10558 LHS = LHSRes; 10559 10560 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10561 if (RHSRes.isInvalid()) 10562 return InvalidOperands(Loc, LHS, RHS); 10563 RHS = RHSRes; 10564 10565 // C++ [expr.log.and]p2 10566 // C++ [expr.log.or]p2 10567 // The result is a bool. 10568 return Context.BoolTy; 10569 } 10570 10571 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10572 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10573 if (!ME) return false; 10574 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10575 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10576 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10577 if (!Base) return false; 10578 return Base->getMethodDecl() != nullptr; 10579 } 10580 10581 /// Is the given expression (which must be 'const') a reference to a 10582 /// variable which was originally non-const, but which has become 10583 /// 'const' due to being captured within a block? 10584 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10585 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10586 assert(E->isLValue() && E->getType().isConstQualified()); 10587 E = E->IgnoreParens(); 10588 10589 // Must be a reference to a declaration from an enclosing scope. 10590 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10591 if (!DRE) return NCCK_None; 10592 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10593 10594 // The declaration must be a variable which is not declared 'const'. 10595 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10596 if (!var) return NCCK_None; 10597 if (var->getType().isConstQualified()) return NCCK_None; 10598 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10599 10600 // Decide whether the first capture was for a block or a lambda. 10601 DeclContext *DC = S.CurContext, *Prev = nullptr; 10602 // Decide whether the first capture was for a block or a lambda. 10603 while (DC) { 10604 // For init-capture, it is possible that the variable belongs to the 10605 // template pattern of the current context. 10606 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10607 if (var->isInitCapture() && 10608 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10609 break; 10610 if (DC == var->getDeclContext()) 10611 break; 10612 Prev = DC; 10613 DC = DC->getParent(); 10614 } 10615 // Unless we have an init-capture, we've gone one step too far. 10616 if (!var->isInitCapture()) 10617 DC = Prev; 10618 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10619 } 10620 10621 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10622 Ty = Ty.getNonReferenceType(); 10623 if (IsDereference && Ty->isPointerType()) 10624 Ty = Ty->getPointeeType(); 10625 return !Ty.isConstQualified(); 10626 } 10627 10628 // Update err_typecheck_assign_const and note_typecheck_assign_const 10629 // when this enum is changed. 10630 enum { 10631 ConstFunction, 10632 ConstVariable, 10633 ConstMember, 10634 ConstMethod, 10635 NestedConstMember, 10636 ConstUnknown, // Keep as last element 10637 }; 10638 10639 /// Emit the "read-only variable not assignable" error and print notes to give 10640 /// more information about why the variable is not assignable, such as pointing 10641 /// to the declaration of a const variable, showing that a method is const, or 10642 /// that the function is returning a const reference. 10643 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10644 SourceLocation Loc) { 10645 SourceRange ExprRange = E->getSourceRange(); 10646 10647 // Only emit one error on the first const found. All other consts will emit 10648 // a note to the error. 10649 bool DiagnosticEmitted = false; 10650 10651 // Track if the current expression is the result of a dereference, and if the 10652 // next checked expression is the result of a dereference. 10653 bool IsDereference = false; 10654 bool NextIsDereference = false; 10655 10656 // Loop to process MemberExpr chains. 10657 while (true) { 10658 IsDereference = NextIsDereference; 10659 10660 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10661 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10662 NextIsDereference = ME->isArrow(); 10663 const ValueDecl *VD = ME->getMemberDecl(); 10664 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10665 // Mutable fields can be modified even if the class is const. 10666 if (Field->isMutable()) { 10667 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10668 break; 10669 } 10670 10671 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10672 if (!DiagnosticEmitted) { 10673 S.Diag(Loc, diag::err_typecheck_assign_const) 10674 << ExprRange << ConstMember << false /*static*/ << Field 10675 << Field->getType(); 10676 DiagnosticEmitted = true; 10677 } 10678 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10679 << ConstMember << false /*static*/ << Field << Field->getType() 10680 << Field->getSourceRange(); 10681 } 10682 E = ME->getBase(); 10683 continue; 10684 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10685 if (VDecl->getType().isConstQualified()) { 10686 if (!DiagnosticEmitted) { 10687 S.Diag(Loc, diag::err_typecheck_assign_const) 10688 << ExprRange << ConstMember << true /*static*/ << VDecl 10689 << VDecl->getType(); 10690 DiagnosticEmitted = true; 10691 } 10692 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10693 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10694 << VDecl->getSourceRange(); 10695 } 10696 // Static fields do not inherit constness from parents. 10697 break; 10698 } 10699 break; // End MemberExpr 10700 } else if (const ArraySubscriptExpr *ASE = 10701 dyn_cast<ArraySubscriptExpr>(E)) { 10702 E = ASE->getBase()->IgnoreParenImpCasts(); 10703 continue; 10704 } else if (const ExtVectorElementExpr *EVE = 10705 dyn_cast<ExtVectorElementExpr>(E)) { 10706 E = EVE->getBase()->IgnoreParenImpCasts(); 10707 continue; 10708 } 10709 break; 10710 } 10711 10712 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10713 // Function calls 10714 const FunctionDecl *FD = CE->getDirectCallee(); 10715 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10716 if (!DiagnosticEmitted) { 10717 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10718 << ConstFunction << FD; 10719 DiagnosticEmitted = true; 10720 } 10721 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10722 diag::note_typecheck_assign_const) 10723 << ConstFunction << FD << FD->getReturnType() 10724 << FD->getReturnTypeSourceRange(); 10725 } 10726 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10727 // Point to variable declaration. 10728 if (const ValueDecl *VD = DRE->getDecl()) { 10729 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10730 if (!DiagnosticEmitted) { 10731 S.Diag(Loc, diag::err_typecheck_assign_const) 10732 << ExprRange << ConstVariable << VD << VD->getType(); 10733 DiagnosticEmitted = true; 10734 } 10735 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10736 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10737 } 10738 } 10739 } else if (isa<CXXThisExpr>(E)) { 10740 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10741 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10742 if (MD->isConst()) { 10743 if (!DiagnosticEmitted) { 10744 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10745 << ConstMethod << MD; 10746 DiagnosticEmitted = true; 10747 } 10748 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10749 << ConstMethod << MD << MD->getSourceRange(); 10750 } 10751 } 10752 } 10753 } 10754 10755 if (DiagnosticEmitted) 10756 return; 10757 10758 // Can't determine a more specific message, so display the generic error. 10759 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10760 } 10761 10762 enum OriginalExprKind { 10763 OEK_Variable, 10764 OEK_Member, 10765 OEK_LValue 10766 }; 10767 10768 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10769 const RecordType *Ty, 10770 SourceLocation Loc, SourceRange Range, 10771 OriginalExprKind OEK, 10772 bool &DiagnosticEmitted, 10773 bool IsNested = false) { 10774 // We walk the record hierarchy breadth-first to ensure that we print 10775 // diagnostics in field nesting order. 10776 // First, check every field for constness. 10777 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10778 if (Field->getType().isConstQualified()) { 10779 if (!DiagnosticEmitted) { 10780 S.Diag(Loc, diag::err_typecheck_assign_const) 10781 << Range << NestedConstMember << OEK << VD 10782 << IsNested << Field; 10783 DiagnosticEmitted = true; 10784 } 10785 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10786 << NestedConstMember << IsNested << Field 10787 << Field->getType() << Field->getSourceRange(); 10788 } 10789 } 10790 // Then, recurse. 10791 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10792 QualType FTy = Field->getType(); 10793 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10794 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10795 OEK, DiagnosticEmitted, true); 10796 } 10797 } 10798 10799 /// Emit an error for the case where a record we are trying to assign to has a 10800 /// const-qualified field somewhere in its hierarchy. 10801 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10802 SourceLocation Loc) { 10803 QualType Ty = E->getType(); 10804 assert(Ty->isRecordType() && "lvalue was not record?"); 10805 SourceRange Range = E->getSourceRange(); 10806 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10807 bool DiagEmitted = false; 10808 10809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10810 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10811 Range, OEK_Member, DiagEmitted); 10812 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10813 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10814 Range, OEK_Variable, DiagEmitted); 10815 else 10816 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10817 Range, OEK_LValue, DiagEmitted); 10818 if (!DiagEmitted) 10819 DiagnoseConstAssignment(S, E, Loc); 10820 } 10821 10822 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10823 /// emit an error and return true. If so, return false. 10824 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10825 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10826 10827 S.CheckShadowingDeclModification(E, Loc); 10828 10829 SourceLocation OrigLoc = Loc; 10830 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10831 &Loc); 10832 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10833 IsLV = Expr::MLV_InvalidMessageExpression; 10834 if (IsLV == Expr::MLV_Valid) 10835 return false; 10836 10837 unsigned DiagID = 0; 10838 bool NeedType = false; 10839 switch (IsLV) { // C99 6.5.16p2 10840 case Expr::MLV_ConstQualified: 10841 // Use a specialized diagnostic when we're assigning to an object 10842 // from an enclosing function or block. 10843 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10844 if (NCCK == NCCK_Block) 10845 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10846 else 10847 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10848 break; 10849 } 10850 10851 // In ARC, use some specialized diagnostics for occasions where we 10852 // infer 'const'. These are always pseudo-strong variables. 10853 if (S.getLangOpts().ObjCAutoRefCount) { 10854 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10855 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10856 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10857 10858 // Use the normal diagnostic if it's pseudo-__strong but the 10859 // user actually wrote 'const'. 10860 if (var->isARCPseudoStrong() && 10861 (!var->getTypeSourceInfo() || 10862 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10863 // There are two pseudo-strong cases: 10864 // - self 10865 ObjCMethodDecl *method = S.getCurMethodDecl(); 10866 if (method && var == method->getSelfDecl()) 10867 DiagID = method->isClassMethod() 10868 ? diag::err_typecheck_arc_assign_self_class_method 10869 : diag::err_typecheck_arc_assign_self; 10870 10871 // - fast enumeration variables 10872 else 10873 DiagID = diag::err_typecheck_arr_assign_enumeration; 10874 10875 SourceRange Assign; 10876 if (Loc != OrigLoc) 10877 Assign = SourceRange(OrigLoc, OrigLoc); 10878 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10879 // We need to preserve the AST regardless, so migration tool 10880 // can do its job. 10881 return false; 10882 } 10883 } 10884 } 10885 10886 // If none of the special cases above are triggered, then this is a 10887 // simple const assignment. 10888 if (DiagID == 0) { 10889 DiagnoseConstAssignment(S, E, Loc); 10890 return true; 10891 } 10892 10893 break; 10894 case Expr::MLV_ConstAddrSpace: 10895 DiagnoseConstAssignment(S, E, Loc); 10896 return true; 10897 case Expr::MLV_ConstQualifiedField: 10898 DiagnoseRecursiveConstFields(S, E, Loc); 10899 return true; 10900 case Expr::MLV_ArrayType: 10901 case Expr::MLV_ArrayTemporary: 10902 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10903 NeedType = true; 10904 break; 10905 case Expr::MLV_NotObjectType: 10906 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10907 NeedType = true; 10908 break; 10909 case Expr::MLV_LValueCast: 10910 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10911 break; 10912 case Expr::MLV_Valid: 10913 llvm_unreachable("did not take early return for MLV_Valid"); 10914 case Expr::MLV_InvalidExpression: 10915 case Expr::MLV_MemberFunction: 10916 case Expr::MLV_ClassTemporary: 10917 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10918 break; 10919 case Expr::MLV_IncompleteType: 10920 case Expr::MLV_IncompleteVoidType: 10921 return S.RequireCompleteType(Loc, E->getType(), 10922 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10923 case Expr::MLV_DuplicateVectorComponents: 10924 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10925 break; 10926 case Expr::MLV_NoSetterProperty: 10927 llvm_unreachable("readonly properties should be processed differently"); 10928 case Expr::MLV_InvalidMessageExpression: 10929 DiagID = diag::err_readonly_message_assignment; 10930 break; 10931 case Expr::MLV_SubObjCPropertySetting: 10932 DiagID = diag::err_no_subobject_property_setting; 10933 break; 10934 } 10935 10936 SourceRange Assign; 10937 if (Loc != OrigLoc) 10938 Assign = SourceRange(OrigLoc, OrigLoc); 10939 if (NeedType) 10940 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10941 else 10942 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10943 return true; 10944 } 10945 10946 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10947 SourceLocation Loc, 10948 Sema &Sema) { 10949 if (Sema.inTemplateInstantiation()) 10950 return; 10951 if (Sema.isUnevaluatedContext()) 10952 return; 10953 if (Loc.isInvalid() || Loc.isMacroID()) 10954 return; 10955 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 10956 return; 10957 10958 // C / C++ fields 10959 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10960 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10961 if (ML && MR) { 10962 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 10963 return; 10964 const ValueDecl *LHSDecl = 10965 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 10966 const ValueDecl *RHSDecl = 10967 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 10968 if (LHSDecl != RHSDecl) 10969 return; 10970 if (LHSDecl->getType().isVolatileQualified()) 10971 return; 10972 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10973 if (RefTy->getPointeeType().isVolatileQualified()) 10974 return; 10975 10976 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10977 } 10978 10979 // Objective-C instance variables 10980 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10981 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10982 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10983 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10984 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10985 if (RL && RR && RL->getDecl() == RR->getDecl()) 10986 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10987 } 10988 } 10989 10990 // C99 6.5.16.1 10991 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10992 SourceLocation Loc, 10993 QualType CompoundType) { 10994 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10995 10996 // Verify that LHS is a modifiable lvalue, and emit error if not. 10997 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10998 return QualType(); 10999 11000 QualType LHSType = LHSExpr->getType(); 11001 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11002 CompoundType; 11003 // OpenCL v1.2 s6.1.1.1 p2: 11004 // The half data type can only be used to declare a pointer to a buffer that 11005 // contains half values 11006 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11007 LHSType->isHalfType()) { 11008 Diag(Loc, diag::err_opencl_half_load_store) << 1 11009 << LHSType.getUnqualifiedType(); 11010 return QualType(); 11011 } 11012 11013 AssignConvertType ConvTy; 11014 if (CompoundType.isNull()) { 11015 Expr *RHSCheck = RHS.get(); 11016 11017 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11018 11019 QualType LHSTy(LHSType); 11020 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11021 if (RHS.isInvalid()) 11022 return QualType(); 11023 // Special case of NSObject attributes on c-style pointer types. 11024 if (ConvTy == IncompatiblePointer && 11025 ((Context.isObjCNSObjectType(LHSType) && 11026 RHSType->isObjCObjectPointerType()) || 11027 (Context.isObjCNSObjectType(RHSType) && 11028 LHSType->isObjCObjectPointerType()))) 11029 ConvTy = Compatible; 11030 11031 if (ConvTy == Compatible && 11032 LHSType->isObjCObjectType()) 11033 Diag(Loc, diag::err_objc_object_assignment) 11034 << LHSType; 11035 11036 // If the RHS is a unary plus or minus, check to see if they = and + are 11037 // right next to each other. If so, the user may have typo'd "x =+ 4" 11038 // instead of "x += 4". 11039 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11040 RHSCheck = ICE->getSubExpr(); 11041 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11042 if ((UO->getOpcode() == UO_Plus || 11043 UO->getOpcode() == UO_Minus) && 11044 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11045 // Only if the two operators are exactly adjacent. 11046 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11047 // And there is a space or other character before the subexpr of the 11048 // unary +/-. We don't want to warn on "x=-1". 11049 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 11050 UO->getSubExpr()->getLocStart().isFileID()) { 11051 Diag(Loc, diag::warn_not_compound_assign) 11052 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11053 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11054 } 11055 } 11056 11057 if (ConvTy == Compatible) { 11058 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11059 // Warn about retain cycles where a block captures the LHS, but 11060 // not if the LHS is a simple variable into which the block is 11061 // being stored...unless that variable can be captured by reference! 11062 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11063 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11064 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11065 checkRetainCycles(LHSExpr, RHS.get()); 11066 } 11067 11068 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11069 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11070 // It is safe to assign a weak reference into a strong variable. 11071 // Although this code can still have problems: 11072 // id x = self.weakProp; 11073 // id y = self.weakProp; 11074 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11075 // paths through the function. This should be revisited if 11076 // -Wrepeated-use-of-weak is made flow-sensitive. 11077 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11078 // variable, which will be valid for the current autorelease scope. 11079 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11080 RHS.get()->getLocStart())) 11081 getCurFunction()->markSafeWeakUse(RHS.get()); 11082 11083 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11084 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11085 } 11086 } 11087 } else { 11088 // Compound assignment "x += y" 11089 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11090 } 11091 11092 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11093 RHS.get(), AA_Assigning)) 11094 return QualType(); 11095 11096 CheckForNullPointerDereference(*this, LHSExpr); 11097 11098 // C99 6.5.16p3: The type of an assignment expression is the type of the 11099 // left operand unless the left operand has qualified type, in which case 11100 // it is the unqualified version of the type of the left operand. 11101 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11102 // is converted to the type of the assignment expression (above). 11103 // C++ 5.17p1: the type of the assignment expression is that of its left 11104 // operand. 11105 return (getLangOpts().CPlusPlus 11106 ? LHSType : LHSType.getUnqualifiedType()); 11107 } 11108 11109 // Only ignore explicit casts to void. 11110 static bool IgnoreCommaOperand(const Expr *E) { 11111 E = E->IgnoreParens(); 11112 11113 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11114 if (CE->getCastKind() == CK_ToVoid) { 11115 return true; 11116 } 11117 } 11118 11119 return false; 11120 } 11121 11122 // Look for instances where it is likely the comma operator is confused with 11123 // another operator. There is a whitelist of acceptable expressions for the 11124 // left hand side of the comma operator, otherwise emit a warning. 11125 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11126 // No warnings in macros 11127 if (Loc.isMacroID()) 11128 return; 11129 11130 // Don't warn in template instantiations. 11131 if (inTemplateInstantiation()) 11132 return; 11133 11134 // Scope isn't fine-grained enough to whitelist the specific cases, so 11135 // instead, skip more than needed, then call back into here with the 11136 // CommaVisitor in SemaStmt.cpp. 11137 // The whitelisted locations are the initialization and increment portions 11138 // of a for loop. The additional checks are on the condition of 11139 // if statements, do/while loops, and for loops. 11140 const unsigned ForIncrementFlags = 11141 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 11142 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11143 const unsigned ScopeFlags = getCurScope()->getFlags(); 11144 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11145 (ScopeFlags & ForInitFlags) == ForInitFlags) 11146 return; 11147 11148 // If there are multiple comma operators used together, get the RHS of the 11149 // of the comma operator as the LHS. 11150 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11151 if (BO->getOpcode() != BO_Comma) 11152 break; 11153 LHS = BO->getRHS(); 11154 } 11155 11156 // Only allow some expressions on LHS to not warn. 11157 if (IgnoreCommaOperand(LHS)) 11158 return; 11159 11160 Diag(Loc, diag::warn_comma_operator); 11161 Diag(LHS->getLocStart(), diag::note_cast_to_void) 11162 << LHS->getSourceRange() 11163 << FixItHint::CreateInsertion(LHS->getLocStart(), 11164 LangOpts.CPlusPlus ? "static_cast<void>(" 11165 : "(void)(") 11166 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 11167 ")"); 11168 } 11169 11170 // C99 6.5.17 11171 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11172 SourceLocation Loc) { 11173 LHS = S.CheckPlaceholderExpr(LHS.get()); 11174 RHS = S.CheckPlaceholderExpr(RHS.get()); 11175 if (LHS.isInvalid() || RHS.isInvalid()) 11176 return QualType(); 11177 11178 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11179 // operands, but not unary promotions. 11180 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11181 11182 // So we treat the LHS as a ignored value, and in C++ we allow the 11183 // containing site to determine what should be done with the RHS. 11184 LHS = S.IgnoredValueConversions(LHS.get()); 11185 if (LHS.isInvalid()) 11186 return QualType(); 11187 11188 S.DiagnoseUnusedExprResult(LHS.get()); 11189 11190 if (!S.getLangOpts().CPlusPlus) { 11191 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11192 if (RHS.isInvalid()) 11193 return QualType(); 11194 if (!RHS.get()->getType()->isVoidType()) 11195 S.RequireCompleteType(Loc, RHS.get()->getType(), 11196 diag::err_incomplete_type); 11197 } 11198 11199 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11200 S.DiagnoseCommaOperator(LHS.get(), Loc); 11201 11202 return RHS.get()->getType(); 11203 } 11204 11205 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11206 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11207 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11208 ExprValueKind &VK, 11209 ExprObjectKind &OK, 11210 SourceLocation OpLoc, 11211 bool IsInc, bool IsPrefix) { 11212 if (Op->isTypeDependent()) 11213 return S.Context.DependentTy; 11214 11215 QualType ResType = Op->getType(); 11216 // Atomic types can be used for increment / decrement where the non-atomic 11217 // versions can, so ignore the _Atomic() specifier for the purpose of 11218 // checking. 11219 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11220 ResType = ResAtomicType->getValueType(); 11221 11222 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11223 11224 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11225 // Decrement of bool is not allowed. 11226 if (!IsInc) { 11227 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11228 return QualType(); 11229 } 11230 // Increment of bool sets it to true, but is deprecated. 11231 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11232 : diag::warn_increment_bool) 11233 << Op->getSourceRange(); 11234 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11235 // Error on enum increments and decrements in C++ mode 11236 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11237 return QualType(); 11238 } else if (ResType->isRealType()) { 11239 // OK! 11240 } else if (ResType->isPointerType()) { 11241 // C99 6.5.2.4p2, 6.5.6p2 11242 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11243 return QualType(); 11244 } else if (ResType->isObjCObjectPointerType()) { 11245 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11246 // Otherwise, we just need a complete type. 11247 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11248 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11249 return QualType(); 11250 } else if (ResType->isAnyComplexType()) { 11251 // C99 does not support ++/-- on complex types, we allow as an extension. 11252 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11253 << ResType << Op->getSourceRange(); 11254 } else if (ResType->isPlaceholderType()) { 11255 ExprResult PR = S.CheckPlaceholderExpr(Op); 11256 if (PR.isInvalid()) return QualType(); 11257 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11258 IsInc, IsPrefix); 11259 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11260 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11261 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11262 (ResType->getAs<VectorType>()->getVectorKind() != 11263 VectorType::AltiVecBool)) { 11264 // The z vector extensions allow ++ and -- for non-bool vectors. 11265 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11266 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11267 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11268 } else { 11269 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11270 << ResType << int(IsInc) << Op->getSourceRange(); 11271 return QualType(); 11272 } 11273 // At this point, we know we have a real, complex or pointer type. 11274 // Now make sure the operand is a modifiable lvalue. 11275 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11276 return QualType(); 11277 // In C++, a prefix increment is the same type as the operand. Otherwise 11278 // (in C or with postfix), the increment is the unqualified type of the 11279 // operand. 11280 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11281 VK = VK_LValue; 11282 OK = Op->getObjectKind(); 11283 return ResType; 11284 } else { 11285 VK = VK_RValue; 11286 return ResType.getUnqualifiedType(); 11287 } 11288 } 11289 11290 11291 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11292 /// This routine allows us to typecheck complex/recursive expressions 11293 /// where the declaration is needed for type checking. We only need to 11294 /// handle cases when the expression references a function designator 11295 /// or is an lvalue. Here are some examples: 11296 /// - &(x) => x 11297 /// - &*****f => f for f a function designator. 11298 /// - &s.xx => s 11299 /// - &s.zz[1].yy -> s, if zz is an array 11300 /// - *(x + 1) -> x, if x is an array 11301 /// - &"123"[2] -> 0 11302 /// - & __real__ x -> x 11303 static ValueDecl *getPrimaryDecl(Expr *E) { 11304 switch (E->getStmtClass()) { 11305 case Stmt::DeclRefExprClass: 11306 return cast<DeclRefExpr>(E)->getDecl(); 11307 case Stmt::MemberExprClass: 11308 // If this is an arrow operator, the address is an offset from 11309 // the base's value, so the object the base refers to is 11310 // irrelevant. 11311 if (cast<MemberExpr>(E)->isArrow()) 11312 return nullptr; 11313 // Otherwise, the expression refers to a part of the base 11314 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11315 case Stmt::ArraySubscriptExprClass: { 11316 // FIXME: This code shouldn't be necessary! We should catch the implicit 11317 // promotion of register arrays earlier. 11318 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11320 if (ICE->getSubExpr()->getType()->isArrayType()) 11321 return getPrimaryDecl(ICE->getSubExpr()); 11322 } 11323 return nullptr; 11324 } 11325 case Stmt::UnaryOperatorClass: { 11326 UnaryOperator *UO = cast<UnaryOperator>(E); 11327 11328 switch(UO->getOpcode()) { 11329 case UO_Real: 11330 case UO_Imag: 11331 case UO_Extension: 11332 return getPrimaryDecl(UO->getSubExpr()); 11333 default: 11334 return nullptr; 11335 } 11336 } 11337 case Stmt::ParenExprClass: 11338 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11339 case Stmt::ImplicitCastExprClass: 11340 // If the result of an implicit cast is an l-value, we care about 11341 // the sub-expression; otherwise, the result here doesn't matter. 11342 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11343 default: 11344 return nullptr; 11345 } 11346 } 11347 11348 namespace { 11349 enum { 11350 AO_Bit_Field = 0, 11351 AO_Vector_Element = 1, 11352 AO_Property_Expansion = 2, 11353 AO_Register_Variable = 3, 11354 AO_No_Error = 4 11355 }; 11356 } 11357 /// \brief Diagnose invalid operand for address of operations. 11358 /// 11359 /// \param Type The type of operand which cannot have its address taken. 11360 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11361 Expr *E, unsigned Type) { 11362 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11363 } 11364 11365 /// CheckAddressOfOperand - The operand of & must be either a function 11366 /// designator or an lvalue designating an object. If it is an lvalue, the 11367 /// object cannot be declared with storage class register or be a bit field. 11368 /// Note: The usual conversions are *not* applied to the operand of the & 11369 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11370 /// In C++, the operand might be an overloaded function name, in which case 11371 /// we allow the '&' but retain the overloaded-function type. 11372 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11373 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11374 if (PTy->getKind() == BuiltinType::Overload) { 11375 Expr *E = OrigOp.get()->IgnoreParens(); 11376 if (!isa<OverloadExpr>(E)) { 11377 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11378 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11379 << OrigOp.get()->getSourceRange(); 11380 return QualType(); 11381 } 11382 11383 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11384 if (isa<UnresolvedMemberExpr>(Ovl)) 11385 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11386 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11387 << OrigOp.get()->getSourceRange(); 11388 return QualType(); 11389 } 11390 11391 return Context.OverloadTy; 11392 } 11393 11394 if (PTy->getKind() == BuiltinType::UnknownAny) 11395 return Context.UnknownAnyTy; 11396 11397 if (PTy->getKind() == BuiltinType::BoundMember) { 11398 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11399 << OrigOp.get()->getSourceRange(); 11400 return QualType(); 11401 } 11402 11403 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11404 if (OrigOp.isInvalid()) return QualType(); 11405 } 11406 11407 if (OrigOp.get()->isTypeDependent()) 11408 return Context.DependentTy; 11409 11410 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11411 11412 // Make sure to ignore parentheses in subsequent checks 11413 Expr *op = OrigOp.get()->IgnoreParens(); 11414 11415 // In OpenCL captures for blocks called as lambda functions 11416 // are located in the private address space. Blocks used in 11417 // enqueue_kernel can be located in a different address space 11418 // depending on a vendor implementation. Thus preventing 11419 // taking an address of the capture to avoid invalid AS casts. 11420 if (LangOpts.OpenCL) { 11421 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11422 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11423 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11424 return QualType(); 11425 } 11426 } 11427 11428 if (getLangOpts().C99) { 11429 // Implement C99-only parts of addressof rules. 11430 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11431 if (uOp->getOpcode() == UO_Deref) 11432 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11433 // (assuming the deref expression is valid). 11434 return uOp->getSubExpr()->getType(); 11435 } 11436 // Technically, there should be a check for array subscript 11437 // expressions here, but the result of one is always an lvalue anyway. 11438 } 11439 ValueDecl *dcl = getPrimaryDecl(op); 11440 11441 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11442 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11443 op->getLocStart())) 11444 return QualType(); 11445 11446 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11447 unsigned AddressOfError = AO_No_Error; 11448 11449 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11450 bool sfinae = (bool)isSFINAEContext(); 11451 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11452 : diag::ext_typecheck_addrof_temporary) 11453 << op->getType() << op->getSourceRange(); 11454 if (sfinae) 11455 return QualType(); 11456 // Materialize the temporary as an lvalue so that we can take its address. 11457 OrigOp = op = 11458 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11459 } else if (isa<ObjCSelectorExpr>(op)) { 11460 return Context.getPointerType(op->getType()); 11461 } else if (lval == Expr::LV_MemberFunction) { 11462 // If it's an instance method, make a member pointer. 11463 // The expression must have exactly the form &A::foo. 11464 11465 // If the underlying expression isn't a decl ref, give up. 11466 if (!isa<DeclRefExpr>(op)) { 11467 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11468 << OrigOp.get()->getSourceRange(); 11469 return QualType(); 11470 } 11471 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11472 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11473 11474 // The id-expression was parenthesized. 11475 if (OrigOp.get() != DRE) { 11476 Diag(OpLoc, diag::err_parens_pointer_member_function) 11477 << OrigOp.get()->getSourceRange(); 11478 11479 // The method was named without a qualifier. 11480 } else if (!DRE->getQualifier()) { 11481 if (MD->getParent()->getName().empty()) 11482 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11483 << op->getSourceRange(); 11484 else { 11485 SmallString<32> Str; 11486 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11487 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11488 << op->getSourceRange() 11489 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11490 } 11491 } 11492 11493 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11494 if (isa<CXXDestructorDecl>(MD)) 11495 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11496 11497 QualType MPTy = Context.getMemberPointerType( 11498 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11499 // Under the MS ABI, lock down the inheritance model now. 11500 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11501 (void)isCompleteType(OpLoc, MPTy); 11502 return MPTy; 11503 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11504 // C99 6.5.3.2p1 11505 // The operand must be either an l-value or a function designator 11506 if (!op->getType()->isFunctionType()) { 11507 // Use a special diagnostic for loads from property references. 11508 if (isa<PseudoObjectExpr>(op)) { 11509 AddressOfError = AO_Property_Expansion; 11510 } else { 11511 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11512 << op->getType() << op->getSourceRange(); 11513 return QualType(); 11514 } 11515 } 11516 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11517 // The operand cannot be a bit-field 11518 AddressOfError = AO_Bit_Field; 11519 } else if (op->getObjectKind() == OK_VectorComponent) { 11520 // The operand cannot be an element of a vector 11521 AddressOfError = AO_Vector_Element; 11522 } else if (dcl) { // C99 6.5.3.2p1 11523 // We have an lvalue with a decl. Make sure the decl is not declared 11524 // with the register storage-class specifier. 11525 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11526 // in C++ it is not error to take address of a register 11527 // variable (c++03 7.1.1P3) 11528 if (vd->getStorageClass() == SC_Register && 11529 !getLangOpts().CPlusPlus) { 11530 AddressOfError = AO_Register_Variable; 11531 } 11532 } else if (isa<MSPropertyDecl>(dcl)) { 11533 AddressOfError = AO_Property_Expansion; 11534 } else if (isa<FunctionTemplateDecl>(dcl)) { 11535 return Context.OverloadTy; 11536 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11537 // Okay: we can take the address of a field. 11538 // Could be a pointer to member, though, if there is an explicit 11539 // scope qualifier for the class. 11540 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11541 DeclContext *Ctx = dcl->getDeclContext(); 11542 if (Ctx && Ctx->isRecord()) { 11543 if (dcl->getType()->isReferenceType()) { 11544 Diag(OpLoc, 11545 diag::err_cannot_form_pointer_to_member_of_reference_type) 11546 << dcl->getDeclName() << dcl->getType(); 11547 return QualType(); 11548 } 11549 11550 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11551 Ctx = Ctx->getParent(); 11552 11553 QualType MPTy = Context.getMemberPointerType( 11554 op->getType(), 11555 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11556 // Under the MS ABI, lock down the inheritance model now. 11557 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11558 (void)isCompleteType(OpLoc, MPTy); 11559 return MPTy; 11560 } 11561 } 11562 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11563 !isa<BindingDecl>(dcl)) 11564 llvm_unreachable("Unknown/unexpected decl type"); 11565 } 11566 11567 if (AddressOfError != AO_No_Error) { 11568 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11569 return QualType(); 11570 } 11571 11572 if (lval == Expr::LV_IncompleteVoidType) { 11573 // Taking the address of a void variable is technically illegal, but we 11574 // allow it in cases which are otherwise valid. 11575 // Example: "extern void x; void* y = &x;". 11576 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11577 } 11578 11579 // If the operand has type "type", the result has type "pointer to type". 11580 if (op->getType()->isObjCObjectType()) 11581 return Context.getObjCObjectPointerType(op->getType()); 11582 11583 CheckAddressOfPackedMember(op); 11584 11585 return Context.getPointerType(op->getType()); 11586 } 11587 11588 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11589 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11590 if (!DRE) 11591 return; 11592 const Decl *D = DRE->getDecl(); 11593 if (!D) 11594 return; 11595 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11596 if (!Param) 11597 return; 11598 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11599 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11600 return; 11601 if (FunctionScopeInfo *FD = S.getCurFunction()) 11602 if (!FD->ModifiedNonNullParams.count(Param)) 11603 FD->ModifiedNonNullParams.insert(Param); 11604 } 11605 11606 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11607 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11608 SourceLocation OpLoc) { 11609 if (Op->isTypeDependent()) 11610 return S.Context.DependentTy; 11611 11612 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11613 if (ConvResult.isInvalid()) 11614 return QualType(); 11615 Op = ConvResult.get(); 11616 QualType OpTy = Op->getType(); 11617 QualType Result; 11618 11619 if (isa<CXXReinterpretCastExpr>(Op)) { 11620 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11621 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11622 Op->getSourceRange()); 11623 } 11624 11625 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11626 { 11627 Result = PT->getPointeeType(); 11628 } 11629 else if (const ObjCObjectPointerType *OPT = 11630 OpTy->getAs<ObjCObjectPointerType>()) 11631 Result = OPT->getPointeeType(); 11632 else { 11633 ExprResult PR = S.CheckPlaceholderExpr(Op); 11634 if (PR.isInvalid()) return QualType(); 11635 if (PR.get() != Op) 11636 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11637 } 11638 11639 if (Result.isNull()) { 11640 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11641 << OpTy << Op->getSourceRange(); 11642 return QualType(); 11643 } 11644 11645 // Note that per both C89 and C99, indirection is always legal, even if Result 11646 // is an incomplete type or void. It would be possible to warn about 11647 // dereferencing a void pointer, but it's completely well-defined, and such a 11648 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11649 // for pointers to 'void' but is fine for any other pointer type: 11650 // 11651 // C++ [expr.unary.op]p1: 11652 // [...] the expression to which [the unary * operator] is applied shall 11653 // be a pointer to an object type, or a pointer to a function type 11654 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11655 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11656 << OpTy << Op->getSourceRange(); 11657 11658 // Dereferences are usually l-values... 11659 VK = VK_LValue; 11660 11661 // ...except that certain expressions are never l-values in C. 11662 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11663 VK = VK_RValue; 11664 11665 return Result; 11666 } 11667 11668 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11669 BinaryOperatorKind Opc; 11670 switch (Kind) { 11671 default: llvm_unreachable("Unknown binop!"); 11672 case tok::periodstar: Opc = BO_PtrMemD; break; 11673 case tok::arrowstar: Opc = BO_PtrMemI; break; 11674 case tok::star: Opc = BO_Mul; break; 11675 case tok::slash: Opc = BO_Div; break; 11676 case tok::percent: Opc = BO_Rem; break; 11677 case tok::plus: Opc = BO_Add; break; 11678 case tok::minus: Opc = BO_Sub; break; 11679 case tok::lessless: Opc = BO_Shl; break; 11680 case tok::greatergreater: Opc = BO_Shr; break; 11681 case tok::lessequal: Opc = BO_LE; break; 11682 case tok::less: Opc = BO_LT; break; 11683 case tok::greaterequal: Opc = BO_GE; break; 11684 case tok::greater: Opc = BO_GT; break; 11685 case tok::exclaimequal: Opc = BO_NE; break; 11686 case tok::equalequal: Opc = BO_EQ; break; 11687 case tok::spaceship: Opc = BO_Cmp; break; 11688 case tok::amp: Opc = BO_And; break; 11689 case tok::caret: Opc = BO_Xor; break; 11690 case tok::pipe: Opc = BO_Or; break; 11691 case tok::ampamp: Opc = BO_LAnd; break; 11692 case tok::pipepipe: Opc = BO_LOr; break; 11693 case tok::equal: Opc = BO_Assign; break; 11694 case tok::starequal: Opc = BO_MulAssign; break; 11695 case tok::slashequal: Opc = BO_DivAssign; break; 11696 case tok::percentequal: Opc = BO_RemAssign; break; 11697 case tok::plusequal: Opc = BO_AddAssign; break; 11698 case tok::minusequal: Opc = BO_SubAssign; break; 11699 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11700 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11701 case tok::ampequal: Opc = BO_AndAssign; break; 11702 case tok::caretequal: Opc = BO_XorAssign; break; 11703 case tok::pipeequal: Opc = BO_OrAssign; break; 11704 case tok::comma: Opc = BO_Comma; break; 11705 } 11706 return Opc; 11707 } 11708 11709 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11710 tok::TokenKind Kind) { 11711 UnaryOperatorKind Opc; 11712 switch (Kind) { 11713 default: llvm_unreachable("Unknown unary op!"); 11714 case tok::plusplus: Opc = UO_PreInc; break; 11715 case tok::minusminus: Opc = UO_PreDec; break; 11716 case tok::amp: Opc = UO_AddrOf; break; 11717 case tok::star: Opc = UO_Deref; break; 11718 case tok::plus: Opc = UO_Plus; break; 11719 case tok::minus: Opc = UO_Minus; break; 11720 case tok::tilde: Opc = UO_Not; break; 11721 case tok::exclaim: Opc = UO_LNot; break; 11722 case tok::kw___real: Opc = UO_Real; break; 11723 case tok::kw___imag: Opc = UO_Imag; break; 11724 case tok::kw___extension__: Opc = UO_Extension; break; 11725 } 11726 return Opc; 11727 } 11728 11729 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11730 /// This warning suppressed in the event of macro expansions. 11731 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11732 SourceLocation OpLoc, bool IsBuiltin) { 11733 if (S.inTemplateInstantiation()) 11734 return; 11735 if (S.isUnevaluatedContext()) 11736 return; 11737 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11738 return; 11739 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11740 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11741 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11742 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11743 if (!LHSDeclRef || !RHSDeclRef || 11744 LHSDeclRef->getLocation().isMacroID() || 11745 RHSDeclRef->getLocation().isMacroID()) 11746 return; 11747 const ValueDecl *LHSDecl = 11748 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11749 const ValueDecl *RHSDecl = 11750 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11751 if (LHSDecl != RHSDecl) 11752 return; 11753 if (LHSDecl->getType().isVolatileQualified()) 11754 return; 11755 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11756 if (RefTy->getPointeeType().isVolatileQualified()) 11757 return; 11758 11759 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11760 : diag::warn_self_assignment_overloaded) 11761 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11762 << RHSExpr->getSourceRange(); 11763 } 11764 11765 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11766 /// is usually indicative of introspection within the Objective-C pointer. 11767 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11768 SourceLocation OpLoc) { 11769 if (!S.getLangOpts().ObjC1) 11770 return; 11771 11772 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11773 const Expr *LHS = L.get(); 11774 const Expr *RHS = R.get(); 11775 11776 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11777 ObjCPointerExpr = LHS; 11778 OtherExpr = RHS; 11779 } 11780 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11781 ObjCPointerExpr = RHS; 11782 OtherExpr = LHS; 11783 } 11784 11785 // This warning is deliberately made very specific to reduce false 11786 // positives with logic that uses '&' for hashing. This logic mainly 11787 // looks for code trying to introspect into tagged pointers, which 11788 // code should generally never do. 11789 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11790 unsigned Diag = diag::warn_objc_pointer_masking; 11791 // Determine if we are introspecting the result of performSelectorXXX. 11792 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11793 // Special case messages to -performSelector and friends, which 11794 // can return non-pointer values boxed in a pointer value. 11795 // Some clients may wish to silence warnings in this subcase. 11796 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11797 Selector S = ME->getSelector(); 11798 StringRef SelArg0 = S.getNameForSlot(0); 11799 if (SelArg0.startswith("performSelector")) 11800 Diag = diag::warn_objc_pointer_masking_performSelector; 11801 } 11802 11803 S.Diag(OpLoc, Diag) 11804 << ObjCPointerExpr->getSourceRange(); 11805 } 11806 } 11807 11808 static NamedDecl *getDeclFromExpr(Expr *E) { 11809 if (!E) 11810 return nullptr; 11811 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11812 return DRE->getDecl(); 11813 if (auto *ME = dyn_cast<MemberExpr>(E)) 11814 return ME->getMemberDecl(); 11815 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11816 return IRE->getDecl(); 11817 return nullptr; 11818 } 11819 11820 // This helper function promotes a binary operator's operands (which are of a 11821 // half vector type) to a vector of floats and then truncates the result to 11822 // a vector of either half or short. 11823 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11824 BinaryOperatorKind Opc, QualType ResultTy, 11825 ExprValueKind VK, ExprObjectKind OK, 11826 bool IsCompAssign, SourceLocation OpLoc, 11827 FPOptions FPFeatures) { 11828 auto &Context = S.getASTContext(); 11829 assert((isVector(ResultTy, Context.HalfTy) || 11830 isVector(ResultTy, Context.ShortTy)) && 11831 "Result must be a vector of half or short"); 11832 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11833 isVector(RHS.get()->getType(), Context.HalfTy) && 11834 "both operands expected to be a half vector"); 11835 11836 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11837 QualType BinOpResTy = RHS.get()->getType(); 11838 11839 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11840 // change BinOpResTy to a vector of ints. 11841 if (isVector(ResultTy, Context.ShortTy)) 11842 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11843 11844 if (IsCompAssign) 11845 return new (Context) CompoundAssignOperator( 11846 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11847 OpLoc, FPFeatures); 11848 11849 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11850 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11851 VK, OK, OpLoc, FPFeatures); 11852 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11853 } 11854 11855 static std::pair<ExprResult, ExprResult> 11856 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11857 Expr *RHSExpr) { 11858 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11859 if (!S.getLangOpts().CPlusPlus) { 11860 // C cannot handle TypoExpr nodes on either side of a binop because it 11861 // doesn't handle dependent types properly, so make sure any TypoExprs have 11862 // been dealt with before checking the operands. 11863 LHS = S.CorrectDelayedTyposInExpr(LHS); 11864 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11865 if (Opc != BO_Assign) 11866 return ExprResult(E); 11867 // Avoid correcting the RHS to the same Expr as the LHS. 11868 Decl *D = getDeclFromExpr(E); 11869 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11870 }); 11871 } 11872 return std::make_pair(LHS, RHS); 11873 } 11874 11875 /// Returns true if conversion between vectors of halfs and vectors of floats 11876 /// is needed. 11877 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11878 QualType SrcType) { 11879 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11880 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11881 isVector(SrcType, Ctx.HalfTy); 11882 } 11883 11884 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11885 /// operator @p Opc at location @c TokLoc. This routine only supports 11886 /// built-in operations; ActOnBinOp handles overloaded operators. 11887 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11888 BinaryOperatorKind Opc, 11889 Expr *LHSExpr, Expr *RHSExpr) { 11890 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11891 // The syntax only allows initializer lists on the RHS of assignment, 11892 // so we don't need to worry about accepting invalid code for 11893 // non-assignment operators. 11894 // C++11 5.17p9: 11895 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11896 // of x = {} is x = T(). 11897 InitializationKind Kind = InitializationKind::CreateDirectList( 11898 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11899 InitializedEntity Entity = 11900 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11901 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11902 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11903 if (Init.isInvalid()) 11904 return Init; 11905 RHSExpr = Init.get(); 11906 } 11907 11908 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11909 QualType ResultTy; // Result type of the binary operator. 11910 // The following two variables are used for compound assignment operators 11911 QualType CompLHSTy; // Type of LHS after promotions for computation 11912 QualType CompResultTy; // Type of computation result 11913 ExprValueKind VK = VK_RValue; 11914 ExprObjectKind OK = OK_Ordinary; 11915 bool ConvertHalfVec = false; 11916 11917 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11918 if (!LHS.isUsable() || !RHS.isUsable()) 11919 return ExprError(); 11920 11921 if (getLangOpts().OpenCL) { 11922 QualType LHSTy = LHSExpr->getType(); 11923 QualType RHSTy = RHSExpr->getType(); 11924 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11925 // the ATOMIC_VAR_INIT macro. 11926 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11927 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11928 if (BO_Assign == Opc) 11929 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11930 else 11931 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11932 return ExprError(); 11933 } 11934 11935 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11936 // only with a builtin functions and therefore should be disallowed here. 11937 if (LHSTy->isImageType() || RHSTy->isImageType() || 11938 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11939 LHSTy->isPipeType() || RHSTy->isPipeType() || 11940 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11941 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11942 return ExprError(); 11943 } 11944 } 11945 11946 switch (Opc) { 11947 case BO_Assign: 11948 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11949 if (getLangOpts().CPlusPlus && 11950 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11951 VK = LHS.get()->getValueKind(); 11952 OK = LHS.get()->getObjectKind(); 11953 } 11954 if (!ResultTy.isNull()) { 11955 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 11956 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11957 } 11958 RecordModifiableNonNullParam(*this, LHS.get()); 11959 break; 11960 case BO_PtrMemD: 11961 case BO_PtrMemI: 11962 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11963 Opc == BO_PtrMemI); 11964 break; 11965 case BO_Mul: 11966 case BO_Div: 11967 ConvertHalfVec = true; 11968 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11969 Opc == BO_Div); 11970 break; 11971 case BO_Rem: 11972 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11973 break; 11974 case BO_Add: 11975 ConvertHalfVec = true; 11976 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11977 break; 11978 case BO_Sub: 11979 ConvertHalfVec = true; 11980 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11981 break; 11982 case BO_Shl: 11983 case BO_Shr: 11984 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11985 break; 11986 case BO_LE: 11987 case BO_LT: 11988 case BO_GE: 11989 case BO_GT: 11990 ConvertHalfVec = true; 11991 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 11992 break; 11993 case BO_EQ: 11994 case BO_NE: 11995 ConvertHalfVec = true; 11996 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 11997 break; 11998 case BO_Cmp: 11999 ConvertHalfVec = true; 12000 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12001 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12002 break; 12003 case BO_And: 12004 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12005 LLVM_FALLTHROUGH; 12006 case BO_Xor: 12007 case BO_Or: 12008 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12009 break; 12010 case BO_LAnd: 12011 case BO_LOr: 12012 ConvertHalfVec = true; 12013 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12014 break; 12015 case BO_MulAssign: 12016 case BO_DivAssign: 12017 ConvertHalfVec = true; 12018 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12019 Opc == BO_DivAssign); 12020 CompLHSTy = CompResultTy; 12021 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12022 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12023 break; 12024 case BO_RemAssign: 12025 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12026 CompLHSTy = CompResultTy; 12027 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12028 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12029 break; 12030 case BO_AddAssign: 12031 ConvertHalfVec = true; 12032 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12033 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12034 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12035 break; 12036 case BO_SubAssign: 12037 ConvertHalfVec = true; 12038 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12039 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12040 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12041 break; 12042 case BO_ShlAssign: 12043 case BO_ShrAssign: 12044 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12045 CompLHSTy = CompResultTy; 12046 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12047 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12048 break; 12049 case BO_AndAssign: 12050 case BO_OrAssign: // fallthrough 12051 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12052 LLVM_FALLTHROUGH; 12053 case BO_XorAssign: 12054 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12055 CompLHSTy = CompResultTy; 12056 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12057 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12058 break; 12059 case BO_Comma: 12060 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12061 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12062 VK = RHS.get()->getValueKind(); 12063 OK = RHS.get()->getObjectKind(); 12064 } 12065 break; 12066 } 12067 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12068 return ExprError(); 12069 12070 // Some of the binary operations require promoting operands of half vector to 12071 // float vectors and truncating the result back to half vector. For now, we do 12072 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12073 // arm64). 12074 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12075 isVector(LHS.get()->getType(), Context.HalfTy) && 12076 "both sides are half vectors or neither sides are"); 12077 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12078 LHS.get()->getType()); 12079 12080 // Check for array bounds violations for both sides of the BinaryOperator 12081 CheckArrayAccess(LHS.get()); 12082 CheckArrayAccess(RHS.get()); 12083 12084 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12085 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12086 &Context.Idents.get("object_setClass"), 12087 SourceLocation(), LookupOrdinaryName); 12088 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12089 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 12090 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 12091 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 12092 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 12093 FixItHint::CreateInsertion(RHSLocEnd, ")"); 12094 } 12095 else 12096 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12097 } 12098 else if (const ObjCIvarRefExpr *OIRE = 12099 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12100 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12101 12102 // Opc is not a compound assignment if CompResultTy is null. 12103 if (CompResultTy.isNull()) { 12104 if (ConvertHalfVec) 12105 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12106 OpLoc, FPFeatures); 12107 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12108 OK, OpLoc, FPFeatures); 12109 } 12110 12111 // Handle compound assignments. 12112 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12113 OK_ObjCProperty) { 12114 VK = VK_LValue; 12115 OK = LHS.get()->getObjectKind(); 12116 } 12117 12118 if (ConvertHalfVec) 12119 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12120 OpLoc, FPFeatures); 12121 12122 return new (Context) CompoundAssignOperator( 12123 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12124 OpLoc, FPFeatures); 12125 } 12126 12127 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12128 /// operators are mixed in a way that suggests that the programmer forgot that 12129 /// comparison operators have higher precedence. The most typical example of 12130 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12131 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12132 SourceLocation OpLoc, Expr *LHSExpr, 12133 Expr *RHSExpr) { 12134 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12135 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12136 12137 // Check that one of the sides is a comparison operator and the other isn't. 12138 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12139 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12140 if (isLeftComp == isRightComp) 12141 return; 12142 12143 // Bitwise operations are sometimes used as eager logical ops. 12144 // Don't diagnose this. 12145 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12146 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12147 if (isLeftBitwise || isRightBitwise) 12148 return; 12149 12150 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 12151 OpLoc) 12152 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 12153 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12154 SourceRange ParensRange = isLeftComp ? 12155 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 12156 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 12157 12158 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12159 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12160 SuggestParentheses(Self, OpLoc, 12161 Self.PDiag(diag::note_precedence_silence) << OpStr, 12162 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12163 SuggestParentheses(Self, OpLoc, 12164 Self.PDiag(diag::note_precedence_bitwise_first) 12165 << BinaryOperator::getOpcodeStr(Opc), 12166 ParensRange); 12167 } 12168 12169 /// \brief It accepts a '&&' expr that is inside a '||' one. 12170 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12171 /// in parentheses. 12172 static void 12173 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12174 BinaryOperator *Bop) { 12175 assert(Bop->getOpcode() == BO_LAnd); 12176 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12177 << Bop->getSourceRange() << OpLoc; 12178 SuggestParentheses(Self, Bop->getOperatorLoc(), 12179 Self.PDiag(diag::note_precedence_silence) 12180 << Bop->getOpcodeStr(), 12181 Bop->getSourceRange()); 12182 } 12183 12184 /// \brief Returns true if the given expression can be evaluated as a constant 12185 /// 'true'. 12186 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12187 bool Res; 12188 return !E->isValueDependent() && 12189 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12190 } 12191 12192 /// \brief Returns true if the given expression can be evaluated as a constant 12193 /// 'false'. 12194 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12195 bool Res; 12196 return !E->isValueDependent() && 12197 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12198 } 12199 12200 /// \brief Look for '&&' in the left hand of a '||' expr. 12201 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12202 Expr *LHSExpr, Expr *RHSExpr) { 12203 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12204 if (Bop->getOpcode() == BO_LAnd) { 12205 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12206 if (EvaluatesAsFalse(S, RHSExpr)) 12207 return; 12208 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12209 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12210 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12211 } else if (Bop->getOpcode() == BO_LOr) { 12212 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12213 // If it's "a || b && 1 || c" we didn't warn earlier for 12214 // "a || b && 1", but warn now. 12215 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12216 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12217 } 12218 } 12219 } 12220 } 12221 12222 /// \brief Look for '&&' in the right hand of a '||' expr. 12223 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12224 Expr *LHSExpr, Expr *RHSExpr) { 12225 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12226 if (Bop->getOpcode() == BO_LAnd) { 12227 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12228 if (EvaluatesAsFalse(S, LHSExpr)) 12229 return; 12230 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12231 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12232 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12233 } 12234 } 12235 } 12236 12237 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 12238 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12239 /// the '&' expression in parentheses. 12240 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12241 SourceLocation OpLoc, Expr *SubExpr) { 12242 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12243 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12244 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12245 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12246 << Bop->getSourceRange() << OpLoc; 12247 SuggestParentheses(S, Bop->getOperatorLoc(), 12248 S.PDiag(diag::note_precedence_silence) 12249 << Bop->getOpcodeStr(), 12250 Bop->getSourceRange()); 12251 } 12252 } 12253 } 12254 12255 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12256 Expr *SubExpr, StringRef Shift) { 12257 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12258 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12259 StringRef Op = Bop->getOpcodeStr(); 12260 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12261 << Bop->getSourceRange() << OpLoc << Shift << Op; 12262 SuggestParentheses(S, Bop->getOperatorLoc(), 12263 S.PDiag(diag::note_precedence_silence) << Op, 12264 Bop->getSourceRange()); 12265 } 12266 } 12267 } 12268 12269 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12270 Expr *LHSExpr, Expr *RHSExpr) { 12271 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12272 if (!OCE) 12273 return; 12274 12275 FunctionDecl *FD = OCE->getDirectCallee(); 12276 if (!FD || !FD->isOverloadedOperator()) 12277 return; 12278 12279 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12280 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12281 return; 12282 12283 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12284 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12285 << (Kind == OO_LessLess); 12286 SuggestParentheses(S, OCE->getOperatorLoc(), 12287 S.PDiag(diag::note_precedence_silence) 12288 << (Kind == OO_LessLess ? "<<" : ">>"), 12289 OCE->getSourceRange()); 12290 SuggestParentheses(S, OpLoc, 12291 S.PDiag(diag::note_evaluate_comparison_first), 12292 SourceRange(OCE->getArg(1)->getLocStart(), 12293 RHSExpr->getLocEnd())); 12294 } 12295 12296 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12297 /// precedence. 12298 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12299 SourceLocation OpLoc, Expr *LHSExpr, 12300 Expr *RHSExpr){ 12301 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12302 if (BinaryOperator::isBitwiseOp(Opc)) 12303 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12304 12305 // Diagnose "arg1 & arg2 | arg3" 12306 if ((Opc == BO_Or || Opc == BO_Xor) && 12307 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12308 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12309 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12310 } 12311 12312 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12313 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12314 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12315 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12316 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12317 } 12318 12319 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12320 || Opc == BO_Shr) { 12321 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12322 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12323 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12324 } 12325 12326 // Warn on overloaded shift operators and comparisons, such as: 12327 // cout << 5 == 4; 12328 if (BinaryOperator::isComparisonOp(Opc)) 12329 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12330 } 12331 12332 // Binary Operators. 'Tok' is the token for the operator. 12333 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12334 tok::TokenKind Kind, 12335 Expr *LHSExpr, Expr *RHSExpr) { 12336 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12337 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12338 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12339 12340 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12341 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12342 12343 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12344 } 12345 12346 /// Build an overloaded binary operator expression in the given scope. 12347 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12348 BinaryOperatorKind Opc, 12349 Expr *LHS, Expr *RHS) { 12350 switch (Opc) { 12351 case BO_Assign: 12352 case BO_DivAssign: 12353 case BO_RemAssign: 12354 case BO_SubAssign: 12355 case BO_AndAssign: 12356 case BO_OrAssign: 12357 case BO_XorAssign: 12358 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12359 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12360 break; 12361 default: 12362 break; 12363 } 12364 12365 // Find all of the overloaded operators visible from this 12366 // point. We perform both an operator-name lookup from the local 12367 // scope and an argument-dependent lookup based on the types of 12368 // the arguments. 12369 UnresolvedSet<16> Functions; 12370 OverloadedOperatorKind OverOp 12371 = BinaryOperator::getOverloadedOperator(Opc); 12372 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12373 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12374 RHS->getType(), Functions); 12375 12376 // Build the (potentially-overloaded, potentially-dependent) 12377 // binary operation. 12378 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12379 } 12380 12381 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12382 BinaryOperatorKind Opc, 12383 Expr *LHSExpr, Expr *RHSExpr) { 12384 ExprResult LHS, RHS; 12385 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12386 if (!LHS.isUsable() || !RHS.isUsable()) 12387 return ExprError(); 12388 LHSExpr = LHS.get(); 12389 RHSExpr = RHS.get(); 12390 12391 // We want to end up calling one of checkPseudoObjectAssignment 12392 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12393 // both expressions are overloadable or either is type-dependent), 12394 // or CreateBuiltinBinOp (in any other case). We also want to get 12395 // any placeholder types out of the way. 12396 12397 // Handle pseudo-objects in the LHS. 12398 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12399 // Assignments with a pseudo-object l-value need special analysis. 12400 if (pty->getKind() == BuiltinType::PseudoObject && 12401 BinaryOperator::isAssignmentOp(Opc)) 12402 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12403 12404 // Don't resolve overloads if the other type is overloadable. 12405 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12406 // We can't actually test that if we still have a placeholder, 12407 // though. Fortunately, none of the exceptions we see in that 12408 // code below are valid when the LHS is an overload set. Note 12409 // that an overload set can be dependently-typed, but it never 12410 // instantiates to having an overloadable type. 12411 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12412 if (resolvedRHS.isInvalid()) return ExprError(); 12413 RHSExpr = resolvedRHS.get(); 12414 12415 if (RHSExpr->isTypeDependent() || 12416 RHSExpr->getType()->isOverloadableType()) 12417 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12418 } 12419 12420 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12421 // template, diagnose the missing 'template' keyword instead of diagnosing 12422 // an invalid use of a bound member function. 12423 // 12424 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12425 // to C++1z [over.over]/1.4, but we already checked for that case above. 12426 if (Opc == BO_LT && inTemplateInstantiation() && 12427 (pty->getKind() == BuiltinType::BoundMember || 12428 pty->getKind() == BuiltinType::Overload)) { 12429 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12430 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12431 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12432 return isa<FunctionTemplateDecl>(ND); 12433 })) { 12434 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12435 : OE->getNameLoc(), 12436 diag::err_template_kw_missing) 12437 << OE->getName().getAsString() << ""; 12438 return ExprError(); 12439 } 12440 } 12441 12442 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12443 if (LHS.isInvalid()) return ExprError(); 12444 LHSExpr = LHS.get(); 12445 } 12446 12447 // Handle pseudo-objects in the RHS. 12448 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12449 // An overload in the RHS can potentially be resolved by the type 12450 // being assigned to. 12451 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12452 if (getLangOpts().CPlusPlus && 12453 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12454 LHSExpr->getType()->isOverloadableType())) 12455 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12456 12457 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12458 } 12459 12460 // Don't resolve overloads if the other type is overloadable. 12461 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12462 LHSExpr->getType()->isOverloadableType()) 12463 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12464 12465 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12466 if (!resolvedRHS.isUsable()) return ExprError(); 12467 RHSExpr = resolvedRHS.get(); 12468 } 12469 12470 if (getLangOpts().CPlusPlus) { 12471 // If either expression is type-dependent, always build an 12472 // overloaded op. 12473 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12474 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12475 12476 // Otherwise, build an overloaded op if either expression has an 12477 // overloadable type. 12478 if (LHSExpr->getType()->isOverloadableType() || 12479 RHSExpr->getType()->isOverloadableType()) 12480 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12481 } 12482 12483 // Build a built-in binary operation. 12484 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12485 } 12486 12487 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12488 if (T.isNull() || T->isDependentType()) 12489 return false; 12490 12491 if (!T->isPromotableIntegerType()) 12492 return true; 12493 12494 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12495 } 12496 12497 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12498 UnaryOperatorKind Opc, 12499 Expr *InputExpr) { 12500 ExprResult Input = InputExpr; 12501 ExprValueKind VK = VK_RValue; 12502 ExprObjectKind OK = OK_Ordinary; 12503 QualType resultType; 12504 bool CanOverflow = false; 12505 12506 bool ConvertHalfVec = false; 12507 if (getLangOpts().OpenCL) { 12508 QualType Ty = InputExpr->getType(); 12509 // The only legal unary operation for atomics is '&'. 12510 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12511 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12512 // only with a builtin functions and therefore should be disallowed here. 12513 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12514 || Ty->isBlockPointerType())) { 12515 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12516 << InputExpr->getType() 12517 << Input.get()->getSourceRange()); 12518 } 12519 } 12520 switch (Opc) { 12521 case UO_PreInc: 12522 case UO_PreDec: 12523 case UO_PostInc: 12524 case UO_PostDec: 12525 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12526 OpLoc, 12527 Opc == UO_PreInc || 12528 Opc == UO_PostInc, 12529 Opc == UO_PreInc || 12530 Opc == UO_PreDec); 12531 CanOverflow = isOverflowingIntegerType(Context, resultType); 12532 break; 12533 case UO_AddrOf: 12534 resultType = CheckAddressOfOperand(Input, OpLoc); 12535 RecordModifiableNonNullParam(*this, InputExpr); 12536 break; 12537 case UO_Deref: { 12538 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12539 if (Input.isInvalid()) return ExprError(); 12540 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12541 break; 12542 } 12543 case UO_Plus: 12544 case UO_Minus: 12545 CanOverflow = Opc == UO_Minus && 12546 isOverflowingIntegerType(Context, Input.get()->getType()); 12547 Input = UsualUnaryConversions(Input.get()); 12548 if (Input.isInvalid()) return ExprError(); 12549 // Unary plus and minus require promoting an operand of half vector to a 12550 // float vector and truncating the result back to a half vector. For now, we 12551 // do this only when HalfArgsAndReturns is set (that is, when the target is 12552 // arm or arm64). 12553 ConvertHalfVec = 12554 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12555 12556 // If the operand is a half vector, promote it to a float vector. 12557 if (ConvertHalfVec) 12558 Input = convertVector(Input.get(), Context.FloatTy, *this); 12559 resultType = Input.get()->getType(); 12560 if (resultType->isDependentType()) 12561 break; 12562 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12563 break; 12564 else if (resultType->isVectorType() && 12565 // The z vector extensions don't allow + or - with bool vectors. 12566 (!Context.getLangOpts().ZVector || 12567 resultType->getAs<VectorType>()->getVectorKind() != 12568 VectorType::AltiVecBool)) 12569 break; 12570 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12571 Opc == UO_Plus && 12572 resultType->isPointerType()) 12573 break; 12574 12575 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12576 << resultType << Input.get()->getSourceRange()); 12577 12578 case UO_Not: // bitwise complement 12579 Input = UsualUnaryConversions(Input.get()); 12580 if (Input.isInvalid()) 12581 return ExprError(); 12582 resultType = Input.get()->getType(); 12583 12584 if (resultType->isDependentType()) 12585 break; 12586 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12587 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12588 // C99 does not support '~' for complex conjugation. 12589 Diag(OpLoc, diag::ext_integer_complement_complex) 12590 << resultType << Input.get()->getSourceRange(); 12591 else if (resultType->hasIntegerRepresentation()) 12592 break; 12593 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12594 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12595 // on vector float types. 12596 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12597 if (!T->isIntegerType()) 12598 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12599 << resultType << Input.get()->getSourceRange()); 12600 } else { 12601 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12602 << resultType << Input.get()->getSourceRange()); 12603 } 12604 break; 12605 12606 case UO_LNot: // logical negation 12607 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12608 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12609 if (Input.isInvalid()) return ExprError(); 12610 resultType = Input.get()->getType(); 12611 12612 // Though we still have to promote half FP to float... 12613 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12614 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12615 resultType = Context.FloatTy; 12616 } 12617 12618 if (resultType->isDependentType()) 12619 break; 12620 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12621 // C99 6.5.3.3p1: ok, fallthrough; 12622 if (Context.getLangOpts().CPlusPlus) { 12623 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12624 // operand contextually converted to bool. 12625 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12626 ScalarTypeToBooleanCastKind(resultType)); 12627 } else if (Context.getLangOpts().OpenCL && 12628 Context.getLangOpts().OpenCLVersion < 120) { 12629 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12630 // operate on scalar float types. 12631 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12632 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12633 << resultType << Input.get()->getSourceRange()); 12634 } 12635 } else if (resultType->isExtVectorType()) { 12636 if (Context.getLangOpts().OpenCL && 12637 Context.getLangOpts().OpenCLVersion < 120) { 12638 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12639 // operate on vector float types. 12640 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12641 if (!T->isIntegerType()) 12642 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12643 << resultType << Input.get()->getSourceRange()); 12644 } 12645 // Vector logical not returns the signed variant of the operand type. 12646 resultType = GetSignedVectorType(resultType); 12647 break; 12648 } else { 12649 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12650 // type in C++. We should allow that here too. 12651 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12652 << resultType << Input.get()->getSourceRange()); 12653 } 12654 12655 // LNot always has type int. C99 6.5.3.3p5. 12656 // In C++, it's bool. C++ 5.3.1p8 12657 resultType = Context.getLogicalOperationType(); 12658 break; 12659 case UO_Real: 12660 case UO_Imag: 12661 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12662 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12663 // complex l-values to ordinary l-values and all other values to r-values. 12664 if (Input.isInvalid()) return ExprError(); 12665 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12666 if (Input.get()->getValueKind() != VK_RValue && 12667 Input.get()->getObjectKind() == OK_Ordinary) 12668 VK = Input.get()->getValueKind(); 12669 } else if (!getLangOpts().CPlusPlus) { 12670 // In C, a volatile scalar is read by __imag. In C++, it is not. 12671 Input = DefaultLvalueConversion(Input.get()); 12672 } 12673 break; 12674 case UO_Extension: 12675 resultType = Input.get()->getType(); 12676 VK = Input.get()->getValueKind(); 12677 OK = Input.get()->getObjectKind(); 12678 break; 12679 case UO_Coawait: 12680 // It's unnecessary to represent the pass-through operator co_await in the 12681 // AST; just return the input expression instead. 12682 assert(!Input.get()->getType()->isDependentType() && 12683 "the co_await expression must be non-dependant before " 12684 "building operator co_await"); 12685 return Input; 12686 } 12687 if (resultType.isNull() || Input.isInvalid()) 12688 return ExprError(); 12689 12690 // Check for array bounds violations in the operand of the UnaryOperator, 12691 // except for the '*' and '&' operators that have to be handled specially 12692 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12693 // that are explicitly defined as valid by the standard). 12694 if (Opc != UO_AddrOf && Opc != UO_Deref) 12695 CheckArrayAccess(Input.get()); 12696 12697 auto *UO = new (Context) 12698 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12699 // Convert the result back to a half vector. 12700 if (ConvertHalfVec) 12701 return convertVector(UO, Context.HalfTy, *this); 12702 return UO; 12703 } 12704 12705 /// \brief Determine whether the given expression is a qualified member 12706 /// access expression, of a form that could be turned into a pointer to member 12707 /// with the address-of operator. 12708 static bool isQualifiedMemberAccess(Expr *E) { 12709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12710 if (!DRE->getQualifier()) 12711 return false; 12712 12713 ValueDecl *VD = DRE->getDecl(); 12714 if (!VD->isCXXClassMember()) 12715 return false; 12716 12717 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12718 return true; 12719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12720 return Method->isInstance(); 12721 12722 return false; 12723 } 12724 12725 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12726 if (!ULE->getQualifier()) 12727 return false; 12728 12729 for (NamedDecl *D : ULE->decls()) { 12730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12731 if (Method->isInstance()) 12732 return true; 12733 } else { 12734 // Overload set does not contain methods. 12735 break; 12736 } 12737 } 12738 12739 return false; 12740 } 12741 12742 return false; 12743 } 12744 12745 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12746 UnaryOperatorKind Opc, Expr *Input) { 12747 // First things first: handle placeholders so that the 12748 // overloaded-operator check considers the right type. 12749 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12750 // Increment and decrement of pseudo-object references. 12751 if (pty->getKind() == BuiltinType::PseudoObject && 12752 UnaryOperator::isIncrementDecrementOp(Opc)) 12753 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12754 12755 // extension is always a builtin operator. 12756 if (Opc == UO_Extension) 12757 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12758 12759 // & gets special logic for several kinds of placeholder. 12760 // The builtin code knows what to do. 12761 if (Opc == UO_AddrOf && 12762 (pty->getKind() == BuiltinType::Overload || 12763 pty->getKind() == BuiltinType::UnknownAny || 12764 pty->getKind() == BuiltinType::BoundMember)) 12765 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12766 12767 // Anything else needs to be handled now. 12768 ExprResult Result = CheckPlaceholderExpr(Input); 12769 if (Result.isInvalid()) return ExprError(); 12770 Input = Result.get(); 12771 } 12772 12773 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12774 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12775 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12776 // Find all of the overloaded operators visible from this 12777 // point. We perform both an operator-name lookup from the local 12778 // scope and an argument-dependent lookup based on the types of 12779 // the arguments. 12780 UnresolvedSet<16> Functions; 12781 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12782 if (S && OverOp != OO_None) 12783 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12784 Functions); 12785 12786 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12787 } 12788 12789 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12790 } 12791 12792 // Unary Operators. 'Tok' is the token for the operator. 12793 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12794 tok::TokenKind Op, Expr *Input) { 12795 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12796 } 12797 12798 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12799 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12800 LabelDecl *TheDecl) { 12801 TheDecl->markUsed(Context); 12802 // Create the AST node. The address of a label always has type 'void*'. 12803 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12804 Context.getPointerType(Context.VoidTy)); 12805 } 12806 12807 /// Given the last statement in a statement-expression, check whether 12808 /// the result is a producing expression (like a call to an 12809 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12810 /// release out of the full-expression. Otherwise, return null. 12811 /// Cannot fail. 12812 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12813 // Should always be wrapped with one of these. 12814 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12815 if (!cleanups) return nullptr; 12816 12817 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12818 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12819 return nullptr; 12820 12821 // Splice out the cast. This shouldn't modify any interesting 12822 // features of the statement. 12823 Expr *producer = cast->getSubExpr(); 12824 assert(producer->getType() == cast->getType()); 12825 assert(producer->getValueKind() == cast->getValueKind()); 12826 cleanups->setSubExpr(producer); 12827 return cleanups; 12828 } 12829 12830 void Sema::ActOnStartStmtExpr() { 12831 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12832 } 12833 12834 void Sema::ActOnStmtExprError() { 12835 // Note that function is also called by TreeTransform when leaving a 12836 // StmtExpr scope without rebuilding anything. 12837 12838 DiscardCleanupsInEvaluationContext(); 12839 PopExpressionEvaluationContext(); 12840 } 12841 12842 ExprResult 12843 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12844 SourceLocation RPLoc) { // "({..})" 12845 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12846 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12847 12848 if (hasAnyUnrecoverableErrorsInThisFunction()) 12849 DiscardCleanupsInEvaluationContext(); 12850 assert(!Cleanup.exprNeedsCleanups() && 12851 "cleanups within StmtExpr not correctly bound!"); 12852 PopExpressionEvaluationContext(); 12853 12854 // FIXME: there are a variety of strange constraints to enforce here, for 12855 // example, it is not possible to goto into a stmt expression apparently. 12856 // More semantic analysis is needed. 12857 12858 // If there are sub-stmts in the compound stmt, take the type of the last one 12859 // as the type of the stmtexpr. 12860 QualType Ty = Context.VoidTy; 12861 bool StmtExprMayBindToTemp = false; 12862 if (!Compound->body_empty()) { 12863 Stmt *LastStmt = Compound->body_back(); 12864 LabelStmt *LastLabelStmt = nullptr; 12865 // If LastStmt is a label, skip down through into the body. 12866 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12867 LastLabelStmt = Label; 12868 LastStmt = Label->getSubStmt(); 12869 } 12870 12871 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12872 // Do function/array conversion on the last expression, but not 12873 // lvalue-to-rvalue. However, initialize an unqualified type. 12874 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12875 if (LastExpr.isInvalid()) 12876 return ExprError(); 12877 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12878 12879 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12880 // In ARC, if the final expression ends in a consume, splice 12881 // the consume out and bind it later. In the alternate case 12882 // (when dealing with a retainable type), the result 12883 // initialization will create a produce. In both cases the 12884 // result will be +1, and we'll need to balance that out with 12885 // a bind. 12886 if (Expr *rebuiltLastStmt 12887 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12888 LastExpr = rebuiltLastStmt; 12889 } else { 12890 LastExpr = PerformCopyInitialization( 12891 InitializedEntity::InitializeResult(LPLoc, 12892 Ty, 12893 false), 12894 SourceLocation(), 12895 LastExpr); 12896 } 12897 12898 if (LastExpr.isInvalid()) 12899 return ExprError(); 12900 if (LastExpr.get() != nullptr) { 12901 if (!LastLabelStmt) 12902 Compound->setLastStmt(LastExpr.get()); 12903 else 12904 LastLabelStmt->setSubStmt(LastExpr.get()); 12905 StmtExprMayBindToTemp = true; 12906 } 12907 } 12908 } 12909 } 12910 12911 // FIXME: Check that expression type is complete/non-abstract; statement 12912 // expressions are not lvalues. 12913 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12914 if (StmtExprMayBindToTemp) 12915 return MaybeBindToTemporary(ResStmtExpr); 12916 return ResStmtExpr; 12917 } 12918 12919 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12920 TypeSourceInfo *TInfo, 12921 ArrayRef<OffsetOfComponent> Components, 12922 SourceLocation RParenLoc) { 12923 QualType ArgTy = TInfo->getType(); 12924 bool Dependent = ArgTy->isDependentType(); 12925 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12926 12927 // We must have at least one component that refers to the type, and the first 12928 // one is known to be a field designator. Verify that the ArgTy represents 12929 // a struct/union/class. 12930 if (!Dependent && !ArgTy->isRecordType()) 12931 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12932 << ArgTy << TypeRange); 12933 12934 // Type must be complete per C99 7.17p3 because a declaring a variable 12935 // with an incomplete type would be ill-formed. 12936 if (!Dependent 12937 && RequireCompleteType(BuiltinLoc, ArgTy, 12938 diag::err_offsetof_incomplete_type, TypeRange)) 12939 return ExprError(); 12940 12941 bool DidWarnAboutNonPOD = false; 12942 QualType CurrentType = ArgTy; 12943 SmallVector<OffsetOfNode, 4> Comps; 12944 SmallVector<Expr*, 4> Exprs; 12945 for (const OffsetOfComponent &OC : Components) { 12946 if (OC.isBrackets) { 12947 // Offset of an array sub-field. TODO: Should we allow vector elements? 12948 if (!CurrentType->isDependentType()) { 12949 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12950 if(!AT) 12951 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12952 << CurrentType); 12953 CurrentType = AT->getElementType(); 12954 } else 12955 CurrentType = Context.DependentTy; 12956 12957 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12958 if (IdxRval.isInvalid()) 12959 return ExprError(); 12960 Expr *Idx = IdxRval.get(); 12961 12962 // The expression must be an integral expression. 12963 // FIXME: An integral constant expression? 12964 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12965 !Idx->getType()->isIntegerType()) 12966 return ExprError(Diag(Idx->getLocStart(), 12967 diag::err_typecheck_subscript_not_integer) 12968 << Idx->getSourceRange()); 12969 12970 // Record this array index. 12971 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12972 Exprs.push_back(Idx); 12973 continue; 12974 } 12975 12976 // Offset of a field. 12977 if (CurrentType->isDependentType()) { 12978 // We have the offset of a field, but we can't look into the dependent 12979 // type. Just record the identifier of the field. 12980 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12981 CurrentType = Context.DependentTy; 12982 continue; 12983 } 12984 12985 // We need to have a complete type to look into. 12986 if (RequireCompleteType(OC.LocStart, CurrentType, 12987 diag::err_offsetof_incomplete_type)) 12988 return ExprError(); 12989 12990 // Look for the designated field. 12991 const RecordType *RC = CurrentType->getAs<RecordType>(); 12992 if (!RC) 12993 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12994 << CurrentType); 12995 RecordDecl *RD = RC->getDecl(); 12996 12997 // C++ [lib.support.types]p5: 12998 // The macro offsetof accepts a restricted set of type arguments in this 12999 // International Standard. type shall be a POD structure or a POD union 13000 // (clause 9). 13001 // C++11 [support.types]p4: 13002 // If type is not a standard-layout class (Clause 9), the results are 13003 // undefined. 13004 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13005 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13006 unsigned DiagID = 13007 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13008 : diag::ext_offsetof_non_pod_type; 13009 13010 if (!IsSafe && !DidWarnAboutNonPOD && 13011 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13012 PDiag(DiagID) 13013 << SourceRange(Components[0].LocStart, OC.LocEnd) 13014 << CurrentType)) 13015 DidWarnAboutNonPOD = true; 13016 } 13017 13018 // Look for the field. 13019 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13020 LookupQualifiedName(R, RD); 13021 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13022 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13023 if (!MemberDecl) { 13024 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13025 MemberDecl = IndirectMemberDecl->getAnonField(); 13026 } 13027 13028 if (!MemberDecl) 13029 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13030 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13031 OC.LocEnd)); 13032 13033 // C99 7.17p3: 13034 // (If the specified member is a bit-field, the behavior is undefined.) 13035 // 13036 // We diagnose this as an error. 13037 if (MemberDecl->isBitField()) { 13038 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13039 << MemberDecl->getDeclName() 13040 << SourceRange(BuiltinLoc, RParenLoc); 13041 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13042 return ExprError(); 13043 } 13044 13045 RecordDecl *Parent = MemberDecl->getParent(); 13046 if (IndirectMemberDecl) 13047 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13048 13049 // If the member was found in a base class, introduce OffsetOfNodes for 13050 // the base class indirections. 13051 CXXBasePaths Paths; 13052 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13053 Paths)) { 13054 if (Paths.getDetectedVirtual()) { 13055 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13056 << MemberDecl->getDeclName() 13057 << SourceRange(BuiltinLoc, RParenLoc); 13058 return ExprError(); 13059 } 13060 13061 CXXBasePath &Path = Paths.front(); 13062 for (const CXXBasePathElement &B : Path) 13063 Comps.push_back(OffsetOfNode(B.Base)); 13064 } 13065 13066 if (IndirectMemberDecl) { 13067 for (auto *FI : IndirectMemberDecl->chain()) { 13068 assert(isa<FieldDecl>(FI)); 13069 Comps.push_back(OffsetOfNode(OC.LocStart, 13070 cast<FieldDecl>(FI), OC.LocEnd)); 13071 } 13072 } else 13073 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13074 13075 CurrentType = MemberDecl->getType().getNonReferenceType(); 13076 } 13077 13078 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13079 Comps, Exprs, RParenLoc); 13080 } 13081 13082 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13083 SourceLocation BuiltinLoc, 13084 SourceLocation TypeLoc, 13085 ParsedType ParsedArgTy, 13086 ArrayRef<OffsetOfComponent> Components, 13087 SourceLocation RParenLoc) { 13088 13089 TypeSourceInfo *ArgTInfo; 13090 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13091 if (ArgTy.isNull()) 13092 return ExprError(); 13093 13094 if (!ArgTInfo) 13095 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13096 13097 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13098 } 13099 13100 13101 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13102 Expr *CondExpr, 13103 Expr *LHSExpr, Expr *RHSExpr, 13104 SourceLocation RPLoc) { 13105 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13106 13107 ExprValueKind VK = VK_RValue; 13108 ExprObjectKind OK = OK_Ordinary; 13109 QualType resType; 13110 bool ValueDependent = false; 13111 bool CondIsTrue = false; 13112 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13113 resType = Context.DependentTy; 13114 ValueDependent = true; 13115 } else { 13116 // The conditional expression is required to be a constant expression. 13117 llvm::APSInt condEval(32); 13118 ExprResult CondICE 13119 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13120 diag::err_typecheck_choose_expr_requires_constant, false); 13121 if (CondICE.isInvalid()) 13122 return ExprError(); 13123 CondExpr = CondICE.get(); 13124 CondIsTrue = condEval.getZExtValue(); 13125 13126 // If the condition is > zero, then the AST type is the same as the LSHExpr. 13127 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13128 13129 resType = ActiveExpr->getType(); 13130 ValueDependent = ActiveExpr->isValueDependent(); 13131 VK = ActiveExpr->getValueKind(); 13132 OK = ActiveExpr->getObjectKind(); 13133 } 13134 13135 return new (Context) 13136 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13137 CondIsTrue, resType->isDependentType(), ValueDependent); 13138 } 13139 13140 //===----------------------------------------------------------------------===// 13141 // Clang Extensions. 13142 //===----------------------------------------------------------------------===// 13143 13144 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13145 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13146 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13147 13148 if (LangOpts.CPlusPlus) { 13149 Decl *ManglingContextDecl; 13150 if (MangleNumberingContext *MCtx = 13151 getCurrentMangleNumberContext(Block->getDeclContext(), 13152 ManglingContextDecl)) { 13153 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13154 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13155 } 13156 } 13157 13158 PushBlockScope(CurScope, Block); 13159 CurContext->addDecl(Block); 13160 if (CurScope) 13161 PushDeclContext(CurScope, Block); 13162 else 13163 CurContext = Block; 13164 13165 getCurBlock()->HasImplicitReturnType = true; 13166 13167 // Enter a new evaluation context to insulate the block from any 13168 // cleanups from the enclosing full-expression. 13169 PushExpressionEvaluationContext( 13170 ExpressionEvaluationContext::PotentiallyEvaluated); 13171 } 13172 13173 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13174 Scope *CurScope) { 13175 assert(ParamInfo.getIdentifier() == nullptr && 13176 "block-id should have no identifier!"); 13177 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13178 BlockScopeInfo *CurBlock = getCurBlock(); 13179 13180 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13181 QualType T = Sig->getType(); 13182 13183 // FIXME: We should allow unexpanded parameter packs here, but that would, 13184 // in turn, make the block expression contain unexpanded parameter packs. 13185 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13186 // Drop the parameters. 13187 FunctionProtoType::ExtProtoInfo EPI; 13188 EPI.HasTrailingReturn = false; 13189 EPI.TypeQuals |= DeclSpec::TQ_const; 13190 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13191 Sig = Context.getTrivialTypeSourceInfo(T); 13192 } 13193 13194 // GetTypeForDeclarator always produces a function type for a block 13195 // literal signature. Furthermore, it is always a FunctionProtoType 13196 // unless the function was written with a typedef. 13197 assert(T->isFunctionType() && 13198 "GetTypeForDeclarator made a non-function block signature"); 13199 13200 // Look for an explicit signature in that function type. 13201 FunctionProtoTypeLoc ExplicitSignature; 13202 13203 if ((ExplicitSignature = 13204 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13205 13206 // Check whether that explicit signature was synthesized by 13207 // GetTypeForDeclarator. If so, don't save that as part of the 13208 // written signature. 13209 if (ExplicitSignature.getLocalRangeBegin() == 13210 ExplicitSignature.getLocalRangeEnd()) { 13211 // This would be much cheaper if we stored TypeLocs instead of 13212 // TypeSourceInfos. 13213 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13214 unsigned Size = Result.getFullDataSize(); 13215 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13216 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13217 13218 ExplicitSignature = FunctionProtoTypeLoc(); 13219 } 13220 } 13221 13222 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13223 CurBlock->FunctionType = T; 13224 13225 const FunctionType *Fn = T->getAs<FunctionType>(); 13226 QualType RetTy = Fn->getReturnType(); 13227 bool isVariadic = 13228 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13229 13230 CurBlock->TheDecl->setIsVariadic(isVariadic); 13231 13232 // Context.DependentTy is used as a placeholder for a missing block 13233 // return type. TODO: what should we do with declarators like: 13234 // ^ * { ... } 13235 // If the answer is "apply template argument deduction".... 13236 if (RetTy != Context.DependentTy) { 13237 CurBlock->ReturnType = RetTy; 13238 CurBlock->TheDecl->setBlockMissingReturnType(false); 13239 CurBlock->HasImplicitReturnType = false; 13240 } 13241 13242 // Push block parameters from the declarator if we had them. 13243 SmallVector<ParmVarDecl*, 8> Params; 13244 if (ExplicitSignature) { 13245 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13246 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13247 if (Param->getIdentifier() == nullptr && 13248 !Param->isImplicit() && 13249 !Param->isInvalidDecl() && 13250 !getLangOpts().CPlusPlus) 13251 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13252 Params.push_back(Param); 13253 } 13254 13255 // Fake up parameter variables if we have a typedef, like 13256 // ^ fntype { ... } 13257 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13258 for (const auto &I : Fn->param_types()) { 13259 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13260 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 13261 Params.push_back(Param); 13262 } 13263 } 13264 13265 // Set the parameters on the block decl. 13266 if (!Params.empty()) { 13267 CurBlock->TheDecl->setParams(Params); 13268 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13269 /*CheckParameterNames=*/false); 13270 } 13271 13272 // Finally we can process decl attributes. 13273 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13274 13275 // Put the parameter variables in scope. 13276 for (auto AI : CurBlock->TheDecl->parameters()) { 13277 AI->setOwningFunction(CurBlock->TheDecl); 13278 13279 // If this has an identifier, add it to the scope stack. 13280 if (AI->getIdentifier()) { 13281 CheckShadow(CurBlock->TheScope, AI); 13282 13283 PushOnScopeChains(AI, CurBlock->TheScope); 13284 } 13285 } 13286 } 13287 13288 /// ActOnBlockError - If there is an error parsing a block, this callback 13289 /// is invoked to pop the information about the block from the action impl. 13290 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13291 // Leave the expression-evaluation context. 13292 DiscardCleanupsInEvaluationContext(); 13293 PopExpressionEvaluationContext(); 13294 13295 // Pop off CurBlock, handle nested blocks. 13296 PopDeclContext(); 13297 PopFunctionScopeInfo(); 13298 } 13299 13300 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13301 /// literal was successfully completed. ^(int x){...} 13302 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13303 Stmt *Body, Scope *CurScope) { 13304 // If blocks are disabled, emit an error. 13305 if (!LangOpts.Blocks) 13306 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13307 13308 // Leave the expression-evaluation context. 13309 if (hasAnyUnrecoverableErrorsInThisFunction()) 13310 DiscardCleanupsInEvaluationContext(); 13311 assert(!Cleanup.exprNeedsCleanups() && 13312 "cleanups within block not correctly bound!"); 13313 PopExpressionEvaluationContext(); 13314 13315 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13316 13317 if (BSI->HasImplicitReturnType) 13318 deduceClosureReturnType(*BSI); 13319 13320 PopDeclContext(); 13321 13322 QualType RetTy = Context.VoidTy; 13323 if (!BSI->ReturnType.isNull()) 13324 RetTy = BSI->ReturnType; 13325 13326 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13327 QualType BlockTy; 13328 13329 // Set the captured variables on the block. 13330 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13331 SmallVector<BlockDecl::Capture, 4> Captures; 13332 for (Capture &Cap : BSI->Captures) { 13333 if (Cap.isThisCapture()) 13334 continue; 13335 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13336 Cap.isNested(), Cap.getInitExpr()); 13337 Captures.push_back(NewCap); 13338 } 13339 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13340 13341 // If the user wrote a function type in some form, try to use that. 13342 if (!BSI->FunctionType.isNull()) { 13343 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13344 13345 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13346 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13347 13348 // Turn protoless block types into nullary block types. 13349 if (isa<FunctionNoProtoType>(FTy)) { 13350 FunctionProtoType::ExtProtoInfo EPI; 13351 EPI.ExtInfo = Ext; 13352 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13353 13354 // Otherwise, if we don't need to change anything about the function type, 13355 // preserve its sugar structure. 13356 } else if (FTy->getReturnType() == RetTy && 13357 (!NoReturn || FTy->getNoReturnAttr())) { 13358 BlockTy = BSI->FunctionType; 13359 13360 // Otherwise, make the minimal modifications to the function type. 13361 } else { 13362 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13363 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13364 EPI.TypeQuals = 0; // FIXME: silently? 13365 EPI.ExtInfo = Ext; 13366 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13367 } 13368 13369 // If we don't have a function type, just build one from nothing. 13370 } else { 13371 FunctionProtoType::ExtProtoInfo EPI; 13372 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13373 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13374 } 13375 13376 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13377 BlockTy = Context.getBlockPointerType(BlockTy); 13378 13379 // If needed, diagnose invalid gotos and switches in the block. 13380 if (getCurFunction()->NeedsScopeChecking() && 13381 !PP.isCodeCompletionEnabled()) 13382 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13383 13384 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13385 13386 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13387 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13388 13389 // Try to apply the named return value optimization. We have to check again 13390 // if we can do this, though, because blocks keep return statements around 13391 // to deduce an implicit return type. 13392 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13393 !BSI->TheDecl->isDependentContext()) 13394 computeNRVO(Body, BSI); 13395 13396 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13397 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13398 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13399 13400 // If the block isn't obviously global, i.e. it captures anything at 13401 // all, then we need to do a few things in the surrounding context: 13402 if (Result->getBlockDecl()->hasCaptures()) { 13403 // First, this expression has a new cleanup object. 13404 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13405 Cleanup.setExprNeedsCleanups(true); 13406 13407 // It also gets a branch-protected scope if any of the captured 13408 // variables needs destruction. 13409 for (const auto &CI : Result->getBlockDecl()->captures()) { 13410 const VarDecl *var = CI.getVariable(); 13411 if (var->getType().isDestructedType() != QualType::DK_none) { 13412 setFunctionHasBranchProtectedScope(); 13413 break; 13414 } 13415 } 13416 } 13417 13418 return Result; 13419 } 13420 13421 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13422 SourceLocation RPLoc) { 13423 TypeSourceInfo *TInfo; 13424 GetTypeFromParser(Ty, &TInfo); 13425 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13426 } 13427 13428 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13429 Expr *E, TypeSourceInfo *TInfo, 13430 SourceLocation RPLoc) { 13431 Expr *OrigExpr = E; 13432 bool IsMS = false; 13433 13434 // CUDA device code does not support varargs. 13435 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13436 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13437 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13438 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13439 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13440 } 13441 } 13442 13443 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13444 // as Microsoft ABI on an actual Microsoft platform, where 13445 // __builtin_ms_va_list and __builtin_va_list are the same.) 13446 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13447 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13448 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13449 if (Context.hasSameType(MSVaListType, E->getType())) { 13450 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13451 return ExprError(); 13452 IsMS = true; 13453 } 13454 } 13455 13456 // Get the va_list type 13457 QualType VaListType = Context.getBuiltinVaListType(); 13458 if (!IsMS) { 13459 if (VaListType->isArrayType()) { 13460 // Deal with implicit array decay; for example, on x86-64, 13461 // va_list is an array, but it's supposed to decay to 13462 // a pointer for va_arg. 13463 VaListType = Context.getArrayDecayedType(VaListType); 13464 // Make sure the input expression also decays appropriately. 13465 ExprResult Result = UsualUnaryConversions(E); 13466 if (Result.isInvalid()) 13467 return ExprError(); 13468 E = Result.get(); 13469 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13470 // If va_list is a record type and we are compiling in C++ mode, 13471 // check the argument using reference binding. 13472 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13473 Context, Context.getLValueReferenceType(VaListType), false); 13474 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13475 if (Init.isInvalid()) 13476 return ExprError(); 13477 E = Init.getAs<Expr>(); 13478 } else { 13479 // Otherwise, the va_list argument must be an l-value because 13480 // it is modified by va_arg. 13481 if (!E->isTypeDependent() && 13482 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13483 return ExprError(); 13484 } 13485 } 13486 13487 if (!IsMS && !E->isTypeDependent() && 13488 !Context.hasSameType(VaListType, E->getType())) 13489 return ExprError(Diag(E->getLocStart(), 13490 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13491 << OrigExpr->getType() << E->getSourceRange()); 13492 13493 if (!TInfo->getType()->isDependentType()) { 13494 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13495 diag::err_second_parameter_to_va_arg_incomplete, 13496 TInfo->getTypeLoc())) 13497 return ExprError(); 13498 13499 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13500 TInfo->getType(), 13501 diag::err_second_parameter_to_va_arg_abstract, 13502 TInfo->getTypeLoc())) 13503 return ExprError(); 13504 13505 if (!TInfo->getType().isPODType(Context)) { 13506 Diag(TInfo->getTypeLoc().getBeginLoc(), 13507 TInfo->getType()->isObjCLifetimeType() 13508 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13509 : diag::warn_second_parameter_to_va_arg_not_pod) 13510 << TInfo->getType() 13511 << TInfo->getTypeLoc().getSourceRange(); 13512 } 13513 13514 // Check for va_arg where arguments of the given type will be promoted 13515 // (i.e. this va_arg is guaranteed to have undefined behavior). 13516 QualType PromoteType; 13517 if (TInfo->getType()->isPromotableIntegerType()) { 13518 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13519 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13520 PromoteType = QualType(); 13521 } 13522 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13523 PromoteType = Context.DoubleTy; 13524 if (!PromoteType.isNull()) 13525 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13526 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13527 << TInfo->getType() 13528 << PromoteType 13529 << TInfo->getTypeLoc().getSourceRange()); 13530 } 13531 13532 QualType T = TInfo->getType().getNonLValueExprType(Context); 13533 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13534 } 13535 13536 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13537 // The type of __null will be int or long, depending on the size of 13538 // pointers on the target. 13539 QualType Ty; 13540 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13541 if (pw == Context.getTargetInfo().getIntWidth()) 13542 Ty = Context.IntTy; 13543 else if (pw == Context.getTargetInfo().getLongWidth()) 13544 Ty = Context.LongTy; 13545 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13546 Ty = Context.LongLongTy; 13547 else { 13548 llvm_unreachable("I don't know size of pointer!"); 13549 } 13550 13551 return new (Context) GNUNullExpr(Ty, TokenLoc); 13552 } 13553 13554 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13555 bool Diagnose) { 13556 if (!getLangOpts().ObjC1) 13557 return false; 13558 13559 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13560 if (!PT) 13561 return false; 13562 13563 if (!PT->isObjCIdType()) { 13564 // Check if the destination is the 'NSString' interface. 13565 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13566 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13567 return false; 13568 } 13569 13570 // Ignore any parens, implicit casts (should only be 13571 // array-to-pointer decays), and not-so-opaque values. The last is 13572 // important for making this trigger for property assignments. 13573 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13574 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13575 if (OV->getSourceExpr()) 13576 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13577 13578 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13579 if (!SL || !SL->isAscii()) 13580 return false; 13581 if (Diagnose) { 13582 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13583 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13584 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13585 } 13586 return true; 13587 } 13588 13589 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13590 const Expr *SrcExpr) { 13591 if (!DstType->isFunctionPointerType() || 13592 !SrcExpr->getType()->isFunctionType()) 13593 return false; 13594 13595 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13596 if (!DRE) 13597 return false; 13598 13599 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13600 if (!FD) 13601 return false; 13602 13603 return !S.checkAddressOfFunctionIsAvailable(FD, 13604 /*Complain=*/true, 13605 SrcExpr->getLocStart()); 13606 } 13607 13608 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13609 SourceLocation Loc, 13610 QualType DstType, QualType SrcType, 13611 Expr *SrcExpr, AssignmentAction Action, 13612 bool *Complained) { 13613 if (Complained) 13614 *Complained = false; 13615 13616 // Decode the result (notice that AST's are still created for extensions). 13617 bool CheckInferredResultType = false; 13618 bool isInvalid = false; 13619 unsigned DiagKind = 0; 13620 FixItHint Hint; 13621 ConversionFixItGenerator ConvHints; 13622 bool MayHaveConvFixit = false; 13623 bool MayHaveFunctionDiff = false; 13624 const ObjCInterfaceDecl *IFace = nullptr; 13625 const ObjCProtocolDecl *PDecl = nullptr; 13626 13627 switch (ConvTy) { 13628 case Compatible: 13629 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13630 return false; 13631 13632 case PointerToInt: 13633 DiagKind = diag::ext_typecheck_convert_pointer_int; 13634 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13635 MayHaveConvFixit = true; 13636 break; 13637 case IntToPointer: 13638 DiagKind = diag::ext_typecheck_convert_int_pointer; 13639 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13640 MayHaveConvFixit = true; 13641 break; 13642 case IncompatiblePointer: 13643 if (Action == AA_Passing_CFAudited) 13644 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13645 else if (SrcType->isFunctionPointerType() && 13646 DstType->isFunctionPointerType()) 13647 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13648 else 13649 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13650 13651 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13652 SrcType->isObjCObjectPointerType(); 13653 if (Hint.isNull() && !CheckInferredResultType) { 13654 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13655 } 13656 else if (CheckInferredResultType) { 13657 SrcType = SrcType.getUnqualifiedType(); 13658 DstType = DstType.getUnqualifiedType(); 13659 } 13660 MayHaveConvFixit = true; 13661 break; 13662 case IncompatiblePointerSign: 13663 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13664 break; 13665 case FunctionVoidPointer: 13666 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13667 break; 13668 case IncompatiblePointerDiscardsQualifiers: { 13669 // Perform array-to-pointer decay if necessary. 13670 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13671 13672 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13673 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13674 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13675 DiagKind = diag::err_typecheck_incompatible_address_space; 13676 break; 13677 13678 13679 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13680 DiagKind = diag::err_typecheck_incompatible_ownership; 13681 break; 13682 } 13683 13684 llvm_unreachable("unknown error case for discarding qualifiers!"); 13685 // fallthrough 13686 } 13687 case CompatiblePointerDiscardsQualifiers: 13688 // If the qualifiers lost were because we were applying the 13689 // (deprecated) C++ conversion from a string literal to a char* 13690 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13691 // Ideally, this check would be performed in 13692 // checkPointerTypesForAssignment. However, that would require a 13693 // bit of refactoring (so that the second argument is an 13694 // expression, rather than a type), which should be done as part 13695 // of a larger effort to fix checkPointerTypesForAssignment for 13696 // C++ semantics. 13697 if (getLangOpts().CPlusPlus && 13698 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13699 return false; 13700 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13701 break; 13702 case IncompatibleNestedPointerQualifiers: 13703 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13704 break; 13705 case IntToBlockPointer: 13706 DiagKind = diag::err_int_to_block_pointer; 13707 break; 13708 case IncompatibleBlockPointer: 13709 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13710 break; 13711 case IncompatibleObjCQualifiedId: { 13712 if (SrcType->isObjCQualifiedIdType()) { 13713 const ObjCObjectPointerType *srcOPT = 13714 SrcType->getAs<ObjCObjectPointerType>(); 13715 for (auto *srcProto : srcOPT->quals()) { 13716 PDecl = srcProto; 13717 break; 13718 } 13719 if (const ObjCInterfaceType *IFaceT = 13720 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13721 IFace = IFaceT->getDecl(); 13722 } 13723 else if (DstType->isObjCQualifiedIdType()) { 13724 const ObjCObjectPointerType *dstOPT = 13725 DstType->getAs<ObjCObjectPointerType>(); 13726 for (auto *dstProto : dstOPT->quals()) { 13727 PDecl = dstProto; 13728 break; 13729 } 13730 if (const ObjCInterfaceType *IFaceT = 13731 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13732 IFace = IFaceT->getDecl(); 13733 } 13734 DiagKind = diag::warn_incompatible_qualified_id; 13735 break; 13736 } 13737 case IncompatibleVectors: 13738 DiagKind = diag::warn_incompatible_vectors; 13739 break; 13740 case IncompatibleObjCWeakRef: 13741 DiagKind = diag::err_arc_weak_unavailable_assign; 13742 break; 13743 case Incompatible: 13744 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13745 if (Complained) 13746 *Complained = true; 13747 return true; 13748 } 13749 13750 DiagKind = diag::err_typecheck_convert_incompatible; 13751 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13752 MayHaveConvFixit = true; 13753 isInvalid = true; 13754 MayHaveFunctionDiff = true; 13755 break; 13756 } 13757 13758 QualType FirstType, SecondType; 13759 switch (Action) { 13760 case AA_Assigning: 13761 case AA_Initializing: 13762 // The destination type comes first. 13763 FirstType = DstType; 13764 SecondType = SrcType; 13765 break; 13766 13767 case AA_Returning: 13768 case AA_Passing: 13769 case AA_Passing_CFAudited: 13770 case AA_Converting: 13771 case AA_Sending: 13772 case AA_Casting: 13773 // The source type comes first. 13774 FirstType = SrcType; 13775 SecondType = DstType; 13776 break; 13777 } 13778 13779 PartialDiagnostic FDiag = PDiag(DiagKind); 13780 if (Action == AA_Passing_CFAudited) 13781 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13782 else 13783 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13784 13785 // If we can fix the conversion, suggest the FixIts. 13786 assert(ConvHints.isNull() || Hint.isNull()); 13787 if (!ConvHints.isNull()) { 13788 for (FixItHint &H : ConvHints.Hints) 13789 FDiag << H; 13790 } else { 13791 FDiag << Hint; 13792 } 13793 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13794 13795 if (MayHaveFunctionDiff) 13796 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13797 13798 Diag(Loc, FDiag); 13799 if (DiagKind == diag::warn_incompatible_qualified_id && 13800 PDecl && IFace && !IFace->hasDefinition()) 13801 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13802 << IFace << PDecl; 13803 13804 if (SecondType == Context.OverloadTy) 13805 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13806 FirstType, /*TakingAddress=*/true); 13807 13808 if (CheckInferredResultType) 13809 EmitRelatedResultTypeNote(SrcExpr); 13810 13811 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13812 EmitRelatedResultTypeNoteForReturn(DstType); 13813 13814 if (Complained) 13815 *Complained = true; 13816 return isInvalid; 13817 } 13818 13819 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13820 llvm::APSInt *Result) { 13821 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13822 public: 13823 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13824 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13825 } 13826 } Diagnoser; 13827 13828 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13829 } 13830 13831 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13832 llvm::APSInt *Result, 13833 unsigned DiagID, 13834 bool AllowFold) { 13835 class IDDiagnoser : public VerifyICEDiagnoser { 13836 unsigned DiagID; 13837 13838 public: 13839 IDDiagnoser(unsigned DiagID) 13840 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13841 13842 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13843 S.Diag(Loc, DiagID) << SR; 13844 } 13845 } Diagnoser(DiagID); 13846 13847 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13848 } 13849 13850 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13851 SourceRange SR) { 13852 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13853 } 13854 13855 ExprResult 13856 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13857 VerifyICEDiagnoser &Diagnoser, 13858 bool AllowFold) { 13859 SourceLocation DiagLoc = E->getLocStart(); 13860 13861 if (getLangOpts().CPlusPlus11) { 13862 // C++11 [expr.const]p5: 13863 // If an expression of literal class type is used in a context where an 13864 // integral constant expression is required, then that class type shall 13865 // have a single non-explicit conversion function to an integral or 13866 // unscoped enumeration type 13867 ExprResult Converted; 13868 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13869 public: 13870 CXX11ConvertDiagnoser(bool Silent) 13871 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13872 Silent, true) {} 13873 13874 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13875 QualType T) override { 13876 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13877 } 13878 13879 SemaDiagnosticBuilder diagnoseIncomplete( 13880 Sema &S, SourceLocation Loc, QualType T) override { 13881 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13882 } 13883 13884 SemaDiagnosticBuilder diagnoseExplicitConv( 13885 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13886 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13887 } 13888 13889 SemaDiagnosticBuilder noteExplicitConv( 13890 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13891 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13892 << ConvTy->isEnumeralType() << ConvTy; 13893 } 13894 13895 SemaDiagnosticBuilder diagnoseAmbiguous( 13896 Sema &S, SourceLocation Loc, QualType T) override { 13897 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13898 } 13899 13900 SemaDiagnosticBuilder noteAmbiguous( 13901 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13902 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13903 << ConvTy->isEnumeralType() << ConvTy; 13904 } 13905 13906 SemaDiagnosticBuilder diagnoseConversion( 13907 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13908 llvm_unreachable("conversion functions are permitted"); 13909 } 13910 } ConvertDiagnoser(Diagnoser.Suppress); 13911 13912 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13913 ConvertDiagnoser); 13914 if (Converted.isInvalid()) 13915 return Converted; 13916 E = Converted.get(); 13917 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13918 return ExprError(); 13919 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13920 // An ICE must be of integral or unscoped enumeration type. 13921 if (!Diagnoser.Suppress) 13922 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13923 return ExprError(); 13924 } 13925 13926 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13927 // in the non-ICE case. 13928 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13929 if (Result) 13930 *Result = E->EvaluateKnownConstInt(Context); 13931 return E; 13932 } 13933 13934 Expr::EvalResult EvalResult; 13935 SmallVector<PartialDiagnosticAt, 8> Notes; 13936 EvalResult.Diag = &Notes; 13937 13938 // Try to evaluate the expression, and produce diagnostics explaining why it's 13939 // not a constant expression as a side-effect. 13940 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13941 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13942 13943 // In C++11, we can rely on diagnostics being produced for any expression 13944 // which is not a constant expression. If no diagnostics were produced, then 13945 // this is a constant expression. 13946 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13947 if (Result) 13948 *Result = EvalResult.Val.getInt(); 13949 return E; 13950 } 13951 13952 // If our only note is the usual "invalid subexpression" note, just point 13953 // the caret at its location rather than producing an essentially 13954 // redundant note. 13955 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13956 diag::note_invalid_subexpr_in_const_expr) { 13957 DiagLoc = Notes[0].first; 13958 Notes.clear(); 13959 } 13960 13961 if (!Folded || !AllowFold) { 13962 if (!Diagnoser.Suppress) { 13963 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13964 for (const PartialDiagnosticAt &Note : Notes) 13965 Diag(Note.first, Note.second); 13966 } 13967 13968 return ExprError(); 13969 } 13970 13971 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13972 for (const PartialDiagnosticAt &Note : Notes) 13973 Diag(Note.first, Note.second); 13974 13975 if (Result) 13976 *Result = EvalResult.Val.getInt(); 13977 return E; 13978 } 13979 13980 namespace { 13981 // Handle the case where we conclude a expression which we speculatively 13982 // considered to be unevaluated is actually evaluated. 13983 class TransformToPE : public TreeTransform<TransformToPE> { 13984 typedef TreeTransform<TransformToPE> BaseTransform; 13985 13986 public: 13987 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13988 13989 // Make sure we redo semantic analysis 13990 bool AlwaysRebuild() { return true; } 13991 13992 // Make sure we handle LabelStmts correctly. 13993 // FIXME: This does the right thing, but maybe we need a more general 13994 // fix to TreeTransform? 13995 StmtResult TransformLabelStmt(LabelStmt *S) { 13996 S->getDecl()->setStmt(nullptr); 13997 return BaseTransform::TransformLabelStmt(S); 13998 } 13999 14000 // We need to special-case DeclRefExprs referring to FieldDecls which 14001 // are not part of a member pointer formation; normal TreeTransforming 14002 // doesn't catch this case because of the way we represent them in the AST. 14003 // FIXME: This is a bit ugly; is it really the best way to handle this 14004 // case? 14005 // 14006 // Error on DeclRefExprs referring to FieldDecls. 14007 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14008 if (isa<FieldDecl>(E->getDecl()) && 14009 !SemaRef.isUnevaluatedContext()) 14010 return SemaRef.Diag(E->getLocation(), 14011 diag::err_invalid_non_static_member_use) 14012 << E->getDecl() << E->getSourceRange(); 14013 14014 return BaseTransform::TransformDeclRefExpr(E); 14015 } 14016 14017 // Exception: filter out member pointer formation 14018 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14019 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14020 return E; 14021 14022 return BaseTransform::TransformUnaryOperator(E); 14023 } 14024 14025 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14026 // Lambdas never need to be transformed. 14027 return E; 14028 } 14029 }; 14030 } 14031 14032 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14033 assert(isUnevaluatedContext() && 14034 "Should only transform unevaluated expressions"); 14035 ExprEvalContexts.back().Context = 14036 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14037 if (isUnevaluatedContext()) 14038 return E; 14039 return TransformToPE(*this).TransformExpr(E); 14040 } 14041 14042 void 14043 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 14044 Decl *LambdaContextDecl, 14045 bool IsDecltype) { 14046 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14047 LambdaContextDecl, IsDecltype); 14048 Cleanup.reset(); 14049 if (!MaybeODRUseExprs.empty()) 14050 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14051 } 14052 14053 void 14054 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 14055 ReuseLambdaContextDecl_t, 14056 bool IsDecltype) { 14057 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14058 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 14059 } 14060 14061 void Sema::PopExpressionEvaluationContext() { 14062 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14063 unsigned NumTypos = Rec.NumTypos; 14064 14065 if (!Rec.Lambdas.empty()) { 14066 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14067 unsigned D; 14068 if (Rec.isUnevaluated()) { 14069 // C++11 [expr.prim.lambda]p2: 14070 // A lambda-expression shall not appear in an unevaluated operand 14071 // (Clause 5). 14072 D = diag::err_lambda_unevaluated_operand; 14073 } else { 14074 // C++1y [expr.const]p2: 14075 // A conditional-expression e is a core constant expression unless the 14076 // evaluation of e, following the rules of the abstract machine, would 14077 // evaluate [...] a lambda-expression. 14078 D = diag::err_lambda_in_constant_expression; 14079 } 14080 14081 // C++1z allows lambda expressions as core constant expressions. 14082 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 14083 // 1607) from appearing within template-arguments and array-bounds that 14084 // are part of function-signatures. Be mindful that P0315 (Lambdas in 14085 // unevaluated contexts) might lift some of these restrictions in a 14086 // future version. 14087 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 14088 for (const auto *L : Rec.Lambdas) 14089 Diag(L->getLocStart(), D); 14090 } else { 14091 // Mark the capture expressions odr-used. This was deferred 14092 // during lambda expression creation. 14093 for (auto *Lambda : Rec.Lambdas) { 14094 for (auto *C : Lambda->capture_inits()) 14095 MarkDeclarationsReferencedInExpr(C); 14096 } 14097 } 14098 } 14099 14100 // When are coming out of an unevaluated context, clear out any 14101 // temporaries that we may have created as part of the evaluation of 14102 // the expression in that context: they aren't relevant because they 14103 // will never be constructed. 14104 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14105 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14106 ExprCleanupObjects.end()); 14107 Cleanup = Rec.ParentCleanup; 14108 CleanupVarDeclMarking(); 14109 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14110 // Otherwise, merge the contexts together. 14111 } else { 14112 Cleanup.mergeFrom(Rec.ParentCleanup); 14113 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14114 Rec.SavedMaybeODRUseExprs.end()); 14115 } 14116 14117 // Pop the current expression evaluation context off the stack. 14118 ExprEvalContexts.pop_back(); 14119 14120 if (!ExprEvalContexts.empty()) 14121 ExprEvalContexts.back().NumTypos += NumTypos; 14122 else 14123 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14124 "last ExpressionEvaluationContextRecord"); 14125 } 14126 14127 void Sema::DiscardCleanupsInEvaluationContext() { 14128 ExprCleanupObjects.erase( 14129 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14130 ExprCleanupObjects.end()); 14131 Cleanup.reset(); 14132 MaybeODRUseExprs.clear(); 14133 } 14134 14135 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14136 if (!E->getType()->isVariablyModifiedType()) 14137 return E; 14138 return TransformToPotentiallyEvaluated(E); 14139 } 14140 14141 /// Are we within a context in which some evaluation could be performed (be it 14142 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14143 /// captured by C++'s idea of an "unevaluated context". 14144 static bool isEvaluatableContext(Sema &SemaRef) { 14145 switch (SemaRef.ExprEvalContexts.back().Context) { 14146 case Sema::ExpressionEvaluationContext::Unevaluated: 14147 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14148 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14149 // Expressions in this context are never evaluated. 14150 return false; 14151 14152 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14153 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14154 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14155 // Expressions in this context could be evaluated. 14156 return true; 14157 14158 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14159 // Referenced declarations will only be used if the construct in the 14160 // containing expression is used, at which point we'll be given another 14161 // turn to mark them. 14162 return false; 14163 } 14164 llvm_unreachable("Invalid context"); 14165 } 14166 14167 /// Are we within a context in which references to resolved functions or to 14168 /// variables result in odr-use? 14169 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14170 // An expression in a template is not really an expression until it's been 14171 // instantiated, so it doesn't trigger odr-use. 14172 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14173 return false; 14174 14175 switch (SemaRef.ExprEvalContexts.back().Context) { 14176 case Sema::ExpressionEvaluationContext::Unevaluated: 14177 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14178 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14179 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14180 return false; 14181 14182 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14183 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14184 return true; 14185 14186 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14187 return false; 14188 } 14189 llvm_unreachable("Invalid context"); 14190 } 14191 14192 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14193 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14194 return Func->isConstexpr() && 14195 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14196 } 14197 14198 /// \brief Mark a function referenced, and check whether it is odr-used 14199 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14200 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14201 bool MightBeOdrUse) { 14202 assert(Func && "No function?"); 14203 14204 Func->setReferenced(); 14205 14206 // C++11 [basic.def.odr]p3: 14207 // A function whose name appears as a potentially-evaluated expression is 14208 // odr-used if it is the unique lookup result or the selected member of a 14209 // set of overloaded functions [...]. 14210 // 14211 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14212 // can just check that here. 14213 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14214 14215 // Determine whether we require a function definition to exist, per 14216 // C++11 [temp.inst]p3: 14217 // Unless a function template specialization has been explicitly 14218 // instantiated or explicitly specialized, the function template 14219 // specialization is implicitly instantiated when the specialization is 14220 // referenced in a context that requires a function definition to exist. 14221 // 14222 // That is either when this is an odr-use, or when a usage of a constexpr 14223 // function occurs within an evaluatable context. 14224 bool NeedDefinition = 14225 OdrUse || (isEvaluatableContext(*this) && 14226 isImplicitlyDefinableConstexprFunction(Func)); 14227 14228 // C++14 [temp.expl.spec]p6: 14229 // If a template [...] is explicitly specialized then that specialization 14230 // shall be declared before the first use of that specialization that would 14231 // cause an implicit instantiation to take place, in every translation unit 14232 // in which such a use occurs 14233 if (NeedDefinition && 14234 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14235 Func->getMemberSpecializationInfo())) 14236 checkSpecializationVisibility(Loc, Func); 14237 14238 // C++14 [except.spec]p17: 14239 // An exception-specification is considered to be needed when: 14240 // - the function is odr-used or, if it appears in an unevaluated operand, 14241 // would be odr-used if the expression were potentially-evaluated; 14242 // 14243 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14244 // function is a pure virtual function we're calling, and in that case the 14245 // function was selected by overload resolution and we need to resolve its 14246 // exception specification for a different reason. 14247 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14248 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14249 ResolveExceptionSpec(Loc, FPT); 14250 14251 // If we don't need to mark the function as used, and we don't need to 14252 // try to provide a definition, there's nothing more to do. 14253 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14254 (!NeedDefinition || Func->getBody())) 14255 return; 14256 14257 // Note that this declaration has been used. 14258 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14259 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14260 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14261 if (Constructor->isDefaultConstructor()) { 14262 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14263 return; 14264 DefineImplicitDefaultConstructor(Loc, Constructor); 14265 } else if (Constructor->isCopyConstructor()) { 14266 DefineImplicitCopyConstructor(Loc, Constructor); 14267 } else if (Constructor->isMoveConstructor()) { 14268 DefineImplicitMoveConstructor(Loc, Constructor); 14269 } 14270 } else if (Constructor->getInheritedConstructor()) { 14271 DefineInheritingConstructor(Loc, Constructor); 14272 } 14273 } else if (CXXDestructorDecl *Destructor = 14274 dyn_cast<CXXDestructorDecl>(Func)) { 14275 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14276 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14277 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14278 return; 14279 DefineImplicitDestructor(Loc, Destructor); 14280 } 14281 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14282 MarkVTableUsed(Loc, Destructor->getParent()); 14283 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14284 if (MethodDecl->isOverloadedOperator() && 14285 MethodDecl->getOverloadedOperator() == OO_Equal) { 14286 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14287 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14288 if (MethodDecl->isCopyAssignmentOperator()) 14289 DefineImplicitCopyAssignment(Loc, MethodDecl); 14290 else if (MethodDecl->isMoveAssignmentOperator()) 14291 DefineImplicitMoveAssignment(Loc, MethodDecl); 14292 } 14293 } else if (isa<CXXConversionDecl>(MethodDecl) && 14294 MethodDecl->getParent()->isLambda()) { 14295 CXXConversionDecl *Conversion = 14296 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14297 if (Conversion->isLambdaToBlockPointerConversion()) 14298 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14299 else 14300 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14301 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14302 MarkVTableUsed(Loc, MethodDecl->getParent()); 14303 } 14304 14305 // Recursive functions should be marked when used from another function. 14306 // FIXME: Is this really right? 14307 if (CurContext == Func) return; 14308 14309 // Implicit instantiation of function templates and member functions of 14310 // class templates. 14311 if (Func->isImplicitlyInstantiable()) { 14312 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14313 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14314 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14315 if (FirstInstantiation) { 14316 PointOfInstantiation = Loc; 14317 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14318 } else if (TSK != TSK_ImplicitInstantiation) { 14319 // Use the point of use as the point of instantiation, instead of the 14320 // point of explicit instantiation (which we track as the actual point of 14321 // instantiation). This gives better backtraces in diagnostics. 14322 PointOfInstantiation = Loc; 14323 } 14324 14325 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14326 Func->isConstexpr()) { 14327 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14328 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14329 CodeSynthesisContexts.size()) 14330 PendingLocalImplicitInstantiations.push_back( 14331 std::make_pair(Func, PointOfInstantiation)); 14332 else if (Func->isConstexpr()) 14333 // Do not defer instantiations of constexpr functions, to avoid the 14334 // expression evaluator needing to call back into Sema if it sees a 14335 // call to such a function. 14336 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14337 else { 14338 Func->setInstantiationIsPending(true); 14339 PendingInstantiations.push_back(std::make_pair(Func, 14340 PointOfInstantiation)); 14341 // Notify the consumer that a function was implicitly instantiated. 14342 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14343 } 14344 } 14345 } else { 14346 // Walk redefinitions, as some of them may be instantiable. 14347 for (auto i : Func->redecls()) { 14348 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14349 MarkFunctionReferenced(Loc, i, OdrUse); 14350 } 14351 } 14352 14353 if (!OdrUse) return; 14354 14355 // Keep track of used but undefined functions. 14356 if (!Func->isDefined()) { 14357 if (mightHaveNonExternalLinkage(Func)) 14358 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14359 else if (Func->getMostRecentDecl()->isInlined() && 14360 !LangOpts.GNUInline && 14361 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14362 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14363 else if (isExternalWithNoLinkageType(Func)) 14364 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14365 } 14366 14367 Func->markUsed(Context); 14368 } 14369 14370 static void 14371 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14372 ValueDecl *var, DeclContext *DC) { 14373 DeclContext *VarDC = var->getDeclContext(); 14374 14375 // If the parameter still belongs to the translation unit, then 14376 // we're actually just using one parameter in the declaration of 14377 // the next. 14378 if (isa<ParmVarDecl>(var) && 14379 isa<TranslationUnitDecl>(VarDC)) 14380 return; 14381 14382 // For C code, don't diagnose about capture if we're not actually in code 14383 // right now; it's impossible to write a non-constant expression outside of 14384 // function context, so we'll get other (more useful) diagnostics later. 14385 // 14386 // For C++, things get a bit more nasty... it would be nice to suppress this 14387 // diagnostic for certain cases like using a local variable in an array bound 14388 // for a member of a local class, but the correct predicate is not obvious. 14389 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14390 return; 14391 14392 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14393 unsigned ContextKind = 3; // unknown 14394 if (isa<CXXMethodDecl>(VarDC) && 14395 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14396 ContextKind = 2; 14397 } else if (isa<FunctionDecl>(VarDC)) { 14398 ContextKind = 0; 14399 } else if (isa<BlockDecl>(VarDC)) { 14400 ContextKind = 1; 14401 } 14402 14403 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14404 << var << ValueKind << ContextKind << VarDC; 14405 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14406 << var; 14407 14408 // FIXME: Add additional diagnostic info about class etc. which prevents 14409 // capture. 14410 } 14411 14412 14413 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14414 bool &SubCapturesAreNested, 14415 QualType &CaptureType, 14416 QualType &DeclRefType) { 14417 // Check whether we've already captured it. 14418 if (CSI->CaptureMap.count(Var)) { 14419 // If we found a capture, any subcaptures are nested. 14420 SubCapturesAreNested = true; 14421 14422 // Retrieve the capture type for this variable. 14423 CaptureType = CSI->getCapture(Var).getCaptureType(); 14424 14425 // Compute the type of an expression that refers to this variable. 14426 DeclRefType = CaptureType.getNonReferenceType(); 14427 14428 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14429 // are mutable in the sense that user can change their value - they are 14430 // private instances of the captured declarations. 14431 const Capture &Cap = CSI->getCapture(Var); 14432 if (Cap.isCopyCapture() && 14433 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14434 !(isa<CapturedRegionScopeInfo>(CSI) && 14435 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14436 DeclRefType.addConst(); 14437 return true; 14438 } 14439 return false; 14440 } 14441 14442 // Only block literals, captured statements, and lambda expressions can 14443 // capture; other scopes don't work. 14444 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14445 SourceLocation Loc, 14446 const bool Diagnose, Sema &S) { 14447 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14448 return getLambdaAwareParentOfDeclContext(DC); 14449 else if (Var->hasLocalStorage()) { 14450 if (Diagnose) 14451 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14452 } 14453 return nullptr; 14454 } 14455 14456 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14457 // certain types of variables (unnamed, variably modified types etc.) 14458 // so check for eligibility. 14459 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14460 SourceLocation Loc, 14461 const bool Diagnose, Sema &S) { 14462 14463 bool IsBlock = isa<BlockScopeInfo>(CSI); 14464 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14465 14466 // Lambdas are not allowed to capture unnamed variables 14467 // (e.g. anonymous unions). 14468 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14469 // assuming that's the intent. 14470 if (IsLambda && !Var->getDeclName()) { 14471 if (Diagnose) { 14472 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14473 S.Diag(Var->getLocation(), diag::note_declared_at); 14474 } 14475 return false; 14476 } 14477 14478 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14479 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14480 if (Diagnose) { 14481 S.Diag(Loc, diag::err_ref_vm_type); 14482 S.Diag(Var->getLocation(), diag::note_previous_decl) 14483 << Var->getDeclName(); 14484 } 14485 return false; 14486 } 14487 // Prohibit structs with flexible array members too. 14488 // We cannot capture what is in the tail end of the struct. 14489 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14490 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14491 if (Diagnose) { 14492 if (IsBlock) 14493 S.Diag(Loc, diag::err_ref_flexarray_type); 14494 else 14495 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14496 << Var->getDeclName(); 14497 S.Diag(Var->getLocation(), diag::note_previous_decl) 14498 << Var->getDeclName(); 14499 } 14500 return false; 14501 } 14502 } 14503 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14504 // Lambdas and captured statements are not allowed to capture __block 14505 // variables; they don't support the expected semantics. 14506 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14507 if (Diagnose) { 14508 S.Diag(Loc, diag::err_capture_block_variable) 14509 << Var->getDeclName() << !IsLambda; 14510 S.Diag(Var->getLocation(), diag::note_previous_decl) 14511 << Var->getDeclName(); 14512 } 14513 return false; 14514 } 14515 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14516 if (S.getLangOpts().OpenCL && IsBlock && 14517 Var->getType()->isBlockPointerType()) { 14518 if (Diagnose) 14519 S.Diag(Loc, diag::err_opencl_block_ref_block); 14520 return false; 14521 } 14522 14523 return true; 14524 } 14525 14526 // Returns true if the capture by block was successful. 14527 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14528 SourceLocation Loc, 14529 const bool BuildAndDiagnose, 14530 QualType &CaptureType, 14531 QualType &DeclRefType, 14532 const bool Nested, 14533 Sema &S) { 14534 Expr *CopyExpr = nullptr; 14535 bool ByRef = false; 14536 14537 // Blocks are not allowed to capture arrays. 14538 if (CaptureType->isArrayType()) { 14539 if (BuildAndDiagnose) { 14540 S.Diag(Loc, diag::err_ref_array_type); 14541 S.Diag(Var->getLocation(), diag::note_previous_decl) 14542 << Var->getDeclName(); 14543 } 14544 return false; 14545 } 14546 14547 // Forbid the block-capture of autoreleasing variables. 14548 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14549 if (BuildAndDiagnose) { 14550 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14551 << /*block*/ 0; 14552 S.Diag(Var->getLocation(), diag::note_previous_decl) 14553 << Var->getDeclName(); 14554 } 14555 return false; 14556 } 14557 14558 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14559 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14560 // This function finds out whether there is an AttributedType of kind 14561 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14562 // attr_objc_ownership implies __autoreleasing was explicitly specified 14563 // rather than being added implicitly by the compiler. 14564 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14565 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14566 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14567 return true; 14568 14569 // Peel off AttributedTypes that are not of kind objc_ownership. 14570 Ty = AttrTy->getModifiedType(); 14571 } 14572 14573 return false; 14574 }; 14575 14576 QualType PointeeTy = PT->getPointeeType(); 14577 14578 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14579 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14580 !IsObjCOwnershipAttributedType(PointeeTy)) { 14581 if (BuildAndDiagnose) { 14582 SourceLocation VarLoc = Var->getLocation(); 14583 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14584 { 14585 auto AddAutoreleaseNote = 14586 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14587 // Provide a fix-it for the '__autoreleasing' keyword at the 14588 // appropriate location in the variable's type. 14589 if (const auto *TSI = Var->getTypeSourceInfo()) { 14590 PointerTypeLoc PTL = 14591 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14592 if (PTL) { 14593 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14594 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14595 S.getLangOpts()); 14596 if (Loc.isValid()) { 14597 StringRef CharAtLoc = Lexer::getSourceText( 14598 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14599 S.getSourceManager(), S.getLangOpts()); 14600 AddAutoreleaseNote << FixItHint::CreateInsertion( 14601 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14602 ? " __autoreleasing " 14603 : " __autoreleasing"); 14604 } 14605 } 14606 } 14607 } 14608 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14609 } 14610 } 14611 } 14612 14613 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14614 if (HasBlocksAttr || CaptureType->isReferenceType() || 14615 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14616 // Block capture by reference does not change the capture or 14617 // declaration reference types. 14618 ByRef = true; 14619 } else { 14620 // Block capture by copy introduces 'const'. 14621 CaptureType = CaptureType.getNonReferenceType().withConst(); 14622 DeclRefType = CaptureType; 14623 14624 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14625 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14626 // The capture logic needs the destructor, so make sure we mark it. 14627 // Usually this is unnecessary because most local variables have 14628 // their destructors marked at declaration time, but parameters are 14629 // an exception because it's technically only the call site that 14630 // actually requires the destructor. 14631 if (isa<ParmVarDecl>(Var)) 14632 S.FinalizeVarWithDestructor(Var, Record); 14633 14634 // Enter a new evaluation context to insulate the copy 14635 // full-expression. 14636 EnterExpressionEvaluationContext scope( 14637 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14638 14639 // According to the blocks spec, the capture of a variable from 14640 // the stack requires a const copy constructor. This is not true 14641 // of the copy/move done to move a __block variable to the heap. 14642 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14643 DeclRefType.withConst(), 14644 VK_LValue, Loc); 14645 14646 ExprResult Result 14647 = S.PerformCopyInitialization( 14648 InitializedEntity::InitializeBlock(Var->getLocation(), 14649 CaptureType, false), 14650 Loc, DeclRef); 14651 14652 // Build a full-expression copy expression if initialization 14653 // succeeded and used a non-trivial constructor. Recover from 14654 // errors by pretending that the copy isn't necessary. 14655 if (!Result.isInvalid() && 14656 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14657 ->isTrivial()) { 14658 Result = S.MaybeCreateExprWithCleanups(Result); 14659 CopyExpr = Result.get(); 14660 } 14661 } 14662 } 14663 } 14664 14665 // Actually capture the variable. 14666 if (BuildAndDiagnose) 14667 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14668 SourceLocation(), CaptureType, CopyExpr); 14669 14670 return true; 14671 14672 } 14673 14674 14675 /// \brief Capture the given variable in the captured region. 14676 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14677 VarDecl *Var, 14678 SourceLocation Loc, 14679 const bool BuildAndDiagnose, 14680 QualType &CaptureType, 14681 QualType &DeclRefType, 14682 const bool RefersToCapturedVariable, 14683 Sema &S) { 14684 // By default, capture variables by reference. 14685 bool ByRef = true; 14686 // Using an LValue reference type is consistent with Lambdas (see below). 14687 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14688 if (S.isOpenMPCapturedDecl(Var)) { 14689 bool HasConst = DeclRefType.isConstQualified(); 14690 DeclRefType = DeclRefType.getUnqualifiedType(); 14691 // Don't lose diagnostics about assignments to const. 14692 if (HasConst) 14693 DeclRefType.addConst(); 14694 } 14695 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14696 } 14697 14698 if (ByRef) 14699 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14700 else 14701 CaptureType = DeclRefType; 14702 14703 Expr *CopyExpr = nullptr; 14704 if (BuildAndDiagnose) { 14705 // The current implementation assumes that all variables are captured 14706 // by references. Since there is no capture by copy, no expression 14707 // evaluation will be needed. 14708 RecordDecl *RD = RSI->TheRecordDecl; 14709 14710 FieldDecl *Field 14711 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14712 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14713 nullptr, false, ICIS_NoInit); 14714 Field->setImplicit(true); 14715 Field->setAccess(AS_private); 14716 RD->addDecl(Field); 14717 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14718 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14719 14720 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14721 DeclRefType, VK_LValue, Loc); 14722 Var->setReferenced(true); 14723 Var->markUsed(S.Context); 14724 } 14725 14726 // Actually capture the variable. 14727 if (BuildAndDiagnose) 14728 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14729 SourceLocation(), CaptureType, CopyExpr); 14730 14731 14732 return true; 14733 } 14734 14735 /// \brief Create a field within the lambda class for the variable 14736 /// being captured. 14737 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14738 QualType FieldType, QualType DeclRefType, 14739 SourceLocation Loc, 14740 bool RefersToCapturedVariable) { 14741 CXXRecordDecl *Lambda = LSI->Lambda; 14742 14743 // Build the non-static data member. 14744 FieldDecl *Field 14745 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14746 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14747 nullptr, false, ICIS_NoInit); 14748 Field->setImplicit(true); 14749 Field->setAccess(AS_private); 14750 Lambda->addDecl(Field); 14751 } 14752 14753 /// \brief Capture the given variable in the lambda. 14754 static bool captureInLambda(LambdaScopeInfo *LSI, 14755 VarDecl *Var, 14756 SourceLocation Loc, 14757 const bool BuildAndDiagnose, 14758 QualType &CaptureType, 14759 QualType &DeclRefType, 14760 const bool RefersToCapturedVariable, 14761 const Sema::TryCaptureKind Kind, 14762 SourceLocation EllipsisLoc, 14763 const bool IsTopScope, 14764 Sema &S) { 14765 14766 // Determine whether we are capturing by reference or by value. 14767 bool ByRef = false; 14768 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14769 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14770 } else { 14771 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14772 } 14773 14774 // Compute the type of the field that will capture this variable. 14775 if (ByRef) { 14776 // C++11 [expr.prim.lambda]p15: 14777 // An entity is captured by reference if it is implicitly or 14778 // explicitly captured but not captured by copy. It is 14779 // unspecified whether additional unnamed non-static data 14780 // members are declared in the closure type for entities 14781 // captured by reference. 14782 // 14783 // FIXME: It is not clear whether we want to build an lvalue reference 14784 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14785 // to do the former, while EDG does the latter. Core issue 1249 will 14786 // clarify, but for now we follow GCC because it's a more permissive and 14787 // easily defensible position. 14788 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14789 } else { 14790 // C++11 [expr.prim.lambda]p14: 14791 // For each entity captured by copy, an unnamed non-static 14792 // data member is declared in the closure type. The 14793 // declaration order of these members is unspecified. The type 14794 // of such a data member is the type of the corresponding 14795 // captured entity if the entity is not a reference to an 14796 // object, or the referenced type otherwise. [Note: If the 14797 // captured entity is a reference to a function, the 14798 // corresponding data member is also a reference to a 14799 // function. - end note ] 14800 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14801 if (!RefType->getPointeeType()->isFunctionType()) 14802 CaptureType = RefType->getPointeeType(); 14803 } 14804 14805 // Forbid the lambda copy-capture of autoreleasing variables. 14806 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14807 if (BuildAndDiagnose) { 14808 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14809 S.Diag(Var->getLocation(), diag::note_previous_decl) 14810 << Var->getDeclName(); 14811 } 14812 return false; 14813 } 14814 14815 // Make sure that by-copy captures are of a complete and non-abstract type. 14816 if (BuildAndDiagnose) { 14817 if (!CaptureType->isDependentType() && 14818 S.RequireCompleteType(Loc, CaptureType, 14819 diag::err_capture_of_incomplete_type, 14820 Var->getDeclName())) 14821 return false; 14822 14823 if (S.RequireNonAbstractType(Loc, CaptureType, 14824 diag::err_capture_of_abstract_type)) 14825 return false; 14826 } 14827 } 14828 14829 // Capture this variable in the lambda. 14830 if (BuildAndDiagnose) 14831 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14832 RefersToCapturedVariable); 14833 14834 // Compute the type of a reference to this captured variable. 14835 if (ByRef) 14836 DeclRefType = CaptureType.getNonReferenceType(); 14837 else { 14838 // C++ [expr.prim.lambda]p5: 14839 // The closure type for a lambda-expression has a public inline 14840 // function call operator [...]. This function call operator is 14841 // declared const (9.3.1) if and only if the lambda-expression's 14842 // parameter-declaration-clause is not followed by mutable. 14843 DeclRefType = CaptureType.getNonReferenceType(); 14844 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14845 DeclRefType.addConst(); 14846 } 14847 14848 // Add the capture. 14849 if (BuildAndDiagnose) 14850 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14851 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14852 14853 return true; 14854 } 14855 14856 bool Sema::tryCaptureVariable( 14857 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14858 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14859 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14860 // An init-capture is notionally from the context surrounding its 14861 // declaration, but its parent DC is the lambda class. 14862 DeclContext *VarDC = Var->getDeclContext(); 14863 if (Var->isInitCapture()) 14864 VarDC = VarDC->getParent(); 14865 14866 DeclContext *DC = CurContext; 14867 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14868 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14869 // We need to sync up the Declaration Context with the 14870 // FunctionScopeIndexToStopAt 14871 if (FunctionScopeIndexToStopAt) { 14872 unsigned FSIndex = FunctionScopes.size() - 1; 14873 while (FSIndex != MaxFunctionScopesIndex) { 14874 DC = getLambdaAwareParentOfDeclContext(DC); 14875 --FSIndex; 14876 } 14877 } 14878 14879 14880 // If the variable is declared in the current context, there is no need to 14881 // capture it. 14882 if (VarDC == DC) return true; 14883 14884 // Capture global variables if it is required to use private copy of this 14885 // variable. 14886 bool IsGlobal = !Var->hasLocalStorage(); 14887 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 14888 return true; 14889 Var = Var->getCanonicalDecl(); 14890 14891 // Walk up the stack to determine whether we can capture the variable, 14892 // performing the "simple" checks that don't depend on type. We stop when 14893 // we've either hit the declared scope of the variable or find an existing 14894 // capture of that variable. We start from the innermost capturing-entity 14895 // (the DC) and ensure that all intervening capturing-entities 14896 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14897 // declcontext can either capture the variable or have already captured 14898 // the variable. 14899 CaptureType = Var->getType(); 14900 DeclRefType = CaptureType.getNonReferenceType(); 14901 bool Nested = false; 14902 bool Explicit = (Kind != TryCapture_Implicit); 14903 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14904 do { 14905 // Only block literals, captured statements, and lambda expressions can 14906 // capture; other scopes don't work. 14907 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14908 ExprLoc, 14909 BuildAndDiagnose, 14910 *this); 14911 // We need to check for the parent *first* because, if we *have* 14912 // private-captured a global variable, we need to recursively capture it in 14913 // intermediate blocks, lambdas, etc. 14914 if (!ParentDC) { 14915 if (IsGlobal) { 14916 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14917 break; 14918 } 14919 return true; 14920 } 14921 14922 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14923 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14924 14925 14926 // Check whether we've already captured it. 14927 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14928 DeclRefType)) { 14929 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14930 break; 14931 } 14932 // If we are instantiating a generic lambda call operator body, 14933 // we do not want to capture new variables. What was captured 14934 // during either a lambdas transformation or initial parsing 14935 // should be used. 14936 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14937 if (BuildAndDiagnose) { 14938 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14939 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14940 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14941 Diag(Var->getLocation(), diag::note_previous_decl) 14942 << Var->getDeclName(); 14943 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14944 } else 14945 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14946 } 14947 return true; 14948 } 14949 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14950 // certain types of variables (unnamed, variably modified types etc.) 14951 // so check for eligibility. 14952 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14953 return true; 14954 14955 // Try to capture variable-length arrays types. 14956 if (Var->getType()->isVariablyModifiedType()) { 14957 // We're going to walk down into the type and look for VLA 14958 // expressions. 14959 QualType QTy = Var->getType(); 14960 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14961 QTy = PVD->getOriginalType(); 14962 captureVariablyModifiedType(Context, QTy, CSI); 14963 } 14964 14965 if (getLangOpts().OpenMP) { 14966 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14967 // OpenMP private variables should not be captured in outer scope, so 14968 // just break here. Similarly, global variables that are captured in a 14969 // target region should not be captured outside the scope of the region. 14970 if (RSI->CapRegionKind == CR_OpenMP) { 14971 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14972 auto IsTargetCap = !IsOpenMPPrivateDecl && 14973 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14974 // When we detect target captures we are looking from inside the 14975 // target region, therefore we need to propagate the capture from the 14976 // enclosing region. Therefore, the capture is not initially nested. 14977 if (IsTargetCap) 14978 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14979 14980 if (IsTargetCap || IsOpenMPPrivateDecl) { 14981 Nested = !IsTargetCap; 14982 DeclRefType = DeclRefType.getUnqualifiedType(); 14983 CaptureType = Context.getLValueReferenceType(DeclRefType); 14984 break; 14985 } 14986 } 14987 } 14988 } 14989 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14990 // No capture-default, and this is not an explicit capture 14991 // so cannot capture this variable. 14992 if (BuildAndDiagnose) { 14993 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14994 Diag(Var->getLocation(), diag::note_previous_decl) 14995 << Var->getDeclName(); 14996 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14997 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14998 diag::note_lambda_decl); 14999 // FIXME: If we error out because an outer lambda can not implicitly 15000 // capture a variable that an inner lambda explicitly captures, we 15001 // should have the inner lambda do the explicit capture - because 15002 // it makes for cleaner diagnostics later. This would purely be done 15003 // so that the diagnostic does not misleadingly claim that a variable 15004 // can not be captured by a lambda implicitly even though it is captured 15005 // explicitly. Suggestion: 15006 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15007 // at the function head 15008 // - cache the StartingDeclContext - this must be a lambda 15009 // - captureInLambda in the innermost lambda the variable. 15010 } 15011 return true; 15012 } 15013 15014 FunctionScopesIndex--; 15015 DC = ParentDC; 15016 Explicit = false; 15017 } while (!VarDC->Equals(DC)); 15018 15019 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15020 // computing the type of the capture at each step, checking type-specific 15021 // requirements, and adding captures if requested. 15022 // If the variable had already been captured previously, we start capturing 15023 // at the lambda nested within that one. 15024 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15025 ++I) { 15026 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15027 15028 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15029 if (!captureInBlock(BSI, Var, ExprLoc, 15030 BuildAndDiagnose, CaptureType, 15031 DeclRefType, Nested, *this)) 15032 return true; 15033 Nested = true; 15034 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15035 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15036 BuildAndDiagnose, CaptureType, 15037 DeclRefType, Nested, *this)) 15038 return true; 15039 Nested = true; 15040 } else { 15041 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15042 if (!captureInLambda(LSI, Var, ExprLoc, 15043 BuildAndDiagnose, CaptureType, 15044 DeclRefType, Nested, Kind, EllipsisLoc, 15045 /*IsTopScope*/I == N - 1, *this)) 15046 return true; 15047 Nested = true; 15048 } 15049 } 15050 return false; 15051 } 15052 15053 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15054 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15055 QualType CaptureType; 15056 QualType DeclRefType; 15057 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15058 /*BuildAndDiagnose=*/true, CaptureType, 15059 DeclRefType, nullptr); 15060 } 15061 15062 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15063 QualType CaptureType; 15064 QualType DeclRefType; 15065 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15066 /*BuildAndDiagnose=*/false, CaptureType, 15067 DeclRefType, nullptr); 15068 } 15069 15070 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15071 QualType CaptureType; 15072 QualType DeclRefType; 15073 15074 // Determine whether we can capture this variable. 15075 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15076 /*BuildAndDiagnose=*/false, CaptureType, 15077 DeclRefType, nullptr)) 15078 return QualType(); 15079 15080 return DeclRefType; 15081 } 15082 15083 15084 15085 // If either the type of the variable or the initializer is dependent, 15086 // return false. Otherwise, determine whether the variable is a constant 15087 // expression. Use this if you need to know if a variable that might or 15088 // might not be dependent is truly a constant expression. 15089 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15090 ASTContext &Context) { 15091 15092 if (Var->getType()->isDependentType()) 15093 return false; 15094 const VarDecl *DefVD = nullptr; 15095 Var->getAnyInitializer(DefVD); 15096 if (!DefVD) 15097 return false; 15098 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15099 Expr *Init = cast<Expr>(Eval->Value); 15100 if (Init->isValueDependent()) 15101 return false; 15102 return IsVariableAConstantExpression(Var, Context); 15103 } 15104 15105 15106 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15107 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15108 // an object that satisfies the requirements for appearing in a 15109 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15110 // is immediately applied." This function handles the lvalue-to-rvalue 15111 // conversion part. 15112 MaybeODRUseExprs.erase(E->IgnoreParens()); 15113 15114 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15115 // to a variable that is a constant expression, and if so, identify it as 15116 // a reference to a variable that does not involve an odr-use of that 15117 // variable. 15118 if (LambdaScopeInfo *LSI = getCurLambda()) { 15119 Expr *SansParensExpr = E->IgnoreParens(); 15120 VarDecl *Var = nullptr; 15121 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15122 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15123 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15124 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15125 15126 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15127 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15128 } 15129 } 15130 15131 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15132 Res = CorrectDelayedTyposInExpr(Res); 15133 15134 if (!Res.isUsable()) 15135 return Res; 15136 15137 // If a constant-expression is a reference to a variable where we delay 15138 // deciding whether it is an odr-use, just assume we will apply the 15139 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15140 // (a non-type template argument), we have special handling anyway. 15141 UpdateMarkingForLValueToRValue(Res.get()); 15142 return Res; 15143 } 15144 15145 void Sema::CleanupVarDeclMarking() { 15146 for (Expr *E : MaybeODRUseExprs) { 15147 VarDecl *Var; 15148 SourceLocation Loc; 15149 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15150 Var = cast<VarDecl>(DRE->getDecl()); 15151 Loc = DRE->getLocation(); 15152 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15153 Var = cast<VarDecl>(ME->getMemberDecl()); 15154 Loc = ME->getMemberLoc(); 15155 } else { 15156 llvm_unreachable("Unexpected expression"); 15157 } 15158 15159 MarkVarDeclODRUsed(Var, Loc, *this, 15160 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15161 } 15162 15163 MaybeODRUseExprs.clear(); 15164 } 15165 15166 15167 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15168 VarDecl *Var, Expr *E) { 15169 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15170 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15171 Var->setReferenced(); 15172 15173 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15174 15175 bool OdrUseContext = isOdrUseContext(SemaRef); 15176 bool UsableInConstantExpr = 15177 Var->isUsableInConstantExpressions(SemaRef.Context); 15178 bool NeedDefinition = 15179 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15180 15181 VarTemplateSpecializationDecl *VarSpec = 15182 dyn_cast<VarTemplateSpecializationDecl>(Var); 15183 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15184 "Can't instantiate a partial template specialization."); 15185 15186 // If this might be a member specialization of a static data member, check 15187 // the specialization is visible. We already did the checks for variable 15188 // template specializations when we created them. 15189 if (NeedDefinition && TSK != TSK_Undeclared && 15190 !isa<VarTemplateSpecializationDecl>(Var)) 15191 SemaRef.checkSpecializationVisibility(Loc, Var); 15192 15193 // Perform implicit instantiation of static data members, static data member 15194 // templates of class templates, and variable template specializations. Delay 15195 // instantiations of variable templates, except for those that could be used 15196 // in a constant expression. 15197 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15198 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15199 // instantiation declaration if a variable is usable in a constant 15200 // expression (among other cases). 15201 bool TryInstantiating = 15202 TSK == TSK_ImplicitInstantiation || 15203 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15204 15205 if (TryInstantiating) { 15206 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15207 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15208 if (FirstInstantiation) { 15209 PointOfInstantiation = Loc; 15210 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15211 } 15212 15213 bool InstantiationDependent = false; 15214 bool IsNonDependent = 15215 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15216 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15217 : true; 15218 15219 // Do not instantiate specializations that are still type-dependent. 15220 if (IsNonDependent) { 15221 if (UsableInConstantExpr) { 15222 // Do not defer instantiations of variables that could be used in a 15223 // constant expression. 15224 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15225 } else if (FirstInstantiation || 15226 isa<VarTemplateSpecializationDecl>(Var)) { 15227 // FIXME: For a specialization of a variable template, we don't 15228 // distinguish between "declaration and type implicitly instantiated" 15229 // and "implicit instantiation of definition requested", so we have 15230 // no direct way to avoid enqueueing the pending instantiation 15231 // multiple times. 15232 SemaRef.PendingInstantiations 15233 .push_back(std::make_pair(Var, PointOfInstantiation)); 15234 } 15235 } 15236 } 15237 } 15238 15239 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15240 // the requirements for appearing in a constant expression (5.19) and, if 15241 // it is an object, the lvalue-to-rvalue conversion (4.1) 15242 // is immediately applied." We check the first part here, and 15243 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15244 // Note that we use the C++11 definition everywhere because nothing in 15245 // C++03 depends on whether we get the C++03 version correct. The second 15246 // part does not apply to references, since they are not objects. 15247 if (OdrUseContext && E && 15248 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15249 // A reference initialized by a constant expression can never be 15250 // odr-used, so simply ignore it. 15251 if (!Var->getType()->isReferenceType() || 15252 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15253 SemaRef.MaybeODRUseExprs.insert(E); 15254 } else if (OdrUseContext) { 15255 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15256 /*MaxFunctionScopeIndex ptr*/ nullptr); 15257 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15258 // If this is a dependent context, we don't need to mark variables as 15259 // odr-used, but we may still need to track them for lambda capture. 15260 // FIXME: Do we also need to do this inside dependent typeid expressions 15261 // (which are modeled as unevaluated at this point)? 15262 const bool RefersToEnclosingScope = 15263 (SemaRef.CurContext != Var->getDeclContext() && 15264 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15265 if (RefersToEnclosingScope) { 15266 LambdaScopeInfo *const LSI = 15267 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15268 if (LSI && (!LSI->CallOperator || 15269 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15270 // If a variable could potentially be odr-used, defer marking it so 15271 // until we finish analyzing the full expression for any 15272 // lvalue-to-rvalue 15273 // or discarded value conversions that would obviate odr-use. 15274 // Add it to the list of potential captures that will be analyzed 15275 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15276 // unless the variable is a reference that was initialized by a constant 15277 // expression (this will never need to be captured or odr-used). 15278 assert(E && "Capture variable should be used in an expression."); 15279 if (!Var->getType()->isReferenceType() || 15280 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15281 LSI->addPotentialCapture(E->IgnoreParens()); 15282 } 15283 } 15284 } 15285 } 15286 15287 /// \brief Mark a variable referenced, and check whether it is odr-used 15288 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15289 /// used directly for normal expressions referring to VarDecl. 15290 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15291 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15292 } 15293 15294 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15295 Decl *D, Expr *E, bool MightBeOdrUse) { 15296 if (SemaRef.isInOpenMPDeclareTargetContext()) 15297 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15298 15299 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15300 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15301 return; 15302 } 15303 15304 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15305 15306 // If this is a call to a method via a cast, also mark the method in the 15307 // derived class used in case codegen can devirtualize the call. 15308 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15309 if (!ME) 15310 return; 15311 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15312 if (!MD) 15313 return; 15314 // Only attempt to devirtualize if this is truly a virtual call. 15315 bool IsVirtualCall = MD->isVirtual() && 15316 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15317 if (!IsVirtualCall) 15318 return; 15319 15320 // If it's possible to devirtualize the call, mark the called function 15321 // referenced. 15322 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15323 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15324 if (DM) 15325 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15326 } 15327 15328 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 15329 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15330 // TODO: update this with DR# once a defect report is filed. 15331 // C++11 defect. The address of a pure member should not be an ODR use, even 15332 // if it's a qualified reference. 15333 bool OdrUse = true; 15334 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15335 if (Method->isVirtual() && 15336 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15337 OdrUse = false; 15338 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15339 } 15340 15341 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15342 void Sema::MarkMemberReferenced(MemberExpr *E) { 15343 // C++11 [basic.def.odr]p2: 15344 // A non-overloaded function whose name appears as a potentially-evaluated 15345 // expression or a member of a set of candidate functions, if selected by 15346 // overload resolution when referred to from a potentially-evaluated 15347 // expression, is odr-used, unless it is a pure virtual function and its 15348 // name is not explicitly qualified. 15349 bool MightBeOdrUse = true; 15350 if (E->performsVirtualDispatch(getLangOpts())) { 15351 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15352 if (Method->isPure()) 15353 MightBeOdrUse = false; 15354 } 15355 SourceLocation Loc = E->getMemberLoc().isValid() ? 15356 E->getMemberLoc() : E->getLocStart(); 15357 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15358 } 15359 15360 /// \brief Perform marking for a reference to an arbitrary declaration. It 15361 /// marks the declaration referenced, and performs odr-use checking for 15362 /// functions and variables. This method should not be used when building a 15363 /// normal expression which refers to a variable. 15364 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15365 bool MightBeOdrUse) { 15366 if (MightBeOdrUse) { 15367 if (auto *VD = dyn_cast<VarDecl>(D)) { 15368 MarkVariableReferenced(Loc, VD); 15369 return; 15370 } 15371 } 15372 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15373 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15374 return; 15375 } 15376 D->setReferenced(); 15377 } 15378 15379 namespace { 15380 // Mark all of the declarations used by a type as referenced. 15381 // FIXME: Not fully implemented yet! We need to have a better understanding 15382 // of when we're entering a context we should not recurse into. 15383 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15384 // TreeTransforms rebuilding the type in a new context. Rather than 15385 // duplicating the TreeTransform logic, we should consider reusing it here. 15386 // Currently that causes problems when rebuilding LambdaExprs. 15387 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15388 Sema &S; 15389 SourceLocation Loc; 15390 15391 public: 15392 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15393 15394 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15395 15396 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15397 }; 15398 } 15399 15400 bool MarkReferencedDecls::TraverseTemplateArgument( 15401 const TemplateArgument &Arg) { 15402 { 15403 // A non-type template argument is a constant-evaluated context. 15404 EnterExpressionEvaluationContext Evaluated( 15405 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15406 if (Arg.getKind() == TemplateArgument::Declaration) { 15407 if (Decl *D = Arg.getAsDecl()) 15408 S.MarkAnyDeclReferenced(Loc, D, true); 15409 } else if (Arg.getKind() == TemplateArgument::Expression) { 15410 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15411 } 15412 } 15413 15414 return Inherited::TraverseTemplateArgument(Arg); 15415 } 15416 15417 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15418 MarkReferencedDecls Marker(*this, Loc); 15419 Marker.TraverseType(T); 15420 } 15421 15422 namespace { 15423 /// \brief Helper class that marks all of the declarations referenced by 15424 /// potentially-evaluated subexpressions as "referenced". 15425 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15426 Sema &S; 15427 bool SkipLocalVariables; 15428 15429 public: 15430 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15431 15432 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15433 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15434 15435 void VisitDeclRefExpr(DeclRefExpr *E) { 15436 // If we were asked not to visit local variables, don't. 15437 if (SkipLocalVariables) { 15438 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15439 if (VD->hasLocalStorage()) 15440 return; 15441 } 15442 15443 S.MarkDeclRefReferenced(E); 15444 } 15445 15446 void VisitMemberExpr(MemberExpr *E) { 15447 S.MarkMemberReferenced(E); 15448 Inherited::VisitMemberExpr(E); 15449 } 15450 15451 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15452 S.MarkFunctionReferenced(E->getLocStart(), 15453 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15454 Visit(E->getSubExpr()); 15455 } 15456 15457 void VisitCXXNewExpr(CXXNewExpr *E) { 15458 if (E->getOperatorNew()) 15459 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15460 if (E->getOperatorDelete()) 15461 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15462 Inherited::VisitCXXNewExpr(E); 15463 } 15464 15465 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15466 if (E->getOperatorDelete()) 15467 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15468 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15469 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15470 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15471 S.MarkFunctionReferenced(E->getLocStart(), 15472 S.LookupDestructor(Record)); 15473 } 15474 15475 Inherited::VisitCXXDeleteExpr(E); 15476 } 15477 15478 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15479 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15480 Inherited::VisitCXXConstructExpr(E); 15481 } 15482 15483 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15484 Visit(E->getExpr()); 15485 } 15486 15487 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15488 Inherited::VisitImplicitCastExpr(E); 15489 15490 if (E->getCastKind() == CK_LValueToRValue) 15491 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15492 } 15493 }; 15494 } 15495 15496 /// \brief Mark any declarations that appear within this expression or any 15497 /// potentially-evaluated subexpressions as "referenced". 15498 /// 15499 /// \param SkipLocalVariables If true, don't mark local variables as 15500 /// 'referenced'. 15501 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15502 bool SkipLocalVariables) { 15503 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15504 } 15505 15506 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15507 /// of the program being compiled. 15508 /// 15509 /// This routine emits the given diagnostic when the code currently being 15510 /// type-checked is "potentially evaluated", meaning that there is a 15511 /// possibility that the code will actually be executable. Code in sizeof() 15512 /// expressions, code used only during overload resolution, etc., are not 15513 /// potentially evaluated. This routine will suppress such diagnostics or, 15514 /// in the absolutely nutty case of potentially potentially evaluated 15515 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15516 /// later. 15517 /// 15518 /// This routine should be used for all diagnostics that describe the run-time 15519 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15520 /// Failure to do so will likely result in spurious diagnostics or failures 15521 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15522 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15523 const PartialDiagnostic &PD) { 15524 switch (ExprEvalContexts.back().Context) { 15525 case ExpressionEvaluationContext::Unevaluated: 15526 case ExpressionEvaluationContext::UnevaluatedList: 15527 case ExpressionEvaluationContext::UnevaluatedAbstract: 15528 case ExpressionEvaluationContext::DiscardedStatement: 15529 // The argument will never be evaluated, so don't complain. 15530 break; 15531 15532 case ExpressionEvaluationContext::ConstantEvaluated: 15533 // Relevant diagnostics should be produced by constant evaluation. 15534 break; 15535 15536 case ExpressionEvaluationContext::PotentiallyEvaluated: 15537 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15538 if (Statement && getCurFunctionOrMethodDecl()) { 15539 FunctionScopes.back()->PossiblyUnreachableDiags. 15540 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15541 return true; 15542 } 15543 15544 // The initializer of a constexpr variable or of the first declaration of a 15545 // static data member is not syntactically a constant evaluated constant, 15546 // but nonetheless is always required to be a constant expression, so we 15547 // can skip diagnosing. 15548 // FIXME: Using the mangling context here is a hack. 15549 if (auto *VD = dyn_cast_or_null<VarDecl>( 15550 ExprEvalContexts.back().ManglingContextDecl)) { 15551 if (VD->isConstexpr() || 15552 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15553 break; 15554 // FIXME: For any other kind of variable, we should build a CFG for its 15555 // initializer and check whether the context in question is reachable. 15556 } 15557 15558 Diag(Loc, PD); 15559 return true; 15560 } 15561 15562 return false; 15563 } 15564 15565 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15566 CallExpr *CE, FunctionDecl *FD) { 15567 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15568 return false; 15569 15570 // If we're inside a decltype's expression, don't check for a valid return 15571 // type or construct temporaries until we know whether this is the last call. 15572 if (ExprEvalContexts.back().IsDecltype) { 15573 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15574 return false; 15575 } 15576 15577 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15578 FunctionDecl *FD; 15579 CallExpr *CE; 15580 15581 public: 15582 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15583 : FD(FD), CE(CE) { } 15584 15585 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15586 if (!FD) { 15587 S.Diag(Loc, diag::err_call_incomplete_return) 15588 << T << CE->getSourceRange(); 15589 return; 15590 } 15591 15592 S.Diag(Loc, diag::err_call_function_incomplete_return) 15593 << CE->getSourceRange() << FD->getDeclName() << T; 15594 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15595 << FD->getDeclName(); 15596 } 15597 } Diagnoser(FD, CE); 15598 15599 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15600 return true; 15601 15602 return false; 15603 } 15604 15605 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15606 // will prevent this condition from triggering, which is what we want. 15607 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15608 SourceLocation Loc; 15609 15610 unsigned diagnostic = diag::warn_condition_is_assignment; 15611 bool IsOrAssign = false; 15612 15613 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15614 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15615 return; 15616 15617 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15618 15619 // Greylist some idioms by putting them into a warning subcategory. 15620 if (ObjCMessageExpr *ME 15621 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15622 Selector Sel = ME->getSelector(); 15623 15624 // self = [<foo> init...] 15625 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15626 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15627 15628 // <foo> = [<bar> nextObject] 15629 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15630 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15631 } 15632 15633 Loc = Op->getOperatorLoc(); 15634 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15635 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15636 return; 15637 15638 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15639 Loc = Op->getOperatorLoc(); 15640 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15641 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15642 else { 15643 // Not an assignment. 15644 return; 15645 } 15646 15647 Diag(Loc, diagnostic) << E->getSourceRange(); 15648 15649 SourceLocation Open = E->getLocStart(); 15650 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15651 Diag(Loc, diag::note_condition_assign_silence) 15652 << FixItHint::CreateInsertion(Open, "(") 15653 << FixItHint::CreateInsertion(Close, ")"); 15654 15655 if (IsOrAssign) 15656 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15657 << FixItHint::CreateReplacement(Loc, "!="); 15658 else 15659 Diag(Loc, diag::note_condition_assign_to_comparison) 15660 << FixItHint::CreateReplacement(Loc, "=="); 15661 } 15662 15663 /// \brief Redundant parentheses over an equality comparison can indicate 15664 /// that the user intended an assignment used as condition. 15665 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15666 // Don't warn if the parens came from a macro. 15667 SourceLocation parenLoc = ParenE->getLocStart(); 15668 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15669 return; 15670 // Don't warn for dependent expressions. 15671 if (ParenE->isTypeDependent()) 15672 return; 15673 15674 Expr *E = ParenE->IgnoreParens(); 15675 15676 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15677 if (opE->getOpcode() == BO_EQ && 15678 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15679 == Expr::MLV_Valid) { 15680 SourceLocation Loc = opE->getOperatorLoc(); 15681 15682 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15683 SourceRange ParenERange = ParenE->getSourceRange(); 15684 Diag(Loc, diag::note_equality_comparison_silence) 15685 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15686 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15687 Diag(Loc, diag::note_equality_comparison_to_assign) 15688 << FixItHint::CreateReplacement(Loc, "="); 15689 } 15690 } 15691 15692 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15693 bool IsConstexpr) { 15694 DiagnoseAssignmentAsCondition(E); 15695 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15696 DiagnoseEqualityWithExtraParens(parenE); 15697 15698 ExprResult result = CheckPlaceholderExpr(E); 15699 if (result.isInvalid()) return ExprError(); 15700 E = result.get(); 15701 15702 if (!E->isTypeDependent()) { 15703 if (getLangOpts().CPlusPlus) 15704 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15705 15706 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15707 if (ERes.isInvalid()) 15708 return ExprError(); 15709 E = ERes.get(); 15710 15711 QualType T = E->getType(); 15712 if (!T->isScalarType()) { // C99 6.8.4.1p1 15713 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15714 << T << E->getSourceRange(); 15715 return ExprError(); 15716 } 15717 CheckBoolLikeConversion(E, Loc); 15718 } 15719 15720 return E; 15721 } 15722 15723 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15724 Expr *SubExpr, ConditionKind CK) { 15725 // Empty conditions are valid in for-statements. 15726 if (!SubExpr) 15727 return ConditionResult(); 15728 15729 ExprResult Cond; 15730 switch (CK) { 15731 case ConditionKind::Boolean: 15732 Cond = CheckBooleanCondition(Loc, SubExpr); 15733 break; 15734 15735 case ConditionKind::ConstexprIf: 15736 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15737 break; 15738 15739 case ConditionKind::Switch: 15740 Cond = CheckSwitchCondition(Loc, SubExpr); 15741 break; 15742 } 15743 if (Cond.isInvalid()) 15744 return ConditionError(); 15745 15746 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15747 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15748 if (!FullExpr.get()) 15749 return ConditionError(); 15750 15751 return ConditionResult(*this, nullptr, FullExpr, 15752 CK == ConditionKind::ConstexprIf); 15753 } 15754 15755 namespace { 15756 /// A visitor for rebuilding a call to an __unknown_any expression 15757 /// to have an appropriate type. 15758 struct RebuildUnknownAnyFunction 15759 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15760 15761 Sema &S; 15762 15763 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15764 15765 ExprResult VisitStmt(Stmt *S) { 15766 llvm_unreachable("unexpected statement!"); 15767 } 15768 15769 ExprResult VisitExpr(Expr *E) { 15770 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15771 << E->getSourceRange(); 15772 return ExprError(); 15773 } 15774 15775 /// Rebuild an expression which simply semantically wraps another 15776 /// expression which it shares the type and value kind of. 15777 template <class T> ExprResult rebuildSugarExpr(T *E) { 15778 ExprResult SubResult = Visit(E->getSubExpr()); 15779 if (SubResult.isInvalid()) return ExprError(); 15780 15781 Expr *SubExpr = SubResult.get(); 15782 E->setSubExpr(SubExpr); 15783 E->setType(SubExpr->getType()); 15784 E->setValueKind(SubExpr->getValueKind()); 15785 assert(E->getObjectKind() == OK_Ordinary); 15786 return E; 15787 } 15788 15789 ExprResult VisitParenExpr(ParenExpr *E) { 15790 return rebuildSugarExpr(E); 15791 } 15792 15793 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15794 return rebuildSugarExpr(E); 15795 } 15796 15797 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15798 ExprResult SubResult = Visit(E->getSubExpr()); 15799 if (SubResult.isInvalid()) return ExprError(); 15800 15801 Expr *SubExpr = SubResult.get(); 15802 E->setSubExpr(SubExpr); 15803 E->setType(S.Context.getPointerType(SubExpr->getType())); 15804 assert(E->getValueKind() == VK_RValue); 15805 assert(E->getObjectKind() == OK_Ordinary); 15806 return E; 15807 } 15808 15809 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15810 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15811 15812 E->setType(VD->getType()); 15813 15814 assert(E->getValueKind() == VK_RValue); 15815 if (S.getLangOpts().CPlusPlus && 15816 !(isa<CXXMethodDecl>(VD) && 15817 cast<CXXMethodDecl>(VD)->isInstance())) 15818 E->setValueKind(VK_LValue); 15819 15820 return E; 15821 } 15822 15823 ExprResult VisitMemberExpr(MemberExpr *E) { 15824 return resolveDecl(E, E->getMemberDecl()); 15825 } 15826 15827 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15828 return resolveDecl(E, E->getDecl()); 15829 } 15830 }; 15831 } 15832 15833 /// Given a function expression of unknown-any type, try to rebuild it 15834 /// to have a function type. 15835 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15836 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15837 if (Result.isInvalid()) return ExprError(); 15838 return S.DefaultFunctionArrayConversion(Result.get()); 15839 } 15840 15841 namespace { 15842 /// A visitor for rebuilding an expression of type __unknown_anytype 15843 /// into one which resolves the type directly on the referring 15844 /// expression. Strict preservation of the original source 15845 /// structure is not a goal. 15846 struct RebuildUnknownAnyExpr 15847 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15848 15849 Sema &S; 15850 15851 /// The current destination type. 15852 QualType DestType; 15853 15854 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15855 : S(S), DestType(CastType) {} 15856 15857 ExprResult VisitStmt(Stmt *S) { 15858 llvm_unreachable("unexpected statement!"); 15859 } 15860 15861 ExprResult VisitExpr(Expr *E) { 15862 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15863 << E->getSourceRange(); 15864 return ExprError(); 15865 } 15866 15867 ExprResult VisitCallExpr(CallExpr *E); 15868 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15869 15870 /// Rebuild an expression which simply semantically wraps another 15871 /// expression which it shares the type and value kind of. 15872 template <class T> ExprResult rebuildSugarExpr(T *E) { 15873 ExprResult SubResult = Visit(E->getSubExpr()); 15874 if (SubResult.isInvalid()) return ExprError(); 15875 Expr *SubExpr = SubResult.get(); 15876 E->setSubExpr(SubExpr); 15877 E->setType(SubExpr->getType()); 15878 E->setValueKind(SubExpr->getValueKind()); 15879 assert(E->getObjectKind() == OK_Ordinary); 15880 return E; 15881 } 15882 15883 ExprResult VisitParenExpr(ParenExpr *E) { 15884 return rebuildSugarExpr(E); 15885 } 15886 15887 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15888 return rebuildSugarExpr(E); 15889 } 15890 15891 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15892 const PointerType *Ptr = DestType->getAs<PointerType>(); 15893 if (!Ptr) { 15894 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15895 << E->getSourceRange(); 15896 return ExprError(); 15897 } 15898 15899 if (isa<CallExpr>(E->getSubExpr())) { 15900 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15901 << E->getSourceRange(); 15902 return ExprError(); 15903 } 15904 15905 assert(E->getValueKind() == VK_RValue); 15906 assert(E->getObjectKind() == OK_Ordinary); 15907 E->setType(DestType); 15908 15909 // Build the sub-expression as if it were an object of the pointee type. 15910 DestType = Ptr->getPointeeType(); 15911 ExprResult SubResult = Visit(E->getSubExpr()); 15912 if (SubResult.isInvalid()) return ExprError(); 15913 E->setSubExpr(SubResult.get()); 15914 return E; 15915 } 15916 15917 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15918 15919 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15920 15921 ExprResult VisitMemberExpr(MemberExpr *E) { 15922 return resolveDecl(E, E->getMemberDecl()); 15923 } 15924 15925 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15926 return resolveDecl(E, E->getDecl()); 15927 } 15928 }; 15929 } 15930 15931 /// Rebuilds a call expression which yielded __unknown_anytype. 15932 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15933 Expr *CalleeExpr = E->getCallee(); 15934 15935 enum FnKind { 15936 FK_MemberFunction, 15937 FK_FunctionPointer, 15938 FK_BlockPointer 15939 }; 15940 15941 FnKind Kind; 15942 QualType CalleeType = CalleeExpr->getType(); 15943 if (CalleeType == S.Context.BoundMemberTy) { 15944 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15945 Kind = FK_MemberFunction; 15946 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15947 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15948 CalleeType = Ptr->getPointeeType(); 15949 Kind = FK_FunctionPointer; 15950 } else { 15951 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15952 Kind = FK_BlockPointer; 15953 } 15954 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15955 15956 // Verify that this is a legal result type of a function. 15957 if (DestType->isArrayType() || DestType->isFunctionType()) { 15958 unsigned diagID = diag::err_func_returning_array_function; 15959 if (Kind == FK_BlockPointer) 15960 diagID = diag::err_block_returning_array_function; 15961 15962 S.Diag(E->getExprLoc(), diagID) 15963 << DestType->isFunctionType() << DestType; 15964 return ExprError(); 15965 } 15966 15967 // Otherwise, go ahead and set DestType as the call's result. 15968 E->setType(DestType.getNonLValueExprType(S.Context)); 15969 E->setValueKind(Expr::getValueKindForType(DestType)); 15970 assert(E->getObjectKind() == OK_Ordinary); 15971 15972 // Rebuild the function type, replacing the result type with DestType. 15973 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15974 if (Proto) { 15975 // __unknown_anytype(...) is a special case used by the debugger when 15976 // it has no idea what a function's signature is. 15977 // 15978 // We want to build this call essentially under the K&R 15979 // unprototyped rules, but making a FunctionNoProtoType in C++ 15980 // would foul up all sorts of assumptions. However, we cannot 15981 // simply pass all arguments as variadic arguments, nor can we 15982 // portably just call the function under a non-variadic type; see 15983 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15984 // However, it turns out that in practice it is generally safe to 15985 // call a function declared as "A foo(B,C,D);" under the prototype 15986 // "A foo(B,C,D,...);". The only known exception is with the 15987 // Windows ABI, where any variadic function is implicitly cdecl 15988 // regardless of its normal CC. Therefore we change the parameter 15989 // types to match the types of the arguments. 15990 // 15991 // This is a hack, but it is far superior to moving the 15992 // corresponding target-specific code from IR-gen to Sema/AST. 15993 15994 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15995 SmallVector<QualType, 8> ArgTypes; 15996 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15997 ArgTypes.reserve(E->getNumArgs()); 15998 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15999 Expr *Arg = E->getArg(i); 16000 QualType ArgType = Arg->getType(); 16001 if (E->isLValue()) { 16002 ArgType = S.Context.getLValueReferenceType(ArgType); 16003 } else if (E->isXValue()) { 16004 ArgType = S.Context.getRValueReferenceType(ArgType); 16005 } 16006 ArgTypes.push_back(ArgType); 16007 } 16008 ParamTypes = ArgTypes; 16009 } 16010 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16011 Proto->getExtProtoInfo()); 16012 } else { 16013 DestType = S.Context.getFunctionNoProtoType(DestType, 16014 FnType->getExtInfo()); 16015 } 16016 16017 // Rebuild the appropriate pointer-to-function type. 16018 switch (Kind) { 16019 case FK_MemberFunction: 16020 // Nothing to do. 16021 break; 16022 16023 case FK_FunctionPointer: 16024 DestType = S.Context.getPointerType(DestType); 16025 break; 16026 16027 case FK_BlockPointer: 16028 DestType = S.Context.getBlockPointerType(DestType); 16029 break; 16030 } 16031 16032 // Finally, we can recurse. 16033 ExprResult CalleeResult = Visit(CalleeExpr); 16034 if (!CalleeResult.isUsable()) return ExprError(); 16035 E->setCallee(CalleeResult.get()); 16036 16037 // Bind a temporary if necessary. 16038 return S.MaybeBindToTemporary(E); 16039 } 16040 16041 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16042 // Verify that this is a legal result type of a call. 16043 if (DestType->isArrayType() || DestType->isFunctionType()) { 16044 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16045 << DestType->isFunctionType() << DestType; 16046 return ExprError(); 16047 } 16048 16049 // Rewrite the method result type if available. 16050 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16051 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16052 Method->setReturnType(DestType); 16053 } 16054 16055 // Change the type of the message. 16056 E->setType(DestType.getNonReferenceType()); 16057 E->setValueKind(Expr::getValueKindForType(DestType)); 16058 16059 return S.MaybeBindToTemporary(E); 16060 } 16061 16062 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16063 // The only case we should ever see here is a function-to-pointer decay. 16064 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16065 assert(E->getValueKind() == VK_RValue); 16066 assert(E->getObjectKind() == OK_Ordinary); 16067 16068 E->setType(DestType); 16069 16070 // Rebuild the sub-expression as the pointee (function) type. 16071 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16072 16073 ExprResult Result = Visit(E->getSubExpr()); 16074 if (!Result.isUsable()) return ExprError(); 16075 16076 E->setSubExpr(Result.get()); 16077 return E; 16078 } else if (E->getCastKind() == CK_LValueToRValue) { 16079 assert(E->getValueKind() == VK_RValue); 16080 assert(E->getObjectKind() == OK_Ordinary); 16081 16082 assert(isa<BlockPointerType>(E->getType())); 16083 16084 E->setType(DestType); 16085 16086 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16087 DestType = S.Context.getLValueReferenceType(DestType); 16088 16089 ExprResult Result = Visit(E->getSubExpr()); 16090 if (!Result.isUsable()) return ExprError(); 16091 16092 E->setSubExpr(Result.get()); 16093 return E; 16094 } else { 16095 llvm_unreachable("Unhandled cast type!"); 16096 } 16097 } 16098 16099 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16100 ExprValueKind ValueKind = VK_LValue; 16101 QualType Type = DestType; 16102 16103 // We know how to make this work for certain kinds of decls: 16104 16105 // - functions 16106 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16107 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16108 DestType = Ptr->getPointeeType(); 16109 ExprResult Result = resolveDecl(E, VD); 16110 if (Result.isInvalid()) return ExprError(); 16111 return S.ImpCastExprToType(Result.get(), Type, 16112 CK_FunctionToPointerDecay, VK_RValue); 16113 } 16114 16115 if (!Type->isFunctionType()) { 16116 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16117 << VD << E->getSourceRange(); 16118 return ExprError(); 16119 } 16120 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16121 // We must match the FunctionDecl's type to the hack introduced in 16122 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16123 // type. See the lengthy commentary in that routine. 16124 QualType FDT = FD->getType(); 16125 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16126 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16127 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16128 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16129 SourceLocation Loc = FD->getLocation(); 16130 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16131 FD->getDeclContext(), 16132 Loc, Loc, FD->getNameInfo().getName(), 16133 DestType, FD->getTypeSourceInfo(), 16134 SC_None, false/*isInlineSpecified*/, 16135 FD->hasPrototype(), 16136 false/*isConstexprSpecified*/); 16137 16138 if (FD->getQualifier()) 16139 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16140 16141 SmallVector<ParmVarDecl*, 16> Params; 16142 for (const auto &AI : FT->param_types()) { 16143 ParmVarDecl *Param = 16144 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16145 Param->setScopeInfo(0, Params.size()); 16146 Params.push_back(Param); 16147 } 16148 NewFD->setParams(Params); 16149 DRE->setDecl(NewFD); 16150 VD = DRE->getDecl(); 16151 } 16152 } 16153 16154 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16155 if (MD->isInstance()) { 16156 ValueKind = VK_RValue; 16157 Type = S.Context.BoundMemberTy; 16158 } 16159 16160 // Function references aren't l-values in C. 16161 if (!S.getLangOpts().CPlusPlus) 16162 ValueKind = VK_RValue; 16163 16164 // - variables 16165 } else if (isa<VarDecl>(VD)) { 16166 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16167 Type = RefTy->getPointeeType(); 16168 } else if (Type->isFunctionType()) { 16169 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16170 << VD << E->getSourceRange(); 16171 return ExprError(); 16172 } 16173 16174 // - nothing else 16175 } else { 16176 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16177 << VD << E->getSourceRange(); 16178 return ExprError(); 16179 } 16180 16181 // Modifying the declaration like this is friendly to IR-gen but 16182 // also really dangerous. 16183 VD->setType(DestType); 16184 E->setType(Type); 16185 E->setValueKind(ValueKind); 16186 return E; 16187 } 16188 16189 /// Check a cast of an unknown-any type. We intentionally only 16190 /// trigger this for C-style casts. 16191 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16192 Expr *CastExpr, CastKind &CastKind, 16193 ExprValueKind &VK, CXXCastPath &Path) { 16194 // The type we're casting to must be either void or complete. 16195 if (!CastType->isVoidType() && 16196 RequireCompleteType(TypeRange.getBegin(), CastType, 16197 diag::err_typecheck_cast_to_incomplete)) 16198 return ExprError(); 16199 16200 // Rewrite the casted expression from scratch. 16201 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16202 if (!result.isUsable()) return ExprError(); 16203 16204 CastExpr = result.get(); 16205 VK = CastExpr->getValueKind(); 16206 CastKind = CK_NoOp; 16207 16208 return CastExpr; 16209 } 16210 16211 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16212 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16213 } 16214 16215 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16216 Expr *arg, QualType ¶mType) { 16217 // If the syntactic form of the argument is not an explicit cast of 16218 // any sort, just do default argument promotion. 16219 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16220 if (!castArg) { 16221 ExprResult result = DefaultArgumentPromotion(arg); 16222 if (result.isInvalid()) return ExprError(); 16223 paramType = result.get()->getType(); 16224 return result; 16225 } 16226 16227 // Otherwise, use the type that was written in the explicit cast. 16228 assert(!arg->hasPlaceholderType()); 16229 paramType = castArg->getTypeAsWritten(); 16230 16231 // Copy-initialize a parameter of that type. 16232 InitializedEntity entity = 16233 InitializedEntity::InitializeParameter(Context, paramType, 16234 /*consumed*/ false); 16235 return PerformCopyInitialization(entity, callLoc, arg); 16236 } 16237 16238 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16239 Expr *orig = E; 16240 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16241 while (true) { 16242 E = E->IgnoreParenImpCasts(); 16243 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16244 E = call->getCallee(); 16245 diagID = diag::err_uncasted_call_of_unknown_any; 16246 } else { 16247 break; 16248 } 16249 } 16250 16251 SourceLocation loc; 16252 NamedDecl *d; 16253 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16254 loc = ref->getLocation(); 16255 d = ref->getDecl(); 16256 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16257 loc = mem->getMemberLoc(); 16258 d = mem->getMemberDecl(); 16259 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16260 diagID = diag::err_uncasted_call_of_unknown_any; 16261 loc = msg->getSelectorStartLoc(); 16262 d = msg->getMethodDecl(); 16263 if (!d) { 16264 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16265 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16266 << orig->getSourceRange(); 16267 return ExprError(); 16268 } 16269 } else { 16270 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16271 << E->getSourceRange(); 16272 return ExprError(); 16273 } 16274 16275 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16276 16277 // Never recoverable. 16278 return ExprError(); 16279 } 16280 16281 /// Check for operands with placeholder types and complain if found. 16282 /// Returns ExprError() if there was an error and no recovery was possible. 16283 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16284 if (!getLangOpts().CPlusPlus) { 16285 // C cannot handle TypoExpr nodes on either side of a binop because it 16286 // doesn't handle dependent types properly, so make sure any TypoExprs have 16287 // been dealt with before checking the operands. 16288 ExprResult Result = CorrectDelayedTyposInExpr(E); 16289 if (!Result.isUsable()) return ExprError(); 16290 E = Result.get(); 16291 } 16292 16293 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16294 if (!placeholderType) return E; 16295 16296 switch (placeholderType->getKind()) { 16297 16298 // Overloaded expressions. 16299 case BuiltinType::Overload: { 16300 // Try to resolve a single function template specialization. 16301 // This is obligatory. 16302 ExprResult Result = E; 16303 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16304 return Result; 16305 16306 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16307 // leaves Result unchanged on failure. 16308 Result = E; 16309 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16310 return Result; 16311 16312 // If that failed, try to recover with a call. 16313 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16314 /*complain*/ true); 16315 return Result; 16316 } 16317 16318 // Bound member functions. 16319 case BuiltinType::BoundMember: { 16320 ExprResult result = E; 16321 const Expr *BME = E->IgnoreParens(); 16322 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16323 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16324 if (isa<CXXPseudoDestructorExpr>(BME)) { 16325 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16326 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16327 if (ME->getMemberNameInfo().getName().getNameKind() == 16328 DeclarationName::CXXDestructorName) 16329 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16330 } 16331 tryToRecoverWithCall(result, PD, 16332 /*complain*/ true); 16333 return result; 16334 } 16335 16336 // ARC unbridged casts. 16337 case BuiltinType::ARCUnbridgedCast: { 16338 Expr *realCast = stripARCUnbridgedCast(E); 16339 diagnoseARCUnbridgedCast(realCast); 16340 return realCast; 16341 } 16342 16343 // Expressions of unknown type. 16344 case BuiltinType::UnknownAny: 16345 return diagnoseUnknownAnyExpr(*this, E); 16346 16347 // Pseudo-objects. 16348 case BuiltinType::PseudoObject: 16349 return checkPseudoObjectRValue(E); 16350 16351 case BuiltinType::BuiltinFn: { 16352 // Accept __noop without parens by implicitly converting it to a call expr. 16353 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16354 if (DRE) { 16355 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16356 if (FD->getBuiltinID() == Builtin::BI__noop) { 16357 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16358 CK_BuiltinFnToFnPtr).get(); 16359 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16360 VK_RValue, SourceLocation()); 16361 } 16362 } 16363 16364 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16365 return ExprError(); 16366 } 16367 16368 // Expressions of unknown type. 16369 case BuiltinType::OMPArraySection: 16370 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16371 return ExprError(); 16372 16373 // Everything else should be impossible. 16374 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16375 case BuiltinType::Id: 16376 #include "clang/Basic/OpenCLImageTypes.def" 16377 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16378 #define PLACEHOLDER_TYPE(Id, SingletonId) 16379 #include "clang/AST/BuiltinTypes.def" 16380 break; 16381 } 16382 16383 llvm_unreachable("invalid placeholder type!"); 16384 } 16385 16386 bool Sema::CheckCaseExpression(Expr *E) { 16387 if (E->isTypeDependent()) 16388 return true; 16389 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16390 return E->getType()->isIntegralOrEnumerationType(); 16391 return false; 16392 } 16393 16394 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16395 ExprResult 16396 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16397 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16398 "Unknown Objective-C Boolean value!"); 16399 QualType BoolT = Context.ObjCBuiltinBoolTy; 16400 if (!Context.getBOOLDecl()) { 16401 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16402 Sema::LookupOrdinaryName); 16403 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16404 NamedDecl *ND = Result.getFoundDecl(); 16405 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16406 Context.setBOOLDecl(TD); 16407 } 16408 } 16409 if (Context.getBOOLDecl()) 16410 BoolT = Context.getBOOLType(); 16411 return new (Context) 16412 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16413 } 16414 16415 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16416 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16417 SourceLocation RParen) { 16418 16419 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16420 16421 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16422 [&](const AvailabilitySpec &Spec) { 16423 return Spec.getPlatform() == Platform; 16424 }); 16425 16426 VersionTuple Version; 16427 if (Spec != AvailSpecs.end()) 16428 Version = Spec->getVersion(); 16429 16430 // The use of `@available` in the enclosing function should be analyzed to 16431 // warn when it's used inappropriately (i.e. not if(@available)). 16432 if (getCurFunctionOrMethodDecl()) 16433 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16434 else if (getCurBlock() || getCurLambda()) 16435 getCurFunction()->HasPotentialAvailabilityViolations = true; 16436 16437 return new (Context) 16438 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16439 } 16440