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/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 83 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 84 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 85 if (DC && !DC->hasAttr<UnusedAttr>()) 86 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 87 } 88 } 89 } 90 91 /// \brief Emit a note explaining that this function is deleted. 92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 93 assert(Decl->isDeleted()); 94 95 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 96 97 if (Method && Method->isDeleted() && Method->isDefaulted()) { 98 // If the method was explicitly defaulted, point at that declaration. 99 if (!Method->isImplicit()) 100 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 101 102 // Try to diagnose why this special member function was implicitly 103 // deleted. This might fail, if that reason no longer applies. 104 CXXSpecialMember CSM = getSpecialMember(Method); 105 if (CSM != CXXInvalid) 106 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 107 108 return; 109 } 110 111 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 112 if (Ctor && Ctor->isInheritingConstructor()) 113 return NoteDeletedInheritingConstructor(Ctor); 114 115 Diag(Decl->getLocation(), diag::note_availability_specified_here) 116 << Decl << true; 117 } 118 119 /// \brief Determine whether a FunctionDecl was ever declared with an 120 /// explicit storage class. 121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 122 for (auto I : D->redecls()) { 123 if (I->getStorageClass() != SC_None) 124 return true; 125 } 126 return false; 127 } 128 129 /// \brief Check whether we're in an extern inline function and referring to a 130 /// variable or function with internal linkage (C11 6.7.4p3). 131 /// 132 /// This is only a warning because we used to silently accept this code, but 133 /// in many cases it will not behave correctly. This is not enabled in C++ mode 134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 135 /// and so while there may still be user mistakes, most of the time we can't 136 /// prove that there are errors. 137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 138 const NamedDecl *D, 139 SourceLocation Loc) { 140 // This is disabled under C++; there are too many ways for this to fire in 141 // contexts where the warning is a false positive, or where it is technically 142 // correct but benign. 143 if (S.getLangOpts().CPlusPlus) 144 return; 145 146 // Check if this is an inlined function or method. 147 FunctionDecl *Current = S.getCurFunctionDecl(); 148 if (!Current) 149 return; 150 if (!Current->isInlined()) 151 return; 152 if (!Current->isExternallyVisible()) 153 return; 154 155 // Check if the decl has internal linkage. 156 if (D->getFormalLinkage() != InternalLinkage) 157 return; 158 159 // Downgrade from ExtWarn to Extension if 160 // (1) the supposedly external inline function is in the main file, 161 // and probably won't be included anywhere else. 162 // (2) the thing we're referencing is a pure function. 163 // (3) the thing we're referencing is another inline function. 164 // This last can give us false negatives, but it's better than warning on 165 // wrappers for simple C library functions. 166 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 167 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 168 if (!DowngradeWarning && UsedFn) 169 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 170 171 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 172 : diag::ext_internal_in_extern_inline) 173 << /*IsVar=*/!UsedFn << D; 174 175 S.MaybeSuggestAddingStaticToDecl(Current); 176 177 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 178 << D; 179 } 180 181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 182 const FunctionDecl *First = Cur->getFirstDecl(); 183 184 // Suggest "static" on the function, if possible. 185 if (!hasAnyExplicitStorageClass(First)) { 186 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 187 Diag(DeclBegin, diag::note_convert_inline_to_static) 188 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 189 } 190 } 191 192 /// \brief Determine whether the use of this declaration is valid, and 193 /// emit any corresponding diagnostics. 194 /// 195 /// This routine diagnoses various problems with referencing 196 /// declarations that can occur when using a declaration. For example, 197 /// it might warn if a deprecated or unavailable declaration is being 198 /// used, or produce an error (and return true) if a C++0x deleted 199 /// function is being used. 200 /// 201 /// \returns true if there was an error (this declaration cannot be 202 /// referenced), false otherwise. 203 /// 204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 205 const ObjCInterfaceDecl *UnknownObjCClass, 206 bool ObjCPropertyAccess, 207 bool AvoidPartialAvailabilityChecks) { 208 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 209 // If there were any diagnostics suppressed by template argument deduction, 210 // emit them now. 211 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 212 if (Pos != SuppressedDiagnostics.end()) { 213 for (const PartialDiagnosticAt &Suppressed : Pos->second) 214 Diag(Suppressed.first, Suppressed.second); 215 216 // Clear out the list of suppressed diagnostics, so that we don't emit 217 // them again for this specialization. However, we don't obsolete this 218 // entry from the table, because we want to avoid ever emitting these 219 // diagnostics again. 220 Pos->second.clear(); 221 } 222 223 // C++ [basic.start.main]p3: 224 // The function 'main' shall not be used within a program. 225 if (cast<FunctionDecl>(D)->isMain()) 226 Diag(Loc, diag::ext_main_used); 227 } 228 229 // See if this is an auto-typed variable whose initializer we are parsing. 230 if (ParsingInitForAutoVars.count(D)) { 231 if (isa<BindingDecl>(D)) { 232 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 233 << D->getDeclName(); 234 } else { 235 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 236 << D->getDeclName() << cast<VarDecl>(D)->getType(); 237 } 238 return true; 239 } 240 241 // See if this is a deleted function. 242 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 243 if (FD->isDeleted()) { 244 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 245 if (Ctor && Ctor->isInheritingConstructor()) 246 Diag(Loc, diag::err_deleted_inherited_ctor_use) 247 << Ctor->getParent() 248 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 249 else 250 Diag(Loc, diag::err_deleted_function_use); 251 NoteDeletedFunction(FD); 252 return true; 253 } 254 255 // If the function has a deduced return type, and we can't deduce it, 256 // then we can't use it either. 257 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 258 DeduceReturnType(FD, Loc)) 259 return true; 260 261 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 262 return true; 263 } 264 265 auto getReferencedObjCProp = [](const NamedDecl *D) -> 266 const ObjCPropertyDecl * { 267 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 268 return MD->findPropertyDecl(); 269 return nullptr; 270 }; 271 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 272 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 273 return true; 274 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 275 return true; 276 } 277 278 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 279 // Only the variables omp_in and omp_out are allowed in the combiner. 280 // Only the variables omp_priv and omp_orig are allowed in the 281 // initializer-clause. 282 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 283 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 284 isa<VarDecl>(D)) { 285 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 286 << getCurFunction()->HasOMPDeclareReductionCombiner; 287 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 288 return true; 289 } 290 291 DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess, 292 AvoidPartialAvailabilityChecks); 293 294 DiagnoseUnusedOfDecl(*this, D, Loc); 295 296 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 297 298 return false; 299 } 300 301 /// \brief Retrieve the message suffix that should be added to a 302 /// diagnostic complaining about the given function being deleted or 303 /// unavailable. 304 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 305 std::string Message; 306 if (FD->getAvailability(&Message)) 307 return ": " + Message; 308 309 return std::string(); 310 } 311 312 /// DiagnoseSentinelCalls - This routine checks whether a call or 313 /// message-send is to a declaration with the sentinel attribute, and 314 /// if so, it checks that the requirements of the sentinel are 315 /// satisfied. 316 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 317 ArrayRef<Expr *> Args) { 318 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 319 if (!attr) 320 return; 321 322 // The number of formal parameters of the declaration. 323 unsigned numFormalParams; 324 325 // The kind of declaration. This is also an index into a %select in 326 // the diagnostic. 327 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 328 329 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 330 numFormalParams = MD->param_size(); 331 calleeType = CT_Method; 332 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 333 numFormalParams = FD->param_size(); 334 calleeType = CT_Function; 335 } else if (isa<VarDecl>(D)) { 336 QualType type = cast<ValueDecl>(D)->getType(); 337 const FunctionType *fn = nullptr; 338 if (const PointerType *ptr = type->getAs<PointerType>()) { 339 fn = ptr->getPointeeType()->getAs<FunctionType>(); 340 if (!fn) return; 341 calleeType = CT_Function; 342 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 343 fn = ptr->getPointeeType()->castAs<FunctionType>(); 344 calleeType = CT_Block; 345 } else { 346 return; 347 } 348 349 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 350 numFormalParams = proto->getNumParams(); 351 } else { 352 numFormalParams = 0; 353 } 354 } else { 355 return; 356 } 357 358 // "nullPos" is the number of formal parameters at the end which 359 // effectively count as part of the variadic arguments. This is 360 // useful if you would prefer to not have *any* formal parameters, 361 // but the language forces you to have at least one. 362 unsigned nullPos = attr->getNullPos(); 363 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 364 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 365 366 // The number of arguments which should follow the sentinel. 367 unsigned numArgsAfterSentinel = attr->getSentinel(); 368 369 // If there aren't enough arguments for all the formal parameters, 370 // the sentinel, and the args after the sentinel, complain. 371 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 372 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 373 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 374 return; 375 } 376 377 // Otherwise, find the sentinel expression. 378 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 379 if (!sentinelExpr) return; 380 if (sentinelExpr->isValueDependent()) return; 381 if (Context.isSentinelNullExpr(sentinelExpr)) return; 382 383 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 384 // or 'NULL' if those are actually defined in the context. Only use 385 // 'nil' for ObjC methods, where it's much more likely that the 386 // variadic arguments form a list of object pointers. 387 SourceLocation MissingNilLoc 388 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 389 std::string NullValue; 390 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 391 NullValue = "nil"; 392 else if (getLangOpts().CPlusPlus11) 393 NullValue = "nullptr"; 394 else if (PP.isMacroDefined("NULL")) 395 NullValue = "NULL"; 396 else 397 NullValue = "(void*) 0"; 398 399 if (MissingNilLoc.isInvalid()) 400 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 401 else 402 Diag(MissingNilLoc, diag::warn_missing_sentinel) 403 << int(calleeType) 404 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 405 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 406 } 407 408 SourceRange Sema::getExprRange(Expr *E) const { 409 return E ? E->getSourceRange() : SourceRange(); 410 } 411 412 //===----------------------------------------------------------------------===// 413 // Standard Promotions and Conversions 414 //===----------------------------------------------------------------------===// 415 416 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 417 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 418 // Handle any placeholder expressions which made it here. 419 if (E->getType()->isPlaceholderType()) { 420 ExprResult result = CheckPlaceholderExpr(E); 421 if (result.isInvalid()) return ExprError(); 422 E = result.get(); 423 } 424 425 QualType Ty = E->getType(); 426 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 427 428 if (Ty->isFunctionType()) { 429 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 430 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 431 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 432 return ExprError(); 433 434 E = ImpCastExprToType(E, Context.getPointerType(Ty), 435 CK_FunctionToPointerDecay).get(); 436 } else if (Ty->isArrayType()) { 437 // In C90 mode, arrays only promote to pointers if the array expression is 438 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 439 // type 'array of type' is converted to an expression that has type 'pointer 440 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 441 // that has type 'array of type' ...". The relevant change is "an lvalue" 442 // (C90) to "an expression" (C99). 443 // 444 // C++ 4.2p1: 445 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 446 // T" can be converted to an rvalue of type "pointer to T". 447 // 448 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 449 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 450 CK_ArrayToPointerDecay).get(); 451 } 452 return E; 453 } 454 455 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 456 // Check to see if we are dereferencing a null pointer. If so, 457 // and if not volatile-qualified, this is undefined behavior that the 458 // optimizer will delete, so warn about it. People sometimes try to use this 459 // to get a deterministic trap and are surprised by clang's behavior. This 460 // only handles the pattern "*null", which is a very syntactic check. 461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 462 if (UO->getOpcode() == UO_Deref && 463 UO->getSubExpr()->IgnoreParenCasts()-> 464 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 465 !UO->getType().isVolatileQualified()) { 466 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 467 S.PDiag(diag::warn_indirection_through_null) 468 << UO->getSubExpr()->getSourceRange()); 469 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 470 S.PDiag(diag::note_indirection_through_null)); 471 } 472 } 473 474 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 475 SourceLocation AssignLoc, 476 const Expr* RHS) { 477 const ObjCIvarDecl *IV = OIRE->getDecl(); 478 if (!IV) 479 return; 480 481 DeclarationName MemberName = IV->getDeclName(); 482 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 483 if (!Member || !Member->isStr("isa")) 484 return; 485 486 const Expr *Base = OIRE->getBase(); 487 QualType BaseType = Base->getType(); 488 if (OIRE->isArrow()) 489 BaseType = BaseType->getPointeeType(); 490 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 491 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 492 ObjCInterfaceDecl *ClassDeclared = nullptr; 493 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 494 if (!ClassDeclared->getSuperClass() 495 && (*ClassDeclared->ivar_begin()) == IV) { 496 if (RHS) { 497 NamedDecl *ObjectSetClass = 498 S.LookupSingleName(S.TUScope, 499 &S.Context.Idents.get("object_setClass"), 500 SourceLocation(), S.LookupOrdinaryName); 501 if (ObjectSetClass) { 502 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 503 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 504 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 505 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 506 AssignLoc), ",") << 507 FixItHint::CreateInsertion(RHSLocEnd, ")"); 508 } 509 else 510 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 511 } else { 512 NamedDecl *ObjectGetClass = 513 S.LookupSingleName(S.TUScope, 514 &S.Context.Idents.get("object_getClass"), 515 SourceLocation(), S.LookupOrdinaryName); 516 if (ObjectGetClass) 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 518 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 519 FixItHint::CreateReplacement( 520 SourceRange(OIRE->getOpLoc(), 521 OIRE->getLocEnd()), ")"); 522 else 523 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 524 } 525 S.Diag(IV->getLocation(), diag::note_ivar_decl); 526 } 527 } 528 } 529 530 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 531 // Handle any placeholder expressions which made it here. 532 if (E->getType()->isPlaceholderType()) { 533 ExprResult result = CheckPlaceholderExpr(E); 534 if (result.isInvalid()) return ExprError(); 535 E = result.get(); 536 } 537 538 // C++ [conv.lval]p1: 539 // A glvalue of a non-function, non-array type T can be 540 // converted to a prvalue. 541 if (!E->isGLValue()) return E; 542 543 QualType T = E->getType(); 544 assert(!T.isNull() && "r-value conversion on typeless expression?"); 545 546 // We don't want to throw lvalue-to-rvalue casts on top of 547 // expressions of certain types in C++. 548 if (getLangOpts().CPlusPlus && 549 (E->getType() == Context.OverloadTy || 550 T->isDependentType() || 551 T->isRecordType())) 552 return E; 553 554 // The C standard is actually really unclear on this point, and 555 // DR106 tells us what the result should be but not why. It's 556 // generally best to say that void types just doesn't undergo 557 // lvalue-to-rvalue at all. Note that expressions of unqualified 558 // 'void' type are never l-values, but qualified void can be. 559 if (T->isVoidType()) 560 return E; 561 562 // OpenCL usually rejects direct accesses to values of 'half' type. 563 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 564 T->isHalfType()) { 565 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 566 << 0 << T; 567 return ExprError(); 568 } 569 570 CheckForNullPointerDereference(*this, E); 571 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 572 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 573 &Context.Idents.get("object_getClass"), 574 SourceLocation(), LookupOrdinaryName); 575 if (ObjectGetClass) 576 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 577 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 578 FixItHint::CreateReplacement( 579 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 580 else 581 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 582 } 583 else if (const ObjCIvarRefExpr *OIRE = 584 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 585 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 586 587 // C++ [conv.lval]p1: 588 // [...] If T is a non-class type, the type of the prvalue is the 589 // cv-unqualified version of T. Otherwise, the type of the 590 // rvalue is T. 591 // 592 // C99 6.3.2.1p2: 593 // If the lvalue has qualified type, the value has the unqualified 594 // version of the type of the lvalue; otherwise, the value has the 595 // type of the lvalue. 596 if (T.hasQualifiers()) 597 T = T.getUnqualifiedType(); 598 599 // Under the MS ABI, lock down the inheritance model now. 600 if (T->isMemberPointerType() && 601 Context.getTargetInfo().getCXXABI().isMicrosoft()) 602 (void)isCompleteType(E->getExprLoc(), T); 603 604 UpdateMarkingForLValueToRValue(E); 605 606 // Loading a __weak object implicitly retains the value, so we need a cleanup to 607 // balance that. 608 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 609 Cleanup.setExprNeedsCleanups(true); 610 611 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 612 nullptr, VK_RValue); 613 614 // C11 6.3.2.1p2: 615 // ... if the lvalue has atomic type, the value has the non-atomic version 616 // of the type of the lvalue ... 617 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 618 T = Atomic->getValueType().getUnqualifiedType(); 619 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 620 nullptr, VK_RValue); 621 } 622 623 return Res; 624 } 625 626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 627 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 628 if (Res.isInvalid()) 629 return ExprError(); 630 Res = DefaultLvalueConversion(Res.get()); 631 if (Res.isInvalid()) 632 return ExprError(); 633 return Res; 634 } 635 636 /// CallExprUnaryConversions - a special case of an unary conversion 637 /// performed on a function designator of a call expression. 638 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 639 QualType Ty = E->getType(); 640 ExprResult Res = E; 641 // Only do implicit cast for a function type, but not for a pointer 642 // to function type. 643 if (Ty->isFunctionType()) { 644 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 645 CK_FunctionToPointerDecay).get(); 646 if (Res.isInvalid()) 647 return ExprError(); 648 } 649 Res = DefaultLvalueConversion(Res.get()); 650 if (Res.isInvalid()) 651 return ExprError(); 652 return Res.get(); 653 } 654 655 /// UsualUnaryConversions - Performs various conversions that are common to most 656 /// operators (C99 6.3). The conversions of array and function types are 657 /// sometimes suppressed. For example, the array->pointer conversion doesn't 658 /// apply if the array is an argument to the sizeof or address (&) operators. 659 /// In these instances, this routine should *not* be called. 660 ExprResult Sema::UsualUnaryConversions(Expr *E) { 661 // First, convert to an r-value. 662 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 663 if (Res.isInvalid()) 664 return ExprError(); 665 E = Res.get(); 666 667 QualType Ty = E->getType(); 668 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 669 670 // Half FP have to be promoted to float unless it is natively supported 671 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 672 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 673 674 // Try to perform integral promotions if the object has a theoretically 675 // promotable type. 676 if (Ty->isIntegralOrUnscopedEnumerationType()) { 677 // C99 6.3.1.1p2: 678 // 679 // The following may be used in an expression wherever an int or 680 // unsigned int may be used: 681 // - an object or expression with an integer type whose integer 682 // conversion rank is less than or equal to the rank of int 683 // and unsigned int. 684 // - A bit-field of type _Bool, int, signed int, or unsigned int. 685 // 686 // If an int can represent all values of the original type, the 687 // value is converted to an int; otherwise, it is converted to an 688 // unsigned int. These are called the integer promotions. All 689 // other types are unchanged by the integer promotions. 690 691 QualType PTy = Context.isPromotableBitField(E); 692 if (!PTy.isNull()) { 693 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 694 return E; 695 } 696 if (Ty->isPromotableIntegerType()) { 697 QualType PT = Context.getPromotedIntegerType(Ty); 698 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 699 return E; 700 } 701 } 702 return E; 703 } 704 705 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 706 /// do not have a prototype. Arguments that have type float or __fp16 707 /// are promoted to double. All other argument types are converted by 708 /// UsualUnaryConversions(). 709 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 710 QualType Ty = E->getType(); 711 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 712 713 ExprResult Res = UsualUnaryConversions(E); 714 if (Res.isInvalid()) 715 return ExprError(); 716 E = Res.get(); 717 718 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 719 // promote to double. 720 // Note that default argument promotion applies only to float (and 721 // half/fp16); it does not apply to _Float16. 722 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 723 if (BTy && (BTy->getKind() == BuiltinType::Half || 724 BTy->getKind() == BuiltinType::Float)) { 725 if (getLangOpts().OpenCL && 726 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 727 if (BTy->getKind() == BuiltinType::Half) { 728 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 729 } 730 } else { 731 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 732 } 733 } 734 735 // C++ performs lvalue-to-rvalue conversion as a default argument 736 // promotion, even on class types, but note: 737 // C++11 [conv.lval]p2: 738 // When an lvalue-to-rvalue conversion occurs in an unevaluated 739 // operand or a subexpression thereof the value contained in the 740 // referenced object is not accessed. Otherwise, if the glvalue 741 // has a class type, the conversion copy-initializes a temporary 742 // of type T from the glvalue and the result of the conversion 743 // is a prvalue for the temporary. 744 // FIXME: add some way to gate this entire thing for correctness in 745 // potentially potentially evaluated contexts. 746 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 747 ExprResult Temp = PerformCopyInitialization( 748 InitializedEntity::InitializeTemporary(E->getType()), 749 E->getExprLoc(), E); 750 if (Temp.isInvalid()) 751 return ExprError(); 752 E = Temp.get(); 753 } 754 755 return E; 756 } 757 758 /// Determine the degree of POD-ness for an expression. 759 /// Incomplete types are considered POD, since this check can be performed 760 /// when we're in an unevaluated context. 761 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 762 if (Ty->isIncompleteType()) { 763 // C++11 [expr.call]p7: 764 // After these conversions, if the argument does not have arithmetic, 765 // enumeration, pointer, pointer to member, or class type, the program 766 // is ill-formed. 767 // 768 // Since we've already performed array-to-pointer and function-to-pointer 769 // decay, the only such type in C++ is cv void. This also handles 770 // initializer lists as variadic arguments. 771 if (Ty->isVoidType()) 772 return VAK_Invalid; 773 774 if (Ty->isObjCObjectType()) 775 return VAK_Invalid; 776 return VAK_Valid; 777 } 778 779 if (Ty.isCXX98PODType(Context)) 780 return VAK_Valid; 781 782 // C++11 [expr.call]p7: 783 // Passing a potentially-evaluated argument of class type (Clause 9) 784 // having a non-trivial copy constructor, a non-trivial move constructor, 785 // or a non-trivial destructor, with no corresponding parameter, 786 // is conditionally-supported with implementation-defined semantics. 787 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 788 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 789 if (!Record->hasNonTrivialCopyConstructor() && 790 !Record->hasNonTrivialMoveConstructor() && 791 !Record->hasNonTrivialDestructor()) 792 return VAK_ValidInCXX11; 793 794 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 795 return VAK_Valid; 796 797 if (Ty->isObjCObjectType()) 798 return VAK_Invalid; 799 800 if (getLangOpts().MSVCCompat) 801 return VAK_MSVCUndefined; 802 803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 804 // permitted to reject them. We should consider doing so. 805 return VAK_Undefined; 806 } 807 808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 809 // Don't allow one to pass an Objective-C interface to a vararg. 810 const QualType &Ty = E->getType(); 811 VarArgKind VAK = isValidVarArgType(Ty); 812 813 // Complain about passing non-POD types through varargs. 814 switch (VAK) { 815 case VAK_ValidInCXX11: 816 DiagRuntimeBehavior( 817 E->getLocStart(), nullptr, 818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 819 << Ty << CT); 820 LLVM_FALLTHROUGH; 821 case VAK_Valid: 822 if (Ty->isRecordType()) { 823 // This is unlikely to be what the user intended. If the class has a 824 // 'c_str' member function, the user probably meant to call that. 825 DiagRuntimeBehavior(E->getLocStart(), nullptr, 826 PDiag(diag::warn_pass_class_arg_to_vararg) 827 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 828 } 829 break; 830 831 case VAK_Undefined: 832 case VAK_MSVCUndefined: 833 DiagRuntimeBehavior( 834 E->getLocStart(), nullptr, 835 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 836 << getLangOpts().CPlusPlus11 << Ty << CT); 837 break; 838 839 case VAK_Invalid: 840 if (Ty->isObjCObjectType()) 841 DiagRuntimeBehavior( 842 E->getLocStart(), nullptr, 843 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 844 << Ty << CT); 845 else 846 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 847 << isa<InitListExpr>(E) << Ty << CT; 848 break; 849 } 850 } 851 852 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 853 /// will create a trap if the resulting type is not a POD type. 854 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 855 FunctionDecl *FDecl) { 856 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 857 // Strip the unbridged-cast placeholder expression off, if applicable. 858 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 859 (CT == VariadicMethod || 860 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 861 E = stripARCUnbridgedCast(E); 862 863 // Otherwise, do normal placeholder checking. 864 } else { 865 ExprResult ExprRes = CheckPlaceholderExpr(E); 866 if (ExprRes.isInvalid()) 867 return ExprError(); 868 E = ExprRes.get(); 869 } 870 } 871 872 ExprResult ExprRes = DefaultArgumentPromotion(E); 873 if (ExprRes.isInvalid()) 874 return ExprError(); 875 E = ExprRes.get(); 876 877 // Diagnostics regarding non-POD argument types are 878 // emitted along with format string checking in Sema::CheckFunctionCall(). 879 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 880 // Turn this into a trap. 881 CXXScopeSpec SS; 882 SourceLocation TemplateKWLoc; 883 UnqualifiedId Name; 884 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 885 E->getLocStart()); 886 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 887 Name, true, false); 888 if (TrapFn.isInvalid()) 889 return ExprError(); 890 891 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 892 E->getLocStart(), None, 893 E->getLocEnd()); 894 if (Call.isInvalid()) 895 return ExprError(); 896 897 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 898 Call.get(), E); 899 if (Comma.isInvalid()) 900 return ExprError(); 901 return Comma.get(); 902 } 903 904 if (!getLangOpts().CPlusPlus && 905 RequireCompleteType(E->getExprLoc(), E->getType(), 906 diag::err_call_incomplete_argument)) 907 return ExprError(); 908 909 return E; 910 } 911 912 /// \brief Converts an integer to complex float type. Helper function of 913 /// UsualArithmeticConversions() 914 /// 915 /// \return false if the integer expression is an integer type and is 916 /// successfully converted to the complex type. 917 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 918 ExprResult &ComplexExpr, 919 QualType IntTy, 920 QualType ComplexTy, 921 bool SkipCast) { 922 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 923 if (SkipCast) return false; 924 if (IntTy->isIntegerType()) { 925 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 927 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 928 CK_FloatingRealToComplex); 929 } else { 930 assert(IntTy->isComplexIntegerType()); 931 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 932 CK_IntegralComplexToFloatingComplex); 933 } 934 return false; 935 } 936 937 /// \brief Handle arithmetic conversion with complex types. Helper function of 938 /// UsualArithmeticConversions() 939 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 940 ExprResult &RHS, QualType LHSType, 941 QualType RHSType, 942 bool IsCompAssign) { 943 // if we have an integer operand, the result is the complex type. 944 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 945 /*skipCast*/false)) 946 return LHSType; 947 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 948 /*skipCast*/IsCompAssign)) 949 return RHSType; 950 951 // This handles complex/complex, complex/float, or float/complex. 952 // When both operands are complex, the shorter operand is converted to the 953 // type of the longer, and that is the type of the result. This corresponds 954 // to what is done when combining two real floating-point operands. 955 // The fun begins when size promotion occur across type domains. 956 // From H&S 6.3.4: When one operand is complex and the other is a real 957 // floating-point type, the less precise type is converted, within it's 958 // real or complex domain, to the precision of the other type. For example, 959 // when combining a "long double" with a "double _Complex", the 960 // "double _Complex" is promoted to "long double _Complex". 961 962 // Compute the rank of the two types, regardless of whether they are complex. 963 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 964 965 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 966 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 967 QualType LHSElementType = 968 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 969 QualType RHSElementType = 970 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 971 972 QualType ResultType = S.Context.getComplexType(LHSElementType); 973 if (Order < 0) { 974 // Promote the precision of the LHS if not an assignment. 975 ResultType = S.Context.getComplexType(RHSElementType); 976 if (!IsCompAssign) { 977 if (LHSComplexType) 978 LHS = 979 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 980 else 981 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 982 } 983 } else if (Order > 0) { 984 // Promote the precision of the RHS. 985 if (RHSComplexType) 986 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 987 else 988 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 989 } 990 return ResultType; 991 } 992 993 /// \brief Handle arithmetic conversion from integer to float. Helper function 994 /// of UsualArithmeticConversions() 995 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 996 ExprResult &IntExpr, 997 QualType FloatTy, QualType IntTy, 998 bool ConvertFloat, bool ConvertInt) { 999 if (IntTy->isIntegerType()) { 1000 if (ConvertInt) 1001 // Convert intExpr to the lhs floating point type. 1002 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1003 CK_IntegralToFloating); 1004 return FloatTy; 1005 } 1006 1007 // Convert both sides to the appropriate complex float. 1008 assert(IntTy->isComplexIntegerType()); 1009 QualType result = S.Context.getComplexType(FloatTy); 1010 1011 // _Complex int -> _Complex float 1012 if (ConvertInt) 1013 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1014 CK_IntegralComplexToFloatingComplex); 1015 1016 // float -> _Complex float 1017 if (ConvertFloat) 1018 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1019 CK_FloatingRealToComplex); 1020 1021 return result; 1022 } 1023 1024 /// \brief Handle arithmethic conversion with floating point types. Helper 1025 /// function of UsualArithmeticConversions() 1026 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1027 ExprResult &RHS, QualType LHSType, 1028 QualType RHSType, bool IsCompAssign) { 1029 bool LHSFloat = LHSType->isRealFloatingType(); 1030 bool RHSFloat = RHSType->isRealFloatingType(); 1031 1032 // If we have two real floating types, convert the smaller operand 1033 // to the bigger result. 1034 if (LHSFloat && RHSFloat) { 1035 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1036 if (order > 0) { 1037 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1038 return LHSType; 1039 } 1040 1041 assert(order < 0 && "illegal float comparison"); 1042 if (!IsCompAssign) 1043 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1044 return RHSType; 1045 } 1046 1047 if (LHSFloat) { 1048 // Half FP has to be promoted to float unless it is natively supported 1049 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1050 LHSType = S.Context.FloatTy; 1051 1052 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1053 /*convertFloat=*/!IsCompAssign, 1054 /*convertInt=*/ true); 1055 } 1056 assert(RHSFloat); 1057 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1058 /*convertInt=*/ true, 1059 /*convertFloat=*/!IsCompAssign); 1060 } 1061 1062 /// \brief Diagnose attempts to convert between __float128 and long double if 1063 /// there is no support for such conversion. Helper function of 1064 /// UsualArithmeticConversions(). 1065 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1066 QualType RHSType) { 1067 /* No issue converting if at least one of the types is not a floating point 1068 type or the two types have the same rank. 1069 */ 1070 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1071 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1072 return false; 1073 1074 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1075 "The remaining types must be floating point types."); 1076 1077 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1078 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1079 1080 QualType LHSElemType = LHSComplex ? 1081 LHSComplex->getElementType() : LHSType; 1082 QualType RHSElemType = RHSComplex ? 1083 RHSComplex->getElementType() : RHSType; 1084 1085 // No issue if the two types have the same representation 1086 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1087 &S.Context.getFloatTypeSemantics(RHSElemType)) 1088 return false; 1089 1090 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1091 RHSElemType == S.Context.LongDoubleTy); 1092 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1093 RHSElemType == S.Context.Float128Ty); 1094 1095 /* We've handled the situation where __float128 and long double have the same 1096 representation. The only other allowable conversion is if long double is 1097 really just double. 1098 */ 1099 return Float128AndLongDouble && 1100 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1101 &llvm::APFloat::IEEEdouble()); 1102 } 1103 1104 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1105 1106 namespace { 1107 /// These helper callbacks are placed in an anonymous namespace to 1108 /// permit their use as function template parameters. 1109 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1110 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1111 } 1112 1113 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1114 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1115 CK_IntegralComplexCast); 1116 } 1117 } 1118 1119 /// \brief Handle integer arithmetic conversions. Helper function of 1120 /// UsualArithmeticConversions() 1121 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1122 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 // The rules for this case are in C99 6.3.1.8 1126 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1127 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1128 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1129 if (LHSSigned == RHSSigned) { 1130 // Same signedness; use the higher-ranked type 1131 if (order >= 0) { 1132 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1133 return LHSType; 1134 } else if (!IsCompAssign) 1135 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1136 return RHSType; 1137 } else if (order != (LHSSigned ? 1 : -1)) { 1138 // The unsigned type has greater than or equal rank to the 1139 // signed type, so use the unsigned type 1140 if (RHSSigned) { 1141 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1142 return LHSType; 1143 } else if (!IsCompAssign) 1144 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1145 return RHSType; 1146 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1147 // The two types are different widths; if we are here, that 1148 // means the signed type is larger than the unsigned type, so 1149 // use the signed type. 1150 if (LHSSigned) { 1151 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1152 return LHSType; 1153 } else if (!IsCompAssign) 1154 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1155 return RHSType; 1156 } else { 1157 // The signed type is higher-ranked than the unsigned type, 1158 // but isn't actually any bigger (like unsigned int and long 1159 // on most 32-bit systems). Use the unsigned type corresponding 1160 // to the signed type. 1161 QualType result = 1162 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1163 RHS = (*doRHSCast)(S, RHS.get(), result); 1164 if (!IsCompAssign) 1165 LHS = (*doLHSCast)(S, LHS.get(), result); 1166 return result; 1167 } 1168 } 1169 1170 /// \brief Handle conversions with GCC complex int extension. Helper function 1171 /// of UsualArithmeticConversions() 1172 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1173 ExprResult &RHS, QualType LHSType, 1174 QualType RHSType, 1175 bool IsCompAssign) { 1176 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1177 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1178 1179 if (LHSComplexInt && RHSComplexInt) { 1180 QualType LHSEltType = LHSComplexInt->getElementType(); 1181 QualType RHSEltType = RHSComplexInt->getElementType(); 1182 QualType ScalarType = 1183 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1184 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1185 1186 return S.Context.getComplexType(ScalarType); 1187 } 1188 1189 if (LHSComplexInt) { 1190 QualType LHSEltType = LHSComplexInt->getElementType(); 1191 QualType ScalarType = 1192 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1193 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1194 QualType ComplexType = S.Context.getComplexType(ScalarType); 1195 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1196 CK_IntegralRealToComplex); 1197 1198 return ComplexType; 1199 } 1200 1201 assert(RHSComplexInt); 1202 1203 QualType RHSEltType = RHSComplexInt->getElementType(); 1204 QualType ScalarType = 1205 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1206 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1207 QualType ComplexType = S.Context.getComplexType(ScalarType); 1208 1209 if (!IsCompAssign) 1210 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1211 CK_IntegralRealToComplex); 1212 return ComplexType; 1213 } 1214 1215 /// UsualArithmeticConversions - Performs various conversions that are common to 1216 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1217 /// routine returns the first non-arithmetic type found. The client is 1218 /// responsible for emitting appropriate error diagnostics. 1219 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1220 bool IsCompAssign) { 1221 if (!IsCompAssign) { 1222 LHS = UsualUnaryConversions(LHS.get()); 1223 if (LHS.isInvalid()) 1224 return QualType(); 1225 } 1226 1227 RHS = UsualUnaryConversions(RHS.get()); 1228 if (RHS.isInvalid()) 1229 return QualType(); 1230 1231 // For conversion purposes, we ignore any qualifiers. 1232 // For example, "const float" and "float" are equivalent. 1233 QualType LHSType = 1234 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1235 QualType RHSType = 1236 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1237 1238 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1239 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1240 LHSType = AtomicLHS->getValueType(); 1241 1242 // If both types are identical, no conversion is needed. 1243 if (LHSType == RHSType) 1244 return LHSType; 1245 1246 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1247 // The caller can deal with this (e.g. pointer + int). 1248 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1249 return QualType(); 1250 1251 // Apply unary and bitfield promotions to the LHS's type. 1252 QualType LHSUnpromotedType = LHSType; 1253 if (LHSType->isPromotableIntegerType()) 1254 LHSType = Context.getPromotedIntegerType(LHSType); 1255 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1256 if (!LHSBitfieldPromoteTy.isNull()) 1257 LHSType = LHSBitfieldPromoteTy; 1258 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1259 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1260 1261 // If both types are identical, no conversion is needed. 1262 if (LHSType == RHSType) 1263 return LHSType; 1264 1265 // At this point, we have two different arithmetic types. 1266 1267 // Diagnose attempts to convert between __float128 and long double where 1268 // such conversions currently can't be handled. 1269 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1270 return QualType(); 1271 1272 // Handle complex types first (C99 6.3.1.8p1). 1273 if (LHSType->isComplexType() || RHSType->isComplexType()) 1274 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1275 IsCompAssign); 1276 1277 // Now handle "real" floating types (i.e. float, double, long double). 1278 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1279 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Handle GCC complex int extension. 1283 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1284 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Finally, we have two differing integer types. 1288 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1289 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1290 } 1291 1292 1293 //===----------------------------------------------------------------------===// 1294 // Semantic Analysis for various Expression Types 1295 //===----------------------------------------------------------------------===// 1296 1297 1298 ExprResult 1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1300 SourceLocation DefaultLoc, 1301 SourceLocation RParenLoc, 1302 Expr *ControllingExpr, 1303 ArrayRef<ParsedType> ArgTypes, 1304 ArrayRef<Expr *> ArgExprs) { 1305 unsigned NumAssocs = ArgTypes.size(); 1306 assert(NumAssocs == ArgExprs.size()); 1307 1308 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1309 for (unsigned i = 0; i < NumAssocs; ++i) { 1310 if (ArgTypes[i]) 1311 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1312 else 1313 Types[i] = nullptr; 1314 } 1315 1316 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1317 ControllingExpr, 1318 llvm::makeArrayRef(Types, NumAssocs), 1319 ArgExprs); 1320 delete [] Types; 1321 return ER; 1322 } 1323 1324 ExprResult 1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1326 SourceLocation DefaultLoc, 1327 SourceLocation RParenLoc, 1328 Expr *ControllingExpr, 1329 ArrayRef<TypeSourceInfo *> Types, 1330 ArrayRef<Expr *> Exprs) { 1331 unsigned NumAssocs = Types.size(); 1332 assert(NumAssocs == Exprs.size()); 1333 1334 // Decay and strip qualifiers for the controlling expression type, and handle 1335 // placeholder type replacement. See committee discussion from WG14 DR423. 1336 { 1337 EnterExpressionEvaluationContext Unevaluated( 1338 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1339 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1340 if (R.isInvalid()) 1341 return ExprError(); 1342 ControllingExpr = R.get(); 1343 } 1344 1345 // The controlling expression is an unevaluated operand, so side effects are 1346 // likely unintended. 1347 if (!inTemplateInstantiation() && 1348 ControllingExpr->HasSideEffects(Context, false)) 1349 Diag(ControllingExpr->getExprLoc(), 1350 diag::warn_side_effects_unevaluated_context); 1351 1352 bool TypeErrorFound = false, 1353 IsResultDependent = ControllingExpr->isTypeDependent(), 1354 ContainsUnexpandedParameterPack 1355 = ControllingExpr->containsUnexpandedParameterPack(); 1356 1357 for (unsigned i = 0; i < NumAssocs; ++i) { 1358 if (Exprs[i]->containsUnexpandedParameterPack()) 1359 ContainsUnexpandedParameterPack = true; 1360 1361 if (Types[i]) { 1362 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1363 ContainsUnexpandedParameterPack = true; 1364 1365 if (Types[i]->getType()->isDependentType()) { 1366 IsResultDependent = true; 1367 } else { 1368 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1369 // complete object type other than a variably modified type." 1370 unsigned D = 0; 1371 if (Types[i]->getType()->isIncompleteType()) 1372 D = diag::err_assoc_type_incomplete; 1373 else if (!Types[i]->getType()->isObjectType()) 1374 D = diag::err_assoc_type_nonobject; 1375 else if (Types[i]->getType()->isVariablyModifiedType()) 1376 D = diag::err_assoc_type_variably_modified; 1377 1378 if (D != 0) { 1379 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1380 << Types[i]->getTypeLoc().getSourceRange() 1381 << Types[i]->getType(); 1382 TypeErrorFound = true; 1383 } 1384 1385 // C11 6.5.1.1p2 "No two generic associations in the same generic 1386 // selection shall specify compatible types." 1387 for (unsigned j = i+1; j < NumAssocs; ++j) 1388 if (Types[j] && !Types[j]->getType()->isDependentType() && 1389 Context.typesAreCompatible(Types[i]->getType(), 1390 Types[j]->getType())) { 1391 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1392 diag::err_assoc_compatible_types) 1393 << Types[j]->getTypeLoc().getSourceRange() 1394 << Types[j]->getType() 1395 << Types[i]->getType(); 1396 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1397 diag::note_compat_assoc) 1398 << Types[i]->getTypeLoc().getSourceRange() 1399 << Types[i]->getType(); 1400 TypeErrorFound = true; 1401 } 1402 } 1403 } 1404 } 1405 if (TypeErrorFound) 1406 return ExprError(); 1407 1408 // If we determined that the generic selection is result-dependent, don't 1409 // try to compute the result expression. 1410 if (IsResultDependent) 1411 return new (Context) GenericSelectionExpr( 1412 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1413 ContainsUnexpandedParameterPack); 1414 1415 SmallVector<unsigned, 1> CompatIndices; 1416 unsigned DefaultIndex = -1U; 1417 for (unsigned i = 0; i < NumAssocs; ++i) { 1418 if (!Types[i]) 1419 DefaultIndex = i; 1420 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1421 Types[i]->getType())) 1422 CompatIndices.push_back(i); 1423 } 1424 1425 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1426 // type compatible with at most one of the types named in its generic 1427 // association list." 1428 if (CompatIndices.size() > 1) { 1429 // We strip parens here because the controlling expression is typically 1430 // parenthesized in macro definitions. 1431 ControllingExpr = ControllingExpr->IgnoreParens(); 1432 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1433 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1434 << (unsigned) CompatIndices.size(); 1435 for (unsigned I : CompatIndices) { 1436 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1437 diag::note_compat_assoc) 1438 << Types[I]->getTypeLoc().getSourceRange() 1439 << Types[I]->getType(); 1440 } 1441 return ExprError(); 1442 } 1443 1444 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1445 // its controlling expression shall have type compatible with exactly one of 1446 // the types named in its generic association list." 1447 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1448 // We strip parens here because the controlling expression is typically 1449 // parenthesized in macro definitions. 1450 ControllingExpr = ControllingExpr->IgnoreParens(); 1451 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1452 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1453 return ExprError(); 1454 } 1455 1456 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1457 // type name that is compatible with the type of the controlling expression, 1458 // then the result expression of the generic selection is the expression 1459 // in that generic association. Otherwise, the result expression of the 1460 // generic selection is the expression in the default generic association." 1461 unsigned ResultIndex = 1462 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1463 1464 return new (Context) GenericSelectionExpr( 1465 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1466 ContainsUnexpandedParameterPack, ResultIndex); 1467 } 1468 1469 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1470 /// location of the token and the offset of the ud-suffix within it. 1471 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1472 unsigned Offset) { 1473 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1474 S.getLangOpts()); 1475 } 1476 1477 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1478 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1479 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1480 IdentifierInfo *UDSuffix, 1481 SourceLocation UDSuffixLoc, 1482 ArrayRef<Expr*> Args, 1483 SourceLocation LitEndLoc) { 1484 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1485 1486 QualType ArgTy[2]; 1487 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1488 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1489 if (ArgTy[ArgIdx]->isArrayType()) 1490 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1491 } 1492 1493 DeclarationName OpName = 1494 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1495 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1496 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1497 1498 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1499 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1500 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1501 /*AllowStringTemplate*/ false, 1502 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1503 return ExprError(); 1504 1505 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1506 } 1507 1508 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1509 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1510 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1511 /// multiple tokens. However, the common case is that StringToks points to one 1512 /// string. 1513 /// 1514 ExprResult 1515 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1516 assert(!StringToks.empty() && "Must have at least one string!"); 1517 1518 StringLiteralParser Literal(StringToks, PP); 1519 if (Literal.hadError) 1520 return ExprError(); 1521 1522 SmallVector<SourceLocation, 4> StringTokLocs; 1523 for (const Token &Tok : StringToks) 1524 StringTokLocs.push_back(Tok.getLocation()); 1525 1526 QualType CharTy = Context.CharTy; 1527 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1528 if (Literal.isWide()) { 1529 CharTy = Context.getWideCharType(); 1530 Kind = StringLiteral::Wide; 1531 } else if (Literal.isUTF8()) { 1532 Kind = StringLiteral::UTF8; 1533 } else if (Literal.isUTF16()) { 1534 CharTy = Context.Char16Ty; 1535 Kind = StringLiteral::UTF16; 1536 } else if (Literal.isUTF32()) { 1537 CharTy = Context.Char32Ty; 1538 Kind = StringLiteral::UTF32; 1539 } else if (Literal.isPascal()) { 1540 CharTy = Context.UnsignedCharTy; 1541 } 1542 1543 QualType CharTyConst = CharTy; 1544 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1545 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1546 CharTyConst.addConst(); 1547 1548 // Get an array type for the string, according to C99 6.4.5. This includes 1549 // the nul terminator character as well as the string length for pascal 1550 // strings. 1551 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1552 llvm::APInt(32, Literal.GetNumStringChars()+1), 1553 ArrayType::Normal, 0); 1554 1555 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1556 if (getLangOpts().OpenCL) { 1557 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1558 } 1559 1560 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1561 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1562 Kind, Literal.Pascal, StrTy, 1563 &StringTokLocs[0], 1564 StringTokLocs.size()); 1565 if (Literal.getUDSuffix().empty()) 1566 return Lit; 1567 1568 // We're building a user-defined literal. 1569 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1570 SourceLocation UDSuffixLoc = 1571 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1572 Literal.getUDSuffixOffset()); 1573 1574 // Make sure we're allowed user-defined literals here. 1575 if (!UDLScope) 1576 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1577 1578 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1579 // operator "" X (str, len) 1580 QualType SizeType = Context.getSizeType(); 1581 1582 DeclarationName OpName = 1583 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1584 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1585 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1586 1587 QualType ArgTy[] = { 1588 Context.getArrayDecayedType(StrTy), SizeType 1589 }; 1590 1591 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1592 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1593 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1594 /*AllowStringTemplate*/ true, 1595 /*DiagnoseMissing*/ true)) { 1596 1597 case LOLR_Cooked: { 1598 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1599 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1600 StringTokLocs[0]); 1601 Expr *Args[] = { Lit, LenArg }; 1602 1603 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1604 } 1605 1606 case LOLR_StringTemplate: { 1607 TemplateArgumentListInfo ExplicitArgs; 1608 1609 unsigned CharBits = Context.getIntWidth(CharTy); 1610 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1611 llvm::APSInt Value(CharBits, CharIsUnsigned); 1612 1613 TemplateArgument TypeArg(CharTy); 1614 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1615 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1616 1617 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1618 Value = Lit->getCodeUnit(I); 1619 TemplateArgument Arg(Context, Value, CharTy); 1620 TemplateArgumentLocInfo ArgInfo; 1621 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1622 } 1623 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1624 &ExplicitArgs); 1625 } 1626 case LOLR_Raw: 1627 case LOLR_Template: 1628 case LOLR_ErrorNoDiagnostic: 1629 llvm_unreachable("unexpected literal operator lookup result"); 1630 case LOLR_Error: 1631 return ExprError(); 1632 } 1633 llvm_unreachable("unexpected literal operator lookup result"); 1634 } 1635 1636 ExprResult 1637 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1638 SourceLocation Loc, 1639 const CXXScopeSpec *SS) { 1640 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1641 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1642 } 1643 1644 /// BuildDeclRefExpr - Build an expression that references a 1645 /// declaration that does not require a closure capture. 1646 ExprResult 1647 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1648 const DeclarationNameInfo &NameInfo, 1649 const CXXScopeSpec *SS, NamedDecl *FoundD, 1650 const TemplateArgumentListInfo *TemplateArgs) { 1651 bool RefersToCapturedVariable = 1652 isa<VarDecl>(D) && 1653 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1654 1655 DeclRefExpr *E; 1656 if (isa<VarTemplateSpecializationDecl>(D)) { 1657 VarTemplateSpecializationDecl *VarSpec = 1658 cast<VarTemplateSpecializationDecl>(D); 1659 1660 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1661 : NestedNameSpecifierLoc(), 1662 VarSpec->getTemplateKeywordLoc(), D, 1663 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1664 FoundD, TemplateArgs); 1665 } else { 1666 assert(!TemplateArgs && "No template arguments for non-variable" 1667 " template specialization references"); 1668 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1669 : NestedNameSpecifierLoc(), 1670 SourceLocation(), D, RefersToCapturedVariable, 1671 NameInfo, Ty, VK, FoundD); 1672 } 1673 1674 MarkDeclRefReferenced(E); 1675 1676 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1677 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1678 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1679 recordUseOfEvaluatedWeak(E); 1680 1681 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1682 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1683 FD = IFD->getAnonField(); 1684 if (FD) { 1685 UnusedPrivateFields.remove(FD); 1686 // Just in case we're building an illegal pointer-to-member. 1687 if (FD->isBitField()) 1688 E->setObjectKind(OK_BitField); 1689 } 1690 1691 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1692 // designates a bit-field. 1693 if (auto *BD = dyn_cast<BindingDecl>(D)) 1694 if (auto *BE = BD->getBinding()) 1695 E->setObjectKind(BE->getObjectKind()); 1696 1697 return E; 1698 } 1699 1700 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1701 /// possibly a list of template arguments. 1702 /// 1703 /// If this produces template arguments, it is permitted to call 1704 /// DecomposeTemplateName. 1705 /// 1706 /// This actually loses a lot of source location information for 1707 /// non-standard name kinds; we should consider preserving that in 1708 /// some way. 1709 void 1710 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1711 TemplateArgumentListInfo &Buffer, 1712 DeclarationNameInfo &NameInfo, 1713 const TemplateArgumentListInfo *&TemplateArgs) { 1714 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1715 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1716 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1717 1718 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1719 Id.TemplateId->NumArgs); 1720 translateTemplateArguments(TemplateArgsPtr, Buffer); 1721 1722 TemplateName TName = Id.TemplateId->Template.get(); 1723 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1724 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1725 TemplateArgs = &Buffer; 1726 } else { 1727 NameInfo = GetNameFromUnqualifiedId(Id); 1728 TemplateArgs = nullptr; 1729 } 1730 } 1731 1732 static void emitEmptyLookupTypoDiagnostic( 1733 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1734 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1735 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1736 DeclContext *Ctx = 1737 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1738 if (!TC) { 1739 // Emit a special diagnostic for failed member lookups. 1740 // FIXME: computing the declaration context might fail here (?) 1741 if (Ctx) 1742 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1743 << SS.getRange(); 1744 else 1745 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1746 return; 1747 } 1748 1749 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1750 bool DroppedSpecifier = 1751 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1752 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1753 ? diag::note_implicit_param_decl 1754 : diag::note_previous_decl; 1755 if (!Ctx) 1756 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1757 SemaRef.PDiag(NoteID)); 1758 else 1759 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1760 << Typo << Ctx << DroppedSpecifier 1761 << SS.getRange(), 1762 SemaRef.PDiag(NoteID)); 1763 } 1764 1765 /// Diagnose an empty lookup. 1766 /// 1767 /// \return false if new lookup candidates were found 1768 bool 1769 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1770 std::unique_ptr<CorrectionCandidateCallback> CCC, 1771 TemplateArgumentListInfo *ExplicitTemplateArgs, 1772 ArrayRef<Expr *> Args, TypoExpr **Out) { 1773 DeclarationName Name = R.getLookupName(); 1774 1775 unsigned diagnostic = diag::err_undeclared_var_use; 1776 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1777 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1778 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1779 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1780 diagnostic = diag::err_undeclared_use; 1781 diagnostic_suggest = diag::err_undeclared_use_suggest; 1782 } 1783 1784 // If the original lookup was an unqualified lookup, fake an 1785 // unqualified lookup. This is useful when (for example) the 1786 // original lookup would not have found something because it was a 1787 // dependent name. 1788 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1789 while (DC) { 1790 if (isa<CXXRecordDecl>(DC)) { 1791 LookupQualifiedName(R, DC); 1792 1793 if (!R.empty()) { 1794 // Don't give errors about ambiguities in this lookup. 1795 R.suppressDiagnostics(); 1796 1797 // During a default argument instantiation the CurContext points 1798 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1799 // function parameter list, hence add an explicit check. 1800 bool isDefaultArgument = 1801 !CodeSynthesisContexts.empty() && 1802 CodeSynthesisContexts.back().Kind == 1803 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1804 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1805 bool isInstance = CurMethod && 1806 CurMethod->isInstance() && 1807 DC == CurMethod->getParent() && !isDefaultArgument; 1808 1809 // Give a code modification hint to insert 'this->'. 1810 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1811 // Actually quite difficult! 1812 if (getLangOpts().MSVCCompat) 1813 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1814 if (isInstance) { 1815 Diag(R.getNameLoc(), diagnostic) << Name 1816 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1817 CheckCXXThisCapture(R.getNameLoc()); 1818 } else { 1819 Diag(R.getNameLoc(), diagnostic) << Name; 1820 } 1821 1822 // Do we really want to note all of these? 1823 for (NamedDecl *D : R) 1824 Diag(D->getLocation(), diag::note_dependent_var_use); 1825 1826 // Return true if we are inside a default argument instantiation 1827 // and the found name refers to an instance member function, otherwise 1828 // the function calling DiagnoseEmptyLookup will try to create an 1829 // implicit member call and this is wrong for default argument. 1830 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1831 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1832 return true; 1833 } 1834 1835 // Tell the callee to try to recover. 1836 return false; 1837 } 1838 1839 R.clear(); 1840 } 1841 1842 // In Microsoft mode, if we are performing lookup from within a friend 1843 // function definition declared at class scope then we must set 1844 // DC to the lexical parent to be able to search into the parent 1845 // class. 1846 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1847 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1848 DC->getLexicalParent()->isRecord()) 1849 DC = DC->getLexicalParent(); 1850 else 1851 DC = DC->getParent(); 1852 } 1853 1854 // We didn't find anything, so try to correct for a typo. 1855 TypoCorrection Corrected; 1856 if (S && Out) { 1857 SourceLocation TypoLoc = R.getNameLoc(); 1858 assert(!ExplicitTemplateArgs && 1859 "Diagnosing an empty lookup with explicit template args!"); 1860 *Out = CorrectTypoDelayed( 1861 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1862 [=](const TypoCorrection &TC) { 1863 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1864 diagnostic, diagnostic_suggest); 1865 }, 1866 nullptr, CTK_ErrorRecovery); 1867 if (*Out) 1868 return true; 1869 } else if (S && (Corrected = 1870 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1871 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1872 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1873 bool DroppedSpecifier = 1874 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1875 R.setLookupName(Corrected.getCorrection()); 1876 1877 bool AcceptableWithRecovery = false; 1878 bool AcceptableWithoutRecovery = false; 1879 NamedDecl *ND = Corrected.getFoundDecl(); 1880 if (ND) { 1881 if (Corrected.isOverloaded()) { 1882 OverloadCandidateSet OCS(R.getNameLoc(), 1883 OverloadCandidateSet::CSK_Normal); 1884 OverloadCandidateSet::iterator Best; 1885 for (NamedDecl *CD : Corrected) { 1886 if (FunctionTemplateDecl *FTD = 1887 dyn_cast<FunctionTemplateDecl>(CD)) 1888 AddTemplateOverloadCandidate( 1889 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1890 Args, OCS); 1891 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1892 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1893 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1894 Args, OCS); 1895 } 1896 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1897 case OR_Success: 1898 ND = Best->FoundDecl; 1899 Corrected.setCorrectionDecl(ND); 1900 break; 1901 default: 1902 // FIXME: Arbitrarily pick the first declaration for the note. 1903 Corrected.setCorrectionDecl(ND); 1904 break; 1905 } 1906 } 1907 R.addDecl(ND); 1908 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1909 CXXRecordDecl *Record = nullptr; 1910 if (Corrected.getCorrectionSpecifier()) { 1911 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1912 Record = Ty->getAsCXXRecordDecl(); 1913 } 1914 if (!Record) 1915 Record = cast<CXXRecordDecl>( 1916 ND->getDeclContext()->getRedeclContext()); 1917 R.setNamingClass(Record); 1918 } 1919 1920 auto *UnderlyingND = ND->getUnderlyingDecl(); 1921 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1922 isa<FunctionTemplateDecl>(UnderlyingND); 1923 // FIXME: If we ended up with a typo for a type name or 1924 // Objective-C class name, we're in trouble because the parser 1925 // is in the wrong place to recover. Suggest the typo 1926 // correction, but don't make it a fix-it since we're not going 1927 // to recover well anyway. 1928 AcceptableWithoutRecovery = 1929 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1930 } else { 1931 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1932 // because we aren't able to recover. 1933 AcceptableWithoutRecovery = true; 1934 } 1935 1936 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1937 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1938 ? diag::note_implicit_param_decl 1939 : diag::note_previous_decl; 1940 if (SS.isEmpty()) 1941 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1942 PDiag(NoteID), AcceptableWithRecovery); 1943 else 1944 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1945 << Name << computeDeclContext(SS, false) 1946 << DroppedSpecifier << SS.getRange(), 1947 PDiag(NoteID), AcceptableWithRecovery); 1948 1949 // Tell the callee whether to try to recover. 1950 return !AcceptableWithRecovery; 1951 } 1952 } 1953 R.clear(); 1954 1955 // Emit a special diagnostic for failed member lookups. 1956 // FIXME: computing the declaration context might fail here (?) 1957 if (!SS.isEmpty()) { 1958 Diag(R.getNameLoc(), diag::err_no_member) 1959 << Name << computeDeclContext(SS, false) 1960 << SS.getRange(); 1961 return true; 1962 } 1963 1964 // Give up, we can't recover. 1965 Diag(R.getNameLoc(), diagnostic) << Name; 1966 return true; 1967 } 1968 1969 /// In Microsoft mode, if we are inside a template class whose parent class has 1970 /// dependent base classes, and we can't resolve an unqualified identifier, then 1971 /// assume the identifier is a member of a dependent base class. We can only 1972 /// recover successfully in static methods, instance methods, and other contexts 1973 /// where 'this' is available. This doesn't precisely match MSVC's 1974 /// instantiation model, but it's close enough. 1975 static Expr * 1976 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1977 DeclarationNameInfo &NameInfo, 1978 SourceLocation TemplateKWLoc, 1979 const TemplateArgumentListInfo *TemplateArgs) { 1980 // Only try to recover from lookup into dependent bases in static methods or 1981 // contexts where 'this' is available. 1982 QualType ThisType = S.getCurrentThisType(); 1983 const CXXRecordDecl *RD = nullptr; 1984 if (!ThisType.isNull()) 1985 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1986 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1987 RD = MD->getParent(); 1988 if (!RD || !RD->hasAnyDependentBases()) 1989 return nullptr; 1990 1991 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1992 // is available, suggest inserting 'this->' as a fixit. 1993 SourceLocation Loc = NameInfo.getLoc(); 1994 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1995 DB << NameInfo.getName() << RD; 1996 1997 if (!ThisType.isNull()) { 1998 DB << FixItHint::CreateInsertion(Loc, "this->"); 1999 return CXXDependentScopeMemberExpr::Create( 2000 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2001 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2002 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2003 } 2004 2005 // Synthesize a fake NNS that points to the derived class. This will 2006 // perform name lookup during template instantiation. 2007 CXXScopeSpec SS; 2008 auto *NNS = 2009 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2010 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2011 return DependentScopeDeclRefExpr::Create( 2012 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2013 TemplateArgs); 2014 } 2015 2016 ExprResult 2017 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2018 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2019 bool HasTrailingLParen, bool IsAddressOfOperand, 2020 std::unique_ptr<CorrectionCandidateCallback> CCC, 2021 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2022 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2023 "cannot be direct & operand and have a trailing lparen"); 2024 if (SS.isInvalid()) 2025 return ExprError(); 2026 2027 TemplateArgumentListInfo TemplateArgsBuffer; 2028 2029 // Decompose the UnqualifiedId into the following data. 2030 DeclarationNameInfo NameInfo; 2031 const TemplateArgumentListInfo *TemplateArgs; 2032 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2033 2034 DeclarationName Name = NameInfo.getName(); 2035 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2036 SourceLocation NameLoc = NameInfo.getLoc(); 2037 2038 if (II && II->isEditorPlaceholder()) { 2039 // FIXME: When typed placeholders are supported we can create a typed 2040 // placeholder expression node. 2041 return ExprError(); 2042 } 2043 2044 // C++ [temp.dep.expr]p3: 2045 // An id-expression is type-dependent if it contains: 2046 // -- an identifier that was declared with a dependent type, 2047 // (note: handled after lookup) 2048 // -- a template-id that is dependent, 2049 // (note: handled in BuildTemplateIdExpr) 2050 // -- a conversion-function-id that specifies a dependent type, 2051 // -- a nested-name-specifier that contains a class-name that 2052 // names a dependent type. 2053 // Determine whether this is a member of an unknown specialization; 2054 // we need to handle these differently. 2055 bool DependentID = false; 2056 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2057 Name.getCXXNameType()->isDependentType()) { 2058 DependentID = true; 2059 } else if (SS.isSet()) { 2060 if (DeclContext *DC = computeDeclContext(SS, false)) { 2061 if (RequireCompleteDeclContext(SS, DC)) 2062 return ExprError(); 2063 } else { 2064 DependentID = true; 2065 } 2066 } 2067 2068 if (DependentID) 2069 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2070 IsAddressOfOperand, TemplateArgs); 2071 2072 // Perform the required lookup. 2073 LookupResult R(*this, NameInfo, 2074 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2075 ? LookupObjCImplicitSelfParam 2076 : LookupOrdinaryName); 2077 if (TemplateArgs) { 2078 // Lookup the template name again to correctly establish the context in 2079 // which it was found. This is really unfortunate as we already did the 2080 // lookup to determine that it was a template name in the first place. If 2081 // this becomes a performance hit, we can work harder to preserve those 2082 // results until we get here but it's likely not worth it. 2083 bool MemberOfUnknownSpecialization; 2084 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2085 MemberOfUnknownSpecialization); 2086 2087 if (MemberOfUnknownSpecialization || 2088 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2089 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2090 IsAddressOfOperand, TemplateArgs); 2091 } else { 2092 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2093 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2094 2095 // If the result might be in a dependent base class, this is a dependent 2096 // id-expression. 2097 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2098 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2099 IsAddressOfOperand, TemplateArgs); 2100 2101 // If this reference is in an Objective-C method, then we need to do 2102 // some special Objective-C lookup, too. 2103 if (IvarLookupFollowUp) { 2104 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2105 if (E.isInvalid()) 2106 return ExprError(); 2107 2108 if (Expr *Ex = E.getAs<Expr>()) 2109 return Ex; 2110 } 2111 } 2112 2113 if (R.isAmbiguous()) 2114 return ExprError(); 2115 2116 // This could be an implicitly declared function reference (legal in C90, 2117 // extension in C99, forbidden in C++). 2118 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2119 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2120 if (D) R.addDecl(D); 2121 } 2122 2123 // Determine whether this name might be a candidate for 2124 // argument-dependent lookup. 2125 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2126 2127 if (R.empty() && !ADL) { 2128 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2129 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2130 TemplateKWLoc, TemplateArgs)) 2131 return E; 2132 } 2133 2134 // Don't diagnose an empty lookup for inline assembly. 2135 if (IsInlineAsmIdentifier) 2136 return ExprError(); 2137 2138 // If this name wasn't predeclared and if this is not a function 2139 // call, diagnose the problem. 2140 TypoExpr *TE = nullptr; 2141 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2142 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2143 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2144 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2145 "Typo correction callback misconfigured"); 2146 if (CCC) { 2147 // Make sure the callback knows what the typo being diagnosed is. 2148 CCC->setTypoName(II); 2149 if (SS.isValid()) 2150 CCC->setTypoNNS(SS.getScopeRep()); 2151 } 2152 if (DiagnoseEmptyLookup(S, SS, R, 2153 CCC ? std::move(CCC) : std::move(DefaultValidator), 2154 nullptr, None, &TE)) { 2155 if (TE && KeywordReplacement) { 2156 auto &State = getTypoExprState(TE); 2157 auto BestTC = State.Consumer->getNextCorrection(); 2158 if (BestTC.isKeyword()) { 2159 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2160 if (State.DiagHandler) 2161 State.DiagHandler(BestTC); 2162 KeywordReplacement->startToken(); 2163 KeywordReplacement->setKind(II->getTokenID()); 2164 KeywordReplacement->setIdentifierInfo(II); 2165 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2166 // Clean up the state associated with the TypoExpr, since it has 2167 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2168 clearDelayedTypo(TE); 2169 // Signal that a correction to a keyword was performed by returning a 2170 // valid-but-null ExprResult. 2171 return (Expr*)nullptr; 2172 } 2173 State.Consumer->resetCorrectionStream(); 2174 } 2175 return TE ? TE : ExprError(); 2176 } 2177 2178 assert(!R.empty() && 2179 "DiagnoseEmptyLookup returned false but added no results"); 2180 2181 // If we found an Objective-C instance variable, let 2182 // LookupInObjCMethod build the appropriate expression to 2183 // reference the ivar. 2184 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2185 R.clear(); 2186 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2187 // In a hopelessly buggy code, Objective-C instance variable 2188 // lookup fails and no expression will be built to reference it. 2189 if (!E.isInvalid() && !E.get()) 2190 return ExprError(); 2191 return E; 2192 } 2193 } 2194 2195 // This is guaranteed from this point on. 2196 assert(!R.empty() || ADL); 2197 2198 // Check whether this might be a C++ implicit instance member access. 2199 // C++ [class.mfct.non-static]p3: 2200 // When an id-expression that is not part of a class member access 2201 // syntax and not used to form a pointer to member is used in the 2202 // body of a non-static member function of class X, if name lookup 2203 // resolves the name in the id-expression to a non-static non-type 2204 // member of some class C, the id-expression is transformed into a 2205 // class member access expression using (*this) as the 2206 // postfix-expression to the left of the . operator. 2207 // 2208 // But we don't actually need to do this for '&' operands if R 2209 // resolved to a function or overloaded function set, because the 2210 // expression is ill-formed if it actually works out to be a 2211 // non-static member function: 2212 // 2213 // C++ [expr.ref]p4: 2214 // Otherwise, if E1.E2 refers to a non-static member function. . . 2215 // [t]he expression can be used only as the left-hand operand of a 2216 // member function call. 2217 // 2218 // There are other safeguards against such uses, but it's important 2219 // to get this right here so that we don't end up making a 2220 // spuriously dependent expression if we're inside a dependent 2221 // instance method. 2222 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2223 bool MightBeImplicitMember; 2224 if (!IsAddressOfOperand) 2225 MightBeImplicitMember = true; 2226 else if (!SS.isEmpty()) 2227 MightBeImplicitMember = false; 2228 else if (R.isOverloadedResult()) 2229 MightBeImplicitMember = false; 2230 else if (R.isUnresolvableResult()) 2231 MightBeImplicitMember = true; 2232 else 2233 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2234 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2235 isa<MSPropertyDecl>(R.getFoundDecl()); 2236 2237 if (MightBeImplicitMember) 2238 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2239 R, TemplateArgs, S); 2240 } 2241 2242 if (TemplateArgs || TemplateKWLoc.isValid()) { 2243 2244 // In C++1y, if this is a variable template id, then check it 2245 // in BuildTemplateIdExpr(). 2246 // The single lookup result must be a variable template declaration. 2247 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2248 Id.TemplateId->Kind == TNK_Var_template) { 2249 assert(R.getAsSingle<VarTemplateDecl>() && 2250 "There should only be one declaration found."); 2251 } 2252 2253 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2254 } 2255 2256 return BuildDeclarationNameExpr(SS, R, ADL); 2257 } 2258 2259 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2260 /// declaration name, generally during template instantiation. 2261 /// There's a large number of things which don't need to be done along 2262 /// this path. 2263 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2264 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2265 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2266 DeclContext *DC = computeDeclContext(SS, false); 2267 if (!DC) 2268 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2269 NameInfo, /*TemplateArgs=*/nullptr); 2270 2271 if (RequireCompleteDeclContext(SS, DC)) 2272 return ExprError(); 2273 2274 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2275 LookupQualifiedName(R, DC); 2276 2277 if (R.isAmbiguous()) 2278 return ExprError(); 2279 2280 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2281 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2282 NameInfo, /*TemplateArgs=*/nullptr); 2283 2284 if (R.empty()) { 2285 Diag(NameInfo.getLoc(), diag::err_no_member) 2286 << NameInfo.getName() << DC << SS.getRange(); 2287 return ExprError(); 2288 } 2289 2290 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2291 // Diagnose a missing typename if this resolved unambiguously to a type in 2292 // a dependent context. If we can recover with a type, downgrade this to 2293 // a warning in Microsoft compatibility mode. 2294 unsigned DiagID = diag::err_typename_missing; 2295 if (RecoveryTSI && getLangOpts().MSVCCompat) 2296 DiagID = diag::ext_typename_missing; 2297 SourceLocation Loc = SS.getBeginLoc(); 2298 auto D = Diag(Loc, DiagID); 2299 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2300 << SourceRange(Loc, NameInfo.getEndLoc()); 2301 2302 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2303 // context. 2304 if (!RecoveryTSI) 2305 return ExprError(); 2306 2307 // Only issue the fixit if we're prepared to recover. 2308 D << FixItHint::CreateInsertion(Loc, "typename "); 2309 2310 // Recover by pretending this was an elaborated type. 2311 QualType Ty = Context.getTypeDeclType(TD); 2312 TypeLocBuilder TLB; 2313 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2314 2315 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2316 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2317 QTL.setElaboratedKeywordLoc(SourceLocation()); 2318 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2319 2320 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2321 2322 return ExprEmpty(); 2323 } 2324 2325 // Defend against this resolving to an implicit member access. We usually 2326 // won't get here if this might be a legitimate a class member (we end up in 2327 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2328 // a pointer-to-member or in an unevaluated context in C++11. 2329 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2330 return BuildPossibleImplicitMemberExpr(SS, 2331 /*TemplateKWLoc=*/SourceLocation(), 2332 R, /*TemplateArgs=*/nullptr, S); 2333 2334 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2335 } 2336 2337 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2338 /// detected that we're currently inside an ObjC method. Perform some 2339 /// additional lookup. 2340 /// 2341 /// Ideally, most of this would be done by lookup, but there's 2342 /// actually quite a lot of extra work involved. 2343 /// 2344 /// Returns a null sentinel to indicate trivial success. 2345 ExprResult 2346 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2347 IdentifierInfo *II, bool AllowBuiltinCreation) { 2348 SourceLocation Loc = Lookup.getNameLoc(); 2349 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2350 2351 // Check for error condition which is already reported. 2352 if (!CurMethod) 2353 return ExprError(); 2354 2355 // There are two cases to handle here. 1) scoped lookup could have failed, 2356 // in which case we should look for an ivar. 2) scoped lookup could have 2357 // found a decl, but that decl is outside the current instance method (i.e. 2358 // a global variable). In these two cases, we do a lookup for an ivar with 2359 // this name, if the lookup sucedes, we replace it our current decl. 2360 2361 // If we're in a class method, we don't normally want to look for 2362 // ivars. But if we don't find anything else, and there's an 2363 // ivar, that's an error. 2364 bool IsClassMethod = CurMethod->isClassMethod(); 2365 2366 bool LookForIvars; 2367 if (Lookup.empty()) 2368 LookForIvars = true; 2369 else if (IsClassMethod) 2370 LookForIvars = false; 2371 else 2372 LookForIvars = (Lookup.isSingleResult() && 2373 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2374 ObjCInterfaceDecl *IFace = nullptr; 2375 if (LookForIvars) { 2376 IFace = CurMethod->getClassInterface(); 2377 ObjCInterfaceDecl *ClassDeclared; 2378 ObjCIvarDecl *IV = nullptr; 2379 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2380 // Diagnose using an ivar in a class method. 2381 if (IsClassMethod) 2382 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2383 << IV->getDeclName()); 2384 2385 // If we're referencing an invalid decl, just return this as a silent 2386 // error node. The error diagnostic was already emitted on the decl. 2387 if (IV->isInvalidDecl()) 2388 return ExprError(); 2389 2390 // Check if referencing a field with __attribute__((deprecated)). 2391 if (DiagnoseUseOfDecl(IV, Loc)) 2392 return ExprError(); 2393 2394 // Diagnose the use of an ivar outside of the declaring class. 2395 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2396 !declaresSameEntity(ClassDeclared, IFace) && 2397 !getLangOpts().DebuggerSupport) 2398 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2399 2400 // FIXME: This should use a new expr for a direct reference, don't 2401 // turn this into Self->ivar, just return a BareIVarExpr or something. 2402 IdentifierInfo &II = Context.Idents.get("self"); 2403 UnqualifiedId SelfName; 2404 SelfName.setIdentifier(&II, SourceLocation()); 2405 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2406 CXXScopeSpec SelfScopeSpec; 2407 SourceLocation TemplateKWLoc; 2408 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2409 SelfName, false, false); 2410 if (SelfExpr.isInvalid()) 2411 return ExprError(); 2412 2413 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2414 if (SelfExpr.isInvalid()) 2415 return ExprError(); 2416 2417 MarkAnyDeclReferenced(Loc, IV, true); 2418 2419 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2420 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2421 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2422 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2423 2424 ObjCIvarRefExpr *Result = new (Context) 2425 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2426 IV->getLocation(), SelfExpr.get(), true, true); 2427 2428 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2429 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2430 recordUseOfEvaluatedWeak(Result); 2431 } 2432 if (getLangOpts().ObjCAutoRefCount) { 2433 if (CurContext->isClosure()) 2434 Diag(Loc, diag::warn_implicitly_retains_self) 2435 << FixItHint::CreateInsertion(Loc, "self->"); 2436 } 2437 2438 return Result; 2439 } 2440 } else if (CurMethod->isInstanceMethod()) { 2441 // We should warn if a local variable hides an ivar. 2442 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2443 ObjCInterfaceDecl *ClassDeclared; 2444 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2445 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2446 declaresSameEntity(IFace, ClassDeclared)) 2447 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2448 } 2449 } 2450 } else if (Lookup.isSingleResult() && 2451 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2452 // If accessing a stand-alone ivar in a class method, this is an error. 2453 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2454 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2455 << IV->getDeclName()); 2456 } 2457 2458 if (Lookup.empty() && II && AllowBuiltinCreation) { 2459 // FIXME. Consolidate this with similar code in LookupName. 2460 if (unsigned BuiltinID = II->getBuiltinID()) { 2461 if (!(getLangOpts().CPlusPlus && 2462 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2463 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2464 S, Lookup.isForRedeclaration(), 2465 Lookup.getNameLoc()); 2466 if (D) Lookup.addDecl(D); 2467 } 2468 } 2469 } 2470 // Sentinel value saying that we didn't do anything special. 2471 return ExprResult((Expr *)nullptr); 2472 } 2473 2474 /// \brief Cast a base object to a member's actual type. 2475 /// 2476 /// Logically this happens in three phases: 2477 /// 2478 /// * First we cast from the base type to the naming class. 2479 /// The naming class is the class into which we were looking 2480 /// when we found the member; it's the qualifier type if a 2481 /// qualifier was provided, and otherwise it's the base type. 2482 /// 2483 /// * Next we cast from the naming class to the declaring class. 2484 /// If the member we found was brought into a class's scope by 2485 /// a using declaration, this is that class; otherwise it's 2486 /// the class declaring the member. 2487 /// 2488 /// * Finally we cast from the declaring class to the "true" 2489 /// declaring class of the member. This conversion does not 2490 /// obey access control. 2491 ExprResult 2492 Sema::PerformObjectMemberConversion(Expr *From, 2493 NestedNameSpecifier *Qualifier, 2494 NamedDecl *FoundDecl, 2495 NamedDecl *Member) { 2496 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2497 if (!RD) 2498 return From; 2499 2500 QualType DestRecordType; 2501 QualType DestType; 2502 QualType FromRecordType; 2503 QualType FromType = From->getType(); 2504 bool PointerConversions = false; 2505 if (isa<FieldDecl>(Member)) { 2506 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2507 2508 if (FromType->getAs<PointerType>()) { 2509 DestType = Context.getPointerType(DestRecordType); 2510 FromRecordType = FromType->getPointeeType(); 2511 PointerConversions = true; 2512 } else { 2513 DestType = DestRecordType; 2514 FromRecordType = FromType; 2515 } 2516 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2517 if (Method->isStatic()) 2518 return From; 2519 2520 DestType = Method->getThisType(Context); 2521 DestRecordType = DestType->getPointeeType(); 2522 2523 if (FromType->getAs<PointerType>()) { 2524 FromRecordType = FromType->getPointeeType(); 2525 PointerConversions = true; 2526 } else { 2527 FromRecordType = FromType; 2528 DestType = DestRecordType; 2529 } 2530 } else { 2531 // No conversion necessary. 2532 return From; 2533 } 2534 2535 if (DestType->isDependentType() || FromType->isDependentType()) 2536 return From; 2537 2538 // If the unqualified types are the same, no conversion is necessary. 2539 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2540 return From; 2541 2542 SourceRange FromRange = From->getSourceRange(); 2543 SourceLocation FromLoc = FromRange.getBegin(); 2544 2545 ExprValueKind VK = From->getValueKind(); 2546 2547 // C++ [class.member.lookup]p8: 2548 // [...] Ambiguities can often be resolved by qualifying a name with its 2549 // class name. 2550 // 2551 // If the member was a qualified name and the qualified referred to a 2552 // specific base subobject type, we'll cast to that intermediate type 2553 // first and then to the object in which the member is declared. That allows 2554 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2555 // 2556 // class Base { public: int x; }; 2557 // class Derived1 : public Base { }; 2558 // class Derived2 : public Base { }; 2559 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2560 // 2561 // void VeryDerived::f() { 2562 // x = 17; // error: ambiguous base subobjects 2563 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2564 // } 2565 if (Qualifier && Qualifier->getAsType()) { 2566 QualType QType = QualType(Qualifier->getAsType(), 0); 2567 assert(QType->isRecordType() && "lookup done with non-record type"); 2568 2569 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2570 2571 // In C++98, the qualifier type doesn't actually have to be a base 2572 // type of the object type, in which case we just ignore it. 2573 // Otherwise build the appropriate casts. 2574 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2575 CXXCastPath BasePath; 2576 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2577 FromLoc, FromRange, &BasePath)) 2578 return ExprError(); 2579 2580 if (PointerConversions) 2581 QType = Context.getPointerType(QType); 2582 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2583 VK, &BasePath).get(); 2584 2585 FromType = QType; 2586 FromRecordType = QRecordType; 2587 2588 // If the qualifier type was the same as the destination type, 2589 // we're done. 2590 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2591 return From; 2592 } 2593 } 2594 2595 bool IgnoreAccess = false; 2596 2597 // If we actually found the member through a using declaration, cast 2598 // down to the using declaration's type. 2599 // 2600 // Pointer equality is fine here because only one declaration of a 2601 // class ever has member declarations. 2602 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2603 assert(isa<UsingShadowDecl>(FoundDecl)); 2604 QualType URecordType = Context.getTypeDeclType( 2605 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2606 2607 // We only need to do this if the naming-class to declaring-class 2608 // conversion is non-trivial. 2609 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2610 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2611 CXXCastPath BasePath; 2612 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2613 FromLoc, FromRange, &BasePath)) 2614 return ExprError(); 2615 2616 QualType UType = URecordType; 2617 if (PointerConversions) 2618 UType = Context.getPointerType(UType); 2619 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2620 VK, &BasePath).get(); 2621 FromType = UType; 2622 FromRecordType = URecordType; 2623 } 2624 2625 // We don't do access control for the conversion from the 2626 // declaring class to the true declaring class. 2627 IgnoreAccess = true; 2628 } 2629 2630 CXXCastPath BasePath; 2631 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2632 FromLoc, FromRange, &BasePath, 2633 IgnoreAccess)) 2634 return ExprError(); 2635 2636 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2637 VK, &BasePath); 2638 } 2639 2640 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2641 const LookupResult &R, 2642 bool HasTrailingLParen) { 2643 // Only when used directly as the postfix-expression of a call. 2644 if (!HasTrailingLParen) 2645 return false; 2646 2647 // Never if a scope specifier was provided. 2648 if (SS.isSet()) 2649 return false; 2650 2651 // Only in C++ or ObjC++. 2652 if (!getLangOpts().CPlusPlus) 2653 return false; 2654 2655 // Turn off ADL when we find certain kinds of declarations during 2656 // normal lookup: 2657 for (NamedDecl *D : R) { 2658 // C++0x [basic.lookup.argdep]p3: 2659 // -- a declaration of a class member 2660 // Since using decls preserve this property, we check this on the 2661 // original decl. 2662 if (D->isCXXClassMember()) 2663 return false; 2664 2665 // C++0x [basic.lookup.argdep]p3: 2666 // -- a block-scope function declaration that is not a 2667 // using-declaration 2668 // NOTE: we also trigger this for function templates (in fact, we 2669 // don't check the decl type at all, since all other decl types 2670 // turn off ADL anyway). 2671 if (isa<UsingShadowDecl>(D)) 2672 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2673 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2674 return false; 2675 2676 // C++0x [basic.lookup.argdep]p3: 2677 // -- a declaration that is neither a function or a function 2678 // template 2679 // And also for builtin functions. 2680 if (isa<FunctionDecl>(D)) { 2681 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2682 2683 // But also builtin functions. 2684 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2685 return false; 2686 } else if (!isa<FunctionTemplateDecl>(D)) 2687 return false; 2688 } 2689 2690 return true; 2691 } 2692 2693 2694 /// Diagnoses obvious problems with the use of the given declaration 2695 /// as an expression. This is only actually called for lookups that 2696 /// were not overloaded, and it doesn't promise that the declaration 2697 /// will in fact be used. 2698 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2699 if (D->isInvalidDecl()) 2700 return true; 2701 2702 if (isa<TypedefNameDecl>(D)) { 2703 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2704 return true; 2705 } 2706 2707 if (isa<ObjCInterfaceDecl>(D)) { 2708 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2709 return true; 2710 } 2711 2712 if (isa<NamespaceDecl>(D)) { 2713 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2714 return true; 2715 } 2716 2717 return false; 2718 } 2719 2720 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2721 LookupResult &R, bool NeedsADL, 2722 bool AcceptInvalidDecl) { 2723 // If this is a single, fully-resolved result and we don't need ADL, 2724 // just build an ordinary singleton decl ref. 2725 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2726 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2727 R.getRepresentativeDecl(), nullptr, 2728 AcceptInvalidDecl); 2729 2730 // We only need to check the declaration if there's exactly one 2731 // result, because in the overloaded case the results can only be 2732 // functions and function templates. 2733 if (R.isSingleResult() && 2734 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2735 return ExprError(); 2736 2737 // Otherwise, just build an unresolved lookup expression. Suppress 2738 // any lookup-related diagnostics; we'll hash these out later, when 2739 // we've picked a target. 2740 R.suppressDiagnostics(); 2741 2742 UnresolvedLookupExpr *ULE 2743 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2744 SS.getWithLocInContext(Context), 2745 R.getLookupNameInfo(), 2746 NeedsADL, R.isOverloadedResult(), 2747 R.begin(), R.end()); 2748 2749 return ULE; 2750 } 2751 2752 static void 2753 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2754 ValueDecl *var, DeclContext *DC); 2755 2756 /// \brief Complete semantic analysis for a reference to the given declaration. 2757 ExprResult Sema::BuildDeclarationNameExpr( 2758 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2759 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2760 bool AcceptInvalidDecl) { 2761 assert(D && "Cannot refer to a NULL declaration"); 2762 assert(!isa<FunctionTemplateDecl>(D) && 2763 "Cannot refer unambiguously to a function template"); 2764 2765 SourceLocation Loc = NameInfo.getLoc(); 2766 if (CheckDeclInExpr(*this, Loc, D)) 2767 return ExprError(); 2768 2769 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2770 // Specifically diagnose references to class templates that are missing 2771 // a template argument list. 2772 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2773 << Template << SS.getRange(); 2774 Diag(Template->getLocation(), diag::note_template_decl_here); 2775 return ExprError(); 2776 } 2777 2778 // Make sure that we're referring to a value. 2779 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2780 if (!VD) { 2781 Diag(Loc, diag::err_ref_non_value) 2782 << D << SS.getRange(); 2783 Diag(D->getLocation(), diag::note_declared_at); 2784 return ExprError(); 2785 } 2786 2787 // Check whether this declaration can be used. Note that we suppress 2788 // this check when we're going to perform argument-dependent lookup 2789 // on this function name, because this might not be the function 2790 // that overload resolution actually selects. 2791 if (DiagnoseUseOfDecl(VD, Loc)) 2792 return ExprError(); 2793 2794 // Only create DeclRefExpr's for valid Decl's. 2795 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2796 return ExprError(); 2797 2798 // Handle members of anonymous structs and unions. If we got here, 2799 // and the reference is to a class member indirect field, then this 2800 // must be the subject of a pointer-to-member expression. 2801 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2802 if (!indirectField->isCXXClassMember()) 2803 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2804 indirectField); 2805 2806 { 2807 QualType type = VD->getType(); 2808 if (type.isNull()) 2809 return ExprError(); 2810 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2811 // C++ [except.spec]p17: 2812 // An exception-specification is considered to be needed when: 2813 // - in an expression, the function is the unique lookup result or 2814 // the selected member of a set of overloaded functions. 2815 ResolveExceptionSpec(Loc, FPT); 2816 type = VD->getType(); 2817 } 2818 ExprValueKind valueKind = VK_RValue; 2819 2820 switch (D->getKind()) { 2821 // Ignore all the non-ValueDecl kinds. 2822 #define ABSTRACT_DECL(kind) 2823 #define VALUE(type, base) 2824 #define DECL(type, base) \ 2825 case Decl::type: 2826 #include "clang/AST/DeclNodes.inc" 2827 llvm_unreachable("invalid value decl kind"); 2828 2829 // These shouldn't make it here. 2830 case Decl::ObjCAtDefsField: 2831 case Decl::ObjCIvar: 2832 llvm_unreachable("forming non-member reference to ivar?"); 2833 2834 // Enum constants are always r-values and never references. 2835 // Unresolved using declarations are dependent. 2836 case Decl::EnumConstant: 2837 case Decl::UnresolvedUsingValue: 2838 case Decl::OMPDeclareReduction: 2839 valueKind = VK_RValue; 2840 break; 2841 2842 // Fields and indirect fields that got here must be for 2843 // pointer-to-member expressions; we just call them l-values for 2844 // internal consistency, because this subexpression doesn't really 2845 // exist in the high-level semantics. 2846 case Decl::Field: 2847 case Decl::IndirectField: 2848 assert(getLangOpts().CPlusPlus && 2849 "building reference to field in C?"); 2850 2851 // These can't have reference type in well-formed programs, but 2852 // for internal consistency we do this anyway. 2853 type = type.getNonReferenceType(); 2854 valueKind = VK_LValue; 2855 break; 2856 2857 // Non-type template parameters are either l-values or r-values 2858 // depending on the type. 2859 case Decl::NonTypeTemplateParm: { 2860 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2861 type = reftype->getPointeeType(); 2862 valueKind = VK_LValue; // even if the parameter is an r-value reference 2863 break; 2864 } 2865 2866 // For non-references, we need to strip qualifiers just in case 2867 // the template parameter was declared as 'const int' or whatever. 2868 valueKind = VK_RValue; 2869 type = type.getUnqualifiedType(); 2870 break; 2871 } 2872 2873 case Decl::Var: 2874 case Decl::VarTemplateSpecialization: 2875 case Decl::VarTemplatePartialSpecialization: 2876 case Decl::Decomposition: 2877 case Decl::OMPCapturedExpr: 2878 // In C, "extern void blah;" is valid and is an r-value. 2879 if (!getLangOpts().CPlusPlus && 2880 !type.hasQualifiers() && 2881 type->isVoidType()) { 2882 valueKind = VK_RValue; 2883 break; 2884 } 2885 LLVM_FALLTHROUGH; 2886 2887 case Decl::ImplicitParam: 2888 case Decl::ParmVar: { 2889 // These are always l-values. 2890 valueKind = VK_LValue; 2891 type = type.getNonReferenceType(); 2892 2893 // FIXME: Does the addition of const really only apply in 2894 // potentially-evaluated contexts? Since the variable isn't actually 2895 // captured in an unevaluated context, it seems that the answer is no. 2896 if (!isUnevaluatedContext()) { 2897 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2898 if (!CapturedType.isNull()) 2899 type = CapturedType; 2900 } 2901 2902 break; 2903 } 2904 2905 case Decl::Binding: { 2906 // These are always lvalues. 2907 valueKind = VK_LValue; 2908 type = type.getNonReferenceType(); 2909 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2910 // decides how that's supposed to work. 2911 auto *BD = cast<BindingDecl>(VD); 2912 if (BD->getDeclContext()->isFunctionOrMethod() && 2913 BD->getDeclContext() != CurContext) 2914 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2915 break; 2916 } 2917 2918 case Decl::Function: { 2919 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2920 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2921 type = Context.BuiltinFnTy; 2922 valueKind = VK_RValue; 2923 break; 2924 } 2925 } 2926 2927 const FunctionType *fty = type->castAs<FunctionType>(); 2928 2929 // If we're referring to a function with an __unknown_anytype 2930 // result type, make the entire expression __unknown_anytype. 2931 if (fty->getReturnType() == Context.UnknownAnyTy) { 2932 type = Context.UnknownAnyTy; 2933 valueKind = VK_RValue; 2934 break; 2935 } 2936 2937 // Functions are l-values in C++. 2938 if (getLangOpts().CPlusPlus) { 2939 valueKind = VK_LValue; 2940 break; 2941 } 2942 2943 // C99 DR 316 says that, if a function type comes from a 2944 // function definition (without a prototype), that type is only 2945 // used for checking compatibility. Therefore, when referencing 2946 // the function, we pretend that we don't have the full function 2947 // type. 2948 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2949 isa<FunctionProtoType>(fty)) 2950 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2951 fty->getExtInfo()); 2952 2953 // Functions are r-values in C. 2954 valueKind = VK_RValue; 2955 break; 2956 } 2957 2958 case Decl::CXXDeductionGuide: 2959 llvm_unreachable("building reference to deduction guide"); 2960 2961 case Decl::MSProperty: 2962 valueKind = VK_LValue; 2963 break; 2964 2965 case Decl::CXXMethod: 2966 // If we're referring to a method with an __unknown_anytype 2967 // result type, make the entire expression __unknown_anytype. 2968 // This should only be possible with a type written directly. 2969 if (const FunctionProtoType *proto 2970 = dyn_cast<FunctionProtoType>(VD->getType())) 2971 if (proto->getReturnType() == Context.UnknownAnyTy) { 2972 type = Context.UnknownAnyTy; 2973 valueKind = VK_RValue; 2974 break; 2975 } 2976 2977 // C++ methods are l-values if static, r-values if non-static. 2978 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2979 valueKind = VK_LValue; 2980 break; 2981 } 2982 LLVM_FALLTHROUGH; 2983 2984 case Decl::CXXConversion: 2985 case Decl::CXXDestructor: 2986 case Decl::CXXConstructor: 2987 valueKind = VK_RValue; 2988 break; 2989 } 2990 2991 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2992 TemplateArgs); 2993 } 2994 } 2995 2996 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2997 SmallString<32> &Target) { 2998 Target.resize(CharByteWidth * (Source.size() + 1)); 2999 char *ResultPtr = &Target[0]; 3000 const llvm::UTF8 *ErrorPtr; 3001 bool success = 3002 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3003 (void)success; 3004 assert(success); 3005 Target.resize(ResultPtr - &Target[0]); 3006 } 3007 3008 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3009 PredefinedExpr::IdentType IT) { 3010 // Pick the current block, lambda, captured statement or function. 3011 Decl *currentDecl = nullptr; 3012 if (const BlockScopeInfo *BSI = getCurBlock()) 3013 currentDecl = BSI->TheDecl; 3014 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3015 currentDecl = LSI->CallOperator; 3016 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3017 currentDecl = CSI->TheCapturedDecl; 3018 else 3019 currentDecl = getCurFunctionOrMethodDecl(); 3020 3021 if (!currentDecl) { 3022 Diag(Loc, diag::ext_predef_outside_function); 3023 currentDecl = Context.getTranslationUnitDecl(); 3024 } 3025 3026 QualType ResTy; 3027 StringLiteral *SL = nullptr; 3028 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3029 ResTy = Context.DependentTy; 3030 else { 3031 // Pre-defined identifiers are of type char[x], where x is the length of 3032 // the string. 3033 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3034 unsigned Length = Str.length(); 3035 3036 llvm::APInt LengthI(32, Length + 1); 3037 if (IT == PredefinedExpr::LFunction) { 3038 ResTy = Context.WideCharTy.withConst(); 3039 SmallString<32> RawChars; 3040 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3041 Str, RawChars); 3042 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3043 /*IndexTypeQuals*/ 0); 3044 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3045 /*Pascal*/ false, ResTy, Loc); 3046 } else { 3047 ResTy = Context.CharTy.withConst(); 3048 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3049 /*IndexTypeQuals*/ 0); 3050 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3051 /*Pascal*/ false, ResTy, Loc); 3052 } 3053 } 3054 3055 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3056 } 3057 3058 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3059 PredefinedExpr::IdentType IT; 3060 3061 switch (Kind) { 3062 default: llvm_unreachable("Unknown simple primary expr!"); 3063 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3064 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3065 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3066 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3067 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3068 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3069 } 3070 3071 return BuildPredefinedExpr(Loc, IT); 3072 } 3073 3074 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3075 SmallString<16> CharBuffer; 3076 bool Invalid = false; 3077 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3078 if (Invalid) 3079 return ExprError(); 3080 3081 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3082 PP, Tok.getKind()); 3083 if (Literal.hadError()) 3084 return ExprError(); 3085 3086 QualType Ty; 3087 if (Literal.isWide()) 3088 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3089 else if (Literal.isUTF16()) 3090 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3091 else if (Literal.isUTF32()) 3092 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3093 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3094 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3095 else 3096 Ty = Context.CharTy; // 'x' -> char in C++ 3097 3098 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3099 if (Literal.isWide()) 3100 Kind = CharacterLiteral::Wide; 3101 else if (Literal.isUTF16()) 3102 Kind = CharacterLiteral::UTF16; 3103 else if (Literal.isUTF32()) 3104 Kind = CharacterLiteral::UTF32; 3105 else if (Literal.isUTF8()) 3106 Kind = CharacterLiteral::UTF8; 3107 3108 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3109 Tok.getLocation()); 3110 3111 if (Literal.getUDSuffix().empty()) 3112 return Lit; 3113 3114 // We're building a user-defined literal. 3115 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3116 SourceLocation UDSuffixLoc = 3117 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3118 3119 // Make sure we're allowed user-defined literals here. 3120 if (!UDLScope) 3121 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3122 3123 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3124 // operator "" X (ch) 3125 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3126 Lit, Tok.getLocation()); 3127 } 3128 3129 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3130 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3131 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3132 Context.IntTy, Loc); 3133 } 3134 3135 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3136 QualType Ty, SourceLocation Loc) { 3137 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3138 3139 using llvm::APFloat; 3140 APFloat Val(Format); 3141 3142 APFloat::opStatus result = Literal.GetFloatValue(Val); 3143 3144 // Overflow is always an error, but underflow is only an error if 3145 // we underflowed to zero (APFloat reports denormals as underflow). 3146 if ((result & APFloat::opOverflow) || 3147 ((result & APFloat::opUnderflow) && Val.isZero())) { 3148 unsigned diagnostic; 3149 SmallString<20> buffer; 3150 if (result & APFloat::opOverflow) { 3151 diagnostic = diag::warn_float_overflow; 3152 APFloat::getLargest(Format).toString(buffer); 3153 } else { 3154 diagnostic = diag::warn_float_underflow; 3155 APFloat::getSmallest(Format).toString(buffer); 3156 } 3157 3158 S.Diag(Loc, diagnostic) 3159 << Ty 3160 << StringRef(buffer.data(), buffer.size()); 3161 } 3162 3163 bool isExact = (result == APFloat::opOK); 3164 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3165 } 3166 3167 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3168 assert(E && "Invalid expression"); 3169 3170 if (E->isValueDependent()) 3171 return false; 3172 3173 QualType QT = E->getType(); 3174 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3175 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3176 return true; 3177 } 3178 3179 llvm::APSInt ValueAPS; 3180 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3181 3182 if (R.isInvalid()) 3183 return true; 3184 3185 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3186 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3187 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3188 << ValueAPS.toString(10) << ValueIsPositive; 3189 return true; 3190 } 3191 3192 return false; 3193 } 3194 3195 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3196 // Fast path for a single digit (which is quite common). A single digit 3197 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3198 if (Tok.getLength() == 1) { 3199 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3200 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3201 } 3202 3203 SmallString<128> SpellingBuffer; 3204 // NumericLiteralParser wants to overread by one character. Add padding to 3205 // the buffer in case the token is copied to the buffer. If getSpelling() 3206 // returns a StringRef to the memory buffer, it should have a null char at 3207 // the EOF, so it is also safe. 3208 SpellingBuffer.resize(Tok.getLength() + 1); 3209 3210 // Get the spelling of the token, which eliminates trigraphs, etc. 3211 bool Invalid = false; 3212 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3213 if (Invalid) 3214 return ExprError(); 3215 3216 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3217 if (Literal.hadError) 3218 return ExprError(); 3219 3220 if (Literal.hasUDSuffix()) { 3221 // We're building a user-defined literal. 3222 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3223 SourceLocation UDSuffixLoc = 3224 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3225 3226 // Make sure we're allowed user-defined literals here. 3227 if (!UDLScope) 3228 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3229 3230 QualType CookedTy; 3231 if (Literal.isFloatingLiteral()) { 3232 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3233 // long double, the literal is treated as a call of the form 3234 // operator "" X (f L) 3235 CookedTy = Context.LongDoubleTy; 3236 } else { 3237 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3238 // unsigned long long, the literal is treated as a call of the form 3239 // operator "" X (n ULL) 3240 CookedTy = Context.UnsignedLongLongTy; 3241 } 3242 3243 DeclarationName OpName = 3244 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3245 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3246 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3247 3248 SourceLocation TokLoc = Tok.getLocation(); 3249 3250 // Perform literal operator lookup to determine if we're building a raw 3251 // literal or a cooked one. 3252 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3253 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3254 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3255 /*AllowStringTemplate*/ false, 3256 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3257 case LOLR_ErrorNoDiagnostic: 3258 // Lookup failure for imaginary constants isn't fatal, there's still the 3259 // GNU extension producing _Complex types. 3260 break; 3261 case LOLR_Error: 3262 return ExprError(); 3263 case LOLR_Cooked: { 3264 Expr *Lit; 3265 if (Literal.isFloatingLiteral()) { 3266 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3267 } else { 3268 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3269 if (Literal.GetIntegerValue(ResultVal)) 3270 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3271 << /* Unsigned */ 1; 3272 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3273 Tok.getLocation()); 3274 } 3275 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3276 } 3277 3278 case LOLR_Raw: { 3279 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3280 // literal is treated as a call of the form 3281 // operator "" X ("n") 3282 unsigned Length = Literal.getUDSuffixOffset(); 3283 QualType StrTy = Context.getConstantArrayType( 3284 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3285 ArrayType::Normal, 0); 3286 Expr *Lit = StringLiteral::Create( 3287 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3288 /*Pascal*/false, StrTy, &TokLoc, 1); 3289 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3290 } 3291 3292 case LOLR_Template: { 3293 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3294 // template), L is treated as a call fo the form 3295 // operator "" X <'c1', 'c2', ... 'ck'>() 3296 // where n is the source character sequence c1 c2 ... ck. 3297 TemplateArgumentListInfo ExplicitArgs; 3298 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3299 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3300 llvm::APSInt Value(CharBits, CharIsUnsigned); 3301 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3302 Value = TokSpelling[I]; 3303 TemplateArgument Arg(Context, Value, Context.CharTy); 3304 TemplateArgumentLocInfo ArgInfo; 3305 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3306 } 3307 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3308 &ExplicitArgs); 3309 } 3310 case LOLR_StringTemplate: 3311 llvm_unreachable("unexpected literal operator lookup result"); 3312 } 3313 } 3314 3315 Expr *Res; 3316 3317 if (Literal.isFloatingLiteral()) { 3318 QualType Ty; 3319 if (Literal.isHalf){ 3320 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3321 Ty = Context.HalfTy; 3322 else { 3323 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3324 return ExprError(); 3325 } 3326 } else if (Literal.isFloat) 3327 Ty = Context.FloatTy; 3328 else if (Literal.isLong) 3329 Ty = Context.LongDoubleTy; 3330 else if (Literal.isFloat16) 3331 Ty = Context.Float16Ty; 3332 else if (Literal.isFloat128) 3333 Ty = Context.Float128Ty; 3334 else 3335 Ty = Context.DoubleTy; 3336 3337 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3338 3339 if (Ty == Context.DoubleTy) { 3340 if (getLangOpts().SinglePrecisionConstants) { 3341 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3342 if (BTy->getKind() != BuiltinType::Float) { 3343 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3344 } 3345 } else if (getLangOpts().OpenCL && 3346 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3347 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3348 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3349 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3350 } 3351 } 3352 } else if (!Literal.isIntegerLiteral()) { 3353 return ExprError(); 3354 } else { 3355 QualType Ty; 3356 3357 // 'long long' is a C99 or C++11 feature. 3358 if (!getLangOpts().C99 && Literal.isLongLong) { 3359 if (getLangOpts().CPlusPlus) 3360 Diag(Tok.getLocation(), 3361 getLangOpts().CPlusPlus11 ? 3362 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3363 else 3364 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3365 } 3366 3367 // Get the value in the widest-possible width. 3368 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3369 llvm::APInt ResultVal(MaxWidth, 0); 3370 3371 if (Literal.GetIntegerValue(ResultVal)) { 3372 // If this value didn't fit into uintmax_t, error and force to ull. 3373 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3374 << /* Unsigned */ 1; 3375 Ty = Context.UnsignedLongLongTy; 3376 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3377 "long long is not intmax_t?"); 3378 } else { 3379 // If this value fits into a ULL, try to figure out what else it fits into 3380 // according to the rules of C99 6.4.4.1p5. 3381 3382 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3383 // be an unsigned int. 3384 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3385 3386 // Check from smallest to largest, picking the smallest type we can. 3387 unsigned Width = 0; 3388 3389 // Microsoft specific integer suffixes are explicitly sized. 3390 if (Literal.MicrosoftInteger) { 3391 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3392 Width = 8; 3393 Ty = Context.CharTy; 3394 } else { 3395 Width = Literal.MicrosoftInteger; 3396 Ty = Context.getIntTypeForBitwidth(Width, 3397 /*Signed=*/!Literal.isUnsigned); 3398 } 3399 } 3400 3401 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3402 // Are int/unsigned possibilities? 3403 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3404 3405 // Does it fit in a unsigned int? 3406 if (ResultVal.isIntN(IntSize)) { 3407 // Does it fit in a signed int? 3408 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3409 Ty = Context.IntTy; 3410 else if (AllowUnsigned) 3411 Ty = Context.UnsignedIntTy; 3412 Width = IntSize; 3413 } 3414 } 3415 3416 // Are long/unsigned long possibilities? 3417 if (Ty.isNull() && !Literal.isLongLong) { 3418 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3419 3420 // Does it fit in a unsigned long? 3421 if (ResultVal.isIntN(LongSize)) { 3422 // Does it fit in a signed long? 3423 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3424 Ty = Context.LongTy; 3425 else if (AllowUnsigned) 3426 Ty = Context.UnsignedLongTy; 3427 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3428 // is compatible. 3429 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3430 const unsigned LongLongSize = 3431 Context.getTargetInfo().getLongLongWidth(); 3432 Diag(Tok.getLocation(), 3433 getLangOpts().CPlusPlus 3434 ? Literal.isLong 3435 ? diag::warn_old_implicitly_unsigned_long_cxx 3436 : /*C++98 UB*/ diag:: 3437 ext_old_implicitly_unsigned_long_cxx 3438 : diag::warn_old_implicitly_unsigned_long) 3439 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3440 : /*will be ill-formed*/ 1); 3441 Ty = Context.UnsignedLongTy; 3442 } 3443 Width = LongSize; 3444 } 3445 } 3446 3447 // Check long long if needed. 3448 if (Ty.isNull()) { 3449 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3450 3451 // Does it fit in a unsigned long long? 3452 if (ResultVal.isIntN(LongLongSize)) { 3453 // Does it fit in a signed long long? 3454 // To be compatible with MSVC, hex integer literals ending with the 3455 // LL or i64 suffix are always signed in Microsoft mode. 3456 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3457 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3458 Ty = Context.LongLongTy; 3459 else if (AllowUnsigned) 3460 Ty = Context.UnsignedLongLongTy; 3461 Width = LongLongSize; 3462 } 3463 } 3464 3465 // If we still couldn't decide a type, we probably have something that 3466 // does not fit in a signed long long, but has no U suffix. 3467 if (Ty.isNull()) { 3468 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3469 Ty = Context.UnsignedLongLongTy; 3470 Width = Context.getTargetInfo().getLongLongWidth(); 3471 } 3472 3473 if (ResultVal.getBitWidth() != Width) 3474 ResultVal = ResultVal.trunc(Width); 3475 } 3476 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3477 } 3478 3479 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3480 if (Literal.isImaginary) { 3481 Res = new (Context) ImaginaryLiteral(Res, 3482 Context.getComplexType(Res->getType())); 3483 3484 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3485 } 3486 return Res; 3487 } 3488 3489 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3490 assert(E && "ActOnParenExpr() missing expr"); 3491 return new (Context) ParenExpr(L, R, E); 3492 } 3493 3494 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3495 SourceLocation Loc, 3496 SourceRange ArgRange) { 3497 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3498 // scalar or vector data type argument..." 3499 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3500 // type (C99 6.2.5p18) or void. 3501 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3502 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3503 << T << ArgRange; 3504 return true; 3505 } 3506 3507 assert((T->isVoidType() || !T->isIncompleteType()) && 3508 "Scalar types should always be complete"); 3509 return false; 3510 } 3511 3512 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3513 SourceLocation Loc, 3514 SourceRange ArgRange, 3515 UnaryExprOrTypeTrait TraitKind) { 3516 // Invalid types must be hard errors for SFINAE in C++. 3517 if (S.LangOpts.CPlusPlus) 3518 return true; 3519 3520 // C99 6.5.3.4p1: 3521 if (T->isFunctionType() && 3522 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3523 // sizeof(function)/alignof(function) is allowed as an extension. 3524 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3525 << TraitKind << ArgRange; 3526 return false; 3527 } 3528 3529 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3530 // this is an error (OpenCL v1.1 s6.3.k) 3531 if (T->isVoidType()) { 3532 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3533 : diag::ext_sizeof_alignof_void_type; 3534 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3535 return false; 3536 } 3537 3538 return true; 3539 } 3540 3541 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3542 SourceLocation Loc, 3543 SourceRange ArgRange, 3544 UnaryExprOrTypeTrait TraitKind) { 3545 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3546 // runtime doesn't allow it. 3547 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3548 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3549 << T << (TraitKind == UETT_SizeOf) 3550 << ArgRange; 3551 return true; 3552 } 3553 3554 return false; 3555 } 3556 3557 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3558 /// pointer type is equal to T) and emit a warning if it is. 3559 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3560 Expr *E) { 3561 // Don't warn if the operation changed the type. 3562 if (T != E->getType()) 3563 return; 3564 3565 // Now look for array decays. 3566 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3567 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3568 return; 3569 3570 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3571 << ICE->getType() 3572 << ICE->getSubExpr()->getType(); 3573 } 3574 3575 /// \brief Check the constraints on expression operands to unary type expression 3576 /// and type traits. 3577 /// 3578 /// Completes any types necessary and validates the constraints on the operand 3579 /// expression. The logic mostly mirrors the type-based overload, but may modify 3580 /// the expression as it completes the type for that expression through template 3581 /// instantiation, etc. 3582 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3583 UnaryExprOrTypeTrait ExprKind) { 3584 QualType ExprTy = E->getType(); 3585 assert(!ExprTy->isReferenceType()); 3586 3587 if (ExprKind == UETT_VecStep) 3588 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3589 E->getSourceRange()); 3590 3591 // Whitelist some types as extensions 3592 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3593 E->getSourceRange(), ExprKind)) 3594 return false; 3595 3596 // 'alignof' applied to an expression only requires the base element type of 3597 // the expression to be complete. 'sizeof' requires the expression's type to 3598 // be complete (and will attempt to complete it if it's an array of unknown 3599 // bound). 3600 if (ExprKind == UETT_AlignOf) { 3601 if (RequireCompleteType(E->getExprLoc(), 3602 Context.getBaseElementType(E->getType()), 3603 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3604 E->getSourceRange())) 3605 return true; 3606 } else { 3607 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3608 ExprKind, E->getSourceRange())) 3609 return true; 3610 } 3611 3612 // Completing the expression's type may have changed it. 3613 ExprTy = E->getType(); 3614 assert(!ExprTy->isReferenceType()); 3615 3616 if (ExprTy->isFunctionType()) { 3617 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3618 << ExprKind << E->getSourceRange(); 3619 return true; 3620 } 3621 3622 // The operand for sizeof and alignof is in an unevaluated expression context, 3623 // so side effects could result in unintended consequences. 3624 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3625 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3626 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3627 3628 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3629 E->getSourceRange(), ExprKind)) 3630 return true; 3631 3632 if (ExprKind == UETT_SizeOf) { 3633 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3634 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3635 QualType OType = PVD->getOriginalType(); 3636 QualType Type = PVD->getType(); 3637 if (Type->isPointerType() && OType->isArrayType()) { 3638 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3639 << Type << OType; 3640 Diag(PVD->getLocation(), diag::note_declared_at); 3641 } 3642 } 3643 } 3644 3645 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3646 // decays into a pointer and returns an unintended result. This is most 3647 // likely a typo for "sizeof(array) op x". 3648 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3649 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3650 BO->getLHS()); 3651 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3652 BO->getRHS()); 3653 } 3654 } 3655 3656 return false; 3657 } 3658 3659 /// \brief Check the constraints on operands to unary expression and type 3660 /// traits. 3661 /// 3662 /// This will complete any types necessary, and validate the various constraints 3663 /// on those operands. 3664 /// 3665 /// The UsualUnaryConversions() function is *not* called by this routine. 3666 /// C99 6.3.2.1p[2-4] all state: 3667 /// Except when it is the operand of the sizeof operator ... 3668 /// 3669 /// C++ [expr.sizeof]p4 3670 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3671 /// standard conversions are not applied to the operand of sizeof. 3672 /// 3673 /// This policy is followed for all of the unary trait expressions. 3674 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3675 SourceLocation OpLoc, 3676 SourceRange ExprRange, 3677 UnaryExprOrTypeTrait ExprKind) { 3678 if (ExprType->isDependentType()) 3679 return false; 3680 3681 // C++ [expr.sizeof]p2: 3682 // When applied to a reference or a reference type, the result 3683 // is the size of the referenced type. 3684 // C++11 [expr.alignof]p3: 3685 // When alignof is applied to a reference type, the result 3686 // shall be the alignment of the referenced type. 3687 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3688 ExprType = Ref->getPointeeType(); 3689 3690 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3691 // When alignof or _Alignof is applied to an array type, the result 3692 // is the alignment of the element type. 3693 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3694 ExprType = Context.getBaseElementType(ExprType); 3695 3696 if (ExprKind == UETT_VecStep) 3697 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3698 3699 // Whitelist some types as extensions 3700 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3701 ExprKind)) 3702 return false; 3703 3704 if (RequireCompleteType(OpLoc, ExprType, 3705 diag::err_sizeof_alignof_incomplete_type, 3706 ExprKind, ExprRange)) 3707 return true; 3708 3709 if (ExprType->isFunctionType()) { 3710 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3711 << ExprKind << ExprRange; 3712 return true; 3713 } 3714 3715 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3716 ExprKind)) 3717 return true; 3718 3719 return false; 3720 } 3721 3722 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3723 E = E->IgnoreParens(); 3724 3725 // Cannot know anything else if the expression is dependent. 3726 if (E->isTypeDependent()) 3727 return false; 3728 3729 if (E->getObjectKind() == OK_BitField) { 3730 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3731 << 1 << E->getSourceRange(); 3732 return true; 3733 } 3734 3735 ValueDecl *D = nullptr; 3736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3737 D = DRE->getDecl(); 3738 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3739 D = ME->getMemberDecl(); 3740 } 3741 3742 // If it's a field, require the containing struct to have a 3743 // complete definition so that we can compute the layout. 3744 // 3745 // This can happen in C++11 onwards, either by naming the member 3746 // in a way that is not transformed into a member access expression 3747 // (in an unevaluated operand, for instance), or by naming the member 3748 // in a trailing-return-type. 3749 // 3750 // For the record, since __alignof__ on expressions is a GCC 3751 // extension, GCC seems to permit this but always gives the 3752 // nonsensical answer 0. 3753 // 3754 // We don't really need the layout here --- we could instead just 3755 // directly check for all the appropriate alignment-lowing 3756 // attributes --- but that would require duplicating a lot of 3757 // logic that just isn't worth duplicating for such a marginal 3758 // use-case. 3759 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3760 // Fast path this check, since we at least know the record has a 3761 // definition if we can find a member of it. 3762 if (!FD->getParent()->isCompleteDefinition()) { 3763 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3764 << E->getSourceRange(); 3765 return true; 3766 } 3767 3768 // Otherwise, if it's a field, and the field doesn't have 3769 // reference type, then it must have a complete type (or be a 3770 // flexible array member, which we explicitly want to 3771 // white-list anyway), which makes the following checks trivial. 3772 if (!FD->getType()->isReferenceType()) 3773 return false; 3774 } 3775 3776 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3777 } 3778 3779 bool Sema::CheckVecStepExpr(Expr *E) { 3780 E = E->IgnoreParens(); 3781 3782 // Cannot know anything else if the expression is dependent. 3783 if (E->isTypeDependent()) 3784 return false; 3785 3786 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3787 } 3788 3789 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3790 CapturingScopeInfo *CSI) { 3791 assert(T->isVariablyModifiedType()); 3792 assert(CSI != nullptr); 3793 3794 // We're going to walk down into the type and look for VLA expressions. 3795 do { 3796 const Type *Ty = T.getTypePtr(); 3797 switch (Ty->getTypeClass()) { 3798 #define TYPE(Class, Base) 3799 #define ABSTRACT_TYPE(Class, Base) 3800 #define NON_CANONICAL_TYPE(Class, Base) 3801 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3802 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3803 #include "clang/AST/TypeNodes.def" 3804 T = QualType(); 3805 break; 3806 // These types are never variably-modified. 3807 case Type::Builtin: 3808 case Type::Complex: 3809 case Type::Vector: 3810 case Type::ExtVector: 3811 case Type::Record: 3812 case Type::Enum: 3813 case Type::Elaborated: 3814 case Type::TemplateSpecialization: 3815 case Type::ObjCObject: 3816 case Type::ObjCInterface: 3817 case Type::ObjCObjectPointer: 3818 case Type::ObjCTypeParam: 3819 case Type::Pipe: 3820 llvm_unreachable("type class is never variably-modified!"); 3821 case Type::Adjusted: 3822 T = cast<AdjustedType>(Ty)->getOriginalType(); 3823 break; 3824 case Type::Decayed: 3825 T = cast<DecayedType>(Ty)->getPointeeType(); 3826 break; 3827 case Type::Pointer: 3828 T = cast<PointerType>(Ty)->getPointeeType(); 3829 break; 3830 case Type::BlockPointer: 3831 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3832 break; 3833 case Type::LValueReference: 3834 case Type::RValueReference: 3835 T = cast<ReferenceType>(Ty)->getPointeeType(); 3836 break; 3837 case Type::MemberPointer: 3838 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3839 break; 3840 case Type::ConstantArray: 3841 case Type::IncompleteArray: 3842 // Losing element qualification here is fine. 3843 T = cast<ArrayType>(Ty)->getElementType(); 3844 break; 3845 case Type::VariableArray: { 3846 // Losing element qualification here is fine. 3847 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3848 3849 // Unknown size indication requires no size computation. 3850 // Otherwise, evaluate and record it. 3851 if (auto Size = VAT->getSizeExpr()) { 3852 if (!CSI->isVLATypeCaptured(VAT)) { 3853 RecordDecl *CapRecord = nullptr; 3854 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3855 CapRecord = LSI->Lambda; 3856 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3857 CapRecord = CRSI->TheRecordDecl; 3858 } 3859 if (CapRecord) { 3860 auto ExprLoc = Size->getExprLoc(); 3861 auto SizeType = Context.getSizeType(); 3862 // Build the non-static data member. 3863 auto Field = 3864 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3865 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3866 /*BW*/ nullptr, /*Mutable*/ false, 3867 /*InitStyle*/ ICIS_NoInit); 3868 Field->setImplicit(true); 3869 Field->setAccess(AS_private); 3870 Field->setCapturedVLAType(VAT); 3871 CapRecord->addDecl(Field); 3872 3873 CSI->addVLATypeCapture(ExprLoc, SizeType); 3874 } 3875 } 3876 } 3877 T = VAT->getElementType(); 3878 break; 3879 } 3880 case Type::FunctionProto: 3881 case Type::FunctionNoProto: 3882 T = cast<FunctionType>(Ty)->getReturnType(); 3883 break; 3884 case Type::Paren: 3885 case Type::TypeOf: 3886 case Type::UnaryTransform: 3887 case Type::Attributed: 3888 case Type::SubstTemplateTypeParm: 3889 case Type::PackExpansion: 3890 // Keep walking after single level desugaring. 3891 T = T.getSingleStepDesugaredType(Context); 3892 break; 3893 case Type::Typedef: 3894 T = cast<TypedefType>(Ty)->desugar(); 3895 break; 3896 case Type::Decltype: 3897 T = cast<DecltypeType>(Ty)->desugar(); 3898 break; 3899 case Type::Auto: 3900 case Type::DeducedTemplateSpecialization: 3901 T = cast<DeducedType>(Ty)->getDeducedType(); 3902 break; 3903 case Type::TypeOfExpr: 3904 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3905 break; 3906 case Type::Atomic: 3907 T = cast<AtomicType>(Ty)->getValueType(); 3908 break; 3909 } 3910 } while (!T.isNull() && T->isVariablyModifiedType()); 3911 } 3912 3913 /// \brief Build a sizeof or alignof expression given a type operand. 3914 ExprResult 3915 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3916 SourceLocation OpLoc, 3917 UnaryExprOrTypeTrait ExprKind, 3918 SourceRange R) { 3919 if (!TInfo) 3920 return ExprError(); 3921 3922 QualType T = TInfo->getType(); 3923 3924 if (!T->isDependentType() && 3925 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3926 return ExprError(); 3927 3928 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3929 if (auto *TT = T->getAs<TypedefType>()) { 3930 for (auto I = FunctionScopes.rbegin(), 3931 E = std::prev(FunctionScopes.rend()); 3932 I != E; ++I) { 3933 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3934 if (CSI == nullptr) 3935 break; 3936 DeclContext *DC = nullptr; 3937 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3938 DC = LSI->CallOperator; 3939 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3940 DC = CRSI->TheCapturedDecl; 3941 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3942 DC = BSI->TheDecl; 3943 if (DC) { 3944 if (DC->containsDecl(TT->getDecl())) 3945 break; 3946 captureVariablyModifiedType(Context, T, CSI); 3947 } 3948 } 3949 } 3950 } 3951 3952 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3953 return new (Context) UnaryExprOrTypeTraitExpr( 3954 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3955 } 3956 3957 /// \brief Build a sizeof or alignof expression given an expression 3958 /// operand. 3959 ExprResult 3960 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3961 UnaryExprOrTypeTrait ExprKind) { 3962 ExprResult PE = CheckPlaceholderExpr(E); 3963 if (PE.isInvalid()) 3964 return ExprError(); 3965 3966 E = PE.get(); 3967 3968 // Verify that the operand is valid. 3969 bool isInvalid = false; 3970 if (E->isTypeDependent()) { 3971 // Delay type-checking for type-dependent expressions. 3972 } else if (ExprKind == UETT_AlignOf) { 3973 isInvalid = CheckAlignOfExpr(*this, E); 3974 } else if (ExprKind == UETT_VecStep) { 3975 isInvalid = CheckVecStepExpr(E); 3976 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3977 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3978 isInvalid = true; 3979 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3980 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3981 isInvalid = true; 3982 } else { 3983 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3984 } 3985 3986 if (isInvalid) 3987 return ExprError(); 3988 3989 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3990 PE = TransformToPotentiallyEvaluated(E); 3991 if (PE.isInvalid()) return ExprError(); 3992 E = PE.get(); 3993 } 3994 3995 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3996 return new (Context) UnaryExprOrTypeTraitExpr( 3997 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3998 } 3999 4000 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4001 /// expr and the same for @c alignof and @c __alignof 4002 /// Note that the ArgRange is invalid if isType is false. 4003 ExprResult 4004 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4005 UnaryExprOrTypeTrait ExprKind, bool IsType, 4006 void *TyOrEx, SourceRange ArgRange) { 4007 // If error parsing type, ignore. 4008 if (!TyOrEx) return ExprError(); 4009 4010 if (IsType) { 4011 TypeSourceInfo *TInfo; 4012 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4013 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4014 } 4015 4016 Expr *ArgEx = (Expr *)TyOrEx; 4017 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4018 return Result; 4019 } 4020 4021 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4022 bool IsReal) { 4023 if (V.get()->isTypeDependent()) 4024 return S.Context.DependentTy; 4025 4026 // _Real and _Imag are only l-values for normal l-values. 4027 if (V.get()->getObjectKind() != OK_Ordinary) { 4028 V = S.DefaultLvalueConversion(V.get()); 4029 if (V.isInvalid()) 4030 return QualType(); 4031 } 4032 4033 // These operators return the element type of a complex type. 4034 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4035 return CT->getElementType(); 4036 4037 // Otherwise they pass through real integer and floating point types here. 4038 if (V.get()->getType()->isArithmeticType()) 4039 return V.get()->getType(); 4040 4041 // Test for placeholders. 4042 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4043 if (PR.isInvalid()) return QualType(); 4044 if (PR.get() != V.get()) { 4045 V = PR; 4046 return CheckRealImagOperand(S, V, Loc, IsReal); 4047 } 4048 4049 // Reject anything else. 4050 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4051 << (IsReal ? "__real" : "__imag"); 4052 return QualType(); 4053 } 4054 4055 4056 4057 ExprResult 4058 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4059 tok::TokenKind Kind, Expr *Input) { 4060 UnaryOperatorKind Opc; 4061 switch (Kind) { 4062 default: llvm_unreachable("Unknown unary op!"); 4063 case tok::plusplus: Opc = UO_PostInc; break; 4064 case tok::minusminus: Opc = UO_PostDec; break; 4065 } 4066 4067 // Since this might is a postfix expression, get rid of ParenListExprs. 4068 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4069 if (Result.isInvalid()) return ExprError(); 4070 Input = Result.get(); 4071 4072 return BuildUnaryOp(S, OpLoc, Opc, Input); 4073 } 4074 4075 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4076 /// 4077 /// \return true on error 4078 static bool checkArithmeticOnObjCPointer(Sema &S, 4079 SourceLocation opLoc, 4080 Expr *op) { 4081 assert(op->getType()->isObjCObjectPointerType()); 4082 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4083 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4084 return false; 4085 4086 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4087 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4088 << op->getSourceRange(); 4089 return true; 4090 } 4091 4092 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4093 auto *BaseNoParens = Base->IgnoreParens(); 4094 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4095 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4096 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4097 } 4098 4099 ExprResult 4100 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4101 Expr *idx, SourceLocation rbLoc) { 4102 if (base && !base->getType().isNull() && 4103 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4104 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4105 /*Length=*/nullptr, rbLoc); 4106 4107 // Since this might be a postfix expression, get rid of ParenListExprs. 4108 if (isa<ParenListExpr>(base)) { 4109 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4110 if (result.isInvalid()) return ExprError(); 4111 base = result.get(); 4112 } 4113 4114 // Handle any non-overload placeholder types in the base and index 4115 // expressions. We can't handle overloads here because the other 4116 // operand might be an overloadable type, in which case the overload 4117 // resolution for the operator overload should get the first crack 4118 // at the overload. 4119 bool IsMSPropertySubscript = false; 4120 if (base->getType()->isNonOverloadPlaceholderType()) { 4121 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4122 if (!IsMSPropertySubscript) { 4123 ExprResult result = CheckPlaceholderExpr(base); 4124 if (result.isInvalid()) 4125 return ExprError(); 4126 base = result.get(); 4127 } 4128 } 4129 if (idx->getType()->isNonOverloadPlaceholderType()) { 4130 ExprResult result = CheckPlaceholderExpr(idx); 4131 if (result.isInvalid()) return ExprError(); 4132 idx = result.get(); 4133 } 4134 4135 // Build an unanalyzed expression if either operand is type-dependent. 4136 if (getLangOpts().CPlusPlus && 4137 (base->isTypeDependent() || idx->isTypeDependent())) { 4138 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4139 VK_LValue, OK_Ordinary, rbLoc); 4140 } 4141 4142 // MSDN, property (C++) 4143 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4144 // This attribute can also be used in the declaration of an empty array in a 4145 // class or structure definition. For example: 4146 // __declspec(property(get=GetX, put=PutX)) int x[]; 4147 // The above statement indicates that x[] can be used with one or more array 4148 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4149 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4150 if (IsMSPropertySubscript) { 4151 // Build MS property subscript expression if base is MS property reference 4152 // or MS property subscript. 4153 return new (Context) MSPropertySubscriptExpr( 4154 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4155 } 4156 4157 // Use C++ overloaded-operator rules if either operand has record 4158 // type. The spec says to do this if either type is *overloadable*, 4159 // but enum types can't declare subscript operators or conversion 4160 // operators, so there's nothing interesting for overload resolution 4161 // to do if there aren't any record types involved. 4162 // 4163 // ObjC pointers have their own subscripting logic that is not tied 4164 // to overload resolution and so should not take this path. 4165 if (getLangOpts().CPlusPlus && 4166 (base->getType()->isRecordType() || 4167 (!base->getType()->isObjCObjectPointerType() && 4168 idx->getType()->isRecordType()))) { 4169 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4170 } 4171 4172 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4173 } 4174 4175 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4176 Expr *LowerBound, 4177 SourceLocation ColonLoc, Expr *Length, 4178 SourceLocation RBLoc) { 4179 if (Base->getType()->isPlaceholderType() && 4180 !Base->getType()->isSpecificPlaceholderType( 4181 BuiltinType::OMPArraySection)) { 4182 ExprResult Result = CheckPlaceholderExpr(Base); 4183 if (Result.isInvalid()) 4184 return ExprError(); 4185 Base = Result.get(); 4186 } 4187 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4188 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4189 if (Result.isInvalid()) 4190 return ExprError(); 4191 Result = DefaultLvalueConversion(Result.get()); 4192 if (Result.isInvalid()) 4193 return ExprError(); 4194 LowerBound = Result.get(); 4195 } 4196 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4197 ExprResult Result = CheckPlaceholderExpr(Length); 4198 if (Result.isInvalid()) 4199 return ExprError(); 4200 Result = DefaultLvalueConversion(Result.get()); 4201 if (Result.isInvalid()) 4202 return ExprError(); 4203 Length = Result.get(); 4204 } 4205 4206 // Build an unanalyzed expression if either operand is type-dependent. 4207 if (Base->isTypeDependent() || 4208 (LowerBound && 4209 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4210 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4211 return new (Context) 4212 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4213 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4214 } 4215 4216 // Perform default conversions. 4217 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4218 QualType ResultTy; 4219 if (OriginalTy->isAnyPointerType()) { 4220 ResultTy = OriginalTy->getPointeeType(); 4221 } else if (OriginalTy->isArrayType()) { 4222 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4223 } else { 4224 return ExprError( 4225 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4226 << Base->getSourceRange()); 4227 } 4228 // C99 6.5.2.1p1 4229 if (LowerBound) { 4230 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4231 LowerBound); 4232 if (Res.isInvalid()) 4233 return ExprError(Diag(LowerBound->getExprLoc(), 4234 diag::err_omp_typecheck_section_not_integer) 4235 << 0 << LowerBound->getSourceRange()); 4236 LowerBound = Res.get(); 4237 4238 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4239 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4240 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4241 << 0 << LowerBound->getSourceRange(); 4242 } 4243 if (Length) { 4244 auto Res = 4245 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4246 if (Res.isInvalid()) 4247 return ExprError(Diag(Length->getExprLoc(), 4248 diag::err_omp_typecheck_section_not_integer) 4249 << 1 << Length->getSourceRange()); 4250 Length = Res.get(); 4251 4252 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4253 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4254 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4255 << 1 << Length->getSourceRange(); 4256 } 4257 4258 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4259 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4260 // type. Note that functions are not objects, and that (in C99 parlance) 4261 // incomplete types are not object types. 4262 if (ResultTy->isFunctionType()) { 4263 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4264 << ResultTy << Base->getSourceRange(); 4265 return ExprError(); 4266 } 4267 4268 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4269 diag::err_omp_section_incomplete_type, Base)) 4270 return ExprError(); 4271 4272 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4273 llvm::APSInt LowerBoundValue; 4274 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4275 // OpenMP 4.5, [2.4 Array Sections] 4276 // The array section must be a subset of the original array. 4277 if (LowerBoundValue.isNegative()) { 4278 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4279 << LowerBound->getSourceRange(); 4280 return ExprError(); 4281 } 4282 } 4283 } 4284 4285 if (Length) { 4286 llvm::APSInt LengthValue; 4287 if (Length->EvaluateAsInt(LengthValue, Context)) { 4288 // OpenMP 4.5, [2.4 Array Sections] 4289 // The length must evaluate to non-negative integers. 4290 if (LengthValue.isNegative()) { 4291 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4292 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4293 << Length->getSourceRange(); 4294 return ExprError(); 4295 } 4296 } 4297 } else if (ColonLoc.isValid() && 4298 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4299 !OriginalTy->isVariableArrayType()))) { 4300 // OpenMP 4.5, [2.4 Array Sections] 4301 // When the size of the array dimension is not known, the length must be 4302 // specified explicitly. 4303 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4304 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4305 return ExprError(); 4306 } 4307 4308 if (!Base->getType()->isSpecificPlaceholderType( 4309 BuiltinType::OMPArraySection)) { 4310 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4311 if (Result.isInvalid()) 4312 return ExprError(); 4313 Base = Result.get(); 4314 } 4315 return new (Context) 4316 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4317 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4318 } 4319 4320 ExprResult 4321 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4322 Expr *Idx, SourceLocation RLoc) { 4323 Expr *LHSExp = Base; 4324 Expr *RHSExp = Idx; 4325 4326 ExprValueKind VK = VK_LValue; 4327 ExprObjectKind OK = OK_Ordinary; 4328 4329 // Per C++ core issue 1213, the result is an xvalue if either operand is 4330 // a non-lvalue array, and an lvalue otherwise. 4331 if (getLangOpts().CPlusPlus11 && 4332 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4333 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4334 VK = VK_XValue; 4335 4336 // Perform default conversions. 4337 if (!LHSExp->getType()->getAs<VectorType>()) { 4338 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4339 if (Result.isInvalid()) 4340 return ExprError(); 4341 LHSExp = Result.get(); 4342 } 4343 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4344 if (Result.isInvalid()) 4345 return ExprError(); 4346 RHSExp = Result.get(); 4347 4348 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4349 4350 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4351 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4352 // in the subscript position. As a result, we need to derive the array base 4353 // and index from the expression types. 4354 Expr *BaseExpr, *IndexExpr; 4355 QualType ResultType; 4356 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4357 BaseExpr = LHSExp; 4358 IndexExpr = RHSExp; 4359 ResultType = Context.DependentTy; 4360 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4361 BaseExpr = LHSExp; 4362 IndexExpr = RHSExp; 4363 ResultType = PTy->getPointeeType(); 4364 } else if (const ObjCObjectPointerType *PTy = 4365 LHSTy->getAs<ObjCObjectPointerType>()) { 4366 BaseExpr = LHSExp; 4367 IndexExpr = RHSExp; 4368 4369 // Use custom logic if this should be the pseudo-object subscript 4370 // expression. 4371 if (!LangOpts.isSubscriptPointerArithmetic()) 4372 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4373 nullptr); 4374 4375 ResultType = PTy->getPointeeType(); 4376 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4377 // Handle the uncommon case of "123[Ptr]". 4378 BaseExpr = RHSExp; 4379 IndexExpr = LHSExp; 4380 ResultType = PTy->getPointeeType(); 4381 } else if (const ObjCObjectPointerType *PTy = 4382 RHSTy->getAs<ObjCObjectPointerType>()) { 4383 // Handle the uncommon case of "123[Ptr]". 4384 BaseExpr = RHSExp; 4385 IndexExpr = LHSExp; 4386 ResultType = PTy->getPointeeType(); 4387 if (!LangOpts.isSubscriptPointerArithmetic()) { 4388 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4389 << ResultType << BaseExpr->getSourceRange(); 4390 return ExprError(); 4391 } 4392 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4393 BaseExpr = LHSExp; // vectors: V[123] 4394 IndexExpr = RHSExp; 4395 VK = LHSExp->getValueKind(); 4396 if (VK != VK_RValue) 4397 OK = OK_VectorComponent; 4398 4399 // FIXME: need to deal with const... 4400 ResultType = VTy->getElementType(); 4401 } else if (LHSTy->isArrayType()) { 4402 // If we see an array that wasn't promoted by 4403 // DefaultFunctionArrayLvalueConversion, it must be an array that 4404 // wasn't promoted because of the C90 rule that doesn't 4405 // allow promoting non-lvalue arrays. Warn, then 4406 // force the promotion here. 4407 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4408 LHSExp->getSourceRange(); 4409 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4410 CK_ArrayToPointerDecay).get(); 4411 LHSTy = LHSExp->getType(); 4412 4413 BaseExpr = LHSExp; 4414 IndexExpr = RHSExp; 4415 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4416 } else if (RHSTy->isArrayType()) { 4417 // Same as previous, except for 123[f().a] case 4418 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4419 RHSExp->getSourceRange(); 4420 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4421 CK_ArrayToPointerDecay).get(); 4422 RHSTy = RHSExp->getType(); 4423 4424 BaseExpr = RHSExp; 4425 IndexExpr = LHSExp; 4426 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4427 } else { 4428 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4429 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4430 } 4431 // C99 6.5.2.1p1 4432 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4433 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4434 << IndexExpr->getSourceRange()); 4435 4436 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4437 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4438 && !IndexExpr->isTypeDependent()) 4439 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4440 4441 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4442 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4443 // type. Note that Functions are not objects, and that (in C99 parlance) 4444 // incomplete types are not object types. 4445 if (ResultType->isFunctionType()) { 4446 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4447 << ResultType << BaseExpr->getSourceRange(); 4448 return ExprError(); 4449 } 4450 4451 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4452 // GNU extension: subscripting on pointer to void 4453 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4454 << BaseExpr->getSourceRange(); 4455 4456 // C forbids expressions of unqualified void type from being l-values. 4457 // See IsCForbiddenLValueType. 4458 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4459 } else if (!ResultType->isDependentType() && 4460 RequireCompleteType(LLoc, ResultType, 4461 diag::err_subscript_incomplete_type, BaseExpr)) 4462 return ExprError(); 4463 4464 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4465 !ResultType.isCForbiddenLValueType()); 4466 4467 return new (Context) 4468 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4469 } 4470 4471 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4472 ParmVarDecl *Param) { 4473 if (Param->hasUnparsedDefaultArg()) { 4474 Diag(CallLoc, 4475 diag::err_use_of_default_argument_to_function_declared_later) << 4476 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4477 Diag(UnparsedDefaultArgLocs[Param], 4478 diag::note_default_argument_declared_here); 4479 return true; 4480 } 4481 4482 if (Param->hasUninstantiatedDefaultArg()) { 4483 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4484 4485 EnterExpressionEvaluationContext EvalContext( 4486 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4487 4488 // Instantiate the expression. 4489 // 4490 // FIXME: Pass in a correct Pattern argument, otherwise 4491 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4492 // 4493 // template<typename T> 4494 // struct A { 4495 // static int FooImpl(); 4496 // 4497 // template<typename Tp> 4498 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4499 // // template argument list [[T], [Tp]], should be [[Tp]]. 4500 // friend A<Tp> Foo(int a); 4501 // }; 4502 // 4503 // template<typename T> 4504 // A<T> Foo(int a = A<T>::FooImpl()); 4505 MultiLevelTemplateArgumentList MutiLevelArgList 4506 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4507 4508 InstantiatingTemplate Inst(*this, CallLoc, Param, 4509 MutiLevelArgList.getInnermost()); 4510 if (Inst.isInvalid()) 4511 return true; 4512 if (Inst.isAlreadyInstantiating()) { 4513 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4514 Param->setInvalidDecl(); 4515 return true; 4516 } 4517 4518 ExprResult Result; 4519 { 4520 // C++ [dcl.fct.default]p5: 4521 // The names in the [default argument] expression are bound, and 4522 // the semantic constraints are checked, at the point where the 4523 // default argument expression appears. 4524 ContextRAII SavedContext(*this, FD); 4525 LocalInstantiationScope Local(*this); 4526 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4527 /*DirectInit*/false); 4528 } 4529 if (Result.isInvalid()) 4530 return true; 4531 4532 // Check the expression as an initializer for the parameter. 4533 InitializedEntity Entity 4534 = InitializedEntity::InitializeParameter(Context, Param); 4535 InitializationKind Kind 4536 = InitializationKind::CreateCopy(Param->getLocation(), 4537 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4538 Expr *ResultE = Result.getAs<Expr>(); 4539 4540 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4541 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4542 if (Result.isInvalid()) 4543 return true; 4544 4545 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4546 Param->getOuterLocStart()); 4547 if (Result.isInvalid()) 4548 return true; 4549 4550 // Remember the instantiated default argument. 4551 Param->setDefaultArg(Result.getAs<Expr>()); 4552 if (ASTMutationListener *L = getASTMutationListener()) { 4553 L->DefaultArgumentInstantiated(Param); 4554 } 4555 } 4556 4557 // If the default argument expression is not set yet, we are building it now. 4558 if (!Param->hasInit()) { 4559 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4560 Param->setInvalidDecl(); 4561 return true; 4562 } 4563 4564 // If the default expression creates temporaries, we need to 4565 // push them to the current stack of expression temporaries so they'll 4566 // be properly destroyed. 4567 // FIXME: We should really be rebuilding the default argument with new 4568 // bound temporaries; see the comment in PR5810. 4569 // We don't need to do that with block decls, though, because 4570 // blocks in default argument expression can never capture anything. 4571 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4572 // Set the "needs cleanups" bit regardless of whether there are 4573 // any explicit objects. 4574 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4575 4576 // Append all the objects to the cleanup list. Right now, this 4577 // should always be a no-op, because blocks in default argument 4578 // expressions should never be able to capture anything. 4579 assert(!Init->getNumObjects() && 4580 "default argument expression has capturing blocks?"); 4581 } 4582 4583 // We already type-checked the argument, so we know it works. 4584 // Just mark all of the declarations in this potentially-evaluated expression 4585 // as being "referenced". 4586 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4587 /*SkipLocalVariables=*/true); 4588 return false; 4589 } 4590 4591 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4592 FunctionDecl *FD, ParmVarDecl *Param) { 4593 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4594 return ExprError(); 4595 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4596 } 4597 4598 Sema::VariadicCallType 4599 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4600 Expr *Fn) { 4601 if (Proto && Proto->isVariadic()) { 4602 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4603 return VariadicConstructor; 4604 else if (Fn && Fn->getType()->isBlockPointerType()) 4605 return VariadicBlock; 4606 else if (FDecl) { 4607 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4608 if (Method->isInstance()) 4609 return VariadicMethod; 4610 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4611 return VariadicMethod; 4612 return VariadicFunction; 4613 } 4614 return VariadicDoesNotApply; 4615 } 4616 4617 namespace { 4618 class FunctionCallCCC : public FunctionCallFilterCCC { 4619 public: 4620 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4621 unsigned NumArgs, MemberExpr *ME) 4622 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4623 FunctionName(FuncName) {} 4624 4625 bool ValidateCandidate(const TypoCorrection &candidate) override { 4626 if (!candidate.getCorrectionSpecifier() || 4627 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4628 return false; 4629 } 4630 4631 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4632 } 4633 4634 private: 4635 const IdentifierInfo *const FunctionName; 4636 }; 4637 } 4638 4639 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4640 FunctionDecl *FDecl, 4641 ArrayRef<Expr *> Args) { 4642 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4643 DeclarationName FuncName = FDecl->getDeclName(); 4644 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4645 4646 if (TypoCorrection Corrected = S.CorrectTypo( 4647 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4648 S.getScopeForContext(S.CurContext), nullptr, 4649 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4650 Args.size(), ME), 4651 Sema::CTK_ErrorRecovery)) { 4652 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4653 if (Corrected.isOverloaded()) { 4654 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4655 OverloadCandidateSet::iterator Best; 4656 for (NamedDecl *CD : Corrected) { 4657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4658 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4659 OCS); 4660 } 4661 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4662 case OR_Success: 4663 ND = Best->FoundDecl; 4664 Corrected.setCorrectionDecl(ND); 4665 break; 4666 default: 4667 break; 4668 } 4669 } 4670 ND = ND->getUnderlyingDecl(); 4671 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4672 return Corrected; 4673 } 4674 } 4675 return TypoCorrection(); 4676 } 4677 4678 /// ConvertArgumentsForCall - Converts the arguments specified in 4679 /// Args/NumArgs to the parameter types of the function FDecl with 4680 /// function prototype Proto. Call is the call expression itself, and 4681 /// Fn is the function expression. For a C++ member function, this 4682 /// routine does not attempt to convert the object argument. Returns 4683 /// true if the call is ill-formed. 4684 bool 4685 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4686 FunctionDecl *FDecl, 4687 const FunctionProtoType *Proto, 4688 ArrayRef<Expr *> Args, 4689 SourceLocation RParenLoc, 4690 bool IsExecConfig) { 4691 // Bail out early if calling a builtin with custom typechecking. 4692 if (FDecl) 4693 if (unsigned ID = FDecl->getBuiltinID()) 4694 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4695 return false; 4696 4697 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4698 // assignment, to the types of the corresponding parameter, ... 4699 unsigned NumParams = Proto->getNumParams(); 4700 bool Invalid = false; 4701 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4702 unsigned FnKind = Fn->getType()->isBlockPointerType() 4703 ? 1 /* block */ 4704 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4705 : 0 /* function */); 4706 4707 // If too few arguments are available (and we don't have default 4708 // arguments for the remaining parameters), don't make the call. 4709 if (Args.size() < NumParams) { 4710 if (Args.size() < MinArgs) { 4711 TypoCorrection TC; 4712 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4713 unsigned diag_id = 4714 MinArgs == NumParams && !Proto->isVariadic() 4715 ? diag::err_typecheck_call_too_few_args_suggest 4716 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4717 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4718 << static_cast<unsigned>(Args.size()) 4719 << TC.getCorrectionRange()); 4720 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4721 Diag(RParenLoc, 4722 MinArgs == NumParams && !Proto->isVariadic() 4723 ? diag::err_typecheck_call_too_few_args_one 4724 : diag::err_typecheck_call_too_few_args_at_least_one) 4725 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4726 else 4727 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4728 ? diag::err_typecheck_call_too_few_args 4729 : diag::err_typecheck_call_too_few_args_at_least) 4730 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4731 << Fn->getSourceRange(); 4732 4733 // Emit the location of the prototype. 4734 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4735 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4736 << FDecl; 4737 4738 return true; 4739 } 4740 Call->setNumArgs(Context, NumParams); 4741 } 4742 4743 // If too many are passed and not variadic, error on the extras and drop 4744 // them. 4745 if (Args.size() > NumParams) { 4746 if (!Proto->isVariadic()) { 4747 TypoCorrection TC; 4748 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4749 unsigned diag_id = 4750 MinArgs == NumParams && !Proto->isVariadic() 4751 ? diag::err_typecheck_call_too_many_args_suggest 4752 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4753 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4754 << static_cast<unsigned>(Args.size()) 4755 << TC.getCorrectionRange()); 4756 } else if (NumParams == 1 && FDecl && 4757 FDecl->getParamDecl(0)->getDeclName()) 4758 Diag(Args[NumParams]->getLocStart(), 4759 MinArgs == NumParams 4760 ? diag::err_typecheck_call_too_many_args_one 4761 : diag::err_typecheck_call_too_many_args_at_most_one) 4762 << FnKind << FDecl->getParamDecl(0) 4763 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4764 << SourceRange(Args[NumParams]->getLocStart(), 4765 Args.back()->getLocEnd()); 4766 else 4767 Diag(Args[NumParams]->getLocStart(), 4768 MinArgs == NumParams 4769 ? diag::err_typecheck_call_too_many_args 4770 : diag::err_typecheck_call_too_many_args_at_most) 4771 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4772 << Fn->getSourceRange() 4773 << SourceRange(Args[NumParams]->getLocStart(), 4774 Args.back()->getLocEnd()); 4775 4776 // Emit the location of the prototype. 4777 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4778 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4779 << FDecl; 4780 4781 // This deletes the extra arguments. 4782 Call->setNumArgs(Context, NumParams); 4783 return true; 4784 } 4785 } 4786 SmallVector<Expr *, 8> AllArgs; 4787 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4788 4789 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4790 Proto, 0, Args, AllArgs, CallType); 4791 if (Invalid) 4792 return true; 4793 unsigned TotalNumArgs = AllArgs.size(); 4794 for (unsigned i = 0; i < TotalNumArgs; ++i) 4795 Call->setArg(i, AllArgs[i]); 4796 4797 return false; 4798 } 4799 4800 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4801 const FunctionProtoType *Proto, 4802 unsigned FirstParam, ArrayRef<Expr *> Args, 4803 SmallVectorImpl<Expr *> &AllArgs, 4804 VariadicCallType CallType, bool AllowExplicit, 4805 bool IsListInitialization) { 4806 unsigned NumParams = Proto->getNumParams(); 4807 bool Invalid = false; 4808 size_t ArgIx = 0; 4809 // Continue to check argument types (even if we have too few/many args). 4810 for (unsigned i = FirstParam; i < NumParams; i++) { 4811 QualType ProtoArgType = Proto->getParamType(i); 4812 4813 Expr *Arg; 4814 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4815 if (ArgIx < Args.size()) { 4816 Arg = Args[ArgIx++]; 4817 4818 if (RequireCompleteType(Arg->getLocStart(), 4819 ProtoArgType, 4820 diag::err_call_incomplete_argument, Arg)) 4821 return true; 4822 4823 // Strip the unbridged-cast placeholder expression off, if applicable. 4824 bool CFAudited = false; 4825 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4826 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4827 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4828 Arg = stripARCUnbridgedCast(Arg); 4829 else if (getLangOpts().ObjCAutoRefCount && 4830 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4831 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4832 CFAudited = true; 4833 4834 InitializedEntity Entity = 4835 Param ? InitializedEntity::InitializeParameter(Context, Param, 4836 ProtoArgType) 4837 : InitializedEntity::InitializeParameter( 4838 Context, ProtoArgType, Proto->isParamConsumed(i)); 4839 4840 // Remember that parameter belongs to a CF audited API. 4841 if (CFAudited) 4842 Entity.setParameterCFAudited(); 4843 4844 ExprResult ArgE = PerformCopyInitialization( 4845 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4846 if (ArgE.isInvalid()) 4847 return true; 4848 4849 Arg = ArgE.getAs<Expr>(); 4850 } else { 4851 assert(Param && "can't use default arguments without a known callee"); 4852 4853 ExprResult ArgExpr = 4854 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4855 if (ArgExpr.isInvalid()) 4856 return true; 4857 4858 Arg = ArgExpr.getAs<Expr>(); 4859 } 4860 4861 // Check for array bounds violations for each argument to the call. This 4862 // check only triggers warnings when the argument isn't a more complex Expr 4863 // with its own checking, such as a BinaryOperator. 4864 CheckArrayAccess(Arg); 4865 4866 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4867 CheckStaticArrayArgument(CallLoc, Param, Arg); 4868 4869 AllArgs.push_back(Arg); 4870 } 4871 4872 // If this is a variadic call, handle args passed through "...". 4873 if (CallType != VariadicDoesNotApply) { 4874 // Assume that extern "C" functions with variadic arguments that 4875 // return __unknown_anytype aren't *really* variadic. 4876 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4877 FDecl->isExternC()) { 4878 for (Expr *A : Args.slice(ArgIx)) { 4879 QualType paramType; // ignored 4880 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4881 Invalid |= arg.isInvalid(); 4882 AllArgs.push_back(arg.get()); 4883 } 4884 4885 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4886 } else { 4887 for (Expr *A : Args.slice(ArgIx)) { 4888 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4889 Invalid |= Arg.isInvalid(); 4890 AllArgs.push_back(Arg.get()); 4891 } 4892 } 4893 4894 // Check for array bounds violations. 4895 for (Expr *A : Args.slice(ArgIx)) 4896 CheckArrayAccess(A); 4897 } 4898 return Invalid; 4899 } 4900 4901 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4902 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4903 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4904 TL = DTL.getOriginalLoc(); 4905 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4906 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4907 << ATL.getLocalSourceRange(); 4908 } 4909 4910 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4911 /// array parameter, check that it is non-null, and that if it is formed by 4912 /// array-to-pointer decay, the underlying array is sufficiently large. 4913 /// 4914 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4915 /// array type derivation, then for each call to the function, the value of the 4916 /// corresponding actual argument shall provide access to the first element of 4917 /// an array with at least as many elements as specified by the size expression. 4918 void 4919 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4920 ParmVarDecl *Param, 4921 const Expr *ArgExpr) { 4922 // Static array parameters are not supported in C++. 4923 if (!Param || getLangOpts().CPlusPlus) 4924 return; 4925 4926 QualType OrigTy = Param->getOriginalType(); 4927 4928 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4929 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4930 return; 4931 4932 if (ArgExpr->isNullPointerConstant(Context, 4933 Expr::NPC_NeverValueDependent)) { 4934 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4935 DiagnoseCalleeStaticArrayParam(*this, Param); 4936 return; 4937 } 4938 4939 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4940 if (!CAT) 4941 return; 4942 4943 const ConstantArrayType *ArgCAT = 4944 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4945 if (!ArgCAT) 4946 return; 4947 4948 if (ArgCAT->getSize().ult(CAT->getSize())) { 4949 Diag(CallLoc, diag::warn_static_array_too_small) 4950 << ArgExpr->getSourceRange() 4951 << (unsigned) ArgCAT->getSize().getZExtValue() 4952 << (unsigned) CAT->getSize().getZExtValue(); 4953 DiagnoseCalleeStaticArrayParam(*this, Param); 4954 } 4955 } 4956 4957 /// Given a function expression of unknown-any type, try to rebuild it 4958 /// to have a function type. 4959 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4960 4961 /// Is the given type a placeholder that we need to lower out 4962 /// immediately during argument processing? 4963 static bool isPlaceholderToRemoveAsArg(QualType type) { 4964 // Placeholders are never sugared. 4965 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4966 if (!placeholder) return false; 4967 4968 switch (placeholder->getKind()) { 4969 // Ignore all the non-placeholder types. 4970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4971 case BuiltinType::Id: 4972 #include "clang/Basic/OpenCLImageTypes.def" 4973 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4974 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4975 #include "clang/AST/BuiltinTypes.def" 4976 return false; 4977 4978 // We cannot lower out overload sets; they might validly be resolved 4979 // by the call machinery. 4980 case BuiltinType::Overload: 4981 return false; 4982 4983 // Unbridged casts in ARC can be handled in some call positions and 4984 // should be left in place. 4985 case BuiltinType::ARCUnbridgedCast: 4986 return false; 4987 4988 // Pseudo-objects should be converted as soon as possible. 4989 case BuiltinType::PseudoObject: 4990 return true; 4991 4992 // The debugger mode could theoretically but currently does not try 4993 // to resolve unknown-typed arguments based on known parameter types. 4994 case BuiltinType::UnknownAny: 4995 return true; 4996 4997 // These are always invalid as call arguments and should be reported. 4998 case BuiltinType::BoundMember: 4999 case BuiltinType::BuiltinFn: 5000 case BuiltinType::OMPArraySection: 5001 return true; 5002 5003 } 5004 llvm_unreachable("bad builtin type kind"); 5005 } 5006 5007 /// Check an argument list for placeholders that we won't try to 5008 /// handle later. 5009 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5010 // Apply this processing to all the arguments at once instead of 5011 // dying at the first failure. 5012 bool hasInvalid = false; 5013 for (size_t i = 0, e = args.size(); i != e; i++) { 5014 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5015 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5016 if (result.isInvalid()) hasInvalid = true; 5017 else args[i] = result.get(); 5018 } else if (hasInvalid) { 5019 (void)S.CorrectDelayedTyposInExpr(args[i]); 5020 } 5021 } 5022 return hasInvalid; 5023 } 5024 5025 /// If a builtin function has a pointer argument with no explicit address 5026 /// space, then it should be able to accept a pointer to any address 5027 /// space as input. In order to do this, we need to replace the 5028 /// standard builtin declaration with one that uses the same address space 5029 /// as the call. 5030 /// 5031 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5032 /// it does not contain any pointer arguments without 5033 /// an address space qualifer. Otherwise the rewritten 5034 /// FunctionDecl is returned. 5035 /// TODO: Handle pointer return types. 5036 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5037 const FunctionDecl *FDecl, 5038 MultiExprArg ArgExprs) { 5039 5040 QualType DeclType = FDecl->getType(); 5041 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5042 5043 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5044 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5045 return nullptr; 5046 5047 bool NeedsNewDecl = false; 5048 unsigned i = 0; 5049 SmallVector<QualType, 8> OverloadParams; 5050 5051 for (QualType ParamType : FT->param_types()) { 5052 5053 // Convert array arguments to pointer to simplify type lookup. 5054 ExprResult ArgRes = 5055 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5056 if (ArgRes.isInvalid()) 5057 return nullptr; 5058 Expr *Arg = ArgRes.get(); 5059 QualType ArgType = Arg->getType(); 5060 if (!ParamType->isPointerType() || 5061 ParamType.getQualifiers().hasAddressSpace() || 5062 !ArgType->isPointerType() || 5063 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5064 OverloadParams.push_back(ParamType); 5065 continue; 5066 } 5067 5068 NeedsNewDecl = true; 5069 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5070 5071 QualType PointeeType = ParamType->getPointeeType(); 5072 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5073 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5074 } 5075 5076 if (!NeedsNewDecl) 5077 return nullptr; 5078 5079 FunctionProtoType::ExtProtoInfo EPI; 5080 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5081 OverloadParams, EPI); 5082 DeclContext *Parent = Context.getTranslationUnitDecl(); 5083 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5084 FDecl->getLocation(), 5085 FDecl->getLocation(), 5086 FDecl->getIdentifier(), 5087 OverloadTy, 5088 /*TInfo=*/nullptr, 5089 SC_Extern, false, 5090 /*hasPrototype=*/true); 5091 SmallVector<ParmVarDecl*, 16> Params; 5092 FT = cast<FunctionProtoType>(OverloadTy); 5093 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5094 QualType ParamType = FT->getParamType(i); 5095 ParmVarDecl *Parm = 5096 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5097 SourceLocation(), nullptr, ParamType, 5098 /*TInfo=*/nullptr, SC_None, nullptr); 5099 Parm->setScopeInfo(0, i); 5100 Params.push_back(Parm); 5101 } 5102 OverloadDecl->setParams(Params); 5103 return OverloadDecl; 5104 } 5105 5106 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5107 FunctionDecl *Callee, 5108 MultiExprArg ArgExprs) { 5109 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5110 // similar attributes) really don't like it when functions are called with an 5111 // invalid number of args. 5112 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5113 /*PartialOverloading=*/false) && 5114 !Callee->isVariadic()) 5115 return; 5116 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5117 return; 5118 5119 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5120 S.Diag(Fn->getLocStart(), 5121 isa<CXXMethodDecl>(Callee) 5122 ? diag::err_ovl_no_viable_member_function_in_call 5123 : diag::err_ovl_no_viable_function_in_call) 5124 << Callee << Callee->getSourceRange(); 5125 S.Diag(Callee->getLocation(), 5126 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5127 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5128 return; 5129 } 5130 } 5131 5132 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5133 const UnresolvedMemberExpr *const UME, Sema &S) { 5134 5135 const auto GetFunctionLevelDCIfCXXClass = 5136 [](Sema &S) -> const CXXRecordDecl * { 5137 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5138 if (!DC || !DC->getParent()) 5139 return nullptr; 5140 5141 // If the call to some member function was made from within a member 5142 // function body 'M' return return 'M's parent. 5143 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5144 return MD->getParent()->getCanonicalDecl(); 5145 // else the call was made from within a default member initializer of a 5146 // class, so return the class. 5147 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5148 return RD->getCanonicalDecl(); 5149 return nullptr; 5150 }; 5151 // If our DeclContext is neither a member function nor a class (in the 5152 // case of a lambda in a default member initializer), we can't have an 5153 // enclosing 'this'. 5154 5155 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5156 if (!CurParentClass) 5157 return false; 5158 5159 // The naming class for implicit member functions call is the class in which 5160 // name lookup starts. 5161 const CXXRecordDecl *const NamingClass = 5162 UME->getNamingClass()->getCanonicalDecl(); 5163 assert(NamingClass && "Must have naming class even for implicit access"); 5164 5165 // If the unresolved member functions were found in a 'naming class' that is 5166 // related (either the same or derived from) to the class that contains the 5167 // member function that itself contained the implicit member access. 5168 5169 return CurParentClass == NamingClass || 5170 CurParentClass->isDerivedFrom(NamingClass); 5171 } 5172 5173 static void 5174 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5175 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5176 5177 if (!UME) 5178 return; 5179 5180 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5181 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5182 // already been captured, or if this is an implicit member function call (if 5183 // it isn't, an attempt to capture 'this' should already have been made). 5184 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5185 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5186 return; 5187 5188 // Check if the naming class in which the unresolved members were found is 5189 // related (same as or is a base of) to the enclosing class. 5190 5191 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5192 return; 5193 5194 5195 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5196 // If the enclosing function is not dependent, then this lambda is 5197 // capture ready, so if we can capture this, do so. 5198 if (!EnclosingFunctionCtx->isDependentContext()) { 5199 // If the current lambda and all enclosing lambdas can capture 'this' - 5200 // then go ahead and capture 'this' (since our unresolved overload set 5201 // contains at least one non-static member function). 5202 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5203 S.CheckCXXThisCapture(CallLoc); 5204 } else if (S.CurContext->isDependentContext()) { 5205 // ... since this is an implicit member reference, that might potentially 5206 // involve a 'this' capture, mark 'this' for potential capture in 5207 // enclosing lambdas. 5208 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5209 CurLSI->addPotentialThisCapture(CallLoc); 5210 } 5211 } 5212 5213 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5214 /// This provides the location of the left/right parens and a list of comma 5215 /// locations. 5216 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5217 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5218 Expr *ExecConfig, bool IsExecConfig) { 5219 // Since this might be a postfix expression, get rid of ParenListExprs. 5220 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5221 if (Result.isInvalid()) return ExprError(); 5222 Fn = Result.get(); 5223 5224 if (checkArgsForPlaceholders(*this, ArgExprs)) 5225 return ExprError(); 5226 5227 if (getLangOpts().CPlusPlus) { 5228 // If this is a pseudo-destructor expression, build the call immediately. 5229 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5230 if (!ArgExprs.empty()) { 5231 // Pseudo-destructor calls should not have any arguments. 5232 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5233 << FixItHint::CreateRemoval( 5234 SourceRange(ArgExprs.front()->getLocStart(), 5235 ArgExprs.back()->getLocEnd())); 5236 } 5237 5238 return new (Context) 5239 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5240 } 5241 if (Fn->getType() == Context.PseudoObjectTy) { 5242 ExprResult result = CheckPlaceholderExpr(Fn); 5243 if (result.isInvalid()) return ExprError(); 5244 Fn = result.get(); 5245 } 5246 5247 // Determine whether this is a dependent call inside a C++ template, 5248 // in which case we won't do any semantic analysis now. 5249 bool Dependent = false; 5250 if (Fn->isTypeDependent()) 5251 Dependent = true; 5252 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5253 Dependent = true; 5254 5255 if (Dependent) { 5256 if (ExecConfig) { 5257 return new (Context) CUDAKernelCallExpr( 5258 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5259 Context.DependentTy, VK_RValue, RParenLoc); 5260 } else { 5261 5262 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5263 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5264 Fn->getLocStart()); 5265 5266 return new (Context) CallExpr( 5267 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5268 } 5269 } 5270 5271 // Determine whether this is a call to an object (C++ [over.call.object]). 5272 if (Fn->getType()->isRecordType()) 5273 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5274 RParenLoc); 5275 5276 if (Fn->getType() == Context.UnknownAnyTy) { 5277 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5278 if (result.isInvalid()) return ExprError(); 5279 Fn = result.get(); 5280 } 5281 5282 if (Fn->getType() == Context.BoundMemberTy) { 5283 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5284 RParenLoc); 5285 } 5286 } 5287 5288 // Check for overloaded calls. This can happen even in C due to extensions. 5289 if (Fn->getType() == Context.OverloadTy) { 5290 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5291 5292 // We aren't supposed to apply this logic if there's an '&' involved. 5293 if (!find.HasFormOfMemberPointer) { 5294 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5295 return new (Context) CallExpr( 5296 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5297 OverloadExpr *ovl = find.Expression; 5298 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5299 return BuildOverloadedCallExpr( 5300 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5301 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5302 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5303 RParenLoc); 5304 } 5305 } 5306 5307 // If we're directly calling a function, get the appropriate declaration. 5308 if (Fn->getType() == Context.UnknownAnyTy) { 5309 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5310 if (result.isInvalid()) return ExprError(); 5311 Fn = result.get(); 5312 } 5313 5314 Expr *NakedFn = Fn->IgnoreParens(); 5315 5316 bool CallingNDeclIndirectly = false; 5317 NamedDecl *NDecl = nullptr; 5318 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5319 if (UnOp->getOpcode() == UO_AddrOf) { 5320 CallingNDeclIndirectly = true; 5321 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5322 } 5323 } 5324 5325 if (isa<DeclRefExpr>(NakedFn)) { 5326 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5327 5328 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5329 if (FDecl && FDecl->getBuiltinID()) { 5330 // Rewrite the function decl for this builtin by replacing parameters 5331 // with no explicit address space with the address space of the arguments 5332 // in ArgExprs. 5333 if ((FDecl = 5334 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5335 NDecl = FDecl; 5336 Fn = DeclRefExpr::Create( 5337 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5338 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5339 } 5340 } 5341 } else if (isa<MemberExpr>(NakedFn)) 5342 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5343 5344 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5345 if (CallingNDeclIndirectly && 5346 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5347 Fn->getLocStart())) 5348 return ExprError(); 5349 5350 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5351 return ExprError(); 5352 5353 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5354 } 5355 5356 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5357 ExecConfig, IsExecConfig); 5358 } 5359 5360 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5361 /// 5362 /// __builtin_astype( value, dst type ) 5363 /// 5364 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5365 SourceLocation BuiltinLoc, 5366 SourceLocation RParenLoc) { 5367 ExprValueKind VK = VK_RValue; 5368 ExprObjectKind OK = OK_Ordinary; 5369 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5370 QualType SrcTy = E->getType(); 5371 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5372 return ExprError(Diag(BuiltinLoc, 5373 diag::err_invalid_astype_of_different_size) 5374 << DstTy 5375 << SrcTy 5376 << E->getSourceRange()); 5377 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5378 } 5379 5380 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5381 /// provided arguments. 5382 /// 5383 /// __builtin_convertvector( value, dst type ) 5384 /// 5385 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5386 SourceLocation BuiltinLoc, 5387 SourceLocation RParenLoc) { 5388 TypeSourceInfo *TInfo; 5389 GetTypeFromParser(ParsedDestTy, &TInfo); 5390 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5391 } 5392 5393 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5394 /// i.e. an expression not of \p OverloadTy. The expression should 5395 /// unary-convert to an expression of function-pointer or 5396 /// block-pointer type. 5397 /// 5398 /// \param NDecl the declaration being called, if available 5399 ExprResult 5400 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5401 SourceLocation LParenLoc, 5402 ArrayRef<Expr *> Args, 5403 SourceLocation RParenLoc, 5404 Expr *Config, bool IsExecConfig) { 5405 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5406 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5407 5408 // Functions with 'interrupt' attribute cannot be called directly. 5409 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5410 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5411 return ExprError(); 5412 } 5413 5414 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5415 // so there's some risk when calling out to non-interrupt handler functions 5416 // that the callee might not preserve them. This is easy to diagnose here, 5417 // but can be very challenging to debug. 5418 if (auto *Caller = getCurFunctionDecl()) 5419 if (Caller->hasAttr<ARMInterruptAttr>()) { 5420 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5421 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5422 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5423 } 5424 5425 // Promote the function operand. 5426 // We special-case function promotion here because we only allow promoting 5427 // builtin functions to function pointers in the callee of a call. 5428 ExprResult Result; 5429 if (BuiltinID && 5430 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5431 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5432 CK_BuiltinFnToFnPtr).get(); 5433 } else { 5434 Result = CallExprUnaryConversions(Fn); 5435 } 5436 if (Result.isInvalid()) 5437 return ExprError(); 5438 Fn = Result.get(); 5439 5440 // Make the call expr early, before semantic checks. This guarantees cleanup 5441 // of arguments and function on error. 5442 CallExpr *TheCall; 5443 if (Config) 5444 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5445 cast<CallExpr>(Config), Args, 5446 Context.BoolTy, VK_RValue, 5447 RParenLoc); 5448 else 5449 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5450 VK_RValue, RParenLoc); 5451 5452 if (!getLangOpts().CPlusPlus) { 5453 // C cannot always handle TypoExpr nodes in builtin calls and direct 5454 // function calls as their argument checking don't necessarily handle 5455 // dependent types properly, so make sure any TypoExprs have been 5456 // dealt with. 5457 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5458 if (!Result.isUsable()) return ExprError(); 5459 TheCall = dyn_cast<CallExpr>(Result.get()); 5460 if (!TheCall) return Result; 5461 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5462 } 5463 5464 // Bail out early if calling a builtin with custom typechecking. 5465 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5466 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5467 5468 retry: 5469 const FunctionType *FuncT; 5470 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5471 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5472 // have type pointer to function". 5473 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5474 if (!FuncT) 5475 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5476 << Fn->getType() << Fn->getSourceRange()); 5477 } else if (const BlockPointerType *BPT = 5478 Fn->getType()->getAs<BlockPointerType>()) { 5479 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5480 } else { 5481 // Handle calls to expressions of unknown-any type. 5482 if (Fn->getType() == Context.UnknownAnyTy) { 5483 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5484 if (rewrite.isInvalid()) return ExprError(); 5485 Fn = rewrite.get(); 5486 TheCall->setCallee(Fn); 5487 goto retry; 5488 } 5489 5490 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5491 << Fn->getType() << Fn->getSourceRange()); 5492 } 5493 5494 if (getLangOpts().CUDA) { 5495 if (Config) { 5496 // CUDA: Kernel calls must be to global functions 5497 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5498 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5499 << FDecl->getName() << Fn->getSourceRange()); 5500 5501 // CUDA: Kernel function must have 'void' return type 5502 if (!FuncT->getReturnType()->isVoidType()) 5503 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5504 << Fn->getType() << Fn->getSourceRange()); 5505 } else { 5506 // CUDA: Calls to global functions must be configured 5507 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5508 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5509 << FDecl->getName() << Fn->getSourceRange()); 5510 } 5511 } 5512 5513 // Check for a valid return type 5514 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5515 FDecl)) 5516 return ExprError(); 5517 5518 // We know the result type of the call, set it. 5519 TheCall->setType(FuncT->getCallResultType(Context)); 5520 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5521 5522 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5523 if (Proto) { 5524 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5525 IsExecConfig)) 5526 return ExprError(); 5527 } else { 5528 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5529 5530 if (FDecl) { 5531 // Check if we have too few/too many template arguments, based 5532 // on our knowledge of the function definition. 5533 const FunctionDecl *Def = nullptr; 5534 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5535 Proto = Def->getType()->getAs<FunctionProtoType>(); 5536 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5537 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5538 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5539 } 5540 5541 // If the function we're calling isn't a function prototype, but we have 5542 // a function prototype from a prior declaratiom, use that prototype. 5543 if (!FDecl->hasPrototype()) 5544 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5545 } 5546 5547 // Promote the arguments (C99 6.5.2.2p6). 5548 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5549 Expr *Arg = Args[i]; 5550 5551 if (Proto && i < Proto->getNumParams()) { 5552 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5553 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5554 ExprResult ArgE = 5555 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5556 if (ArgE.isInvalid()) 5557 return true; 5558 5559 Arg = ArgE.getAs<Expr>(); 5560 5561 } else { 5562 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5563 5564 if (ArgE.isInvalid()) 5565 return true; 5566 5567 Arg = ArgE.getAs<Expr>(); 5568 } 5569 5570 if (RequireCompleteType(Arg->getLocStart(), 5571 Arg->getType(), 5572 diag::err_call_incomplete_argument, Arg)) 5573 return ExprError(); 5574 5575 TheCall->setArg(i, Arg); 5576 } 5577 } 5578 5579 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5580 if (!Method->isStatic()) 5581 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5582 << Fn->getSourceRange()); 5583 5584 // Check for sentinels 5585 if (NDecl) 5586 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5587 5588 // Do special checking on direct calls to functions. 5589 if (FDecl) { 5590 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5591 return ExprError(); 5592 5593 if (BuiltinID) 5594 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5595 } else if (NDecl) { 5596 if (CheckPointerCall(NDecl, TheCall, Proto)) 5597 return ExprError(); 5598 } else { 5599 if (CheckOtherCall(TheCall, Proto)) 5600 return ExprError(); 5601 } 5602 5603 return MaybeBindToTemporary(TheCall); 5604 } 5605 5606 ExprResult 5607 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5608 SourceLocation RParenLoc, Expr *InitExpr) { 5609 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5610 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5611 5612 TypeSourceInfo *TInfo; 5613 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5614 if (!TInfo) 5615 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5616 5617 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5618 } 5619 5620 ExprResult 5621 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5622 SourceLocation RParenLoc, Expr *LiteralExpr) { 5623 QualType literalType = TInfo->getType(); 5624 5625 if (literalType->isArrayType()) { 5626 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5627 diag::err_illegal_decl_array_incomplete_type, 5628 SourceRange(LParenLoc, 5629 LiteralExpr->getSourceRange().getEnd()))) 5630 return ExprError(); 5631 if (literalType->isVariableArrayType()) 5632 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5633 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5634 } else if (!literalType->isDependentType() && 5635 RequireCompleteType(LParenLoc, literalType, 5636 diag::err_typecheck_decl_incomplete_type, 5637 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5638 return ExprError(); 5639 5640 InitializedEntity Entity 5641 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5642 InitializationKind Kind 5643 = InitializationKind::CreateCStyleCast(LParenLoc, 5644 SourceRange(LParenLoc, RParenLoc), 5645 /*InitList=*/true); 5646 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5647 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5648 &literalType); 5649 if (Result.isInvalid()) 5650 return ExprError(); 5651 LiteralExpr = Result.get(); 5652 5653 bool isFileScope = !CurContext->isFunctionOrMethod(); 5654 if (isFileScope && 5655 !LiteralExpr->isTypeDependent() && 5656 !LiteralExpr->isValueDependent() && 5657 !literalType->isDependentType()) { // 6.5.2.5p3 5658 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5659 return ExprError(); 5660 } 5661 5662 // In C, compound literals are l-values for some reason. 5663 // For GCC compatibility, in C++, file-scope array compound literals with 5664 // constant initializers are also l-values, and compound literals are 5665 // otherwise prvalues. 5666 // 5667 // (GCC also treats C++ list-initialized file-scope array prvalues with 5668 // constant initializers as l-values, but that's non-conforming, so we don't 5669 // follow it there.) 5670 // 5671 // FIXME: It would be better to handle the lvalue cases as materializing and 5672 // lifetime-extending a temporary object, but our materialized temporaries 5673 // representation only supports lifetime extension from a variable, not "out 5674 // of thin air". 5675 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5676 // is bound to the result of applying array-to-pointer decay to the compound 5677 // literal. 5678 // FIXME: GCC supports compound literals of reference type, which should 5679 // obviously have a value kind derived from the kind of reference involved. 5680 ExprValueKind VK = 5681 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5682 ? VK_RValue 5683 : VK_LValue; 5684 5685 return MaybeBindToTemporary( 5686 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5687 VK, LiteralExpr, isFileScope)); 5688 } 5689 5690 ExprResult 5691 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5692 SourceLocation RBraceLoc) { 5693 // Immediately handle non-overload placeholders. Overloads can be 5694 // resolved contextually, but everything else here can't. 5695 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5696 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5697 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5698 5699 // Ignore failures; dropping the entire initializer list because 5700 // of one failure would be terrible for indexing/etc. 5701 if (result.isInvalid()) continue; 5702 5703 InitArgList[I] = result.get(); 5704 } 5705 } 5706 5707 // Semantic analysis for initializers is done by ActOnDeclarator() and 5708 // CheckInitializer() - it requires knowledge of the object being intialized. 5709 5710 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5711 RBraceLoc); 5712 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5713 return E; 5714 } 5715 5716 /// Do an explicit extend of the given block pointer if we're in ARC. 5717 void Sema::maybeExtendBlockObject(ExprResult &E) { 5718 assert(E.get()->getType()->isBlockPointerType()); 5719 assert(E.get()->isRValue()); 5720 5721 // Only do this in an r-value context. 5722 if (!getLangOpts().ObjCAutoRefCount) return; 5723 5724 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5725 CK_ARCExtendBlockObject, E.get(), 5726 /*base path*/ nullptr, VK_RValue); 5727 Cleanup.setExprNeedsCleanups(true); 5728 } 5729 5730 /// Prepare a conversion of the given expression to an ObjC object 5731 /// pointer type. 5732 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5733 QualType type = E.get()->getType(); 5734 if (type->isObjCObjectPointerType()) { 5735 return CK_BitCast; 5736 } else if (type->isBlockPointerType()) { 5737 maybeExtendBlockObject(E); 5738 return CK_BlockPointerToObjCPointerCast; 5739 } else { 5740 assert(type->isPointerType()); 5741 return CK_CPointerToObjCPointerCast; 5742 } 5743 } 5744 5745 /// Prepares for a scalar cast, performing all the necessary stages 5746 /// except the final cast and returning the kind required. 5747 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5748 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5749 // Also, callers should have filtered out the invalid cases with 5750 // pointers. Everything else should be possible. 5751 5752 QualType SrcTy = Src.get()->getType(); 5753 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5754 return CK_NoOp; 5755 5756 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5757 case Type::STK_MemberPointer: 5758 llvm_unreachable("member pointer type in C"); 5759 5760 case Type::STK_CPointer: 5761 case Type::STK_BlockPointer: 5762 case Type::STK_ObjCObjectPointer: 5763 switch (DestTy->getScalarTypeKind()) { 5764 case Type::STK_CPointer: { 5765 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5766 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5767 if (SrcAS != DestAS) 5768 return CK_AddressSpaceConversion; 5769 return CK_BitCast; 5770 } 5771 case Type::STK_BlockPointer: 5772 return (SrcKind == Type::STK_BlockPointer 5773 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5774 case Type::STK_ObjCObjectPointer: 5775 if (SrcKind == Type::STK_ObjCObjectPointer) 5776 return CK_BitCast; 5777 if (SrcKind == Type::STK_CPointer) 5778 return CK_CPointerToObjCPointerCast; 5779 maybeExtendBlockObject(Src); 5780 return CK_BlockPointerToObjCPointerCast; 5781 case Type::STK_Bool: 5782 return CK_PointerToBoolean; 5783 case Type::STK_Integral: 5784 return CK_PointerToIntegral; 5785 case Type::STK_Floating: 5786 case Type::STK_FloatingComplex: 5787 case Type::STK_IntegralComplex: 5788 case Type::STK_MemberPointer: 5789 llvm_unreachable("illegal cast from pointer"); 5790 } 5791 llvm_unreachable("Should have returned before this"); 5792 5793 case Type::STK_Bool: // casting from bool is like casting from an integer 5794 case Type::STK_Integral: 5795 switch (DestTy->getScalarTypeKind()) { 5796 case Type::STK_CPointer: 5797 case Type::STK_ObjCObjectPointer: 5798 case Type::STK_BlockPointer: 5799 if (Src.get()->isNullPointerConstant(Context, 5800 Expr::NPC_ValueDependentIsNull)) 5801 return CK_NullToPointer; 5802 return CK_IntegralToPointer; 5803 case Type::STK_Bool: 5804 return CK_IntegralToBoolean; 5805 case Type::STK_Integral: 5806 return CK_IntegralCast; 5807 case Type::STK_Floating: 5808 return CK_IntegralToFloating; 5809 case Type::STK_IntegralComplex: 5810 Src = ImpCastExprToType(Src.get(), 5811 DestTy->castAs<ComplexType>()->getElementType(), 5812 CK_IntegralCast); 5813 return CK_IntegralRealToComplex; 5814 case Type::STK_FloatingComplex: 5815 Src = ImpCastExprToType(Src.get(), 5816 DestTy->castAs<ComplexType>()->getElementType(), 5817 CK_IntegralToFloating); 5818 return CK_FloatingRealToComplex; 5819 case Type::STK_MemberPointer: 5820 llvm_unreachable("member pointer type in C"); 5821 } 5822 llvm_unreachable("Should have returned before this"); 5823 5824 case Type::STK_Floating: 5825 switch (DestTy->getScalarTypeKind()) { 5826 case Type::STK_Floating: 5827 return CK_FloatingCast; 5828 case Type::STK_Bool: 5829 return CK_FloatingToBoolean; 5830 case Type::STK_Integral: 5831 return CK_FloatingToIntegral; 5832 case Type::STK_FloatingComplex: 5833 Src = ImpCastExprToType(Src.get(), 5834 DestTy->castAs<ComplexType>()->getElementType(), 5835 CK_FloatingCast); 5836 return CK_FloatingRealToComplex; 5837 case Type::STK_IntegralComplex: 5838 Src = ImpCastExprToType(Src.get(), 5839 DestTy->castAs<ComplexType>()->getElementType(), 5840 CK_FloatingToIntegral); 5841 return CK_IntegralRealToComplex; 5842 case Type::STK_CPointer: 5843 case Type::STK_ObjCObjectPointer: 5844 case Type::STK_BlockPointer: 5845 llvm_unreachable("valid float->pointer cast?"); 5846 case Type::STK_MemberPointer: 5847 llvm_unreachable("member pointer type in C"); 5848 } 5849 llvm_unreachable("Should have returned before this"); 5850 5851 case Type::STK_FloatingComplex: 5852 switch (DestTy->getScalarTypeKind()) { 5853 case Type::STK_FloatingComplex: 5854 return CK_FloatingComplexCast; 5855 case Type::STK_IntegralComplex: 5856 return CK_FloatingComplexToIntegralComplex; 5857 case Type::STK_Floating: { 5858 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5859 if (Context.hasSameType(ET, DestTy)) 5860 return CK_FloatingComplexToReal; 5861 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5862 return CK_FloatingCast; 5863 } 5864 case Type::STK_Bool: 5865 return CK_FloatingComplexToBoolean; 5866 case Type::STK_Integral: 5867 Src = ImpCastExprToType(Src.get(), 5868 SrcTy->castAs<ComplexType>()->getElementType(), 5869 CK_FloatingComplexToReal); 5870 return CK_FloatingToIntegral; 5871 case Type::STK_CPointer: 5872 case Type::STK_ObjCObjectPointer: 5873 case Type::STK_BlockPointer: 5874 llvm_unreachable("valid complex float->pointer cast?"); 5875 case Type::STK_MemberPointer: 5876 llvm_unreachable("member pointer type in C"); 5877 } 5878 llvm_unreachable("Should have returned before this"); 5879 5880 case Type::STK_IntegralComplex: 5881 switch (DestTy->getScalarTypeKind()) { 5882 case Type::STK_FloatingComplex: 5883 return CK_IntegralComplexToFloatingComplex; 5884 case Type::STK_IntegralComplex: 5885 return CK_IntegralComplexCast; 5886 case Type::STK_Integral: { 5887 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5888 if (Context.hasSameType(ET, DestTy)) 5889 return CK_IntegralComplexToReal; 5890 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5891 return CK_IntegralCast; 5892 } 5893 case Type::STK_Bool: 5894 return CK_IntegralComplexToBoolean; 5895 case Type::STK_Floating: 5896 Src = ImpCastExprToType(Src.get(), 5897 SrcTy->castAs<ComplexType>()->getElementType(), 5898 CK_IntegralComplexToReal); 5899 return CK_IntegralToFloating; 5900 case Type::STK_CPointer: 5901 case Type::STK_ObjCObjectPointer: 5902 case Type::STK_BlockPointer: 5903 llvm_unreachable("valid complex int->pointer cast?"); 5904 case Type::STK_MemberPointer: 5905 llvm_unreachable("member pointer type in C"); 5906 } 5907 llvm_unreachable("Should have returned before this"); 5908 } 5909 5910 llvm_unreachable("Unhandled scalar cast"); 5911 } 5912 5913 static bool breakDownVectorType(QualType type, uint64_t &len, 5914 QualType &eltType) { 5915 // Vectors are simple. 5916 if (const VectorType *vecType = type->getAs<VectorType>()) { 5917 len = vecType->getNumElements(); 5918 eltType = vecType->getElementType(); 5919 assert(eltType->isScalarType()); 5920 return true; 5921 } 5922 5923 // We allow lax conversion to and from non-vector types, but only if 5924 // they're real types (i.e. non-complex, non-pointer scalar types). 5925 if (!type->isRealType()) return false; 5926 5927 len = 1; 5928 eltType = type; 5929 return true; 5930 } 5931 5932 /// Are the two types lax-compatible vector types? That is, given 5933 /// that one of them is a vector, do they have equal storage sizes, 5934 /// where the storage size is the number of elements times the element 5935 /// size? 5936 /// 5937 /// This will also return false if either of the types is neither a 5938 /// vector nor a real type. 5939 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5940 assert(destTy->isVectorType() || srcTy->isVectorType()); 5941 5942 // Disallow lax conversions between scalars and ExtVectors (these 5943 // conversions are allowed for other vector types because common headers 5944 // depend on them). Most scalar OP ExtVector cases are handled by the 5945 // splat path anyway, which does what we want (convert, not bitcast). 5946 // What this rules out for ExtVectors is crazy things like char4*float. 5947 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5948 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5949 5950 uint64_t srcLen, destLen; 5951 QualType srcEltTy, destEltTy; 5952 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5953 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5954 5955 // ASTContext::getTypeSize will return the size rounded up to a 5956 // power of 2, so instead of using that, we need to use the raw 5957 // element size multiplied by the element count. 5958 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5959 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5960 5961 return (srcLen * srcEltSize == destLen * destEltSize); 5962 } 5963 5964 /// Is this a legal conversion between two types, one of which is 5965 /// known to be a vector type? 5966 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5967 assert(destTy->isVectorType() || srcTy->isVectorType()); 5968 5969 if (!Context.getLangOpts().LaxVectorConversions) 5970 return false; 5971 return areLaxCompatibleVectorTypes(srcTy, destTy); 5972 } 5973 5974 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5975 CastKind &Kind) { 5976 assert(VectorTy->isVectorType() && "Not a vector type!"); 5977 5978 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5979 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5980 return Diag(R.getBegin(), 5981 Ty->isVectorType() ? 5982 diag::err_invalid_conversion_between_vectors : 5983 diag::err_invalid_conversion_between_vector_and_integer) 5984 << VectorTy << Ty << R; 5985 } else 5986 return Diag(R.getBegin(), 5987 diag::err_invalid_conversion_between_vector_and_scalar) 5988 << VectorTy << Ty << R; 5989 5990 Kind = CK_BitCast; 5991 return false; 5992 } 5993 5994 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5995 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5996 5997 if (DestElemTy == SplattedExpr->getType()) 5998 return SplattedExpr; 5999 6000 assert(DestElemTy->isFloatingType() || 6001 DestElemTy->isIntegralOrEnumerationType()); 6002 6003 CastKind CK; 6004 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6005 // OpenCL requires that we convert `true` boolean expressions to -1, but 6006 // only when splatting vectors. 6007 if (DestElemTy->isFloatingType()) { 6008 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6009 // in two steps: boolean to signed integral, then to floating. 6010 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6011 CK_BooleanToSignedIntegral); 6012 SplattedExpr = CastExprRes.get(); 6013 CK = CK_IntegralToFloating; 6014 } else { 6015 CK = CK_BooleanToSignedIntegral; 6016 } 6017 } else { 6018 ExprResult CastExprRes = SplattedExpr; 6019 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6020 if (CastExprRes.isInvalid()) 6021 return ExprError(); 6022 SplattedExpr = CastExprRes.get(); 6023 } 6024 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6025 } 6026 6027 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6028 Expr *CastExpr, CastKind &Kind) { 6029 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6030 6031 QualType SrcTy = CastExpr->getType(); 6032 6033 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6034 // an ExtVectorType. 6035 // In OpenCL, casts between vectors of different types are not allowed. 6036 // (See OpenCL 6.2). 6037 if (SrcTy->isVectorType()) { 6038 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6039 (getLangOpts().OpenCL && 6040 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6041 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6042 << DestTy << SrcTy << R; 6043 return ExprError(); 6044 } 6045 Kind = CK_BitCast; 6046 return CastExpr; 6047 } 6048 6049 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6050 // conversion will take place first from scalar to elt type, and then 6051 // splat from elt type to vector. 6052 if (SrcTy->isPointerType()) 6053 return Diag(R.getBegin(), 6054 diag::err_invalid_conversion_between_vector_and_scalar) 6055 << DestTy << SrcTy << R; 6056 6057 Kind = CK_VectorSplat; 6058 return prepareVectorSplat(DestTy, CastExpr); 6059 } 6060 6061 ExprResult 6062 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6063 Declarator &D, ParsedType &Ty, 6064 SourceLocation RParenLoc, Expr *CastExpr) { 6065 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6066 "ActOnCastExpr(): missing type or expr"); 6067 6068 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6069 if (D.isInvalidType()) 6070 return ExprError(); 6071 6072 if (getLangOpts().CPlusPlus) { 6073 // Check that there are no default arguments (C++ only). 6074 CheckExtraCXXDefaultArguments(D); 6075 } else { 6076 // Make sure any TypoExprs have been dealt with. 6077 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6078 if (!Res.isUsable()) 6079 return ExprError(); 6080 CastExpr = Res.get(); 6081 } 6082 6083 checkUnusedDeclAttributes(D); 6084 6085 QualType castType = castTInfo->getType(); 6086 Ty = CreateParsedType(castType, castTInfo); 6087 6088 bool isVectorLiteral = false; 6089 6090 // Check for an altivec or OpenCL literal, 6091 // i.e. all the elements are integer constants. 6092 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6093 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6094 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6095 && castType->isVectorType() && (PE || PLE)) { 6096 if (PLE && PLE->getNumExprs() == 0) { 6097 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6098 return ExprError(); 6099 } 6100 if (PE || PLE->getNumExprs() == 1) { 6101 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6102 if (!E->getType()->isVectorType()) 6103 isVectorLiteral = true; 6104 } 6105 else 6106 isVectorLiteral = true; 6107 } 6108 6109 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6110 // then handle it as such. 6111 if (isVectorLiteral) 6112 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6113 6114 // If the Expr being casted is a ParenListExpr, handle it specially. 6115 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6116 // sequence of BinOp comma operators. 6117 if (isa<ParenListExpr>(CastExpr)) { 6118 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6119 if (Result.isInvalid()) return ExprError(); 6120 CastExpr = Result.get(); 6121 } 6122 6123 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6124 !getSourceManager().isInSystemMacro(LParenLoc)) 6125 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6126 6127 CheckTollFreeBridgeCast(castType, CastExpr); 6128 6129 CheckObjCBridgeRelatedCast(castType, CastExpr); 6130 6131 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6132 6133 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6134 } 6135 6136 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6137 SourceLocation RParenLoc, Expr *E, 6138 TypeSourceInfo *TInfo) { 6139 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6140 "Expected paren or paren list expression"); 6141 6142 Expr **exprs; 6143 unsigned numExprs; 6144 Expr *subExpr; 6145 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6146 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6147 LiteralLParenLoc = PE->getLParenLoc(); 6148 LiteralRParenLoc = PE->getRParenLoc(); 6149 exprs = PE->getExprs(); 6150 numExprs = PE->getNumExprs(); 6151 } else { // isa<ParenExpr> by assertion at function entrance 6152 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6153 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6154 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6155 exprs = &subExpr; 6156 numExprs = 1; 6157 } 6158 6159 QualType Ty = TInfo->getType(); 6160 assert(Ty->isVectorType() && "Expected vector type"); 6161 6162 SmallVector<Expr *, 8> initExprs; 6163 const VectorType *VTy = Ty->getAs<VectorType>(); 6164 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6165 6166 // '(...)' form of vector initialization in AltiVec: the number of 6167 // initializers must be one or must match the size of the vector. 6168 // If a single value is specified in the initializer then it will be 6169 // replicated to all the components of the vector 6170 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6171 // The number of initializers must be one or must match the size of the 6172 // vector. If a single value is specified in the initializer then it will 6173 // be replicated to all the components of the vector 6174 if (numExprs == 1) { 6175 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6176 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6177 if (Literal.isInvalid()) 6178 return ExprError(); 6179 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6180 PrepareScalarCast(Literal, ElemTy)); 6181 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6182 } 6183 else if (numExprs < numElems) { 6184 Diag(E->getExprLoc(), 6185 diag::err_incorrect_number_of_vector_initializers); 6186 return ExprError(); 6187 } 6188 else 6189 initExprs.append(exprs, exprs + numExprs); 6190 } 6191 else { 6192 // For OpenCL, when the number of initializers is a single value, 6193 // it will be replicated to all components of the vector. 6194 if (getLangOpts().OpenCL && 6195 VTy->getVectorKind() == VectorType::GenericVector && 6196 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 6206 initExprs.append(exprs, exprs + numExprs); 6207 } 6208 // FIXME: This means that pretty-printing the final AST will produce curly 6209 // braces instead of the original commas. 6210 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6211 initExprs, LiteralRParenLoc); 6212 initE->setType(Ty); 6213 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6214 } 6215 6216 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6217 /// the ParenListExpr into a sequence of comma binary operators. 6218 ExprResult 6219 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6220 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6221 if (!E) 6222 return OrigExpr; 6223 6224 ExprResult Result(E->getExpr(0)); 6225 6226 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6227 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6228 E->getExpr(i)); 6229 6230 if (Result.isInvalid()) return ExprError(); 6231 6232 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6233 } 6234 6235 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6236 SourceLocation R, 6237 MultiExprArg Val) { 6238 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6239 return expr; 6240 } 6241 6242 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6243 /// constant and the other is not a pointer. Returns true if a diagnostic is 6244 /// emitted. 6245 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6246 SourceLocation QuestionLoc) { 6247 Expr *NullExpr = LHSExpr; 6248 Expr *NonPointerExpr = RHSExpr; 6249 Expr::NullPointerConstantKind NullKind = 6250 NullExpr->isNullPointerConstant(Context, 6251 Expr::NPC_ValueDependentIsNotNull); 6252 6253 if (NullKind == Expr::NPCK_NotNull) { 6254 NullExpr = RHSExpr; 6255 NonPointerExpr = LHSExpr; 6256 NullKind = 6257 NullExpr->isNullPointerConstant(Context, 6258 Expr::NPC_ValueDependentIsNotNull); 6259 } 6260 6261 if (NullKind == Expr::NPCK_NotNull) 6262 return false; 6263 6264 if (NullKind == Expr::NPCK_ZeroExpression) 6265 return false; 6266 6267 if (NullKind == Expr::NPCK_ZeroLiteral) { 6268 // In this case, check to make sure that we got here from a "NULL" 6269 // string in the source code. 6270 NullExpr = NullExpr->IgnoreParenImpCasts(); 6271 SourceLocation loc = NullExpr->getExprLoc(); 6272 if (!findMacroSpelling(loc, "NULL")) 6273 return false; 6274 } 6275 6276 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6277 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6278 << NonPointerExpr->getType() << DiagType 6279 << NonPointerExpr->getSourceRange(); 6280 return true; 6281 } 6282 6283 /// \brief Return false if the condition expression is valid, true otherwise. 6284 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6285 QualType CondTy = Cond->getType(); 6286 6287 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6288 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6289 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6290 << CondTy << Cond->getSourceRange(); 6291 return true; 6292 } 6293 6294 // C99 6.5.15p2 6295 if (CondTy->isScalarType()) return false; 6296 6297 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6298 << CondTy << Cond->getSourceRange(); 6299 return true; 6300 } 6301 6302 /// \brief Handle when one or both operands are void type. 6303 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6304 ExprResult &RHS) { 6305 Expr *LHSExpr = LHS.get(); 6306 Expr *RHSExpr = RHS.get(); 6307 6308 if (!LHSExpr->getType()->isVoidType()) 6309 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6310 << RHSExpr->getSourceRange(); 6311 if (!RHSExpr->getType()->isVoidType()) 6312 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6313 << LHSExpr->getSourceRange(); 6314 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6315 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6316 return S.Context.VoidTy; 6317 } 6318 6319 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6320 /// true otherwise. 6321 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6322 QualType PointerTy) { 6323 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6324 !NullExpr.get()->isNullPointerConstant(S.Context, 6325 Expr::NPC_ValueDependentIsNull)) 6326 return true; 6327 6328 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6329 return false; 6330 } 6331 6332 /// \brief Checks compatibility between two pointers and return the resulting 6333 /// type. 6334 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6335 ExprResult &RHS, 6336 SourceLocation Loc) { 6337 QualType LHSTy = LHS.get()->getType(); 6338 QualType RHSTy = RHS.get()->getType(); 6339 6340 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6341 // Two identical pointers types are always compatible. 6342 return LHSTy; 6343 } 6344 6345 QualType lhptee, rhptee; 6346 6347 // Get the pointee types. 6348 bool IsBlockPointer = false; 6349 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6350 lhptee = LHSBTy->getPointeeType(); 6351 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6352 IsBlockPointer = true; 6353 } else { 6354 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6355 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6356 } 6357 6358 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6359 // differently qualified versions of compatible types, the result type is 6360 // a pointer to an appropriately qualified version of the composite 6361 // type. 6362 6363 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6364 // clause doesn't make sense for our extensions. E.g. address space 2 should 6365 // be incompatible with address space 3: they may live on different devices or 6366 // anything. 6367 Qualifiers lhQual = lhptee.getQualifiers(); 6368 Qualifiers rhQual = rhptee.getQualifiers(); 6369 6370 LangAS ResultAddrSpace = LangAS::Default; 6371 LangAS LAddrSpace = lhQual.getAddressSpace(); 6372 LangAS RAddrSpace = rhQual.getAddressSpace(); 6373 if (S.getLangOpts().OpenCL) { 6374 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6375 // spaces is disallowed. 6376 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6377 ResultAddrSpace = LAddrSpace; 6378 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6379 ResultAddrSpace = RAddrSpace; 6380 else { 6381 S.Diag(Loc, 6382 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6383 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6384 << RHS.get()->getSourceRange(); 6385 return QualType(); 6386 } 6387 } 6388 6389 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6390 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6391 lhQual.removeCVRQualifiers(); 6392 rhQual.removeCVRQualifiers(); 6393 6394 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6395 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6396 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6397 // qual types are compatible iff 6398 // * corresponded types are compatible 6399 // * CVR qualifiers are equal 6400 // * address spaces are equal 6401 // Thus for conditional operator we merge CVR and address space unqualified 6402 // pointees and if there is a composite type we return a pointer to it with 6403 // merged qualifiers. 6404 if (S.getLangOpts().OpenCL) { 6405 LHSCastKind = LAddrSpace == ResultAddrSpace 6406 ? CK_BitCast 6407 : CK_AddressSpaceConversion; 6408 RHSCastKind = RAddrSpace == ResultAddrSpace 6409 ? CK_BitCast 6410 : CK_AddressSpaceConversion; 6411 lhQual.removeAddressSpace(); 6412 rhQual.removeAddressSpace(); 6413 } 6414 6415 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6416 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6417 6418 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6419 6420 if (CompositeTy.isNull()) { 6421 // In this situation, we assume void* type. No especially good 6422 // reason, but this is what gcc does, and we do have to pick 6423 // to get a consistent AST. 6424 QualType incompatTy; 6425 incompatTy = S.Context.getPointerType( 6426 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6427 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6428 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6429 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6430 // for casts between types with incompatible address space qualifiers. 6431 // For the following code the compiler produces casts between global and 6432 // local address spaces of the corresponded innermost pointees: 6433 // local int *global *a; 6434 // global int *global *b; 6435 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6436 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6437 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6438 << RHS.get()->getSourceRange(); 6439 return incompatTy; 6440 } 6441 6442 // The pointer types are compatible. 6443 // In case of OpenCL ResultTy should have the address space qualifier 6444 // which is a superset of address spaces of both the 2nd and the 3rd 6445 // operands of the conditional operator. 6446 QualType ResultTy = [&, ResultAddrSpace]() { 6447 if (S.getLangOpts().OpenCL) { 6448 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6449 CompositeQuals.setAddressSpace(ResultAddrSpace); 6450 return S.Context 6451 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6452 .withCVRQualifiers(MergedCVRQual); 6453 } 6454 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6455 }(); 6456 if (IsBlockPointer) 6457 ResultTy = S.Context.getBlockPointerType(ResultTy); 6458 else 6459 ResultTy = S.Context.getPointerType(ResultTy); 6460 6461 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6462 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6463 return ResultTy; 6464 } 6465 6466 /// \brief Return the resulting type when the operands are both block pointers. 6467 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6468 ExprResult &LHS, 6469 ExprResult &RHS, 6470 SourceLocation Loc) { 6471 QualType LHSTy = LHS.get()->getType(); 6472 QualType RHSTy = RHS.get()->getType(); 6473 6474 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6475 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6476 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6477 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6478 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6479 return destType; 6480 } 6481 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6482 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6483 << RHS.get()->getSourceRange(); 6484 return QualType(); 6485 } 6486 6487 // We have 2 block pointer types. 6488 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6489 } 6490 6491 /// \brief Return the resulting type when the operands are both pointers. 6492 static QualType 6493 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6494 ExprResult &RHS, 6495 SourceLocation Loc) { 6496 // get the pointer types 6497 QualType LHSTy = LHS.get()->getType(); 6498 QualType RHSTy = RHS.get()->getType(); 6499 6500 // get the "pointed to" types 6501 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6502 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6503 6504 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6505 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6506 // Figure out necessary qualifiers (C99 6.5.15p6) 6507 QualType destPointee 6508 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6509 QualType destType = S.Context.getPointerType(destPointee); 6510 // Add qualifiers if necessary. 6511 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6512 // Promote to void*. 6513 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6514 return destType; 6515 } 6516 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6517 QualType destPointee 6518 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6519 QualType destType = S.Context.getPointerType(destPointee); 6520 // Add qualifiers if necessary. 6521 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6522 // Promote to void*. 6523 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6524 return destType; 6525 } 6526 6527 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6528 } 6529 6530 /// \brief Return false if the first expression is not an integer and the second 6531 /// expression is not a pointer, true otherwise. 6532 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6533 Expr* PointerExpr, SourceLocation Loc, 6534 bool IsIntFirstExpr) { 6535 if (!PointerExpr->getType()->isPointerType() || 6536 !Int.get()->getType()->isIntegerType()) 6537 return false; 6538 6539 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6540 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6541 6542 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6543 << Expr1->getType() << Expr2->getType() 6544 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6545 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6546 CK_IntegralToPointer); 6547 return true; 6548 } 6549 6550 /// \brief Simple conversion between integer and floating point types. 6551 /// 6552 /// Used when handling the OpenCL conditional operator where the 6553 /// condition is a vector while the other operands are scalar. 6554 /// 6555 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6556 /// types are either integer or floating type. Between the two 6557 /// operands, the type with the higher rank is defined as the "result 6558 /// type". The other operand needs to be promoted to the same type. No 6559 /// other type promotion is allowed. We cannot use 6560 /// UsualArithmeticConversions() for this purpose, since it always 6561 /// promotes promotable types. 6562 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6563 ExprResult &RHS, 6564 SourceLocation QuestionLoc) { 6565 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6566 if (LHS.isInvalid()) 6567 return QualType(); 6568 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6569 if (RHS.isInvalid()) 6570 return QualType(); 6571 6572 // For conversion purposes, we ignore any qualifiers. 6573 // For example, "const float" and "float" are equivalent. 6574 QualType LHSType = 6575 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6576 QualType RHSType = 6577 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6578 6579 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6580 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6581 << LHSType << LHS.get()->getSourceRange(); 6582 return QualType(); 6583 } 6584 6585 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6586 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6587 << RHSType << RHS.get()->getSourceRange(); 6588 return QualType(); 6589 } 6590 6591 // If both types are identical, no conversion is needed. 6592 if (LHSType == RHSType) 6593 return LHSType; 6594 6595 // Now handle "real" floating types (i.e. float, double, long double). 6596 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6597 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6598 /*IsCompAssign = */ false); 6599 6600 // Finally, we have two differing integer types. 6601 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6602 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6603 } 6604 6605 /// \brief Convert scalar operands to a vector that matches the 6606 /// condition in length. 6607 /// 6608 /// Used when handling the OpenCL conditional operator where the 6609 /// condition is a vector while the other operands are scalar. 6610 /// 6611 /// We first compute the "result type" for the scalar operands 6612 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6613 /// into a vector of that type where the length matches the condition 6614 /// vector type. s6.11.6 requires that the element types of the result 6615 /// and the condition must have the same number of bits. 6616 static QualType 6617 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6618 QualType CondTy, SourceLocation QuestionLoc) { 6619 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6620 if (ResTy.isNull()) return QualType(); 6621 6622 const VectorType *CV = CondTy->getAs<VectorType>(); 6623 assert(CV); 6624 6625 // Determine the vector result type 6626 unsigned NumElements = CV->getNumElements(); 6627 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6628 6629 // Ensure that all types have the same number of bits 6630 if (S.Context.getTypeSize(CV->getElementType()) 6631 != S.Context.getTypeSize(ResTy)) { 6632 // Since VectorTy is created internally, it does not pretty print 6633 // with an OpenCL name. Instead, we just print a description. 6634 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6635 SmallString<64> Str; 6636 llvm::raw_svector_ostream OS(Str); 6637 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6638 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6639 << CondTy << OS.str(); 6640 return QualType(); 6641 } 6642 6643 // Convert operands to the vector result type 6644 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6645 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6646 6647 return VectorTy; 6648 } 6649 6650 /// \brief Return false if this is a valid OpenCL condition vector 6651 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6652 SourceLocation QuestionLoc) { 6653 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6654 // integral type. 6655 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6656 assert(CondTy); 6657 QualType EleTy = CondTy->getElementType(); 6658 if (EleTy->isIntegerType()) return false; 6659 6660 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6661 << Cond->getType() << Cond->getSourceRange(); 6662 return true; 6663 } 6664 6665 /// \brief Return false if the vector condition type and the vector 6666 /// result type are compatible. 6667 /// 6668 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6669 /// number of elements, and their element types have the same number 6670 /// of bits. 6671 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6672 SourceLocation QuestionLoc) { 6673 const VectorType *CV = CondTy->getAs<VectorType>(); 6674 const VectorType *RV = VecResTy->getAs<VectorType>(); 6675 assert(CV && RV); 6676 6677 if (CV->getNumElements() != RV->getNumElements()) { 6678 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6679 << CondTy << VecResTy; 6680 return true; 6681 } 6682 6683 QualType CVE = CV->getElementType(); 6684 QualType RVE = RV->getElementType(); 6685 6686 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6687 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6688 << CondTy << VecResTy; 6689 return true; 6690 } 6691 6692 return false; 6693 } 6694 6695 /// \brief Return the resulting type for the conditional operator in 6696 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6697 /// s6.3.i) when the condition is a vector type. 6698 static QualType 6699 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6700 ExprResult &LHS, ExprResult &RHS, 6701 SourceLocation QuestionLoc) { 6702 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6703 if (Cond.isInvalid()) 6704 return QualType(); 6705 QualType CondTy = Cond.get()->getType(); 6706 6707 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6708 return QualType(); 6709 6710 // If either operand is a vector then find the vector type of the 6711 // result as specified in OpenCL v1.1 s6.3.i. 6712 if (LHS.get()->getType()->isVectorType() || 6713 RHS.get()->getType()->isVectorType()) { 6714 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6715 /*isCompAssign*/false, 6716 /*AllowBothBool*/true, 6717 /*AllowBoolConversions*/false); 6718 if (VecResTy.isNull()) return QualType(); 6719 // The result type must match the condition type as specified in 6720 // OpenCL v1.1 s6.11.6. 6721 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6722 return QualType(); 6723 return VecResTy; 6724 } 6725 6726 // Both operands are scalar. 6727 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6728 } 6729 6730 /// \brief Return true if the Expr is block type 6731 static bool checkBlockType(Sema &S, const Expr *E) { 6732 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6733 QualType Ty = CE->getCallee()->getType(); 6734 if (Ty->isBlockPointerType()) { 6735 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6736 return true; 6737 } 6738 } 6739 return false; 6740 } 6741 6742 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6743 /// In that case, LHS = cond. 6744 /// C99 6.5.15 6745 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6746 ExprResult &RHS, ExprValueKind &VK, 6747 ExprObjectKind &OK, 6748 SourceLocation QuestionLoc) { 6749 6750 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6751 if (!LHSResult.isUsable()) return QualType(); 6752 LHS = LHSResult; 6753 6754 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6755 if (!RHSResult.isUsable()) return QualType(); 6756 RHS = RHSResult; 6757 6758 // C++ is sufficiently different to merit its own checker. 6759 if (getLangOpts().CPlusPlus) 6760 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6761 6762 VK = VK_RValue; 6763 OK = OK_Ordinary; 6764 6765 // The OpenCL operator with a vector condition is sufficiently 6766 // different to merit its own checker. 6767 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6768 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6769 6770 // First, check the condition. 6771 Cond = UsualUnaryConversions(Cond.get()); 6772 if (Cond.isInvalid()) 6773 return QualType(); 6774 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6775 return QualType(); 6776 6777 // Now check the two expressions. 6778 if (LHS.get()->getType()->isVectorType() || 6779 RHS.get()->getType()->isVectorType()) 6780 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6781 /*AllowBothBool*/true, 6782 /*AllowBoolConversions*/false); 6783 6784 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6785 if (LHS.isInvalid() || RHS.isInvalid()) 6786 return QualType(); 6787 6788 QualType LHSTy = LHS.get()->getType(); 6789 QualType RHSTy = RHS.get()->getType(); 6790 6791 // Diagnose attempts to convert between __float128 and long double where 6792 // such conversions currently can't be handled. 6793 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6794 Diag(QuestionLoc, 6795 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6797 return QualType(); 6798 } 6799 6800 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6801 // selection operator (?:). 6802 if (getLangOpts().OpenCL && 6803 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6804 return QualType(); 6805 } 6806 6807 // If both operands have arithmetic type, do the usual arithmetic conversions 6808 // to find a common type: C99 6.5.15p3,5. 6809 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6810 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6811 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6812 6813 return ResTy; 6814 } 6815 6816 // If both operands are the same structure or union type, the result is that 6817 // type. 6818 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6819 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6820 if (LHSRT->getDecl() == RHSRT->getDecl()) 6821 // "If both the operands have structure or union type, the result has 6822 // that type." This implies that CV qualifiers are dropped. 6823 return LHSTy.getUnqualifiedType(); 6824 // FIXME: Type of conditional expression must be complete in C mode. 6825 } 6826 6827 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6828 // The following || allows only one side to be void (a GCC-ism). 6829 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6830 return checkConditionalVoidType(*this, LHS, RHS); 6831 } 6832 6833 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6834 // the type of the other operand." 6835 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6836 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6837 6838 // All objective-c pointer type analysis is done here. 6839 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6840 QuestionLoc); 6841 if (LHS.isInvalid() || RHS.isInvalid()) 6842 return QualType(); 6843 if (!compositeType.isNull()) 6844 return compositeType; 6845 6846 6847 // Handle block pointer types. 6848 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6849 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6850 QuestionLoc); 6851 6852 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6853 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6854 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6855 QuestionLoc); 6856 6857 // GCC compatibility: soften pointer/integer mismatch. Note that 6858 // null pointers have been filtered out by this point. 6859 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6860 /*isIntFirstExpr=*/true)) 6861 return RHSTy; 6862 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6863 /*isIntFirstExpr=*/false)) 6864 return LHSTy; 6865 6866 // Emit a better diagnostic if one of the expressions is a null pointer 6867 // constant and the other is not a pointer type. In this case, the user most 6868 // likely forgot to take the address of the other expression. 6869 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6870 return QualType(); 6871 6872 // Otherwise, the operands are not compatible. 6873 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6874 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6875 << RHS.get()->getSourceRange(); 6876 return QualType(); 6877 } 6878 6879 /// FindCompositeObjCPointerType - Helper method to find composite type of 6880 /// two objective-c pointer types of the two input expressions. 6881 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6882 SourceLocation QuestionLoc) { 6883 QualType LHSTy = LHS.get()->getType(); 6884 QualType RHSTy = RHS.get()->getType(); 6885 6886 // Handle things like Class and struct objc_class*. Here we case the result 6887 // to the pseudo-builtin, because that will be implicitly cast back to the 6888 // redefinition type if an attempt is made to access its fields. 6889 if (LHSTy->isObjCClassType() && 6890 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6891 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6892 return LHSTy; 6893 } 6894 if (RHSTy->isObjCClassType() && 6895 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6896 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6897 return RHSTy; 6898 } 6899 // And the same for struct objc_object* / id 6900 if (LHSTy->isObjCIdType() && 6901 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6902 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6903 return LHSTy; 6904 } 6905 if (RHSTy->isObjCIdType() && 6906 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6907 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6908 return RHSTy; 6909 } 6910 // And the same for struct objc_selector* / SEL 6911 if (Context.isObjCSelType(LHSTy) && 6912 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6913 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6914 return LHSTy; 6915 } 6916 if (Context.isObjCSelType(RHSTy) && 6917 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6918 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6919 return RHSTy; 6920 } 6921 // Check constraints for Objective-C object pointers types. 6922 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6923 6924 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6925 // Two identical object pointer types are always compatible. 6926 return LHSTy; 6927 } 6928 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6929 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6930 QualType compositeType = LHSTy; 6931 6932 // If both operands are interfaces and either operand can be 6933 // assigned to the other, use that type as the composite 6934 // type. This allows 6935 // xxx ? (A*) a : (B*) b 6936 // where B is a subclass of A. 6937 // 6938 // Additionally, as for assignment, if either type is 'id' 6939 // allow silent coercion. Finally, if the types are 6940 // incompatible then make sure to use 'id' as the composite 6941 // type so the result is acceptable for sending messages to. 6942 6943 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6944 // It could return the composite type. 6945 if (!(compositeType = 6946 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6947 // Nothing more to do. 6948 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6949 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6950 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6951 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6952 } else if ((LHSTy->isObjCQualifiedIdType() || 6953 RHSTy->isObjCQualifiedIdType()) && 6954 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6955 // Need to handle "id<xx>" explicitly. 6956 // GCC allows qualified id and any Objective-C type to devolve to 6957 // id. Currently localizing to here until clear this should be 6958 // part of ObjCQualifiedIdTypesAreCompatible. 6959 compositeType = Context.getObjCIdType(); 6960 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6961 compositeType = Context.getObjCIdType(); 6962 } else { 6963 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6964 << LHSTy << RHSTy 6965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6966 QualType incompatTy = Context.getObjCIdType(); 6967 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6968 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6969 return incompatTy; 6970 } 6971 // The object pointer types are compatible. 6972 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6973 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6974 return compositeType; 6975 } 6976 // Check Objective-C object pointer types and 'void *' 6977 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6978 if (getLangOpts().ObjCAutoRefCount) { 6979 // ARC forbids the implicit conversion of object pointers to 'void *', 6980 // so these types are not compatible. 6981 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6982 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6983 LHS = RHS = true; 6984 return QualType(); 6985 } 6986 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6987 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6988 QualType destPointee 6989 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6990 QualType destType = Context.getPointerType(destPointee); 6991 // Add qualifiers if necessary. 6992 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6993 // Promote to void*. 6994 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6995 return destType; 6996 } 6997 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6998 if (getLangOpts().ObjCAutoRefCount) { 6999 // ARC forbids the implicit conversion of object pointers to 'void *', 7000 // so these types are not compatible. 7001 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7003 LHS = RHS = true; 7004 return QualType(); 7005 } 7006 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7007 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7008 QualType destPointee 7009 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7010 QualType destType = Context.getPointerType(destPointee); 7011 // Add qualifiers if necessary. 7012 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7013 // Promote to void*. 7014 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7015 return destType; 7016 } 7017 return QualType(); 7018 } 7019 7020 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7021 /// ParenRange in parentheses. 7022 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7023 const PartialDiagnostic &Note, 7024 SourceRange ParenRange) { 7025 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7026 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7027 EndLoc.isValid()) { 7028 Self.Diag(Loc, Note) 7029 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7030 << FixItHint::CreateInsertion(EndLoc, ")"); 7031 } else { 7032 // We can't display the parentheses, so just show the bare note. 7033 Self.Diag(Loc, Note) << ParenRange; 7034 } 7035 } 7036 7037 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7038 return BinaryOperator::isAdditiveOp(Opc) || 7039 BinaryOperator::isMultiplicativeOp(Opc) || 7040 BinaryOperator::isShiftOp(Opc); 7041 } 7042 7043 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7044 /// expression, either using a built-in or overloaded operator, 7045 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7046 /// expression. 7047 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7048 Expr **RHSExprs) { 7049 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7050 E = E->IgnoreImpCasts(); 7051 E = E->IgnoreConversionOperator(); 7052 E = E->IgnoreImpCasts(); 7053 7054 // Built-in binary operator. 7055 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7056 if (IsArithmeticOp(OP->getOpcode())) { 7057 *Opcode = OP->getOpcode(); 7058 *RHSExprs = OP->getRHS(); 7059 return true; 7060 } 7061 } 7062 7063 // Overloaded operator. 7064 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7065 if (Call->getNumArgs() != 2) 7066 return false; 7067 7068 // Make sure this is really a binary operator that is safe to pass into 7069 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7070 OverloadedOperatorKind OO = Call->getOperator(); 7071 if (OO < OO_Plus || OO > OO_Arrow || 7072 OO == OO_PlusPlus || OO == OO_MinusMinus) 7073 return false; 7074 7075 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7076 if (IsArithmeticOp(OpKind)) { 7077 *Opcode = OpKind; 7078 *RHSExprs = Call->getArg(1); 7079 return true; 7080 } 7081 } 7082 7083 return false; 7084 } 7085 7086 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7087 /// or is a logical expression such as (x==y) which has int type, but is 7088 /// commonly interpreted as boolean. 7089 static bool ExprLooksBoolean(Expr *E) { 7090 E = E->IgnoreParenImpCasts(); 7091 7092 if (E->getType()->isBooleanType()) 7093 return true; 7094 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7095 return OP->isComparisonOp() || OP->isLogicalOp(); 7096 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7097 return OP->getOpcode() == UO_LNot; 7098 if (E->getType()->isPointerType()) 7099 return true; 7100 7101 return false; 7102 } 7103 7104 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7105 /// and binary operator are mixed in a way that suggests the programmer assumed 7106 /// the conditional operator has higher precedence, for example: 7107 /// "int x = a + someBinaryCondition ? 1 : 2". 7108 static void DiagnoseConditionalPrecedence(Sema &Self, 7109 SourceLocation OpLoc, 7110 Expr *Condition, 7111 Expr *LHSExpr, 7112 Expr *RHSExpr) { 7113 BinaryOperatorKind CondOpcode; 7114 Expr *CondRHS; 7115 7116 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7117 return; 7118 if (!ExprLooksBoolean(CondRHS)) 7119 return; 7120 7121 // The condition is an arithmetic binary expression, with a right- 7122 // hand side that looks boolean, so warn. 7123 7124 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7125 << Condition->getSourceRange() 7126 << BinaryOperator::getOpcodeStr(CondOpcode); 7127 7128 SuggestParentheses(Self, OpLoc, 7129 Self.PDiag(diag::note_precedence_silence) 7130 << BinaryOperator::getOpcodeStr(CondOpcode), 7131 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7132 7133 SuggestParentheses(Self, OpLoc, 7134 Self.PDiag(diag::note_precedence_conditional_first), 7135 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7136 } 7137 7138 /// Compute the nullability of a conditional expression. 7139 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7140 QualType LHSTy, QualType RHSTy, 7141 ASTContext &Ctx) { 7142 if (!ResTy->isAnyPointerType()) 7143 return ResTy; 7144 7145 auto GetNullability = [&Ctx](QualType Ty) { 7146 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7147 if (Kind) 7148 return *Kind; 7149 return NullabilityKind::Unspecified; 7150 }; 7151 7152 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7153 NullabilityKind MergedKind; 7154 7155 // Compute nullability of a binary conditional expression. 7156 if (IsBin) { 7157 if (LHSKind == NullabilityKind::NonNull) 7158 MergedKind = NullabilityKind::NonNull; 7159 else 7160 MergedKind = RHSKind; 7161 // Compute nullability of a normal conditional expression. 7162 } else { 7163 if (LHSKind == NullabilityKind::Nullable || 7164 RHSKind == NullabilityKind::Nullable) 7165 MergedKind = NullabilityKind::Nullable; 7166 else if (LHSKind == NullabilityKind::NonNull) 7167 MergedKind = RHSKind; 7168 else if (RHSKind == NullabilityKind::NonNull) 7169 MergedKind = LHSKind; 7170 else 7171 MergedKind = NullabilityKind::Unspecified; 7172 } 7173 7174 // Return if ResTy already has the correct nullability. 7175 if (GetNullability(ResTy) == MergedKind) 7176 return ResTy; 7177 7178 // Strip all nullability from ResTy. 7179 while (ResTy->getNullability(Ctx)) 7180 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7181 7182 // Create a new AttributedType with the new nullability kind. 7183 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7184 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7185 } 7186 7187 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7188 /// in the case of a the GNU conditional expr extension. 7189 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7190 SourceLocation ColonLoc, 7191 Expr *CondExpr, Expr *LHSExpr, 7192 Expr *RHSExpr) { 7193 if (!getLangOpts().CPlusPlus) { 7194 // C cannot handle TypoExpr nodes in the condition because it 7195 // doesn't handle dependent types properly, so make sure any TypoExprs have 7196 // been dealt with before checking the operands. 7197 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7198 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7199 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7200 7201 if (!CondResult.isUsable()) 7202 return ExprError(); 7203 7204 if (LHSExpr) { 7205 if (!LHSResult.isUsable()) 7206 return ExprError(); 7207 } 7208 7209 if (!RHSResult.isUsable()) 7210 return ExprError(); 7211 7212 CondExpr = CondResult.get(); 7213 LHSExpr = LHSResult.get(); 7214 RHSExpr = RHSResult.get(); 7215 } 7216 7217 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7218 // was the condition. 7219 OpaqueValueExpr *opaqueValue = nullptr; 7220 Expr *commonExpr = nullptr; 7221 if (!LHSExpr) { 7222 commonExpr = CondExpr; 7223 // Lower out placeholder types first. This is important so that we don't 7224 // try to capture a placeholder. This happens in few cases in C++; such 7225 // as Objective-C++'s dictionary subscripting syntax. 7226 if (commonExpr->hasPlaceholderType()) { 7227 ExprResult result = CheckPlaceholderExpr(commonExpr); 7228 if (!result.isUsable()) return ExprError(); 7229 commonExpr = result.get(); 7230 } 7231 // We usually want to apply unary conversions *before* saving, except 7232 // in the special case of a C++ l-value conditional. 7233 if (!(getLangOpts().CPlusPlus 7234 && !commonExpr->isTypeDependent() 7235 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7236 && commonExpr->isGLValue() 7237 && commonExpr->isOrdinaryOrBitFieldObject() 7238 && RHSExpr->isOrdinaryOrBitFieldObject() 7239 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7240 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7241 if (commonRes.isInvalid()) 7242 return ExprError(); 7243 commonExpr = commonRes.get(); 7244 } 7245 7246 // If the common expression is a class or array prvalue, materialize it 7247 // so that we can safely refer to it multiple times. 7248 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7249 commonExpr->getType()->isArrayType())) { 7250 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7251 if (MatExpr.isInvalid()) 7252 return ExprError(); 7253 commonExpr = MatExpr.get(); 7254 } 7255 7256 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7257 commonExpr->getType(), 7258 commonExpr->getValueKind(), 7259 commonExpr->getObjectKind(), 7260 commonExpr); 7261 LHSExpr = CondExpr = opaqueValue; 7262 } 7263 7264 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7265 ExprValueKind VK = VK_RValue; 7266 ExprObjectKind OK = OK_Ordinary; 7267 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7268 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7269 VK, OK, QuestionLoc); 7270 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7271 RHS.isInvalid()) 7272 return ExprError(); 7273 7274 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7275 RHS.get()); 7276 7277 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7278 7279 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7280 Context); 7281 7282 if (!commonExpr) 7283 return new (Context) 7284 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7285 RHS.get(), result, VK, OK); 7286 7287 return new (Context) BinaryConditionalOperator( 7288 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7289 ColonLoc, result, VK, OK); 7290 } 7291 7292 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7293 // being closely modeled after the C99 spec:-). The odd characteristic of this 7294 // routine is it effectively iqnores the qualifiers on the top level pointee. 7295 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7296 // FIXME: add a couple examples in this comment. 7297 static Sema::AssignConvertType 7298 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7299 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7300 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7301 7302 // get the "pointed to" type (ignoring qualifiers at the top level) 7303 const Type *lhptee, *rhptee; 7304 Qualifiers lhq, rhq; 7305 std::tie(lhptee, lhq) = 7306 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7307 std::tie(rhptee, rhq) = 7308 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7309 7310 Sema::AssignConvertType ConvTy = Sema::Compatible; 7311 7312 // C99 6.5.16.1p1: This following citation is common to constraints 7313 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7314 // qualifiers of the type *pointed to* by the right; 7315 7316 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7317 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7318 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7319 // Ignore lifetime for further calculation. 7320 lhq.removeObjCLifetime(); 7321 rhq.removeObjCLifetime(); 7322 } 7323 7324 if (!lhq.compatiblyIncludes(rhq)) { 7325 // Treat address-space mismatches as fatal. TODO: address subspaces 7326 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7327 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7328 7329 // It's okay to add or remove GC or lifetime qualifiers when converting to 7330 // and from void*. 7331 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7332 .compatiblyIncludes( 7333 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7334 && (lhptee->isVoidType() || rhptee->isVoidType())) 7335 ; // keep old 7336 7337 // Treat lifetime mismatches as fatal. 7338 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7339 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7340 7341 // For GCC/MS compatibility, other qualifier mismatches are treated 7342 // as still compatible in C. 7343 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7344 } 7345 7346 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7347 // incomplete type and the other is a pointer to a qualified or unqualified 7348 // version of void... 7349 if (lhptee->isVoidType()) { 7350 if (rhptee->isIncompleteOrObjectType()) 7351 return ConvTy; 7352 7353 // As an extension, we allow cast to/from void* to function pointer. 7354 assert(rhptee->isFunctionType()); 7355 return Sema::FunctionVoidPointer; 7356 } 7357 7358 if (rhptee->isVoidType()) { 7359 if (lhptee->isIncompleteOrObjectType()) 7360 return ConvTy; 7361 7362 // As an extension, we allow cast to/from void* to function pointer. 7363 assert(lhptee->isFunctionType()); 7364 return Sema::FunctionVoidPointer; 7365 } 7366 7367 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7368 // unqualified versions of compatible types, ... 7369 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7370 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7371 // Check if the pointee types are compatible ignoring the sign. 7372 // We explicitly check for char so that we catch "char" vs 7373 // "unsigned char" on systems where "char" is unsigned. 7374 if (lhptee->isCharType()) 7375 ltrans = S.Context.UnsignedCharTy; 7376 else if (lhptee->hasSignedIntegerRepresentation()) 7377 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7378 7379 if (rhptee->isCharType()) 7380 rtrans = S.Context.UnsignedCharTy; 7381 else if (rhptee->hasSignedIntegerRepresentation()) 7382 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7383 7384 if (ltrans == rtrans) { 7385 // Types are compatible ignoring the sign. Qualifier incompatibility 7386 // takes priority over sign incompatibility because the sign 7387 // warning can be disabled. 7388 if (ConvTy != Sema::Compatible) 7389 return ConvTy; 7390 7391 return Sema::IncompatiblePointerSign; 7392 } 7393 7394 // If we are a multi-level pointer, it's possible that our issue is simply 7395 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7396 // the eventual target type is the same and the pointers have the same 7397 // level of indirection, this must be the issue. 7398 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7399 do { 7400 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7401 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7402 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7403 7404 if (lhptee == rhptee) 7405 return Sema::IncompatibleNestedPointerQualifiers; 7406 } 7407 7408 // General pointer incompatibility takes priority over qualifiers. 7409 return Sema::IncompatiblePointer; 7410 } 7411 if (!S.getLangOpts().CPlusPlus && 7412 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7413 return Sema::IncompatiblePointer; 7414 return ConvTy; 7415 } 7416 7417 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7418 /// block pointer types are compatible or whether a block and normal pointer 7419 /// are compatible. It is more restrict than comparing two function pointer 7420 // types. 7421 static Sema::AssignConvertType 7422 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7423 QualType RHSType) { 7424 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7425 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7426 7427 QualType lhptee, rhptee; 7428 7429 // get the "pointed to" type (ignoring qualifiers at the top level) 7430 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7431 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7432 7433 // In C++, the types have to match exactly. 7434 if (S.getLangOpts().CPlusPlus) 7435 return Sema::IncompatibleBlockPointer; 7436 7437 Sema::AssignConvertType ConvTy = Sema::Compatible; 7438 7439 // For blocks we enforce that qualifiers are identical. 7440 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7441 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7442 if (S.getLangOpts().OpenCL) { 7443 LQuals.removeAddressSpace(); 7444 RQuals.removeAddressSpace(); 7445 } 7446 if (LQuals != RQuals) 7447 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7448 7449 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7450 // assignment. 7451 // The current behavior is similar to C++ lambdas. A block might be 7452 // assigned to a variable iff its return type and parameters are compatible 7453 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7454 // an assignment. Presumably it should behave in way that a function pointer 7455 // assignment does in C, so for each parameter and return type: 7456 // * CVR and address space of LHS should be a superset of CVR and address 7457 // space of RHS. 7458 // * unqualified types should be compatible. 7459 if (S.getLangOpts().OpenCL) { 7460 if (!S.Context.typesAreBlockPointerCompatible( 7461 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7462 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7463 return Sema::IncompatibleBlockPointer; 7464 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7465 return Sema::IncompatibleBlockPointer; 7466 7467 return ConvTy; 7468 } 7469 7470 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7471 /// for assignment compatibility. 7472 static Sema::AssignConvertType 7473 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7474 QualType RHSType) { 7475 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7476 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7477 7478 if (LHSType->isObjCBuiltinType()) { 7479 // Class is not compatible with ObjC object pointers. 7480 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7481 !RHSType->isObjCQualifiedClassType()) 7482 return Sema::IncompatiblePointer; 7483 return Sema::Compatible; 7484 } 7485 if (RHSType->isObjCBuiltinType()) { 7486 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7487 !LHSType->isObjCQualifiedClassType()) 7488 return Sema::IncompatiblePointer; 7489 return Sema::Compatible; 7490 } 7491 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7492 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7493 7494 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7495 // make an exception for id<P> 7496 !LHSType->isObjCQualifiedIdType()) 7497 return Sema::CompatiblePointerDiscardsQualifiers; 7498 7499 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7500 return Sema::Compatible; 7501 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7502 return Sema::IncompatibleObjCQualifiedId; 7503 return Sema::IncompatiblePointer; 7504 } 7505 7506 Sema::AssignConvertType 7507 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7508 QualType LHSType, QualType RHSType) { 7509 // Fake up an opaque expression. We don't actually care about what 7510 // cast operations are required, so if CheckAssignmentConstraints 7511 // adds casts to this they'll be wasted, but fortunately that doesn't 7512 // usually happen on valid code. 7513 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7514 ExprResult RHSPtr = &RHSExpr; 7515 CastKind K; 7516 7517 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7518 } 7519 7520 /// This helper function returns true if QT is a vector type that has element 7521 /// type ElementType. 7522 static bool isVector(QualType QT, QualType ElementType) { 7523 if (const VectorType *VT = QT->getAs<VectorType>()) 7524 return VT->getElementType() == ElementType; 7525 return false; 7526 } 7527 7528 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7529 /// has code to accommodate several GCC extensions when type checking 7530 /// pointers. Here are some objectionable examples that GCC considers warnings: 7531 /// 7532 /// int a, *pint; 7533 /// short *pshort; 7534 /// struct foo *pfoo; 7535 /// 7536 /// pint = pshort; // warning: assignment from incompatible pointer type 7537 /// a = pint; // warning: assignment makes integer from pointer without a cast 7538 /// pint = a; // warning: assignment makes pointer from integer without a cast 7539 /// pint = pfoo; // warning: assignment from incompatible pointer type 7540 /// 7541 /// As a result, the code for dealing with pointers is more complex than the 7542 /// C99 spec dictates. 7543 /// 7544 /// Sets 'Kind' for any result kind except Incompatible. 7545 Sema::AssignConvertType 7546 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7547 CastKind &Kind, bool ConvertRHS) { 7548 QualType RHSType = RHS.get()->getType(); 7549 QualType OrigLHSType = LHSType; 7550 7551 // Get canonical types. We're not formatting these types, just comparing 7552 // them. 7553 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7554 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7555 7556 // Common case: no conversion required. 7557 if (LHSType == RHSType) { 7558 Kind = CK_NoOp; 7559 return Compatible; 7560 } 7561 7562 // If we have an atomic type, try a non-atomic assignment, then just add an 7563 // atomic qualification step. 7564 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7565 Sema::AssignConvertType result = 7566 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7567 if (result != Compatible) 7568 return result; 7569 if (Kind != CK_NoOp && ConvertRHS) 7570 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7571 Kind = CK_NonAtomicToAtomic; 7572 return Compatible; 7573 } 7574 7575 // If the left-hand side is a reference type, then we are in a 7576 // (rare!) case where we've allowed the use of references in C, 7577 // e.g., as a parameter type in a built-in function. In this case, 7578 // just make sure that the type referenced is compatible with the 7579 // right-hand side type. The caller is responsible for adjusting 7580 // LHSType so that the resulting expression does not have reference 7581 // type. 7582 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7583 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7584 Kind = CK_LValueBitCast; 7585 return Compatible; 7586 } 7587 return Incompatible; 7588 } 7589 7590 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7591 // to the same ExtVector type. 7592 if (LHSType->isExtVectorType()) { 7593 if (RHSType->isExtVectorType()) 7594 return Incompatible; 7595 if (RHSType->isArithmeticType()) { 7596 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7597 if (ConvertRHS) 7598 RHS = prepareVectorSplat(LHSType, RHS.get()); 7599 Kind = CK_VectorSplat; 7600 return Compatible; 7601 } 7602 } 7603 7604 // Conversions to or from vector type. 7605 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7606 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7607 // Allow assignments of an AltiVec vector type to an equivalent GCC 7608 // vector type and vice versa 7609 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7610 Kind = CK_BitCast; 7611 return Compatible; 7612 } 7613 7614 // If we are allowing lax vector conversions, and LHS and RHS are both 7615 // vectors, the total size only needs to be the same. This is a bitcast; 7616 // no bits are changed but the result type is different. 7617 if (isLaxVectorConversion(RHSType, LHSType)) { 7618 Kind = CK_BitCast; 7619 return IncompatibleVectors; 7620 } 7621 } 7622 7623 // When the RHS comes from another lax conversion (e.g. binops between 7624 // scalars and vectors) the result is canonicalized as a vector. When the 7625 // LHS is also a vector, the lax is allowed by the condition above. Handle 7626 // the case where LHS is a scalar. 7627 if (LHSType->isScalarType()) { 7628 const VectorType *VecType = RHSType->getAs<VectorType>(); 7629 if (VecType && VecType->getNumElements() == 1 && 7630 isLaxVectorConversion(RHSType, LHSType)) { 7631 ExprResult *VecExpr = &RHS; 7632 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7633 Kind = CK_BitCast; 7634 return Compatible; 7635 } 7636 } 7637 7638 return Incompatible; 7639 } 7640 7641 // Diagnose attempts to convert between __float128 and long double where 7642 // such conversions currently can't be handled. 7643 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7644 return Incompatible; 7645 7646 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7647 // discards the imaginary part. 7648 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7649 !LHSType->getAs<ComplexType>()) 7650 return Incompatible; 7651 7652 // Arithmetic conversions. 7653 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7654 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7655 if (ConvertRHS) 7656 Kind = PrepareScalarCast(RHS, LHSType); 7657 return Compatible; 7658 } 7659 7660 // Conversions to normal pointers. 7661 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7662 // U* -> T* 7663 if (isa<PointerType>(RHSType)) { 7664 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7665 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7666 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7667 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7668 } 7669 7670 // int -> T* 7671 if (RHSType->isIntegerType()) { 7672 Kind = CK_IntegralToPointer; // FIXME: null? 7673 return IntToPointer; 7674 } 7675 7676 // C pointers are not compatible with ObjC object pointers, 7677 // with two exceptions: 7678 if (isa<ObjCObjectPointerType>(RHSType)) { 7679 // - conversions to void* 7680 if (LHSPointer->getPointeeType()->isVoidType()) { 7681 Kind = CK_BitCast; 7682 return Compatible; 7683 } 7684 7685 // - conversions from 'Class' to the redefinition type 7686 if (RHSType->isObjCClassType() && 7687 Context.hasSameType(LHSType, 7688 Context.getObjCClassRedefinitionType())) { 7689 Kind = CK_BitCast; 7690 return Compatible; 7691 } 7692 7693 Kind = CK_BitCast; 7694 return IncompatiblePointer; 7695 } 7696 7697 // U^ -> void* 7698 if (RHSType->getAs<BlockPointerType>()) { 7699 if (LHSPointer->getPointeeType()->isVoidType()) { 7700 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7701 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7702 ->getPointeeType() 7703 .getAddressSpace(); 7704 Kind = 7705 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7706 return Compatible; 7707 } 7708 } 7709 7710 return Incompatible; 7711 } 7712 7713 // Conversions to block pointers. 7714 if (isa<BlockPointerType>(LHSType)) { 7715 // U^ -> T^ 7716 if (RHSType->isBlockPointerType()) { 7717 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7718 ->getPointeeType() 7719 .getAddressSpace(); 7720 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7721 ->getPointeeType() 7722 .getAddressSpace(); 7723 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7724 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7725 } 7726 7727 // int or null -> T^ 7728 if (RHSType->isIntegerType()) { 7729 Kind = CK_IntegralToPointer; // FIXME: null 7730 return IntToBlockPointer; 7731 } 7732 7733 // id -> T^ 7734 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7735 Kind = CK_AnyPointerToBlockPointerCast; 7736 return Compatible; 7737 } 7738 7739 // void* -> T^ 7740 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7741 if (RHSPT->getPointeeType()->isVoidType()) { 7742 Kind = CK_AnyPointerToBlockPointerCast; 7743 return Compatible; 7744 } 7745 7746 return Incompatible; 7747 } 7748 7749 // Conversions to Objective-C pointers. 7750 if (isa<ObjCObjectPointerType>(LHSType)) { 7751 // A* -> B* 7752 if (RHSType->isObjCObjectPointerType()) { 7753 Kind = CK_BitCast; 7754 Sema::AssignConvertType result = 7755 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7756 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7757 result == Compatible && 7758 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7759 result = IncompatibleObjCWeakRef; 7760 return result; 7761 } 7762 7763 // int or null -> A* 7764 if (RHSType->isIntegerType()) { 7765 Kind = CK_IntegralToPointer; // FIXME: null 7766 return IntToPointer; 7767 } 7768 7769 // In general, C pointers are not compatible with ObjC object pointers, 7770 // with two exceptions: 7771 if (isa<PointerType>(RHSType)) { 7772 Kind = CK_CPointerToObjCPointerCast; 7773 7774 // - conversions from 'void*' 7775 if (RHSType->isVoidPointerType()) { 7776 return Compatible; 7777 } 7778 7779 // - conversions to 'Class' from its redefinition type 7780 if (LHSType->isObjCClassType() && 7781 Context.hasSameType(RHSType, 7782 Context.getObjCClassRedefinitionType())) { 7783 return Compatible; 7784 } 7785 7786 return IncompatiblePointer; 7787 } 7788 7789 // Only under strict condition T^ is compatible with an Objective-C pointer. 7790 if (RHSType->isBlockPointerType() && 7791 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7792 if (ConvertRHS) 7793 maybeExtendBlockObject(RHS); 7794 Kind = CK_BlockPointerToObjCPointerCast; 7795 return Compatible; 7796 } 7797 7798 return Incompatible; 7799 } 7800 7801 // Conversions from pointers that are not covered by the above. 7802 if (isa<PointerType>(RHSType)) { 7803 // T* -> _Bool 7804 if (LHSType == Context.BoolTy) { 7805 Kind = CK_PointerToBoolean; 7806 return Compatible; 7807 } 7808 7809 // T* -> int 7810 if (LHSType->isIntegerType()) { 7811 Kind = CK_PointerToIntegral; 7812 return PointerToInt; 7813 } 7814 7815 return Incompatible; 7816 } 7817 7818 // Conversions from Objective-C pointers that are not covered by the above. 7819 if (isa<ObjCObjectPointerType>(RHSType)) { 7820 // T* -> _Bool 7821 if (LHSType == Context.BoolTy) { 7822 Kind = CK_PointerToBoolean; 7823 return Compatible; 7824 } 7825 7826 // T* -> int 7827 if (LHSType->isIntegerType()) { 7828 Kind = CK_PointerToIntegral; 7829 return PointerToInt; 7830 } 7831 7832 return Incompatible; 7833 } 7834 7835 // struct A -> struct B 7836 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7837 if (Context.typesAreCompatible(LHSType, RHSType)) { 7838 Kind = CK_NoOp; 7839 return Compatible; 7840 } 7841 } 7842 7843 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7844 Kind = CK_IntToOCLSampler; 7845 return Compatible; 7846 } 7847 7848 return Incompatible; 7849 } 7850 7851 /// \brief Constructs a transparent union from an expression that is 7852 /// used to initialize the transparent union. 7853 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7854 ExprResult &EResult, QualType UnionType, 7855 FieldDecl *Field) { 7856 // Build an initializer list that designates the appropriate member 7857 // of the transparent union. 7858 Expr *E = EResult.get(); 7859 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7860 E, SourceLocation()); 7861 Initializer->setType(UnionType); 7862 Initializer->setInitializedFieldInUnion(Field); 7863 7864 // Build a compound literal constructing a value of the transparent 7865 // union type from this initializer list. 7866 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7867 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7868 VK_RValue, Initializer, false); 7869 } 7870 7871 Sema::AssignConvertType 7872 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7873 ExprResult &RHS) { 7874 QualType RHSType = RHS.get()->getType(); 7875 7876 // If the ArgType is a Union type, we want to handle a potential 7877 // transparent_union GCC extension. 7878 const RecordType *UT = ArgType->getAsUnionType(); 7879 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7880 return Incompatible; 7881 7882 // The field to initialize within the transparent union. 7883 RecordDecl *UD = UT->getDecl(); 7884 FieldDecl *InitField = nullptr; 7885 // It's compatible if the expression matches any of the fields. 7886 for (auto *it : UD->fields()) { 7887 if (it->getType()->isPointerType()) { 7888 // If the transparent union contains a pointer type, we allow: 7889 // 1) void pointer 7890 // 2) null pointer constant 7891 if (RHSType->isPointerType()) 7892 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7893 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7894 InitField = it; 7895 break; 7896 } 7897 7898 if (RHS.get()->isNullPointerConstant(Context, 7899 Expr::NPC_ValueDependentIsNull)) { 7900 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7901 CK_NullToPointer); 7902 InitField = it; 7903 break; 7904 } 7905 } 7906 7907 CastKind Kind; 7908 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7909 == Compatible) { 7910 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7911 InitField = it; 7912 break; 7913 } 7914 } 7915 7916 if (!InitField) 7917 return Incompatible; 7918 7919 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7920 return Compatible; 7921 } 7922 7923 Sema::AssignConvertType 7924 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7925 bool Diagnose, 7926 bool DiagnoseCFAudited, 7927 bool ConvertRHS) { 7928 // We need to be able to tell the caller whether we diagnosed a problem, if 7929 // they ask us to issue diagnostics. 7930 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7931 7932 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7933 // we can't avoid *all* modifications at the moment, so we need some somewhere 7934 // to put the updated value. 7935 ExprResult LocalRHS = CallerRHS; 7936 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7937 7938 if (getLangOpts().CPlusPlus) { 7939 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7940 // C++ 5.17p3: If the left operand is not of class type, the 7941 // expression is implicitly converted (C++ 4) to the 7942 // cv-unqualified type of the left operand. 7943 QualType RHSType = RHS.get()->getType(); 7944 if (Diagnose) { 7945 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7946 AA_Assigning); 7947 } else { 7948 ImplicitConversionSequence ICS = 7949 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7950 /*SuppressUserConversions=*/false, 7951 /*AllowExplicit=*/false, 7952 /*InOverloadResolution=*/false, 7953 /*CStyle=*/false, 7954 /*AllowObjCWritebackConversion=*/false); 7955 if (ICS.isFailure()) 7956 return Incompatible; 7957 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7958 ICS, AA_Assigning); 7959 } 7960 if (RHS.isInvalid()) 7961 return Incompatible; 7962 Sema::AssignConvertType result = Compatible; 7963 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7964 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7965 result = IncompatibleObjCWeakRef; 7966 return result; 7967 } 7968 7969 // FIXME: Currently, we fall through and treat C++ classes like C 7970 // structures. 7971 // FIXME: We also fall through for atomics; not sure what should 7972 // happen there, though. 7973 } else if (RHS.get()->getType() == Context.OverloadTy) { 7974 // As a set of extensions to C, we support overloading on functions. These 7975 // functions need to be resolved here. 7976 DeclAccessPair DAP; 7977 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7978 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7979 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7980 else 7981 return Incompatible; 7982 } 7983 7984 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7985 // a null pointer constant. 7986 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7987 LHSType->isBlockPointerType()) && 7988 RHS.get()->isNullPointerConstant(Context, 7989 Expr::NPC_ValueDependentIsNull)) { 7990 if (Diagnose || ConvertRHS) { 7991 CastKind Kind; 7992 CXXCastPath Path; 7993 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7994 /*IgnoreBaseAccess=*/false, Diagnose); 7995 if (ConvertRHS) 7996 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7997 } 7998 return Compatible; 7999 } 8000 8001 // This check seems unnatural, however it is necessary to ensure the proper 8002 // conversion of functions/arrays. If the conversion were done for all 8003 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8004 // expressions that suppress this implicit conversion (&, sizeof). 8005 // 8006 // Suppress this for references: C++ 8.5.3p5. 8007 if (!LHSType->isReferenceType()) { 8008 // FIXME: We potentially allocate here even if ConvertRHS is false. 8009 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8010 if (RHS.isInvalid()) 8011 return Incompatible; 8012 } 8013 8014 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8015 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8016 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8017 if (PDecl && !PDecl->hasDefinition()) { 8018 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8019 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8020 } 8021 } 8022 8023 CastKind Kind; 8024 Sema::AssignConvertType result = 8025 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8026 8027 // C99 6.5.16.1p2: The value of the right operand is converted to the 8028 // type of the assignment expression. 8029 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8030 // so that we can use references in built-in functions even in C. 8031 // The getNonReferenceType() call makes sure that the resulting expression 8032 // does not have reference type. 8033 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8034 QualType Ty = LHSType.getNonLValueExprType(Context); 8035 Expr *E = RHS.get(); 8036 8037 // Check for various Objective-C errors. If we are not reporting 8038 // diagnostics and just checking for errors, e.g., during overload 8039 // resolution, return Incompatible to indicate the failure. 8040 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8041 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8042 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8043 if (!Diagnose) 8044 return Incompatible; 8045 } 8046 if (getLangOpts().ObjC1 && 8047 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8048 E->getType(), E, Diagnose) || 8049 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8050 if (!Diagnose) 8051 return Incompatible; 8052 // Replace the expression with a corrected version and continue so we 8053 // can find further errors. 8054 RHS = E; 8055 return Compatible; 8056 } 8057 8058 if (ConvertRHS) 8059 RHS = ImpCastExprToType(E, Ty, Kind); 8060 } 8061 return result; 8062 } 8063 8064 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8065 ExprResult &RHS) { 8066 Diag(Loc, diag::err_typecheck_invalid_operands) 8067 << LHS.get()->getType() << RHS.get()->getType() 8068 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8069 return QualType(); 8070 } 8071 8072 // Diagnose cases where a scalar was implicitly converted to a vector and 8073 // diagnose the underlying types. Otherwise, diagnose the error 8074 // as invalid vector logical operands for non-C++ cases. 8075 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8076 ExprResult &RHS) { 8077 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8078 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8079 8080 bool LHSNatVec = LHSType->isVectorType(); 8081 bool RHSNatVec = RHSType->isVectorType(); 8082 8083 if (!(LHSNatVec && RHSNatVec)) { 8084 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8085 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8086 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8087 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8088 << Vector->getSourceRange(); 8089 return QualType(); 8090 } 8091 8092 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8093 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8094 << RHS.get()->getSourceRange(); 8095 8096 return QualType(); 8097 } 8098 8099 /// Try to convert a value of non-vector type to a vector type by converting 8100 /// the type to the element type of the vector and then performing a splat. 8101 /// If the language is OpenCL, we only use conversions that promote scalar 8102 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8103 /// for float->int. 8104 /// 8105 /// OpenCL V2.0 6.2.6.p2: 8106 /// An error shall occur if any scalar operand type has greater rank 8107 /// than the type of the vector element. 8108 /// 8109 /// \param scalar - if non-null, actually perform the conversions 8110 /// \return true if the operation fails (but without diagnosing the failure) 8111 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8112 QualType scalarTy, 8113 QualType vectorEltTy, 8114 QualType vectorTy, 8115 unsigned &DiagID) { 8116 // The conversion to apply to the scalar before splatting it, 8117 // if necessary. 8118 CastKind scalarCast = CK_NoOp; 8119 8120 if (vectorEltTy->isIntegralType(S.Context)) { 8121 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8122 (scalarTy->isIntegerType() && 8123 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8124 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8125 return true; 8126 } 8127 if (!scalarTy->isIntegralType(S.Context)) 8128 return true; 8129 scalarCast = CK_IntegralCast; 8130 } else if (vectorEltTy->isRealFloatingType()) { 8131 if (scalarTy->isRealFloatingType()) { 8132 if (S.getLangOpts().OpenCL && 8133 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8134 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8135 return true; 8136 } 8137 scalarCast = CK_FloatingCast; 8138 } 8139 else if (scalarTy->isIntegralType(S.Context)) 8140 scalarCast = CK_IntegralToFloating; 8141 else 8142 return true; 8143 } else { 8144 return true; 8145 } 8146 8147 // Adjust scalar if desired. 8148 if (scalar) { 8149 if (scalarCast != CK_NoOp) 8150 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8151 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8152 } 8153 return false; 8154 } 8155 8156 /// Convert vector E to a vector with the same number of elements but different 8157 /// element type. 8158 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8159 const auto *VecTy = E->getType()->getAs<VectorType>(); 8160 assert(VecTy && "Expression E must be a vector"); 8161 QualType NewVecTy = S.Context.getVectorType(ElementType, 8162 VecTy->getNumElements(), 8163 VecTy->getVectorKind()); 8164 8165 // Look through the implicit cast. Return the subexpression if its type is 8166 // NewVecTy. 8167 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8168 if (ICE->getSubExpr()->getType() == NewVecTy) 8169 return ICE->getSubExpr(); 8170 8171 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8172 return S.ImpCastExprToType(E, NewVecTy, Cast); 8173 } 8174 8175 /// Test if a (constant) integer Int can be casted to another integer type 8176 /// IntTy without losing precision. 8177 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8178 QualType OtherIntTy) { 8179 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8180 8181 // Reject cases where the value of the Int is unknown as that would 8182 // possibly cause truncation, but accept cases where the scalar can be 8183 // demoted without loss of precision. 8184 llvm::APSInt Result; 8185 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8186 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8187 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8188 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8189 8190 if (CstInt) { 8191 // If the scalar is constant and is of a higher order and has more active 8192 // bits that the vector element type, reject it. 8193 unsigned NumBits = IntSigned 8194 ? (Result.isNegative() ? Result.getMinSignedBits() 8195 : Result.getActiveBits()) 8196 : Result.getActiveBits(); 8197 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8198 return true; 8199 8200 // If the signedness of the scalar type and the vector element type 8201 // differs and the number of bits is greater than that of the vector 8202 // element reject it. 8203 return (IntSigned != OtherIntSigned && 8204 NumBits > S.Context.getIntWidth(OtherIntTy)); 8205 } 8206 8207 // Reject cases where the value of the scalar is not constant and it's 8208 // order is greater than that of the vector element type. 8209 return (Order < 0); 8210 } 8211 8212 /// Test if a (constant) integer Int can be casted to floating point type 8213 /// FloatTy without losing precision. 8214 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8215 QualType FloatTy) { 8216 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8217 8218 // Determine if the integer constant can be expressed as a floating point 8219 // number of the appropiate type. 8220 llvm::APSInt Result; 8221 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8222 uint64_t Bits = 0; 8223 if (CstInt) { 8224 // Reject constants that would be truncated if they were converted to 8225 // the floating point type. Test by simple to/from conversion. 8226 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8227 // could be avoided if there was a convertFromAPInt method 8228 // which could signal back if implicit truncation occurred. 8229 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8230 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8231 llvm::APFloat::rmTowardZero); 8232 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8233 !IntTy->hasSignedIntegerRepresentation()); 8234 bool Ignored = false; 8235 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8236 &Ignored); 8237 if (Result != ConvertBack) 8238 return true; 8239 } else { 8240 // Reject types that cannot be fully encoded into the mantissa of 8241 // the float. 8242 Bits = S.Context.getTypeSize(IntTy); 8243 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8244 S.Context.getFloatTypeSemantics(FloatTy)); 8245 if (Bits > FloatPrec) 8246 return true; 8247 } 8248 8249 return false; 8250 } 8251 8252 /// Attempt to convert and splat Scalar into a vector whose types matches 8253 /// Vector following GCC conversion rules. The rule is that implicit 8254 /// conversion can occur when Scalar can be casted to match Vector's element 8255 /// type without causing truncation of Scalar. 8256 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8257 ExprResult *Vector) { 8258 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8259 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8260 const VectorType *VT = VectorTy->getAs<VectorType>(); 8261 8262 assert(!isa<ExtVectorType>(VT) && 8263 "ExtVectorTypes should not be handled here!"); 8264 8265 QualType VectorEltTy = VT->getElementType(); 8266 8267 // Reject cases where the vector element type or the scalar element type are 8268 // not integral or floating point types. 8269 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8270 return true; 8271 8272 // The conversion to apply to the scalar before splatting it, 8273 // if necessary. 8274 CastKind ScalarCast = CK_NoOp; 8275 8276 // Accept cases where the vector elements are integers and the scalar is 8277 // an integer. 8278 // FIXME: Notionally if the scalar was a floating point value with a precise 8279 // integral representation, we could cast it to an appropriate integer 8280 // type and then perform the rest of the checks here. GCC will perform 8281 // this conversion in some cases as determined by the input language. 8282 // We should accept it on a language independent basis. 8283 if (VectorEltTy->isIntegralType(S.Context) && 8284 ScalarTy->isIntegralType(S.Context) && 8285 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8286 8287 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8288 return true; 8289 8290 ScalarCast = CK_IntegralCast; 8291 } else if (VectorEltTy->isRealFloatingType()) { 8292 if (ScalarTy->isRealFloatingType()) { 8293 8294 // Reject cases where the scalar type is not a constant and has a higher 8295 // Order than the vector element type. 8296 llvm::APFloat Result(0.0); 8297 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8298 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8299 if (!CstScalar && Order < 0) 8300 return true; 8301 8302 // If the scalar cannot be safely casted to the vector element type, 8303 // reject it. 8304 if (CstScalar) { 8305 bool Truncated = false; 8306 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8307 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8308 if (Truncated) 8309 return true; 8310 } 8311 8312 ScalarCast = CK_FloatingCast; 8313 } else if (ScalarTy->isIntegralType(S.Context)) { 8314 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8315 return true; 8316 8317 ScalarCast = CK_IntegralToFloating; 8318 } else 8319 return true; 8320 } 8321 8322 // Adjust scalar if desired. 8323 if (Scalar) { 8324 if (ScalarCast != CK_NoOp) 8325 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8326 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8327 } 8328 return false; 8329 } 8330 8331 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8332 SourceLocation Loc, bool IsCompAssign, 8333 bool AllowBothBool, 8334 bool AllowBoolConversions) { 8335 if (!IsCompAssign) { 8336 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8337 if (LHS.isInvalid()) 8338 return QualType(); 8339 } 8340 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8341 if (RHS.isInvalid()) 8342 return QualType(); 8343 8344 // For conversion purposes, we ignore any qualifiers. 8345 // For example, "const float" and "float" are equivalent. 8346 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8347 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8348 8349 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8350 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8351 assert(LHSVecType || RHSVecType); 8352 8353 // AltiVec-style "vector bool op vector bool" combinations are allowed 8354 // for some operators but not others. 8355 if (!AllowBothBool && 8356 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8357 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8358 return InvalidOperands(Loc, LHS, RHS); 8359 8360 // If the vector types are identical, return. 8361 if (Context.hasSameType(LHSType, RHSType)) 8362 return LHSType; 8363 8364 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8365 if (LHSVecType && RHSVecType && 8366 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8367 if (isa<ExtVectorType>(LHSVecType)) { 8368 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8369 return LHSType; 8370 } 8371 8372 if (!IsCompAssign) 8373 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8374 return RHSType; 8375 } 8376 8377 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8378 // can be mixed, with the result being the non-bool type. The non-bool 8379 // operand must have integer element type. 8380 if (AllowBoolConversions && LHSVecType && RHSVecType && 8381 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8382 (Context.getTypeSize(LHSVecType->getElementType()) == 8383 Context.getTypeSize(RHSVecType->getElementType()))) { 8384 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8385 LHSVecType->getElementType()->isIntegerType() && 8386 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8387 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8388 return LHSType; 8389 } 8390 if (!IsCompAssign && 8391 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8392 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8393 RHSVecType->getElementType()->isIntegerType()) { 8394 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8395 return RHSType; 8396 } 8397 } 8398 8399 // If there's a vector type and a scalar, try to convert the scalar to 8400 // the vector element type and splat. 8401 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8402 if (!RHSVecType) { 8403 if (isa<ExtVectorType>(LHSVecType)) { 8404 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8405 LHSVecType->getElementType(), LHSType, 8406 DiagID)) 8407 return LHSType; 8408 } else { 8409 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8410 return LHSType; 8411 } 8412 } 8413 if (!LHSVecType) { 8414 if (isa<ExtVectorType>(RHSVecType)) { 8415 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8416 LHSType, RHSVecType->getElementType(), 8417 RHSType, DiagID)) 8418 return RHSType; 8419 } else { 8420 if (LHS.get()->getValueKind() == VK_LValue || 8421 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8422 return RHSType; 8423 } 8424 } 8425 8426 // FIXME: The code below also handles conversion between vectors and 8427 // non-scalars, we should break this down into fine grained specific checks 8428 // and emit proper diagnostics. 8429 QualType VecType = LHSVecType ? LHSType : RHSType; 8430 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8431 QualType OtherType = LHSVecType ? RHSType : LHSType; 8432 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8433 if (isLaxVectorConversion(OtherType, VecType)) { 8434 // If we're allowing lax vector conversions, only the total (data) size 8435 // needs to be the same. For non compound assignment, if one of the types is 8436 // scalar, the result is always the vector type. 8437 if (!IsCompAssign) { 8438 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8439 return VecType; 8440 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8441 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8442 // type. Note that this is already done by non-compound assignments in 8443 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8444 // <1 x T> -> T. The result is also a vector type. 8445 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8446 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8447 ExprResult *RHSExpr = &RHS; 8448 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8449 return VecType; 8450 } 8451 } 8452 8453 // Okay, the expression is invalid. 8454 8455 // If there's a non-vector, non-real operand, diagnose that. 8456 if ((!RHSVecType && !RHSType->isRealType()) || 8457 (!LHSVecType && !LHSType->isRealType())) { 8458 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8459 << LHSType << RHSType 8460 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8461 return QualType(); 8462 } 8463 8464 // OpenCL V1.1 6.2.6.p1: 8465 // If the operands are of more than one vector type, then an error shall 8466 // occur. Implicit conversions between vector types are not permitted, per 8467 // section 6.2.1. 8468 if (getLangOpts().OpenCL && 8469 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8470 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8471 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8472 << RHSType; 8473 return QualType(); 8474 } 8475 8476 8477 // If there is a vector type that is not a ExtVector and a scalar, we reach 8478 // this point if scalar could not be converted to the vector's element type 8479 // without truncation. 8480 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8481 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8482 QualType Scalar = LHSVecType ? RHSType : LHSType; 8483 QualType Vector = LHSVecType ? LHSType : RHSType; 8484 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8485 Diag(Loc, 8486 diag::err_typecheck_vector_not_convertable_implict_truncation) 8487 << ScalarOrVector << Scalar << Vector; 8488 8489 return QualType(); 8490 } 8491 8492 // Otherwise, use the generic diagnostic. 8493 Diag(Loc, DiagID) 8494 << LHSType << RHSType 8495 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8496 return QualType(); 8497 } 8498 8499 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8500 // expression. These are mainly cases where the null pointer is used as an 8501 // integer instead of a pointer. 8502 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8503 SourceLocation Loc, bool IsCompare) { 8504 // The canonical way to check for a GNU null is with isNullPointerConstant, 8505 // but we use a bit of a hack here for speed; this is a relatively 8506 // hot path, and isNullPointerConstant is slow. 8507 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8508 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8509 8510 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8511 8512 // Avoid analyzing cases where the result will either be invalid (and 8513 // diagnosed as such) or entirely valid and not something to warn about. 8514 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8515 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8516 return; 8517 8518 // Comparison operations would not make sense with a null pointer no matter 8519 // what the other expression is. 8520 if (!IsCompare) { 8521 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8522 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8523 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8524 return; 8525 } 8526 8527 // The rest of the operations only make sense with a null pointer 8528 // if the other expression is a pointer. 8529 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8530 NonNullType->canDecayToPointerType()) 8531 return; 8532 8533 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8534 << LHSNull /* LHS is NULL */ << NonNullType 8535 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8536 } 8537 8538 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8539 ExprResult &RHS, 8540 SourceLocation Loc, bool IsDiv) { 8541 // Check for division/remainder by zero. 8542 llvm::APSInt RHSValue; 8543 if (!RHS.get()->isValueDependent() && 8544 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8545 S.DiagRuntimeBehavior(Loc, RHS.get(), 8546 S.PDiag(diag::warn_remainder_division_by_zero) 8547 << IsDiv << RHS.get()->getSourceRange()); 8548 } 8549 8550 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8551 SourceLocation Loc, 8552 bool IsCompAssign, bool IsDiv) { 8553 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8554 8555 if (LHS.get()->getType()->isVectorType() || 8556 RHS.get()->getType()->isVectorType()) 8557 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8558 /*AllowBothBool*/getLangOpts().AltiVec, 8559 /*AllowBoolConversions*/false); 8560 8561 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8562 if (LHS.isInvalid() || RHS.isInvalid()) 8563 return QualType(); 8564 8565 8566 if (compType.isNull() || !compType->isArithmeticType()) 8567 return InvalidOperands(Loc, LHS, RHS); 8568 if (IsDiv) 8569 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8570 return compType; 8571 } 8572 8573 QualType Sema::CheckRemainderOperands( 8574 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8575 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8576 8577 if (LHS.get()->getType()->isVectorType() || 8578 RHS.get()->getType()->isVectorType()) { 8579 if (LHS.get()->getType()->hasIntegerRepresentation() && 8580 RHS.get()->getType()->hasIntegerRepresentation()) 8581 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8582 /*AllowBothBool*/getLangOpts().AltiVec, 8583 /*AllowBoolConversions*/false); 8584 return InvalidOperands(Loc, LHS, RHS); 8585 } 8586 8587 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8588 if (LHS.isInvalid() || RHS.isInvalid()) 8589 return QualType(); 8590 8591 if (compType.isNull() || !compType->isIntegerType()) 8592 return InvalidOperands(Loc, LHS, RHS); 8593 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8594 return compType; 8595 } 8596 8597 /// \brief Diagnose invalid arithmetic on two void pointers. 8598 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8599 Expr *LHSExpr, Expr *RHSExpr) { 8600 S.Diag(Loc, S.getLangOpts().CPlusPlus 8601 ? diag::err_typecheck_pointer_arith_void_type 8602 : diag::ext_gnu_void_ptr) 8603 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8604 << RHSExpr->getSourceRange(); 8605 } 8606 8607 /// \brief Diagnose invalid arithmetic on a void pointer. 8608 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8609 Expr *Pointer) { 8610 S.Diag(Loc, S.getLangOpts().CPlusPlus 8611 ? diag::err_typecheck_pointer_arith_void_type 8612 : diag::ext_gnu_void_ptr) 8613 << 0 /* one pointer */ << Pointer->getSourceRange(); 8614 } 8615 8616 /// \brief Diagnose invalid arithmetic on a null pointer. 8617 /// 8618 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8619 /// idiom, which we recognize as a GNU extension. 8620 /// 8621 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8622 Expr *Pointer, bool IsGNUIdiom) { 8623 if (IsGNUIdiom) 8624 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8625 << Pointer->getSourceRange(); 8626 else 8627 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8628 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8629 } 8630 8631 /// \brief Diagnose invalid arithmetic on two function pointers. 8632 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8633 Expr *LHS, Expr *RHS) { 8634 assert(LHS->getType()->isAnyPointerType()); 8635 assert(RHS->getType()->isAnyPointerType()); 8636 S.Diag(Loc, S.getLangOpts().CPlusPlus 8637 ? diag::err_typecheck_pointer_arith_function_type 8638 : diag::ext_gnu_ptr_func_arith) 8639 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8640 // We only show the second type if it differs from the first. 8641 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8642 RHS->getType()) 8643 << RHS->getType()->getPointeeType() 8644 << LHS->getSourceRange() << RHS->getSourceRange(); 8645 } 8646 8647 /// \brief Diagnose invalid arithmetic on a function pointer. 8648 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8649 Expr *Pointer) { 8650 assert(Pointer->getType()->isAnyPointerType()); 8651 S.Diag(Loc, S.getLangOpts().CPlusPlus 8652 ? diag::err_typecheck_pointer_arith_function_type 8653 : diag::ext_gnu_ptr_func_arith) 8654 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8655 << 0 /* one pointer, so only one type */ 8656 << Pointer->getSourceRange(); 8657 } 8658 8659 /// \brief Emit error if Operand is incomplete pointer type 8660 /// 8661 /// \returns True if pointer has incomplete type 8662 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8663 Expr *Operand) { 8664 QualType ResType = Operand->getType(); 8665 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8666 ResType = ResAtomicType->getValueType(); 8667 8668 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8669 QualType PointeeTy = ResType->getPointeeType(); 8670 return S.RequireCompleteType(Loc, PointeeTy, 8671 diag::err_typecheck_arithmetic_incomplete_type, 8672 PointeeTy, Operand->getSourceRange()); 8673 } 8674 8675 /// \brief Check the validity of an arithmetic pointer operand. 8676 /// 8677 /// If the operand has pointer type, this code will check for pointer types 8678 /// which are invalid in arithmetic operations. These will be diagnosed 8679 /// appropriately, including whether or not the use is supported as an 8680 /// extension. 8681 /// 8682 /// \returns True when the operand is valid to use (even if as an extension). 8683 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8684 Expr *Operand) { 8685 QualType ResType = Operand->getType(); 8686 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8687 ResType = ResAtomicType->getValueType(); 8688 8689 if (!ResType->isAnyPointerType()) return true; 8690 8691 QualType PointeeTy = ResType->getPointeeType(); 8692 if (PointeeTy->isVoidType()) { 8693 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8694 return !S.getLangOpts().CPlusPlus; 8695 } 8696 if (PointeeTy->isFunctionType()) { 8697 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8698 return !S.getLangOpts().CPlusPlus; 8699 } 8700 8701 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8702 8703 return true; 8704 } 8705 8706 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8707 /// operands. 8708 /// 8709 /// This routine will diagnose any invalid arithmetic on pointer operands much 8710 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8711 /// for emitting a single diagnostic even for operations where both LHS and RHS 8712 /// are (potentially problematic) pointers. 8713 /// 8714 /// \returns True when the operand is valid to use (even if as an extension). 8715 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8716 Expr *LHSExpr, Expr *RHSExpr) { 8717 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8718 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8719 if (!isLHSPointer && !isRHSPointer) return true; 8720 8721 QualType LHSPointeeTy, RHSPointeeTy; 8722 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8723 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8724 8725 // if both are pointers check if operation is valid wrt address spaces 8726 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8727 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8728 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8729 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8730 S.Diag(Loc, 8731 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8732 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8733 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8734 return false; 8735 } 8736 } 8737 8738 // Check for arithmetic on pointers to incomplete types. 8739 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8740 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8741 if (isLHSVoidPtr || isRHSVoidPtr) { 8742 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8743 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8744 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8745 8746 return !S.getLangOpts().CPlusPlus; 8747 } 8748 8749 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8750 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8751 if (isLHSFuncPtr || isRHSFuncPtr) { 8752 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8753 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8754 RHSExpr); 8755 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8756 8757 return !S.getLangOpts().CPlusPlus; 8758 } 8759 8760 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8761 return false; 8762 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8763 return false; 8764 8765 return true; 8766 } 8767 8768 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8769 /// literal. 8770 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8771 Expr *LHSExpr, Expr *RHSExpr) { 8772 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8773 Expr* IndexExpr = RHSExpr; 8774 if (!StrExpr) { 8775 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8776 IndexExpr = LHSExpr; 8777 } 8778 8779 bool IsStringPlusInt = StrExpr && 8780 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8781 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8782 return; 8783 8784 llvm::APSInt index; 8785 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8786 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8787 if (index.isNonNegative() && 8788 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8789 index.isUnsigned())) 8790 return; 8791 } 8792 8793 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8794 Self.Diag(OpLoc, diag::warn_string_plus_int) 8795 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8796 8797 // Only print a fixit for "str" + int, not for int + "str". 8798 if (IndexExpr == RHSExpr) { 8799 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8800 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8801 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8802 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8803 << FixItHint::CreateInsertion(EndLoc, "]"); 8804 } else 8805 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8806 } 8807 8808 /// \brief Emit a warning when adding a char literal to a string. 8809 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8810 Expr *LHSExpr, Expr *RHSExpr) { 8811 const Expr *StringRefExpr = LHSExpr; 8812 const CharacterLiteral *CharExpr = 8813 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8814 8815 if (!CharExpr) { 8816 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8817 StringRefExpr = RHSExpr; 8818 } 8819 8820 if (!CharExpr || !StringRefExpr) 8821 return; 8822 8823 const QualType StringType = StringRefExpr->getType(); 8824 8825 // Return if not a PointerType. 8826 if (!StringType->isAnyPointerType()) 8827 return; 8828 8829 // Return if not a CharacterType. 8830 if (!StringType->getPointeeType()->isAnyCharacterType()) 8831 return; 8832 8833 ASTContext &Ctx = Self.getASTContext(); 8834 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8835 8836 const QualType CharType = CharExpr->getType(); 8837 if (!CharType->isAnyCharacterType() && 8838 CharType->isIntegerType() && 8839 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8840 Self.Diag(OpLoc, diag::warn_string_plus_char) 8841 << DiagRange << Ctx.CharTy; 8842 } else { 8843 Self.Diag(OpLoc, diag::warn_string_plus_char) 8844 << DiagRange << CharExpr->getType(); 8845 } 8846 8847 // Only print a fixit for str + char, not for char + str. 8848 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8849 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8850 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8851 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8852 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8853 << FixItHint::CreateInsertion(EndLoc, "]"); 8854 } else { 8855 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8856 } 8857 } 8858 8859 /// \brief Emit error when two pointers are incompatible. 8860 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8861 Expr *LHSExpr, Expr *RHSExpr) { 8862 assert(LHSExpr->getType()->isAnyPointerType()); 8863 assert(RHSExpr->getType()->isAnyPointerType()); 8864 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8865 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8866 << RHSExpr->getSourceRange(); 8867 } 8868 8869 // C99 6.5.6 8870 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8871 SourceLocation Loc, BinaryOperatorKind Opc, 8872 QualType* CompLHSTy) { 8873 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8874 8875 if (LHS.get()->getType()->isVectorType() || 8876 RHS.get()->getType()->isVectorType()) { 8877 QualType compType = CheckVectorOperands( 8878 LHS, RHS, Loc, CompLHSTy, 8879 /*AllowBothBool*/getLangOpts().AltiVec, 8880 /*AllowBoolConversions*/getLangOpts().ZVector); 8881 if (CompLHSTy) *CompLHSTy = compType; 8882 return compType; 8883 } 8884 8885 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8886 if (LHS.isInvalid() || RHS.isInvalid()) 8887 return QualType(); 8888 8889 // Diagnose "string literal" '+' int and string '+' "char literal". 8890 if (Opc == BO_Add) { 8891 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8892 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8893 } 8894 8895 // handle the common case first (both operands are arithmetic). 8896 if (!compType.isNull() && compType->isArithmeticType()) { 8897 if (CompLHSTy) *CompLHSTy = compType; 8898 return compType; 8899 } 8900 8901 // Type-checking. Ultimately the pointer's going to be in PExp; 8902 // note that we bias towards the LHS being the pointer. 8903 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8904 8905 bool isObjCPointer; 8906 if (PExp->getType()->isPointerType()) { 8907 isObjCPointer = false; 8908 } else if (PExp->getType()->isObjCObjectPointerType()) { 8909 isObjCPointer = true; 8910 } else { 8911 std::swap(PExp, IExp); 8912 if (PExp->getType()->isPointerType()) { 8913 isObjCPointer = false; 8914 } else if (PExp->getType()->isObjCObjectPointerType()) { 8915 isObjCPointer = true; 8916 } else { 8917 return InvalidOperands(Loc, LHS, RHS); 8918 } 8919 } 8920 assert(PExp->getType()->isAnyPointerType()); 8921 8922 if (!IExp->getType()->isIntegerType()) 8923 return InvalidOperands(Loc, LHS, RHS); 8924 8925 // Adding to a null pointer results in undefined behavior. 8926 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8927 Context, Expr::NPC_ValueDependentIsNotNull)) { 8928 // In C++ adding zero to a null pointer is defined. 8929 llvm::APSInt KnownVal; 8930 if (!getLangOpts().CPlusPlus || 8931 (!IExp->isValueDependent() && 8932 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8933 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8934 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8935 Context, BO_Add, PExp, IExp); 8936 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8937 } 8938 } 8939 8940 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8941 return QualType(); 8942 8943 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8944 return QualType(); 8945 8946 // Check array bounds for pointer arithemtic 8947 CheckArrayAccess(PExp, IExp); 8948 8949 if (CompLHSTy) { 8950 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8951 if (LHSTy.isNull()) { 8952 LHSTy = LHS.get()->getType(); 8953 if (LHSTy->isPromotableIntegerType()) 8954 LHSTy = Context.getPromotedIntegerType(LHSTy); 8955 } 8956 *CompLHSTy = LHSTy; 8957 } 8958 8959 return PExp->getType(); 8960 } 8961 8962 // C99 6.5.6 8963 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8964 SourceLocation Loc, 8965 QualType* CompLHSTy) { 8966 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8967 8968 if (LHS.get()->getType()->isVectorType() || 8969 RHS.get()->getType()->isVectorType()) { 8970 QualType compType = CheckVectorOperands( 8971 LHS, RHS, Loc, CompLHSTy, 8972 /*AllowBothBool*/getLangOpts().AltiVec, 8973 /*AllowBoolConversions*/getLangOpts().ZVector); 8974 if (CompLHSTy) *CompLHSTy = compType; 8975 return compType; 8976 } 8977 8978 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8979 if (LHS.isInvalid() || RHS.isInvalid()) 8980 return QualType(); 8981 8982 // Enforce type constraints: C99 6.5.6p3. 8983 8984 // Handle the common case first (both operands are arithmetic). 8985 if (!compType.isNull() && compType->isArithmeticType()) { 8986 if (CompLHSTy) *CompLHSTy = compType; 8987 return compType; 8988 } 8989 8990 // Either ptr - int or ptr - ptr. 8991 if (LHS.get()->getType()->isAnyPointerType()) { 8992 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8993 8994 // Diagnose bad cases where we step over interface counts. 8995 if (LHS.get()->getType()->isObjCObjectPointerType() && 8996 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8997 return QualType(); 8998 8999 // The result type of a pointer-int computation is the pointer type. 9000 if (RHS.get()->getType()->isIntegerType()) { 9001 // Subtracting from a null pointer should produce a warning. 9002 // The last argument to the diagnose call says this doesn't match the 9003 // GNU int-to-pointer idiom. 9004 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9005 Expr::NPC_ValueDependentIsNotNull)) { 9006 // In C++ adding zero to a null pointer is defined. 9007 llvm::APSInt KnownVal; 9008 if (!getLangOpts().CPlusPlus || 9009 (!RHS.get()->isValueDependent() && 9010 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9011 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9012 } 9013 } 9014 9015 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9016 return QualType(); 9017 9018 // Check array bounds for pointer arithemtic 9019 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9020 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9021 9022 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9023 return LHS.get()->getType(); 9024 } 9025 9026 // Handle pointer-pointer subtractions. 9027 if (const PointerType *RHSPTy 9028 = RHS.get()->getType()->getAs<PointerType>()) { 9029 QualType rpointee = RHSPTy->getPointeeType(); 9030 9031 if (getLangOpts().CPlusPlus) { 9032 // Pointee types must be the same: C++ [expr.add] 9033 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9034 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9035 } 9036 } else { 9037 // Pointee types must be compatible C99 6.5.6p3 9038 if (!Context.typesAreCompatible( 9039 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9040 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9041 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9042 return QualType(); 9043 } 9044 } 9045 9046 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9047 LHS.get(), RHS.get())) 9048 return QualType(); 9049 9050 // FIXME: Add warnings for nullptr - ptr. 9051 9052 // The pointee type may have zero size. As an extension, a structure or 9053 // union may have zero size or an array may have zero length. In this 9054 // case subtraction does not make sense. 9055 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9056 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9057 if (ElementSize.isZero()) { 9058 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9059 << rpointee.getUnqualifiedType() 9060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9061 } 9062 } 9063 9064 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9065 return Context.getPointerDiffType(); 9066 } 9067 } 9068 9069 return InvalidOperands(Loc, LHS, RHS); 9070 } 9071 9072 static bool isScopedEnumerationType(QualType T) { 9073 if (const EnumType *ET = T->getAs<EnumType>()) 9074 return ET->getDecl()->isScoped(); 9075 return false; 9076 } 9077 9078 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9079 SourceLocation Loc, BinaryOperatorKind Opc, 9080 QualType LHSType) { 9081 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9082 // so skip remaining warnings as we don't want to modify values within Sema. 9083 if (S.getLangOpts().OpenCL) 9084 return; 9085 9086 llvm::APSInt Right; 9087 // Check right/shifter operand 9088 if (RHS.get()->isValueDependent() || 9089 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9090 return; 9091 9092 if (Right.isNegative()) { 9093 S.DiagRuntimeBehavior(Loc, RHS.get(), 9094 S.PDiag(diag::warn_shift_negative) 9095 << RHS.get()->getSourceRange()); 9096 return; 9097 } 9098 llvm::APInt LeftBits(Right.getBitWidth(), 9099 S.Context.getTypeSize(LHS.get()->getType())); 9100 if (Right.uge(LeftBits)) { 9101 S.DiagRuntimeBehavior(Loc, RHS.get(), 9102 S.PDiag(diag::warn_shift_gt_typewidth) 9103 << RHS.get()->getSourceRange()); 9104 return; 9105 } 9106 if (Opc != BO_Shl) 9107 return; 9108 9109 // When left shifting an ICE which is signed, we can check for overflow which 9110 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9111 // integers have defined behavior modulo one more than the maximum value 9112 // representable in the result type, so never warn for those. 9113 llvm::APSInt Left; 9114 if (LHS.get()->isValueDependent() || 9115 LHSType->hasUnsignedIntegerRepresentation() || 9116 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9117 return; 9118 9119 // If LHS does not have a signed type and non-negative value 9120 // then, the behavior is undefined. Warn about it. 9121 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9122 S.DiagRuntimeBehavior(Loc, LHS.get(), 9123 S.PDiag(diag::warn_shift_lhs_negative) 9124 << LHS.get()->getSourceRange()); 9125 return; 9126 } 9127 9128 llvm::APInt ResultBits = 9129 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9130 if (LeftBits.uge(ResultBits)) 9131 return; 9132 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9133 Result = Result.shl(Right); 9134 9135 // Print the bit representation of the signed integer as an unsigned 9136 // hexadecimal number. 9137 SmallString<40> HexResult; 9138 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9139 9140 // If we are only missing a sign bit, this is less likely to result in actual 9141 // bugs -- if the result is cast back to an unsigned type, it will have the 9142 // expected value. Thus we place this behind a different warning that can be 9143 // turned off separately if needed. 9144 if (LeftBits == ResultBits - 1) { 9145 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9146 << HexResult << LHSType 9147 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9148 return; 9149 } 9150 9151 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9152 << HexResult.str() << Result.getMinSignedBits() << LHSType 9153 << Left.getBitWidth() << LHS.get()->getSourceRange() 9154 << RHS.get()->getSourceRange(); 9155 } 9156 9157 /// \brief Return the resulting type when a vector is shifted 9158 /// by a scalar or vector shift amount. 9159 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9160 SourceLocation Loc, bool IsCompAssign) { 9161 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9162 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9163 !LHS.get()->getType()->isVectorType()) { 9164 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9165 << RHS.get()->getType() << LHS.get()->getType() 9166 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9167 return QualType(); 9168 } 9169 9170 if (!IsCompAssign) { 9171 LHS = S.UsualUnaryConversions(LHS.get()); 9172 if (LHS.isInvalid()) return QualType(); 9173 } 9174 9175 RHS = S.UsualUnaryConversions(RHS.get()); 9176 if (RHS.isInvalid()) return QualType(); 9177 9178 QualType LHSType = LHS.get()->getType(); 9179 // Note that LHS might be a scalar because the routine calls not only in 9180 // OpenCL case. 9181 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9182 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9183 9184 // Note that RHS might not be a vector. 9185 QualType RHSType = RHS.get()->getType(); 9186 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9187 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9188 9189 // The operands need to be integers. 9190 if (!LHSEleType->isIntegerType()) { 9191 S.Diag(Loc, diag::err_typecheck_expect_int) 9192 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9193 return QualType(); 9194 } 9195 9196 if (!RHSEleType->isIntegerType()) { 9197 S.Diag(Loc, diag::err_typecheck_expect_int) 9198 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9199 return QualType(); 9200 } 9201 9202 if (!LHSVecTy) { 9203 assert(RHSVecTy); 9204 if (IsCompAssign) 9205 return RHSType; 9206 if (LHSEleType != RHSEleType) { 9207 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9208 LHSEleType = RHSEleType; 9209 } 9210 QualType VecTy = 9211 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9212 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9213 LHSType = VecTy; 9214 } else if (RHSVecTy) { 9215 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9216 // are applied component-wise. So if RHS is a vector, then ensure 9217 // that the number of elements is the same as LHS... 9218 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9219 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9220 << LHS.get()->getType() << RHS.get()->getType() 9221 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9222 return QualType(); 9223 } 9224 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9225 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9226 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9227 if (LHSBT != RHSBT && 9228 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9229 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9230 << LHS.get()->getType() << RHS.get()->getType() 9231 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9232 } 9233 } 9234 } else { 9235 // ...else expand RHS to match the number of elements in LHS. 9236 QualType VecTy = 9237 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9238 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9239 } 9240 9241 return LHSType; 9242 } 9243 9244 // C99 6.5.7 9245 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9246 SourceLocation Loc, BinaryOperatorKind Opc, 9247 bool IsCompAssign) { 9248 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9249 9250 // Vector shifts promote their scalar inputs to vector type. 9251 if (LHS.get()->getType()->isVectorType() || 9252 RHS.get()->getType()->isVectorType()) { 9253 if (LangOpts.ZVector) { 9254 // The shift operators for the z vector extensions work basically 9255 // like general shifts, except that neither the LHS nor the RHS is 9256 // allowed to be a "vector bool". 9257 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9258 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9259 return InvalidOperands(Loc, LHS, RHS); 9260 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9261 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9262 return InvalidOperands(Loc, LHS, RHS); 9263 } 9264 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9265 } 9266 9267 // Shifts don't perform usual arithmetic conversions, they just do integer 9268 // promotions on each operand. C99 6.5.7p3 9269 9270 // For the LHS, do usual unary conversions, but then reset them away 9271 // if this is a compound assignment. 9272 ExprResult OldLHS = LHS; 9273 LHS = UsualUnaryConversions(LHS.get()); 9274 if (LHS.isInvalid()) 9275 return QualType(); 9276 QualType LHSType = LHS.get()->getType(); 9277 if (IsCompAssign) LHS = OldLHS; 9278 9279 // The RHS is simpler. 9280 RHS = UsualUnaryConversions(RHS.get()); 9281 if (RHS.isInvalid()) 9282 return QualType(); 9283 QualType RHSType = RHS.get()->getType(); 9284 9285 // C99 6.5.7p2: Each of the operands shall have integer type. 9286 if (!LHSType->hasIntegerRepresentation() || 9287 !RHSType->hasIntegerRepresentation()) 9288 return InvalidOperands(Loc, LHS, RHS); 9289 9290 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9291 // hasIntegerRepresentation() above instead of this. 9292 if (isScopedEnumerationType(LHSType) || 9293 isScopedEnumerationType(RHSType)) { 9294 return InvalidOperands(Loc, LHS, RHS); 9295 } 9296 // Sanity-check shift operands 9297 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9298 9299 // "The type of the result is that of the promoted left operand." 9300 return LHSType; 9301 } 9302 9303 static bool IsWithinTemplateSpecialization(Decl *D) { 9304 if (DeclContext *DC = D->getDeclContext()) { 9305 if (isa<ClassTemplateSpecializationDecl>(DC)) 9306 return true; 9307 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9308 return FD->isFunctionTemplateSpecialization(); 9309 } 9310 return false; 9311 } 9312 9313 /// If two different enums are compared, raise a warning. 9314 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9315 Expr *RHS) { 9316 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9317 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9318 9319 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9320 if (!LHSEnumType) 9321 return; 9322 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9323 if (!RHSEnumType) 9324 return; 9325 9326 // Ignore anonymous enums. 9327 if (!LHSEnumType->getDecl()->getIdentifier() && 9328 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9329 return; 9330 if (!RHSEnumType->getDecl()->getIdentifier() && 9331 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9332 return; 9333 9334 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9335 return; 9336 9337 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9338 << LHSStrippedType << RHSStrippedType 9339 << LHS->getSourceRange() << RHS->getSourceRange(); 9340 } 9341 9342 /// \brief Diagnose bad pointer comparisons. 9343 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9344 ExprResult &LHS, ExprResult &RHS, 9345 bool IsError) { 9346 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9347 : diag::ext_typecheck_comparison_of_distinct_pointers) 9348 << LHS.get()->getType() << RHS.get()->getType() 9349 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9350 } 9351 9352 /// \brief Returns false if the pointers are converted to a composite type, 9353 /// true otherwise. 9354 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9355 ExprResult &LHS, ExprResult &RHS) { 9356 // C++ [expr.rel]p2: 9357 // [...] Pointer conversions (4.10) and qualification 9358 // conversions (4.4) are performed on pointer operands (or on 9359 // a pointer operand and a null pointer constant) to bring 9360 // them to their composite pointer type. [...] 9361 // 9362 // C++ [expr.eq]p1 uses the same notion for (in)equality 9363 // comparisons of pointers. 9364 9365 QualType LHSType = LHS.get()->getType(); 9366 QualType RHSType = RHS.get()->getType(); 9367 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9368 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9369 9370 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9371 if (T.isNull()) { 9372 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9373 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9374 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9375 else 9376 S.InvalidOperands(Loc, LHS, RHS); 9377 return true; 9378 } 9379 9380 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9381 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9382 return false; 9383 } 9384 9385 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9386 ExprResult &LHS, 9387 ExprResult &RHS, 9388 bool IsError) { 9389 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9390 : diag::ext_typecheck_comparison_of_fptr_to_void) 9391 << LHS.get()->getType() << RHS.get()->getType() 9392 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9393 } 9394 9395 static bool isObjCObjectLiteral(ExprResult &E) { 9396 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9397 case Stmt::ObjCArrayLiteralClass: 9398 case Stmt::ObjCDictionaryLiteralClass: 9399 case Stmt::ObjCStringLiteralClass: 9400 case Stmt::ObjCBoxedExprClass: 9401 return true; 9402 default: 9403 // Note that ObjCBoolLiteral is NOT an object literal! 9404 return false; 9405 } 9406 } 9407 9408 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9409 const ObjCObjectPointerType *Type = 9410 LHS->getType()->getAs<ObjCObjectPointerType>(); 9411 9412 // If this is not actually an Objective-C object, bail out. 9413 if (!Type) 9414 return false; 9415 9416 // Get the LHS object's interface type. 9417 QualType InterfaceType = Type->getPointeeType(); 9418 9419 // If the RHS isn't an Objective-C object, bail out. 9420 if (!RHS->getType()->isObjCObjectPointerType()) 9421 return false; 9422 9423 // Try to find the -isEqual: method. 9424 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9425 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9426 InterfaceType, 9427 /*instance=*/true); 9428 if (!Method) { 9429 if (Type->isObjCIdType()) { 9430 // For 'id', just check the global pool. 9431 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9432 /*receiverId=*/true); 9433 } else { 9434 // Check protocols. 9435 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9436 /*instance=*/true); 9437 } 9438 } 9439 9440 if (!Method) 9441 return false; 9442 9443 QualType T = Method->parameters()[0]->getType(); 9444 if (!T->isObjCObjectPointerType()) 9445 return false; 9446 9447 QualType R = Method->getReturnType(); 9448 if (!R->isScalarType()) 9449 return false; 9450 9451 return true; 9452 } 9453 9454 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9455 FromE = FromE->IgnoreParenImpCasts(); 9456 switch (FromE->getStmtClass()) { 9457 default: 9458 break; 9459 case Stmt::ObjCStringLiteralClass: 9460 // "string literal" 9461 return LK_String; 9462 case Stmt::ObjCArrayLiteralClass: 9463 // "array literal" 9464 return LK_Array; 9465 case Stmt::ObjCDictionaryLiteralClass: 9466 // "dictionary literal" 9467 return LK_Dictionary; 9468 case Stmt::BlockExprClass: 9469 return LK_Block; 9470 case Stmt::ObjCBoxedExprClass: { 9471 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9472 switch (Inner->getStmtClass()) { 9473 case Stmt::IntegerLiteralClass: 9474 case Stmt::FloatingLiteralClass: 9475 case Stmt::CharacterLiteralClass: 9476 case Stmt::ObjCBoolLiteralExprClass: 9477 case Stmt::CXXBoolLiteralExprClass: 9478 // "numeric literal" 9479 return LK_Numeric; 9480 case Stmt::ImplicitCastExprClass: { 9481 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9482 // Boolean literals can be represented by implicit casts. 9483 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9484 return LK_Numeric; 9485 break; 9486 } 9487 default: 9488 break; 9489 } 9490 return LK_Boxed; 9491 } 9492 } 9493 return LK_None; 9494 } 9495 9496 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9497 ExprResult &LHS, ExprResult &RHS, 9498 BinaryOperator::Opcode Opc){ 9499 Expr *Literal; 9500 Expr *Other; 9501 if (isObjCObjectLiteral(LHS)) { 9502 Literal = LHS.get(); 9503 Other = RHS.get(); 9504 } else { 9505 Literal = RHS.get(); 9506 Other = LHS.get(); 9507 } 9508 9509 // Don't warn on comparisons against nil. 9510 Other = Other->IgnoreParenCasts(); 9511 if (Other->isNullPointerConstant(S.getASTContext(), 9512 Expr::NPC_ValueDependentIsNotNull)) 9513 return; 9514 9515 // This should be kept in sync with warn_objc_literal_comparison. 9516 // LK_String should always be after the other literals, since it has its own 9517 // warning flag. 9518 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9519 assert(LiteralKind != Sema::LK_Block); 9520 if (LiteralKind == Sema::LK_None) { 9521 llvm_unreachable("Unknown Objective-C object literal kind"); 9522 } 9523 9524 if (LiteralKind == Sema::LK_String) 9525 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9526 << Literal->getSourceRange(); 9527 else 9528 S.Diag(Loc, diag::warn_objc_literal_comparison) 9529 << LiteralKind << Literal->getSourceRange(); 9530 9531 if (BinaryOperator::isEqualityOp(Opc) && 9532 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9533 SourceLocation Start = LHS.get()->getLocStart(); 9534 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9535 CharSourceRange OpRange = 9536 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9537 9538 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9539 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9540 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9541 << FixItHint::CreateInsertion(End, "]"); 9542 } 9543 } 9544 9545 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9546 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9547 ExprResult &RHS, SourceLocation Loc, 9548 BinaryOperatorKind Opc) { 9549 // Check that left hand side is !something. 9550 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9551 if (!UO || UO->getOpcode() != UO_LNot) return; 9552 9553 // Only check if the right hand side is non-bool arithmetic type. 9554 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9555 9556 // Make sure that the something in !something is not bool. 9557 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9558 if (SubExpr->isKnownToHaveBooleanValue()) return; 9559 9560 // Emit warning. 9561 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9562 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9563 << Loc << IsBitwiseOp; 9564 9565 // First note suggest !(x < y) 9566 SourceLocation FirstOpen = SubExpr->getLocStart(); 9567 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9568 FirstClose = S.getLocForEndOfToken(FirstClose); 9569 if (FirstClose.isInvalid()) 9570 FirstOpen = SourceLocation(); 9571 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9572 << IsBitwiseOp 9573 << FixItHint::CreateInsertion(FirstOpen, "(") 9574 << FixItHint::CreateInsertion(FirstClose, ")"); 9575 9576 // Second note suggests (!x) < y 9577 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9578 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9579 SecondClose = S.getLocForEndOfToken(SecondClose); 9580 if (SecondClose.isInvalid()) 9581 SecondOpen = SourceLocation(); 9582 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9583 << FixItHint::CreateInsertion(SecondOpen, "(") 9584 << FixItHint::CreateInsertion(SecondClose, ")"); 9585 } 9586 9587 // Get the decl for a simple expression: a reference to a variable, 9588 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9589 static ValueDecl *getCompareDecl(Expr *E) { 9590 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9591 return DR->getDecl(); 9592 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9593 if (Ivar->isFreeIvar()) 9594 return Ivar->getDecl(); 9595 } 9596 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9597 if (Mem->isImplicitAccess()) 9598 return Mem->getMemberDecl(); 9599 } 9600 return nullptr; 9601 } 9602 9603 // C99 6.5.8, C++ [expr.rel] 9604 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9605 SourceLocation Loc, BinaryOperatorKind Opc, 9606 bool IsRelational) { 9607 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9608 9609 // Handle vector comparisons separately. 9610 if (LHS.get()->getType()->isVectorType() || 9611 RHS.get()->getType()->isVectorType()) 9612 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9613 9614 QualType LHSType = LHS.get()->getType(); 9615 QualType RHSType = RHS.get()->getType(); 9616 9617 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9618 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9619 9620 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9621 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9622 9623 if (!LHSType->hasFloatingRepresentation() && 9624 !(LHSType->isBlockPointerType() && IsRelational) && 9625 !LHS.get()->getLocStart().isMacroID() && 9626 !RHS.get()->getLocStart().isMacroID() && 9627 !inTemplateInstantiation()) { 9628 // For non-floating point types, check for self-comparisons of the form 9629 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9630 // often indicate logic errors in the program. 9631 // 9632 // NOTE: Don't warn about comparison expressions resulting from macro 9633 // expansion. Also don't warn about comparisons which are only self 9634 // comparisons within a template specialization. The warnings should catch 9635 // obvious cases in the definition of the template anyways. The idea is to 9636 // warn when the typed comparison operator will always evaluate to the same 9637 // result. 9638 ValueDecl *DL = getCompareDecl(LHSStripped); 9639 ValueDecl *DR = getCompareDecl(RHSStripped); 9640 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9641 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9642 << 0 // self- 9643 << (Opc == BO_EQ 9644 || Opc == BO_LE 9645 || Opc == BO_GE)); 9646 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9647 !DL->getType()->isReferenceType() && 9648 !DR->getType()->isReferenceType()) { 9649 // what is it always going to eval to? 9650 char always_evals_to; 9651 switch(Opc) { 9652 case BO_EQ: // e.g. array1 == array2 9653 always_evals_to = 0; // false 9654 break; 9655 case BO_NE: // e.g. array1 != array2 9656 always_evals_to = 1; // true 9657 break; 9658 default: 9659 // best we can say is 'a constant' 9660 always_evals_to = 2; // e.g. array1 <= array2 9661 break; 9662 } 9663 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9664 << 1 // array 9665 << always_evals_to); 9666 } 9667 9668 if (isa<CastExpr>(LHSStripped)) 9669 LHSStripped = LHSStripped->IgnoreParenCasts(); 9670 if (isa<CastExpr>(RHSStripped)) 9671 RHSStripped = RHSStripped->IgnoreParenCasts(); 9672 9673 // Warn about comparisons against a string constant (unless the other 9674 // operand is null), the user probably wants strcmp. 9675 Expr *literalString = nullptr; 9676 Expr *literalStringStripped = nullptr; 9677 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9678 !RHSStripped->isNullPointerConstant(Context, 9679 Expr::NPC_ValueDependentIsNull)) { 9680 literalString = LHS.get(); 9681 literalStringStripped = LHSStripped; 9682 } else if ((isa<StringLiteral>(RHSStripped) || 9683 isa<ObjCEncodeExpr>(RHSStripped)) && 9684 !LHSStripped->isNullPointerConstant(Context, 9685 Expr::NPC_ValueDependentIsNull)) { 9686 literalString = RHS.get(); 9687 literalStringStripped = RHSStripped; 9688 } 9689 9690 if (literalString) { 9691 DiagRuntimeBehavior(Loc, nullptr, 9692 PDiag(diag::warn_stringcompare) 9693 << isa<ObjCEncodeExpr>(literalStringStripped) 9694 << literalString->getSourceRange()); 9695 } 9696 } 9697 9698 // C99 6.5.8p3 / C99 6.5.9p4 9699 UsualArithmeticConversions(LHS, RHS); 9700 if (LHS.isInvalid() || RHS.isInvalid()) 9701 return QualType(); 9702 9703 LHSType = LHS.get()->getType(); 9704 RHSType = RHS.get()->getType(); 9705 9706 // The result of comparisons is 'bool' in C++, 'int' in C. 9707 QualType ResultTy = Context.getLogicalOperationType(); 9708 9709 if (IsRelational) { 9710 if (LHSType->isRealType() && RHSType->isRealType()) 9711 return ResultTy; 9712 } else { 9713 // Check for comparisons of floating point operands using != and ==. 9714 if (LHSType->hasFloatingRepresentation()) 9715 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9716 9717 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9718 return ResultTy; 9719 } 9720 9721 const Expr::NullPointerConstantKind LHSNullKind = 9722 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9723 const Expr::NullPointerConstantKind RHSNullKind = 9724 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9725 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9726 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9727 9728 if (!IsRelational && LHSIsNull != RHSIsNull) { 9729 bool IsEquality = Opc == BO_EQ; 9730 if (RHSIsNull) 9731 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9732 RHS.get()->getSourceRange()); 9733 else 9734 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9735 LHS.get()->getSourceRange()); 9736 } 9737 9738 if ((LHSType->isIntegerType() && !LHSIsNull) || 9739 (RHSType->isIntegerType() && !RHSIsNull)) { 9740 // Skip normal pointer conversion checks in this case; we have better 9741 // diagnostics for this below. 9742 } else if (getLangOpts().CPlusPlus) { 9743 // Equality comparison of a function pointer to a void pointer is invalid, 9744 // but we allow it as an extension. 9745 // FIXME: If we really want to allow this, should it be part of composite 9746 // pointer type computation so it works in conditionals too? 9747 if (!IsRelational && 9748 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9749 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9750 // This is a gcc extension compatibility comparison. 9751 // In a SFINAE context, we treat this as a hard error to maintain 9752 // conformance with the C++ standard. 9753 diagnoseFunctionPointerToVoidComparison( 9754 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9755 9756 if (isSFINAEContext()) 9757 return QualType(); 9758 9759 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9760 return ResultTy; 9761 } 9762 9763 // C++ [expr.eq]p2: 9764 // If at least one operand is a pointer [...] bring them to their 9765 // composite pointer type. 9766 // C++ [expr.rel]p2: 9767 // If both operands are pointers, [...] bring them to their composite 9768 // pointer type. 9769 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9770 (IsRelational ? 2 : 1) && 9771 (!LangOpts.ObjCAutoRefCount || 9772 !(LHSType->isObjCObjectPointerType() || 9773 RHSType->isObjCObjectPointerType()))) { 9774 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9775 return QualType(); 9776 else 9777 return ResultTy; 9778 } 9779 } else if (LHSType->isPointerType() && 9780 RHSType->isPointerType()) { // C99 6.5.8p2 9781 // All of the following pointer-related warnings are GCC extensions, except 9782 // when handling null pointer constants. 9783 QualType LCanPointeeTy = 9784 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9785 QualType RCanPointeeTy = 9786 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9787 9788 // C99 6.5.9p2 and C99 6.5.8p2 9789 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9790 RCanPointeeTy.getUnqualifiedType())) { 9791 // Valid unless a relational comparison of function pointers 9792 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9793 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9794 << LHSType << RHSType << LHS.get()->getSourceRange() 9795 << RHS.get()->getSourceRange(); 9796 } 9797 } else if (!IsRelational && 9798 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9799 // Valid unless comparison between non-null pointer and function pointer 9800 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9801 && !LHSIsNull && !RHSIsNull) 9802 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9803 /*isError*/false); 9804 } else { 9805 // Invalid 9806 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9807 } 9808 if (LCanPointeeTy != RCanPointeeTy) { 9809 // Treat NULL constant as a special case in OpenCL. 9810 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9811 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9812 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9813 Diag(Loc, 9814 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9815 << LHSType << RHSType << 0 /* comparison */ 9816 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9817 } 9818 } 9819 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9820 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9821 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9822 : CK_BitCast; 9823 if (LHSIsNull && !RHSIsNull) 9824 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9825 else 9826 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9827 } 9828 return ResultTy; 9829 } 9830 9831 if (getLangOpts().CPlusPlus) { 9832 // C++ [expr.eq]p4: 9833 // Two operands of type std::nullptr_t or one operand of type 9834 // std::nullptr_t and the other a null pointer constant compare equal. 9835 if (!IsRelational && LHSIsNull && RHSIsNull) { 9836 if (LHSType->isNullPtrType()) { 9837 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9838 return ResultTy; 9839 } 9840 if (RHSType->isNullPtrType()) { 9841 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9842 return ResultTy; 9843 } 9844 } 9845 9846 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9847 // These aren't covered by the composite pointer type rules. 9848 if (!IsRelational && RHSType->isNullPtrType() && 9849 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9850 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9851 return ResultTy; 9852 } 9853 if (!IsRelational && LHSType->isNullPtrType() && 9854 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9855 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9856 return ResultTy; 9857 } 9858 9859 if (IsRelational && 9860 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9861 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9862 // HACK: Relational comparison of nullptr_t against a pointer type is 9863 // invalid per DR583, but we allow it within std::less<> and friends, 9864 // since otherwise common uses of it break. 9865 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9866 // friends to have std::nullptr_t overload candidates. 9867 DeclContext *DC = CurContext; 9868 if (isa<FunctionDecl>(DC)) 9869 DC = DC->getParent(); 9870 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9871 if (CTSD->isInStdNamespace() && 9872 llvm::StringSwitch<bool>(CTSD->getName()) 9873 .Cases("less", "less_equal", "greater", "greater_equal", true) 9874 .Default(false)) { 9875 if (RHSType->isNullPtrType()) 9876 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9877 else 9878 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9879 return ResultTy; 9880 } 9881 } 9882 } 9883 9884 // C++ [expr.eq]p2: 9885 // If at least one operand is a pointer to member, [...] bring them to 9886 // their composite pointer type. 9887 if (!IsRelational && 9888 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9889 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9890 return QualType(); 9891 else 9892 return ResultTy; 9893 } 9894 9895 // Handle scoped enumeration types specifically, since they don't promote 9896 // to integers. 9897 if (LHS.get()->getType()->isEnumeralType() && 9898 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9899 RHS.get()->getType())) 9900 return ResultTy; 9901 } 9902 9903 // Handle block pointer types. 9904 if (!IsRelational && LHSType->isBlockPointerType() && 9905 RHSType->isBlockPointerType()) { 9906 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9907 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9908 9909 if (!LHSIsNull && !RHSIsNull && 9910 !Context.typesAreCompatible(lpointee, rpointee)) { 9911 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9912 << LHSType << RHSType << LHS.get()->getSourceRange() 9913 << RHS.get()->getSourceRange(); 9914 } 9915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9916 return ResultTy; 9917 } 9918 9919 // Allow block pointers to be compared with null pointer constants. 9920 if (!IsRelational 9921 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9922 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9923 if (!LHSIsNull && !RHSIsNull) { 9924 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9925 ->getPointeeType()->isVoidType()) 9926 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9927 ->getPointeeType()->isVoidType()))) 9928 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9929 << LHSType << RHSType << LHS.get()->getSourceRange() 9930 << RHS.get()->getSourceRange(); 9931 } 9932 if (LHSIsNull && !RHSIsNull) 9933 LHS = ImpCastExprToType(LHS.get(), RHSType, 9934 RHSType->isPointerType() ? CK_BitCast 9935 : CK_AnyPointerToBlockPointerCast); 9936 else 9937 RHS = ImpCastExprToType(RHS.get(), LHSType, 9938 LHSType->isPointerType() ? CK_BitCast 9939 : CK_AnyPointerToBlockPointerCast); 9940 return ResultTy; 9941 } 9942 9943 if (LHSType->isObjCObjectPointerType() || 9944 RHSType->isObjCObjectPointerType()) { 9945 const PointerType *LPT = LHSType->getAs<PointerType>(); 9946 const PointerType *RPT = RHSType->getAs<PointerType>(); 9947 if (LPT || RPT) { 9948 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9949 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9950 9951 if (!LPtrToVoid && !RPtrToVoid && 9952 !Context.typesAreCompatible(LHSType, RHSType)) { 9953 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9954 /*isError*/false); 9955 } 9956 if (LHSIsNull && !RHSIsNull) { 9957 Expr *E = LHS.get(); 9958 if (getLangOpts().ObjCAutoRefCount) 9959 CheckObjCConversion(SourceRange(), RHSType, E, 9960 CCK_ImplicitConversion); 9961 LHS = ImpCastExprToType(E, RHSType, 9962 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9963 } 9964 else { 9965 Expr *E = RHS.get(); 9966 if (getLangOpts().ObjCAutoRefCount) 9967 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9968 /*Diagnose=*/true, 9969 /*DiagnoseCFAudited=*/false, Opc); 9970 RHS = ImpCastExprToType(E, LHSType, 9971 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9972 } 9973 return ResultTy; 9974 } 9975 if (LHSType->isObjCObjectPointerType() && 9976 RHSType->isObjCObjectPointerType()) { 9977 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9978 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9979 /*isError*/false); 9980 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9981 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9982 9983 if (LHSIsNull && !RHSIsNull) 9984 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9985 else 9986 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9987 return ResultTy; 9988 } 9989 } 9990 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9991 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9992 unsigned DiagID = 0; 9993 bool isError = false; 9994 if (LangOpts.DebuggerSupport) { 9995 // Under a debugger, allow the comparison of pointers to integers, 9996 // since users tend to want to compare addresses. 9997 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9998 (RHSIsNull && RHSType->isIntegerType())) { 9999 if (IsRelational) { 10000 isError = getLangOpts().CPlusPlus; 10001 DiagID = 10002 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10003 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10004 } 10005 } else if (getLangOpts().CPlusPlus) { 10006 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10007 isError = true; 10008 } else if (IsRelational) 10009 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10010 else 10011 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10012 10013 if (DiagID) { 10014 Diag(Loc, DiagID) 10015 << LHSType << RHSType << LHS.get()->getSourceRange() 10016 << RHS.get()->getSourceRange(); 10017 if (isError) 10018 return QualType(); 10019 } 10020 10021 if (LHSType->isIntegerType()) 10022 LHS = ImpCastExprToType(LHS.get(), RHSType, 10023 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10024 else 10025 RHS = ImpCastExprToType(RHS.get(), LHSType, 10026 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10027 return ResultTy; 10028 } 10029 10030 // Handle block pointers. 10031 if (!IsRelational && RHSIsNull 10032 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10033 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10034 return ResultTy; 10035 } 10036 if (!IsRelational && LHSIsNull 10037 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10038 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10039 return ResultTy; 10040 } 10041 10042 if (getLangOpts().OpenCLVersion >= 200) { 10043 if (LHSIsNull && RHSType->isQueueT()) { 10044 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10045 return ResultTy; 10046 } 10047 10048 if (LHSType->isQueueT() && RHSIsNull) { 10049 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10050 return ResultTy; 10051 } 10052 } 10053 10054 return InvalidOperands(Loc, LHS, RHS); 10055 } 10056 10057 // Return a signed ext_vector_type that is of identical size and number of 10058 // elements. For floating point vectors, return an integer type of identical 10059 // size and number of elements. In the non ext_vector_type case, search from 10060 // the largest type to the smallest type to avoid cases where long long == long, 10061 // where long gets picked over long long. 10062 QualType Sema::GetSignedVectorType(QualType V) { 10063 const VectorType *VTy = V->getAs<VectorType>(); 10064 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10065 10066 if (isa<ExtVectorType>(VTy)) { 10067 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10068 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10069 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10070 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10071 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10072 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10073 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10074 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10075 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10076 "Unhandled vector element size in vector compare"); 10077 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10078 } 10079 10080 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10081 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10082 VectorType::GenericVector); 10083 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10084 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10085 VectorType::GenericVector); 10086 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10087 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10088 VectorType::GenericVector); 10089 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10090 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10091 VectorType::GenericVector); 10092 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10093 "Unhandled vector element size in vector compare"); 10094 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10095 VectorType::GenericVector); 10096 } 10097 10098 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10099 /// operates on extended vector types. Instead of producing an IntTy result, 10100 /// like a scalar comparison, a vector comparison produces a vector of integer 10101 /// types. 10102 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10103 SourceLocation Loc, 10104 bool IsRelational) { 10105 // Check to make sure we're operating on vectors of the same type and width, 10106 // Allowing one side to be a scalar of element type. 10107 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10108 /*AllowBothBool*/true, 10109 /*AllowBoolConversions*/getLangOpts().ZVector); 10110 if (vType.isNull()) 10111 return vType; 10112 10113 QualType LHSType = LHS.get()->getType(); 10114 10115 // If AltiVec, the comparison results in a numeric type, i.e. 10116 // bool for C++, int for C 10117 if (getLangOpts().AltiVec && 10118 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10119 return Context.getLogicalOperationType(); 10120 10121 // For non-floating point types, check for self-comparisons of the form 10122 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10123 // often indicate logic errors in the program. 10124 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10125 if (DeclRefExpr* DRL 10126 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10127 if (DeclRefExpr* DRR 10128 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10129 if (DRL->getDecl() == DRR->getDecl()) 10130 DiagRuntimeBehavior(Loc, nullptr, 10131 PDiag(diag::warn_comparison_always) 10132 << 0 // self- 10133 << 2 // "a constant" 10134 ); 10135 } 10136 10137 // Check for comparisons of floating point operands using != and ==. 10138 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10139 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10140 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10141 } 10142 10143 // Return a signed type for the vector. 10144 return GetSignedVectorType(vType); 10145 } 10146 10147 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10148 SourceLocation Loc) { 10149 // Ensure that either both operands are of the same vector type, or 10150 // one operand is of a vector type and the other is of its element type. 10151 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10152 /*AllowBothBool*/true, 10153 /*AllowBoolConversions*/false); 10154 if (vType.isNull()) 10155 return InvalidOperands(Loc, LHS, RHS); 10156 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10157 vType->hasFloatingRepresentation()) 10158 return InvalidOperands(Loc, LHS, RHS); 10159 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10160 // usage of the logical operators && and || with vectors in C. This 10161 // check could be notionally dropped. 10162 if (!getLangOpts().CPlusPlus && 10163 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10164 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10165 10166 return GetSignedVectorType(LHS.get()->getType()); 10167 } 10168 10169 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10170 SourceLocation Loc, 10171 BinaryOperatorKind Opc) { 10172 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10173 10174 bool IsCompAssign = 10175 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10176 10177 if (LHS.get()->getType()->isVectorType() || 10178 RHS.get()->getType()->isVectorType()) { 10179 if (LHS.get()->getType()->hasIntegerRepresentation() && 10180 RHS.get()->getType()->hasIntegerRepresentation()) 10181 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10182 /*AllowBothBool*/true, 10183 /*AllowBoolConversions*/getLangOpts().ZVector); 10184 return InvalidOperands(Loc, LHS, RHS); 10185 } 10186 10187 if (Opc == BO_And) 10188 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10189 10190 ExprResult LHSResult = LHS, RHSResult = RHS; 10191 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10192 IsCompAssign); 10193 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10194 return QualType(); 10195 LHS = LHSResult.get(); 10196 RHS = RHSResult.get(); 10197 10198 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10199 return compType; 10200 return InvalidOperands(Loc, LHS, RHS); 10201 } 10202 10203 // C99 6.5.[13,14] 10204 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10205 SourceLocation Loc, 10206 BinaryOperatorKind Opc) { 10207 // Check vector operands differently. 10208 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10209 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10210 10211 // Diagnose cases where the user write a logical and/or but probably meant a 10212 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10213 // is a constant. 10214 if (LHS.get()->getType()->isIntegerType() && 10215 !LHS.get()->getType()->isBooleanType() && 10216 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10217 // Don't warn in macros or template instantiations. 10218 !Loc.isMacroID() && !inTemplateInstantiation()) { 10219 // If the RHS can be constant folded, and if it constant folds to something 10220 // that isn't 0 or 1 (which indicate a potential logical operation that 10221 // happened to fold to true/false) then warn. 10222 // Parens on the RHS are ignored. 10223 llvm::APSInt Result; 10224 if (RHS.get()->EvaluateAsInt(Result, Context)) 10225 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10226 !RHS.get()->getExprLoc().isMacroID()) || 10227 (Result != 0 && Result != 1)) { 10228 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10229 << RHS.get()->getSourceRange() 10230 << (Opc == BO_LAnd ? "&&" : "||"); 10231 // Suggest replacing the logical operator with the bitwise version 10232 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10233 << (Opc == BO_LAnd ? "&" : "|") 10234 << FixItHint::CreateReplacement(SourceRange( 10235 Loc, getLocForEndOfToken(Loc)), 10236 Opc == BO_LAnd ? "&" : "|"); 10237 if (Opc == BO_LAnd) 10238 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10239 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10240 << FixItHint::CreateRemoval( 10241 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10242 RHS.get()->getLocEnd())); 10243 } 10244 } 10245 10246 if (!Context.getLangOpts().CPlusPlus) { 10247 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10248 // not operate on the built-in scalar and vector float types. 10249 if (Context.getLangOpts().OpenCL && 10250 Context.getLangOpts().OpenCLVersion < 120) { 10251 if (LHS.get()->getType()->isFloatingType() || 10252 RHS.get()->getType()->isFloatingType()) 10253 return InvalidOperands(Loc, LHS, RHS); 10254 } 10255 10256 LHS = UsualUnaryConversions(LHS.get()); 10257 if (LHS.isInvalid()) 10258 return QualType(); 10259 10260 RHS = UsualUnaryConversions(RHS.get()); 10261 if (RHS.isInvalid()) 10262 return QualType(); 10263 10264 if (!LHS.get()->getType()->isScalarType() || 10265 !RHS.get()->getType()->isScalarType()) 10266 return InvalidOperands(Loc, LHS, RHS); 10267 10268 return Context.IntTy; 10269 } 10270 10271 // The following is safe because we only use this method for 10272 // non-overloadable operands. 10273 10274 // C++ [expr.log.and]p1 10275 // C++ [expr.log.or]p1 10276 // The operands are both contextually converted to type bool. 10277 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10278 if (LHSRes.isInvalid()) 10279 return InvalidOperands(Loc, LHS, RHS); 10280 LHS = LHSRes; 10281 10282 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10283 if (RHSRes.isInvalid()) 10284 return InvalidOperands(Loc, LHS, RHS); 10285 RHS = RHSRes; 10286 10287 // C++ [expr.log.and]p2 10288 // C++ [expr.log.or]p2 10289 // The result is a bool. 10290 return Context.BoolTy; 10291 } 10292 10293 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10294 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10295 if (!ME) return false; 10296 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10297 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10298 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10299 if (!Base) return false; 10300 return Base->getMethodDecl() != nullptr; 10301 } 10302 10303 /// Is the given expression (which must be 'const') a reference to a 10304 /// variable which was originally non-const, but which has become 10305 /// 'const' due to being captured within a block? 10306 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10307 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10308 assert(E->isLValue() && E->getType().isConstQualified()); 10309 E = E->IgnoreParens(); 10310 10311 // Must be a reference to a declaration from an enclosing scope. 10312 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10313 if (!DRE) return NCCK_None; 10314 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10315 10316 // The declaration must be a variable which is not declared 'const'. 10317 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10318 if (!var) return NCCK_None; 10319 if (var->getType().isConstQualified()) return NCCK_None; 10320 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10321 10322 // Decide whether the first capture was for a block or a lambda. 10323 DeclContext *DC = S.CurContext, *Prev = nullptr; 10324 // Decide whether the first capture was for a block or a lambda. 10325 while (DC) { 10326 // For init-capture, it is possible that the variable belongs to the 10327 // template pattern of the current context. 10328 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10329 if (var->isInitCapture() && 10330 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10331 break; 10332 if (DC == var->getDeclContext()) 10333 break; 10334 Prev = DC; 10335 DC = DC->getParent(); 10336 } 10337 // Unless we have an init-capture, we've gone one step too far. 10338 if (!var->isInitCapture()) 10339 DC = Prev; 10340 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10341 } 10342 10343 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10344 Ty = Ty.getNonReferenceType(); 10345 if (IsDereference && Ty->isPointerType()) 10346 Ty = Ty->getPointeeType(); 10347 return !Ty.isConstQualified(); 10348 } 10349 10350 // Update err_typecheck_assign_const and note_typecheck_assign_const 10351 // when this enum is changed. 10352 enum { 10353 ConstFunction, 10354 ConstVariable, 10355 ConstMember, 10356 ConstMethod, 10357 NestedConstMember, 10358 ConstUnknown, // Keep as last element 10359 }; 10360 10361 /// Emit the "read-only variable not assignable" error and print notes to give 10362 /// more information about why the variable is not assignable, such as pointing 10363 /// to the declaration of a const variable, showing that a method is const, or 10364 /// that the function is returning a const reference. 10365 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10366 SourceLocation Loc) { 10367 SourceRange ExprRange = E->getSourceRange(); 10368 10369 // Only emit one error on the first const found. All other consts will emit 10370 // a note to the error. 10371 bool DiagnosticEmitted = false; 10372 10373 // Track if the current expression is the result of a dereference, and if the 10374 // next checked expression is the result of a dereference. 10375 bool IsDereference = false; 10376 bool NextIsDereference = false; 10377 10378 // Loop to process MemberExpr chains. 10379 while (true) { 10380 IsDereference = NextIsDereference; 10381 10382 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10383 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10384 NextIsDereference = ME->isArrow(); 10385 const ValueDecl *VD = ME->getMemberDecl(); 10386 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10387 // Mutable fields can be modified even if the class is const. 10388 if (Field->isMutable()) { 10389 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10390 break; 10391 } 10392 10393 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10394 if (!DiagnosticEmitted) { 10395 S.Diag(Loc, diag::err_typecheck_assign_const) 10396 << ExprRange << ConstMember << false /*static*/ << Field 10397 << Field->getType(); 10398 DiagnosticEmitted = true; 10399 } 10400 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10401 << ConstMember << false /*static*/ << Field << Field->getType() 10402 << Field->getSourceRange(); 10403 } 10404 E = ME->getBase(); 10405 continue; 10406 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10407 if (VDecl->getType().isConstQualified()) { 10408 if (!DiagnosticEmitted) { 10409 S.Diag(Loc, diag::err_typecheck_assign_const) 10410 << ExprRange << ConstMember << true /*static*/ << VDecl 10411 << VDecl->getType(); 10412 DiagnosticEmitted = true; 10413 } 10414 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10415 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10416 << VDecl->getSourceRange(); 10417 } 10418 // Static fields do not inherit constness from parents. 10419 break; 10420 } 10421 break; 10422 } // End MemberExpr 10423 break; 10424 } 10425 10426 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10427 // Function calls 10428 const FunctionDecl *FD = CE->getDirectCallee(); 10429 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10430 if (!DiagnosticEmitted) { 10431 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10432 << ConstFunction << FD; 10433 DiagnosticEmitted = true; 10434 } 10435 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10436 diag::note_typecheck_assign_const) 10437 << ConstFunction << FD << FD->getReturnType() 10438 << FD->getReturnTypeSourceRange(); 10439 } 10440 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10441 // Point to variable declaration. 10442 if (const ValueDecl *VD = DRE->getDecl()) { 10443 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10444 if (!DiagnosticEmitted) { 10445 S.Diag(Loc, diag::err_typecheck_assign_const) 10446 << ExprRange << ConstVariable << VD << VD->getType(); 10447 DiagnosticEmitted = true; 10448 } 10449 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10450 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10451 } 10452 } 10453 } else if (isa<CXXThisExpr>(E)) { 10454 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10456 if (MD->isConst()) { 10457 if (!DiagnosticEmitted) { 10458 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10459 << ConstMethod << MD; 10460 DiagnosticEmitted = true; 10461 } 10462 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10463 << ConstMethod << MD << MD->getSourceRange(); 10464 } 10465 } 10466 } 10467 } 10468 10469 if (DiagnosticEmitted) 10470 return; 10471 10472 // Can't determine a more specific message, so display the generic error. 10473 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10474 } 10475 10476 enum OriginalExprKind { 10477 OEK_Variable, 10478 OEK_Member, 10479 OEK_LValue 10480 }; 10481 10482 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10483 const RecordType *Ty, 10484 SourceLocation Loc, SourceRange Range, 10485 OriginalExprKind OEK, 10486 bool &DiagnosticEmitted, 10487 bool IsNested = false) { 10488 // We walk the record hierarchy breadth-first to ensure that we print 10489 // diagnostics in field nesting order. 10490 // First, check every field for constness. 10491 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10492 if (Field->getType().isConstQualified()) { 10493 if (!DiagnosticEmitted) { 10494 S.Diag(Loc, diag::err_typecheck_assign_const) 10495 << Range << NestedConstMember << OEK << VD 10496 << IsNested << Field; 10497 DiagnosticEmitted = true; 10498 } 10499 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10500 << NestedConstMember << IsNested << Field 10501 << Field->getType() << Field->getSourceRange(); 10502 } 10503 } 10504 // Then, recurse. 10505 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10506 QualType FTy = Field->getType(); 10507 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10508 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10509 OEK, DiagnosticEmitted, true); 10510 } 10511 } 10512 10513 /// Emit an error for the case where a record we are trying to assign to has a 10514 /// const-qualified field somewhere in its hierarchy. 10515 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10516 SourceLocation Loc) { 10517 QualType Ty = E->getType(); 10518 assert(Ty->isRecordType() && "lvalue was not record?"); 10519 SourceRange Range = E->getSourceRange(); 10520 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10521 bool DiagEmitted = false; 10522 10523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10524 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10525 Range, OEK_Member, DiagEmitted); 10526 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10527 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10528 Range, OEK_Variable, DiagEmitted); 10529 else 10530 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10531 Range, OEK_LValue, DiagEmitted); 10532 if (!DiagEmitted) 10533 DiagnoseConstAssignment(S, E, Loc); 10534 } 10535 10536 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10537 /// emit an error and return true. If so, return false. 10538 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10539 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10540 10541 S.CheckShadowingDeclModification(E, Loc); 10542 10543 SourceLocation OrigLoc = Loc; 10544 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10545 &Loc); 10546 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10547 IsLV = Expr::MLV_InvalidMessageExpression; 10548 if (IsLV == Expr::MLV_Valid) 10549 return false; 10550 10551 unsigned DiagID = 0; 10552 bool NeedType = false; 10553 switch (IsLV) { // C99 6.5.16p2 10554 case Expr::MLV_ConstQualified: 10555 // Use a specialized diagnostic when we're assigning to an object 10556 // from an enclosing function or block. 10557 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10558 if (NCCK == NCCK_Block) 10559 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10560 else 10561 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10562 break; 10563 } 10564 10565 // In ARC, use some specialized diagnostics for occasions where we 10566 // infer 'const'. These are always pseudo-strong variables. 10567 if (S.getLangOpts().ObjCAutoRefCount) { 10568 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10569 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10570 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10571 10572 // Use the normal diagnostic if it's pseudo-__strong but the 10573 // user actually wrote 'const'. 10574 if (var->isARCPseudoStrong() && 10575 (!var->getTypeSourceInfo() || 10576 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10577 // There are two pseudo-strong cases: 10578 // - self 10579 ObjCMethodDecl *method = S.getCurMethodDecl(); 10580 if (method && var == method->getSelfDecl()) 10581 DiagID = method->isClassMethod() 10582 ? diag::err_typecheck_arc_assign_self_class_method 10583 : diag::err_typecheck_arc_assign_self; 10584 10585 // - fast enumeration variables 10586 else 10587 DiagID = diag::err_typecheck_arr_assign_enumeration; 10588 10589 SourceRange Assign; 10590 if (Loc != OrigLoc) 10591 Assign = SourceRange(OrigLoc, OrigLoc); 10592 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10593 // We need to preserve the AST regardless, so migration tool 10594 // can do its job. 10595 return false; 10596 } 10597 } 10598 } 10599 10600 // If none of the special cases above are triggered, then this is a 10601 // simple const assignment. 10602 if (DiagID == 0) { 10603 DiagnoseConstAssignment(S, E, Loc); 10604 return true; 10605 } 10606 10607 break; 10608 case Expr::MLV_ConstAddrSpace: 10609 DiagnoseConstAssignment(S, E, Loc); 10610 return true; 10611 case Expr::MLV_ConstQualifiedField: 10612 DiagnoseRecursiveConstFields(S, E, Loc); 10613 return true; 10614 case Expr::MLV_ArrayType: 10615 case Expr::MLV_ArrayTemporary: 10616 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10617 NeedType = true; 10618 break; 10619 case Expr::MLV_NotObjectType: 10620 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10621 NeedType = true; 10622 break; 10623 case Expr::MLV_LValueCast: 10624 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10625 break; 10626 case Expr::MLV_Valid: 10627 llvm_unreachable("did not take early return for MLV_Valid"); 10628 case Expr::MLV_InvalidExpression: 10629 case Expr::MLV_MemberFunction: 10630 case Expr::MLV_ClassTemporary: 10631 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10632 break; 10633 case Expr::MLV_IncompleteType: 10634 case Expr::MLV_IncompleteVoidType: 10635 return S.RequireCompleteType(Loc, E->getType(), 10636 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10637 case Expr::MLV_DuplicateVectorComponents: 10638 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10639 break; 10640 case Expr::MLV_NoSetterProperty: 10641 llvm_unreachable("readonly properties should be processed differently"); 10642 case Expr::MLV_InvalidMessageExpression: 10643 DiagID = diag::err_readonly_message_assignment; 10644 break; 10645 case Expr::MLV_SubObjCPropertySetting: 10646 DiagID = diag::err_no_subobject_property_setting; 10647 break; 10648 } 10649 10650 SourceRange Assign; 10651 if (Loc != OrigLoc) 10652 Assign = SourceRange(OrigLoc, OrigLoc); 10653 if (NeedType) 10654 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10655 else 10656 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10657 return true; 10658 } 10659 10660 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10661 SourceLocation Loc, 10662 Sema &Sema) { 10663 // C / C++ fields 10664 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10665 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10666 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10667 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10668 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10669 } 10670 10671 // Objective-C instance variables 10672 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10673 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10674 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10675 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10676 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10677 if (RL && RR && RL->getDecl() == RR->getDecl()) 10678 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10679 } 10680 } 10681 10682 // C99 6.5.16.1 10683 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10684 SourceLocation Loc, 10685 QualType CompoundType) { 10686 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10687 10688 // Verify that LHS is a modifiable lvalue, and emit error if not. 10689 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10690 return QualType(); 10691 10692 QualType LHSType = LHSExpr->getType(); 10693 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10694 CompoundType; 10695 // OpenCL v1.2 s6.1.1.1 p2: 10696 // The half data type can only be used to declare a pointer to a buffer that 10697 // contains half values 10698 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10699 LHSType->isHalfType()) { 10700 Diag(Loc, diag::err_opencl_half_load_store) << 1 10701 << LHSType.getUnqualifiedType(); 10702 return QualType(); 10703 } 10704 10705 AssignConvertType ConvTy; 10706 if (CompoundType.isNull()) { 10707 Expr *RHSCheck = RHS.get(); 10708 10709 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10710 10711 QualType LHSTy(LHSType); 10712 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10713 if (RHS.isInvalid()) 10714 return QualType(); 10715 // Special case of NSObject attributes on c-style pointer types. 10716 if (ConvTy == IncompatiblePointer && 10717 ((Context.isObjCNSObjectType(LHSType) && 10718 RHSType->isObjCObjectPointerType()) || 10719 (Context.isObjCNSObjectType(RHSType) && 10720 LHSType->isObjCObjectPointerType()))) 10721 ConvTy = Compatible; 10722 10723 if (ConvTy == Compatible && 10724 LHSType->isObjCObjectType()) 10725 Diag(Loc, diag::err_objc_object_assignment) 10726 << LHSType; 10727 10728 // If the RHS is a unary plus or minus, check to see if they = and + are 10729 // right next to each other. If so, the user may have typo'd "x =+ 4" 10730 // instead of "x += 4". 10731 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10732 RHSCheck = ICE->getSubExpr(); 10733 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10734 if ((UO->getOpcode() == UO_Plus || 10735 UO->getOpcode() == UO_Minus) && 10736 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10737 // Only if the two operators are exactly adjacent. 10738 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10739 // And there is a space or other character before the subexpr of the 10740 // unary +/-. We don't want to warn on "x=-1". 10741 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10742 UO->getSubExpr()->getLocStart().isFileID()) { 10743 Diag(Loc, diag::warn_not_compound_assign) 10744 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10745 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10746 } 10747 } 10748 10749 if (ConvTy == Compatible) { 10750 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10751 // Warn about retain cycles where a block captures the LHS, but 10752 // not if the LHS is a simple variable into which the block is 10753 // being stored...unless that variable can be captured by reference! 10754 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10755 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10756 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10757 checkRetainCycles(LHSExpr, RHS.get()); 10758 } 10759 10760 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10761 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10762 // It is safe to assign a weak reference into a strong variable. 10763 // Although this code can still have problems: 10764 // id x = self.weakProp; 10765 // id y = self.weakProp; 10766 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10767 // paths through the function. This should be revisited if 10768 // -Wrepeated-use-of-weak is made flow-sensitive. 10769 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10770 // variable, which will be valid for the current autorelease scope. 10771 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10772 RHS.get()->getLocStart())) 10773 getCurFunction()->markSafeWeakUse(RHS.get()); 10774 10775 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10776 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10777 } 10778 } 10779 } else { 10780 // Compound assignment "x += y" 10781 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10782 } 10783 10784 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10785 RHS.get(), AA_Assigning)) 10786 return QualType(); 10787 10788 CheckForNullPointerDereference(*this, LHSExpr); 10789 10790 // C99 6.5.16p3: The type of an assignment expression is the type of the 10791 // left operand unless the left operand has qualified type, in which case 10792 // it is the unqualified version of the type of the left operand. 10793 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10794 // is converted to the type of the assignment expression (above). 10795 // C++ 5.17p1: the type of the assignment expression is that of its left 10796 // operand. 10797 return (getLangOpts().CPlusPlus 10798 ? LHSType : LHSType.getUnqualifiedType()); 10799 } 10800 10801 // Only ignore explicit casts to void. 10802 static bool IgnoreCommaOperand(const Expr *E) { 10803 E = E->IgnoreParens(); 10804 10805 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10806 if (CE->getCastKind() == CK_ToVoid) { 10807 return true; 10808 } 10809 } 10810 10811 return false; 10812 } 10813 10814 // Look for instances where it is likely the comma operator is confused with 10815 // another operator. There is a whitelist of acceptable expressions for the 10816 // left hand side of the comma operator, otherwise emit a warning. 10817 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10818 // No warnings in macros 10819 if (Loc.isMacroID()) 10820 return; 10821 10822 // Don't warn in template instantiations. 10823 if (inTemplateInstantiation()) 10824 return; 10825 10826 // Scope isn't fine-grained enough to whitelist the specific cases, so 10827 // instead, skip more than needed, then call back into here with the 10828 // CommaVisitor in SemaStmt.cpp. 10829 // The whitelisted locations are the initialization and increment portions 10830 // of a for loop. The additional checks are on the condition of 10831 // if statements, do/while loops, and for loops. 10832 const unsigned ForIncrementFlags = 10833 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10834 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10835 const unsigned ScopeFlags = getCurScope()->getFlags(); 10836 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10837 (ScopeFlags & ForInitFlags) == ForInitFlags) 10838 return; 10839 10840 // If there are multiple comma operators used together, get the RHS of the 10841 // of the comma operator as the LHS. 10842 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10843 if (BO->getOpcode() != BO_Comma) 10844 break; 10845 LHS = BO->getRHS(); 10846 } 10847 10848 // Only allow some expressions on LHS to not warn. 10849 if (IgnoreCommaOperand(LHS)) 10850 return; 10851 10852 Diag(Loc, diag::warn_comma_operator); 10853 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10854 << LHS->getSourceRange() 10855 << FixItHint::CreateInsertion(LHS->getLocStart(), 10856 LangOpts.CPlusPlus ? "static_cast<void>(" 10857 : "(void)(") 10858 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10859 ")"); 10860 } 10861 10862 // C99 6.5.17 10863 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10864 SourceLocation Loc) { 10865 LHS = S.CheckPlaceholderExpr(LHS.get()); 10866 RHS = S.CheckPlaceholderExpr(RHS.get()); 10867 if (LHS.isInvalid() || RHS.isInvalid()) 10868 return QualType(); 10869 10870 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10871 // operands, but not unary promotions. 10872 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10873 10874 // So we treat the LHS as a ignored value, and in C++ we allow the 10875 // containing site to determine what should be done with the RHS. 10876 LHS = S.IgnoredValueConversions(LHS.get()); 10877 if (LHS.isInvalid()) 10878 return QualType(); 10879 10880 S.DiagnoseUnusedExprResult(LHS.get()); 10881 10882 if (!S.getLangOpts().CPlusPlus) { 10883 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10884 if (RHS.isInvalid()) 10885 return QualType(); 10886 if (!RHS.get()->getType()->isVoidType()) 10887 S.RequireCompleteType(Loc, RHS.get()->getType(), 10888 diag::err_incomplete_type); 10889 } 10890 10891 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10892 S.DiagnoseCommaOperator(LHS.get(), Loc); 10893 10894 return RHS.get()->getType(); 10895 } 10896 10897 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10898 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10899 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10900 ExprValueKind &VK, 10901 ExprObjectKind &OK, 10902 SourceLocation OpLoc, 10903 bool IsInc, bool IsPrefix) { 10904 if (Op->isTypeDependent()) 10905 return S.Context.DependentTy; 10906 10907 QualType ResType = Op->getType(); 10908 // Atomic types can be used for increment / decrement where the non-atomic 10909 // versions can, so ignore the _Atomic() specifier for the purpose of 10910 // checking. 10911 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10912 ResType = ResAtomicType->getValueType(); 10913 10914 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10915 10916 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10917 // Decrement of bool is not allowed. 10918 if (!IsInc) { 10919 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10920 return QualType(); 10921 } 10922 // Increment of bool sets it to true, but is deprecated. 10923 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 10924 : diag::warn_increment_bool) 10925 << Op->getSourceRange(); 10926 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10927 // Error on enum increments and decrements in C++ mode 10928 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10929 return QualType(); 10930 } else if (ResType->isRealType()) { 10931 // OK! 10932 } else if (ResType->isPointerType()) { 10933 // C99 6.5.2.4p2, 6.5.6p2 10934 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10935 return QualType(); 10936 } else if (ResType->isObjCObjectPointerType()) { 10937 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10938 // Otherwise, we just need a complete type. 10939 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10940 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10941 return QualType(); 10942 } else if (ResType->isAnyComplexType()) { 10943 // C99 does not support ++/-- on complex types, we allow as an extension. 10944 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10945 << ResType << Op->getSourceRange(); 10946 } else if (ResType->isPlaceholderType()) { 10947 ExprResult PR = S.CheckPlaceholderExpr(Op); 10948 if (PR.isInvalid()) return QualType(); 10949 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10950 IsInc, IsPrefix); 10951 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10952 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10953 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10954 (ResType->getAs<VectorType>()->getVectorKind() != 10955 VectorType::AltiVecBool)) { 10956 // The z vector extensions allow ++ and -- for non-bool vectors. 10957 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10958 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10959 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10960 } else { 10961 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10962 << ResType << int(IsInc) << Op->getSourceRange(); 10963 return QualType(); 10964 } 10965 // At this point, we know we have a real, complex or pointer type. 10966 // Now make sure the operand is a modifiable lvalue. 10967 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10968 return QualType(); 10969 // In C++, a prefix increment is the same type as the operand. Otherwise 10970 // (in C or with postfix), the increment is the unqualified type of the 10971 // operand. 10972 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10973 VK = VK_LValue; 10974 OK = Op->getObjectKind(); 10975 return ResType; 10976 } else { 10977 VK = VK_RValue; 10978 return ResType.getUnqualifiedType(); 10979 } 10980 } 10981 10982 10983 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10984 /// This routine allows us to typecheck complex/recursive expressions 10985 /// where the declaration is needed for type checking. We only need to 10986 /// handle cases when the expression references a function designator 10987 /// or is an lvalue. Here are some examples: 10988 /// - &(x) => x 10989 /// - &*****f => f for f a function designator. 10990 /// - &s.xx => s 10991 /// - &s.zz[1].yy -> s, if zz is an array 10992 /// - *(x + 1) -> x, if x is an array 10993 /// - &"123"[2] -> 0 10994 /// - & __real__ x -> x 10995 static ValueDecl *getPrimaryDecl(Expr *E) { 10996 switch (E->getStmtClass()) { 10997 case Stmt::DeclRefExprClass: 10998 return cast<DeclRefExpr>(E)->getDecl(); 10999 case Stmt::MemberExprClass: 11000 // If this is an arrow operator, the address is an offset from 11001 // the base's value, so the object the base refers to is 11002 // irrelevant. 11003 if (cast<MemberExpr>(E)->isArrow()) 11004 return nullptr; 11005 // Otherwise, the expression refers to a part of the base 11006 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11007 case Stmt::ArraySubscriptExprClass: { 11008 // FIXME: This code shouldn't be necessary! We should catch the implicit 11009 // promotion of register arrays earlier. 11010 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11011 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11012 if (ICE->getSubExpr()->getType()->isArrayType()) 11013 return getPrimaryDecl(ICE->getSubExpr()); 11014 } 11015 return nullptr; 11016 } 11017 case Stmt::UnaryOperatorClass: { 11018 UnaryOperator *UO = cast<UnaryOperator>(E); 11019 11020 switch(UO->getOpcode()) { 11021 case UO_Real: 11022 case UO_Imag: 11023 case UO_Extension: 11024 return getPrimaryDecl(UO->getSubExpr()); 11025 default: 11026 return nullptr; 11027 } 11028 } 11029 case Stmt::ParenExprClass: 11030 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11031 case Stmt::ImplicitCastExprClass: 11032 // If the result of an implicit cast is an l-value, we care about 11033 // the sub-expression; otherwise, the result here doesn't matter. 11034 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11035 default: 11036 return nullptr; 11037 } 11038 } 11039 11040 namespace { 11041 enum { 11042 AO_Bit_Field = 0, 11043 AO_Vector_Element = 1, 11044 AO_Property_Expansion = 2, 11045 AO_Register_Variable = 3, 11046 AO_No_Error = 4 11047 }; 11048 } 11049 /// \brief Diagnose invalid operand for address of operations. 11050 /// 11051 /// \param Type The type of operand which cannot have its address taken. 11052 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11053 Expr *E, unsigned Type) { 11054 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11055 } 11056 11057 /// CheckAddressOfOperand - The operand of & must be either a function 11058 /// designator or an lvalue designating an object. If it is an lvalue, the 11059 /// object cannot be declared with storage class register or be a bit field. 11060 /// Note: The usual conversions are *not* applied to the operand of the & 11061 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11062 /// In C++, the operand might be an overloaded function name, in which case 11063 /// we allow the '&' but retain the overloaded-function type. 11064 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11065 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11066 if (PTy->getKind() == BuiltinType::Overload) { 11067 Expr *E = OrigOp.get()->IgnoreParens(); 11068 if (!isa<OverloadExpr>(E)) { 11069 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11070 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11071 << OrigOp.get()->getSourceRange(); 11072 return QualType(); 11073 } 11074 11075 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11076 if (isa<UnresolvedMemberExpr>(Ovl)) 11077 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11078 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11079 << OrigOp.get()->getSourceRange(); 11080 return QualType(); 11081 } 11082 11083 return Context.OverloadTy; 11084 } 11085 11086 if (PTy->getKind() == BuiltinType::UnknownAny) 11087 return Context.UnknownAnyTy; 11088 11089 if (PTy->getKind() == BuiltinType::BoundMember) { 11090 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11091 << OrigOp.get()->getSourceRange(); 11092 return QualType(); 11093 } 11094 11095 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11096 if (OrigOp.isInvalid()) return QualType(); 11097 } 11098 11099 if (OrigOp.get()->isTypeDependent()) 11100 return Context.DependentTy; 11101 11102 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11103 11104 // Make sure to ignore parentheses in subsequent checks 11105 Expr *op = OrigOp.get()->IgnoreParens(); 11106 11107 // In OpenCL captures for blocks called as lambda functions 11108 // are located in the private address space. Blocks used in 11109 // enqueue_kernel can be located in a different address space 11110 // depending on a vendor implementation. Thus preventing 11111 // taking an address of the capture to avoid invalid AS casts. 11112 if (LangOpts.OpenCL) { 11113 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11114 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11115 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11116 return QualType(); 11117 } 11118 } 11119 11120 if (getLangOpts().C99) { 11121 // Implement C99-only parts of addressof rules. 11122 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11123 if (uOp->getOpcode() == UO_Deref) 11124 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11125 // (assuming the deref expression is valid). 11126 return uOp->getSubExpr()->getType(); 11127 } 11128 // Technically, there should be a check for array subscript 11129 // expressions here, but the result of one is always an lvalue anyway. 11130 } 11131 ValueDecl *dcl = getPrimaryDecl(op); 11132 11133 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11134 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11135 op->getLocStart())) 11136 return QualType(); 11137 11138 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11139 unsigned AddressOfError = AO_No_Error; 11140 11141 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11142 bool sfinae = (bool)isSFINAEContext(); 11143 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11144 : diag::ext_typecheck_addrof_temporary) 11145 << op->getType() << op->getSourceRange(); 11146 if (sfinae) 11147 return QualType(); 11148 // Materialize the temporary as an lvalue so that we can take its address. 11149 OrigOp = op = 11150 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11151 } else if (isa<ObjCSelectorExpr>(op)) { 11152 return Context.getPointerType(op->getType()); 11153 } else if (lval == Expr::LV_MemberFunction) { 11154 // If it's an instance method, make a member pointer. 11155 // The expression must have exactly the form &A::foo. 11156 11157 // If the underlying expression isn't a decl ref, give up. 11158 if (!isa<DeclRefExpr>(op)) { 11159 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11160 << OrigOp.get()->getSourceRange(); 11161 return QualType(); 11162 } 11163 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11164 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11165 11166 // The id-expression was parenthesized. 11167 if (OrigOp.get() != DRE) { 11168 Diag(OpLoc, diag::err_parens_pointer_member_function) 11169 << OrigOp.get()->getSourceRange(); 11170 11171 // The method was named without a qualifier. 11172 } else if (!DRE->getQualifier()) { 11173 if (MD->getParent()->getName().empty()) 11174 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11175 << op->getSourceRange(); 11176 else { 11177 SmallString<32> Str; 11178 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11179 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11180 << op->getSourceRange() 11181 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11182 } 11183 } 11184 11185 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11186 if (isa<CXXDestructorDecl>(MD)) 11187 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11188 11189 QualType MPTy = Context.getMemberPointerType( 11190 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11191 // Under the MS ABI, lock down the inheritance model now. 11192 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11193 (void)isCompleteType(OpLoc, MPTy); 11194 return MPTy; 11195 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11196 // C99 6.5.3.2p1 11197 // The operand must be either an l-value or a function designator 11198 if (!op->getType()->isFunctionType()) { 11199 // Use a special diagnostic for loads from property references. 11200 if (isa<PseudoObjectExpr>(op)) { 11201 AddressOfError = AO_Property_Expansion; 11202 } else { 11203 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11204 << op->getType() << op->getSourceRange(); 11205 return QualType(); 11206 } 11207 } 11208 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11209 // The operand cannot be a bit-field 11210 AddressOfError = AO_Bit_Field; 11211 } else if (op->getObjectKind() == OK_VectorComponent) { 11212 // The operand cannot be an element of a vector 11213 AddressOfError = AO_Vector_Element; 11214 } else if (dcl) { // C99 6.5.3.2p1 11215 // We have an lvalue with a decl. Make sure the decl is not declared 11216 // with the register storage-class specifier. 11217 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11218 // in C++ it is not error to take address of a register 11219 // variable (c++03 7.1.1P3) 11220 if (vd->getStorageClass() == SC_Register && 11221 !getLangOpts().CPlusPlus) { 11222 AddressOfError = AO_Register_Variable; 11223 } 11224 } else if (isa<MSPropertyDecl>(dcl)) { 11225 AddressOfError = AO_Property_Expansion; 11226 } else if (isa<FunctionTemplateDecl>(dcl)) { 11227 return Context.OverloadTy; 11228 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11229 // Okay: we can take the address of a field. 11230 // Could be a pointer to member, though, if there is an explicit 11231 // scope qualifier for the class. 11232 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11233 DeclContext *Ctx = dcl->getDeclContext(); 11234 if (Ctx && Ctx->isRecord()) { 11235 if (dcl->getType()->isReferenceType()) { 11236 Diag(OpLoc, 11237 diag::err_cannot_form_pointer_to_member_of_reference_type) 11238 << dcl->getDeclName() << dcl->getType(); 11239 return QualType(); 11240 } 11241 11242 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11243 Ctx = Ctx->getParent(); 11244 11245 QualType MPTy = Context.getMemberPointerType( 11246 op->getType(), 11247 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11248 // Under the MS ABI, lock down the inheritance model now. 11249 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11250 (void)isCompleteType(OpLoc, MPTy); 11251 return MPTy; 11252 } 11253 } 11254 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11255 !isa<BindingDecl>(dcl)) 11256 llvm_unreachable("Unknown/unexpected decl type"); 11257 } 11258 11259 if (AddressOfError != AO_No_Error) { 11260 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11261 return QualType(); 11262 } 11263 11264 if (lval == Expr::LV_IncompleteVoidType) { 11265 // Taking the address of a void variable is technically illegal, but we 11266 // allow it in cases which are otherwise valid. 11267 // Example: "extern void x; void* y = &x;". 11268 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11269 } 11270 11271 // If the operand has type "type", the result has type "pointer to type". 11272 if (op->getType()->isObjCObjectType()) 11273 return Context.getObjCObjectPointerType(op->getType()); 11274 11275 CheckAddressOfPackedMember(op); 11276 11277 return Context.getPointerType(op->getType()); 11278 } 11279 11280 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11281 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11282 if (!DRE) 11283 return; 11284 const Decl *D = DRE->getDecl(); 11285 if (!D) 11286 return; 11287 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11288 if (!Param) 11289 return; 11290 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11291 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11292 return; 11293 if (FunctionScopeInfo *FD = S.getCurFunction()) 11294 if (!FD->ModifiedNonNullParams.count(Param)) 11295 FD->ModifiedNonNullParams.insert(Param); 11296 } 11297 11298 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11299 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11300 SourceLocation OpLoc) { 11301 if (Op->isTypeDependent()) 11302 return S.Context.DependentTy; 11303 11304 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11305 if (ConvResult.isInvalid()) 11306 return QualType(); 11307 Op = ConvResult.get(); 11308 QualType OpTy = Op->getType(); 11309 QualType Result; 11310 11311 if (isa<CXXReinterpretCastExpr>(Op)) { 11312 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11313 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11314 Op->getSourceRange()); 11315 } 11316 11317 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11318 { 11319 Result = PT->getPointeeType(); 11320 } 11321 else if (const ObjCObjectPointerType *OPT = 11322 OpTy->getAs<ObjCObjectPointerType>()) 11323 Result = OPT->getPointeeType(); 11324 else { 11325 ExprResult PR = S.CheckPlaceholderExpr(Op); 11326 if (PR.isInvalid()) return QualType(); 11327 if (PR.get() != Op) 11328 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11329 } 11330 11331 if (Result.isNull()) { 11332 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11333 << OpTy << Op->getSourceRange(); 11334 return QualType(); 11335 } 11336 11337 // Note that per both C89 and C99, indirection is always legal, even if Result 11338 // is an incomplete type or void. It would be possible to warn about 11339 // dereferencing a void pointer, but it's completely well-defined, and such a 11340 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11341 // for pointers to 'void' but is fine for any other pointer type: 11342 // 11343 // C++ [expr.unary.op]p1: 11344 // [...] the expression to which [the unary * operator] is applied shall 11345 // be a pointer to an object type, or a pointer to a function type 11346 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11347 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11348 << OpTy << Op->getSourceRange(); 11349 11350 // Dereferences are usually l-values... 11351 VK = VK_LValue; 11352 11353 // ...except that certain expressions are never l-values in C. 11354 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11355 VK = VK_RValue; 11356 11357 return Result; 11358 } 11359 11360 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11361 BinaryOperatorKind Opc; 11362 switch (Kind) { 11363 default: llvm_unreachable("Unknown binop!"); 11364 case tok::periodstar: Opc = BO_PtrMemD; break; 11365 case tok::arrowstar: Opc = BO_PtrMemI; break; 11366 case tok::star: Opc = BO_Mul; break; 11367 case tok::slash: Opc = BO_Div; break; 11368 case tok::percent: Opc = BO_Rem; break; 11369 case tok::plus: Opc = BO_Add; break; 11370 case tok::minus: Opc = BO_Sub; break; 11371 case tok::lessless: Opc = BO_Shl; break; 11372 case tok::greatergreater: Opc = BO_Shr; break; 11373 case tok::lessequal: Opc = BO_LE; break; 11374 case tok::less: Opc = BO_LT; break; 11375 case tok::greaterequal: Opc = BO_GE; break; 11376 case tok::greater: Opc = BO_GT; break; 11377 case tok::exclaimequal: Opc = BO_NE; break; 11378 case tok::equalequal: Opc = BO_EQ; break; 11379 case tok::spaceship: Opc = BO_Cmp; break; 11380 case tok::amp: Opc = BO_And; break; 11381 case tok::caret: Opc = BO_Xor; break; 11382 case tok::pipe: Opc = BO_Or; break; 11383 case tok::ampamp: Opc = BO_LAnd; break; 11384 case tok::pipepipe: Opc = BO_LOr; break; 11385 case tok::equal: Opc = BO_Assign; break; 11386 case tok::starequal: Opc = BO_MulAssign; break; 11387 case tok::slashequal: Opc = BO_DivAssign; break; 11388 case tok::percentequal: Opc = BO_RemAssign; break; 11389 case tok::plusequal: Opc = BO_AddAssign; break; 11390 case tok::minusequal: Opc = BO_SubAssign; break; 11391 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11392 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11393 case tok::ampequal: Opc = BO_AndAssign; break; 11394 case tok::caretequal: Opc = BO_XorAssign; break; 11395 case tok::pipeequal: Opc = BO_OrAssign; break; 11396 case tok::comma: Opc = BO_Comma; break; 11397 } 11398 return Opc; 11399 } 11400 11401 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11402 tok::TokenKind Kind) { 11403 UnaryOperatorKind Opc; 11404 switch (Kind) { 11405 default: llvm_unreachable("Unknown unary op!"); 11406 case tok::plusplus: Opc = UO_PreInc; break; 11407 case tok::minusminus: Opc = UO_PreDec; break; 11408 case tok::amp: Opc = UO_AddrOf; break; 11409 case tok::star: Opc = UO_Deref; break; 11410 case tok::plus: Opc = UO_Plus; break; 11411 case tok::minus: Opc = UO_Minus; break; 11412 case tok::tilde: Opc = UO_Not; break; 11413 case tok::exclaim: Opc = UO_LNot; break; 11414 case tok::kw___real: Opc = UO_Real; break; 11415 case tok::kw___imag: Opc = UO_Imag; break; 11416 case tok::kw___extension__: Opc = UO_Extension; break; 11417 } 11418 return Opc; 11419 } 11420 11421 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11422 /// This warning is only emitted for builtin assignment operations. It is also 11423 /// suppressed in the event of macro expansions. 11424 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11425 SourceLocation OpLoc) { 11426 if (S.inTemplateInstantiation()) 11427 return; 11428 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11429 return; 11430 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11431 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11432 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11433 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11434 if (!LHSDeclRef || !RHSDeclRef || 11435 LHSDeclRef->getLocation().isMacroID() || 11436 RHSDeclRef->getLocation().isMacroID()) 11437 return; 11438 const ValueDecl *LHSDecl = 11439 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11440 const ValueDecl *RHSDecl = 11441 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11442 if (LHSDecl != RHSDecl) 11443 return; 11444 if (LHSDecl->getType().isVolatileQualified()) 11445 return; 11446 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11447 if (RefTy->getPointeeType().isVolatileQualified()) 11448 return; 11449 11450 S.Diag(OpLoc, diag::warn_self_assignment) 11451 << LHSDeclRef->getType() 11452 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11453 } 11454 11455 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11456 /// is usually indicative of introspection within the Objective-C pointer. 11457 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11458 SourceLocation OpLoc) { 11459 if (!S.getLangOpts().ObjC1) 11460 return; 11461 11462 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11463 const Expr *LHS = L.get(); 11464 const Expr *RHS = R.get(); 11465 11466 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11467 ObjCPointerExpr = LHS; 11468 OtherExpr = RHS; 11469 } 11470 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11471 ObjCPointerExpr = RHS; 11472 OtherExpr = LHS; 11473 } 11474 11475 // This warning is deliberately made very specific to reduce false 11476 // positives with logic that uses '&' for hashing. This logic mainly 11477 // looks for code trying to introspect into tagged pointers, which 11478 // code should generally never do. 11479 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11480 unsigned Diag = diag::warn_objc_pointer_masking; 11481 // Determine if we are introspecting the result of performSelectorXXX. 11482 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11483 // Special case messages to -performSelector and friends, which 11484 // can return non-pointer values boxed in a pointer value. 11485 // Some clients may wish to silence warnings in this subcase. 11486 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11487 Selector S = ME->getSelector(); 11488 StringRef SelArg0 = S.getNameForSlot(0); 11489 if (SelArg0.startswith("performSelector")) 11490 Diag = diag::warn_objc_pointer_masking_performSelector; 11491 } 11492 11493 S.Diag(OpLoc, Diag) 11494 << ObjCPointerExpr->getSourceRange(); 11495 } 11496 } 11497 11498 static NamedDecl *getDeclFromExpr(Expr *E) { 11499 if (!E) 11500 return nullptr; 11501 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11502 return DRE->getDecl(); 11503 if (auto *ME = dyn_cast<MemberExpr>(E)) 11504 return ME->getMemberDecl(); 11505 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11506 return IRE->getDecl(); 11507 return nullptr; 11508 } 11509 11510 // This helper function promotes a binary operator's operands (which are of a 11511 // half vector type) to a vector of floats and then truncates the result to 11512 // a vector of either half or short. 11513 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11514 BinaryOperatorKind Opc, QualType ResultTy, 11515 ExprValueKind VK, ExprObjectKind OK, 11516 bool IsCompAssign, SourceLocation OpLoc, 11517 FPOptions FPFeatures) { 11518 auto &Context = S.getASTContext(); 11519 assert((isVector(ResultTy, Context.HalfTy) || 11520 isVector(ResultTy, Context.ShortTy)) && 11521 "Result must be a vector of half or short"); 11522 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11523 isVector(RHS.get()->getType(), Context.HalfTy) && 11524 "both operands expected to be a half vector"); 11525 11526 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11527 QualType BinOpResTy = RHS.get()->getType(); 11528 11529 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11530 // change BinOpResTy to a vector of ints. 11531 if (isVector(ResultTy, Context.ShortTy)) 11532 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11533 11534 if (IsCompAssign) 11535 return new (Context) CompoundAssignOperator( 11536 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11537 OpLoc, FPFeatures); 11538 11539 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11540 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11541 VK, OK, OpLoc, FPFeatures); 11542 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11543 } 11544 11545 static std::pair<ExprResult, ExprResult> 11546 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11547 Expr *RHSExpr) { 11548 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11549 if (!S.getLangOpts().CPlusPlus) { 11550 // C cannot handle TypoExpr nodes on either side of a binop because it 11551 // doesn't handle dependent types properly, so make sure any TypoExprs have 11552 // been dealt with before checking the operands. 11553 LHS = S.CorrectDelayedTyposInExpr(LHS); 11554 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11555 if (Opc != BO_Assign) 11556 return ExprResult(E); 11557 // Avoid correcting the RHS to the same Expr as the LHS. 11558 Decl *D = getDeclFromExpr(E); 11559 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11560 }); 11561 } 11562 return std::make_pair(LHS, RHS); 11563 } 11564 11565 /// Returns true if conversion between vectors of halfs and vectors of floats 11566 /// is needed. 11567 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11568 QualType SrcType) { 11569 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11570 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11571 isVector(SrcType, Ctx.HalfTy); 11572 } 11573 11574 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11575 /// operator @p Opc at location @c TokLoc. This routine only supports 11576 /// built-in operations; ActOnBinOp handles overloaded operators. 11577 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11578 BinaryOperatorKind Opc, 11579 Expr *LHSExpr, Expr *RHSExpr) { 11580 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11581 // The syntax only allows initializer lists on the RHS of assignment, 11582 // so we don't need to worry about accepting invalid code for 11583 // non-assignment operators. 11584 // C++11 5.17p9: 11585 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11586 // of x = {} is x = T(). 11587 InitializationKind Kind = 11588 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11589 InitializedEntity Entity = 11590 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11591 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11592 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11593 if (Init.isInvalid()) 11594 return Init; 11595 RHSExpr = Init.get(); 11596 } 11597 11598 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11599 QualType ResultTy; // Result type of the binary operator. 11600 // The following two variables are used for compound assignment operators 11601 QualType CompLHSTy; // Type of LHS after promotions for computation 11602 QualType CompResultTy; // Type of computation result 11603 ExprValueKind VK = VK_RValue; 11604 ExprObjectKind OK = OK_Ordinary; 11605 bool ConvertHalfVec = false; 11606 11607 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11608 if (!LHS.isUsable() || !RHS.isUsable()) 11609 return ExprError(); 11610 11611 if (getLangOpts().OpenCL) { 11612 QualType LHSTy = LHSExpr->getType(); 11613 QualType RHSTy = RHSExpr->getType(); 11614 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11615 // the ATOMIC_VAR_INIT macro. 11616 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11617 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11618 if (BO_Assign == Opc) 11619 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11620 else 11621 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11622 return ExprError(); 11623 } 11624 11625 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11626 // only with a builtin functions and therefore should be disallowed here. 11627 if (LHSTy->isImageType() || RHSTy->isImageType() || 11628 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11629 LHSTy->isPipeType() || RHSTy->isPipeType() || 11630 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11631 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11632 return ExprError(); 11633 } 11634 } 11635 11636 switch (Opc) { 11637 case BO_Assign: 11638 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11639 if (getLangOpts().CPlusPlus && 11640 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11641 VK = LHS.get()->getValueKind(); 11642 OK = LHS.get()->getObjectKind(); 11643 } 11644 if (!ResultTy.isNull()) { 11645 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11646 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11647 } 11648 RecordModifiableNonNullParam(*this, LHS.get()); 11649 break; 11650 case BO_PtrMemD: 11651 case BO_PtrMemI: 11652 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11653 Opc == BO_PtrMemI); 11654 break; 11655 case BO_Mul: 11656 case BO_Div: 11657 ConvertHalfVec = true; 11658 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11659 Opc == BO_Div); 11660 break; 11661 case BO_Rem: 11662 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11663 break; 11664 case BO_Add: 11665 ConvertHalfVec = true; 11666 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11667 break; 11668 case BO_Sub: 11669 ConvertHalfVec = true; 11670 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11671 break; 11672 case BO_Shl: 11673 case BO_Shr: 11674 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11675 break; 11676 case BO_LE: 11677 case BO_LT: 11678 case BO_GE: 11679 case BO_GT: 11680 ConvertHalfVec = true; 11681 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11682 break; 11683 case BO_EQ: 11684 case BO_NE: 11685 ConvertHalfVec = true; 11686 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11687 break; 11688 case BO_Cmp: 11689 // FIXME: Implement proper semantic checking of '<=>'. 11690 ConvertHalfVec = true; 11691 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11692 if (!ResultTy.isNull()) 11693 ResultTy = Context.VoidTy; 11694 break; 11695 case BO_And: 11696 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11697 LLVM_FALLTHROUGH; 11698 case BO_Xor: 11699 case BO_Or: 11700 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11701 break; 11702 case BO_LAnd: 11703 case BO_LOr: 11704 ConvertHalfVec = true; 11705 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11706 break; 11707 case BO_MulAssign: 11708 case BO_DivAssign: 11709 ConvertHalfVec = true; 11710 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11711 Opc == BO_DivAssign); 11712 CompLHSTy = CompResultTy; 11713 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11714 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11715 break; 11716 case BO_RemAssign: 11717 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11718 CompLHSTy = CompResultTy; 11719 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11720 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11721 break; 11722 case BO_AddAssign: 11723 ConvertHalfVec = true; 11724 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11725 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11726 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11727 break; 11728 case BO_SubAssign: 11729 ConvertHalfVec = true; 11730 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11731 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11732 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11733 break; 11734 case BO_ShlAssign: 11735 case BO_ShrAssign: 11736 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11737 CompLHSTy = CompResultTy; 11738 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11739 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11740 break; 11741 case BO_AndAssign: 11742 case BO_OrAssign: // fallthrough 11743 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11744 LLVM_FALLTHROUGH; 11745 case BO_XorAssign: 11746 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11747 CompLHSTy = CompResultTy; 11748 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11749 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11750 break; 11751 case BO_Comma: 11752 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11753 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11754 VK = RHS.get()->getValueKind(); 11755 OK = RHS.get()->getObjectKind(); 11756 } 11757 break; 11758 } 11759 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11760 return ExprError(); 11761 11762 // Some of the binary operations require promoting operands of half vector to 11763 // float vectors and truncating the result back to half vector. For now, we do 11764 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11765 // arm64). 11766 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11767 isVector(LHS.get()->getType(), Context.HalfTy) && 11768 "both sides are half vectors or neither sides are"); 11769 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11770 LHS.get()->getType()); 11771 11772 // Check for array bounds violations for both sides of the BinaryOperator 11773 CheckArrayAccess(LHS.get()); 11774 CheckArrayAccess(RHS.get()); 11775 11776 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11777 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11778 &Context.Idents.get("object_setClass"), 11779 SourceLocation(), LookupOrdinaryName); 11780 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11781 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11782 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11783 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11784 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11785 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11786 } 11787 else 11788 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11789 } 11790 else if (const ObjCIvarRefExpr *OIRE = 11791 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11792 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11793 11794 // Opc is not a compound assignment if CompResultTy is null. 11795 if (CompResultTy.isNull()) { 11796 if (ConvertHalfVec) 11797 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11798 OpLoc, FPFeatures); 11799 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11800 OK, OpLoc, FPFeatures); 11801 } 11802 11803 // Handle compound assignments. 11804 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11805 OK_ObjCProperty) { 11806 VK = VK_LValue; 11807 OK = LHS.get()->getObjectKind(); 11808 } 11809 11810 if (ConvertHalfVec) 11811 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11812 OpLoc, FPFeatures); 11813 11814 return new (Context) CompoundAssignOperator( 11815 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11816 OpLoc, FPFeatures); 11817 } 11818 11819 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11820 /// operators are mixed in a way that suggests that the programmer forgot that 11821 /// comparison operators have higher precedence. The most typical example of 11822 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11823 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11824 SourceLocation OpLoc, Expr *LHSExpr, 11825 Expr *RHSExpr) { 11826 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11827 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11828 11829 // Check that one of the sides is a comparison operator and the other isn't. 11830 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11831 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11832 if (isLeftComp == isRightComp) 11833 return; 11834 11835 // Bitwise operations are sometimes used as eager logical ops. 11836 // Don't diagnose this. 11837 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11838 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11839 if (isLeftBitwise || isRightBitwise) 11840 return; 11841 11842 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11843 OpLoc) 11844 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11845 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11846 SourceRange ParensRange = isLeftComp ? 11847 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11848 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11849 11850 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11851 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11852 SuggestParentheses(Self, OpLoc, 11853 Self.PDiag(diag::note_precedence_silence) << OpStr, 11854 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11855 SuggestParentheses(Self, OpLoc, 11856 Self.PDiag(diag::note_precedence_bitwise_first) 11857 << BinaryOperator::getOpcodeStr(Opc), 11858 ParensRange); 11859 } 11860 11861 /// \brief It accepts a '&&' expr that is inside a '||' one. 11862 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11863 /// in parentheses. 11864 static void 11865 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11866 BinaryOperator *Bop) { 11867 assert(Bop->getOpcode() == BO_LAnd); 11868 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11869 << Bop->getSourceRange() << OpLoc; 11870 SuggestParentheses(Self, Bop->getOperatorLoc(), 11871 Self.PDiag(diag::note_precedence_silence) 11872 << Bop->getOpcodeStr(), 11873 Bop->getSourceRange()); 11874 } 11875 11876 /// \brief Returns true if the given expression can be evaluated as a constant 11877 /// 'true'. 11878 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11879 bool Res; 11880 return !E->isValueDependent() && 11881 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11882 } 11883 11884 /// \brief Returns true if the given expression can be evaluated as a constant 11885 /// 'false'. 11886 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11887 bool Res; 11888 return !E->isValueDependent() && 11889 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11890 } 11891 11892 /// \brief Look for '&&' in the left hand of a '||' expr. 11893 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11894 Expr *LHSExpr, Expr *RHSExpr) { 11895 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11896 if (Bop->getOpcode() == BO_LAnd) { 11897 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11898 if (EvaluatesAsFalse(S, RHSExpr)) 11899 return; 11900 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11901 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11902 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11903 } else if (Bop->getOpcode() == BO_LOr) { 11904 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11905 // If it's "a || b && 1 || c" we didn't warn earlier for 11906 // "a || b && 1", but warn now. 11907 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11908 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11909 } 11910 } 11911 } 11912 } 11913 11914 /// \brief Look for '&&' in the right hand of a '||' expr. 11915 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11916 Expr *LHSExpr, Expr *RHSExpr) { 11917 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11918 if (Bop->getOpcode() == BO_LAnd) { 11919 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11920 if (EvaluatesAsFalse(S, LHSExpr)) 11921 return; 11922 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11923 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11924 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11925 } 11926 } 11927 } 11928 11929 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11930 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11931 /// the '&' expression in parentheses. 11932 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11933 SourceLocation OpLoc, Expr *SubExpr) { 11934 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11935 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11936 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11937 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11938 << Bop->getSourceRange() << OpLoc; 11939 SuggestParentheses(S, Bop->getOperatorLoc(), 11940 S.PDiag(diag::note_precedence_silence) 11941 << Bop->getOpcodeStr(), 11942 Bop->getSourceRange()); 11943 } 11944 } 11945 } 11946 11947 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11948 Expr *SubExpr, StringRef Shift) { 11949 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11950 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11951 StringRef Op = Bop->getOpcodeStr(); 11952 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11953 << Bop->getSourceRange() << OpLoc << Shift << Op; 11954 SuggestParentheses(S, Bop->getOperatorLoc(), 11955 S.PDiag(diag::note_precedence_silence) << Op, 11956 Bop->getSourceRange()); 11957 } 11958 } 11959 } 11960 11961 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11962 Expr *LHSExpr, Expr *RHSExpr) { 11963 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11964 if (!OCE) 11965 return; 11966 11967 FunctionDecl *FD = OCE->getDirectCallee(); 11968 if (!FD || !FD->isOverloadedOperator()) 11969 return; 11970 11971 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11972 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11973 return; 11974 11975 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11976 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11977 << (Kind == OO_LessLess); 11978 SuggestParentheses(S, OCE->getOperatorLoc(), 11979 S.PDiag(diag::note_precedence_silence) 11980 << (Kind == OO_LessLess ? "<<" : ">>"), 11981 OCE->getSourceRange()); 11982 SuggestParentheses(S, OpLoc, 11983 S.PDiag(diag::note_evaluate_comparison_first), 11984 SourceRange(OCE->getArg(1)->getLocStart(), 11985 RHSExpr->getLocEnd())); 11986 } 11987 11988 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11989 /// precedence. 11990 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11991 SourceLocation OpLoc, Expr *LHSExpr, 11992 Expr *RHSExpr){ 11993 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11994 if (BinaryOperator::isBitwiseOp(Opc)) 11995 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11996 11997 // Diagnose "arg1 & arg2 | arg3" 11998 if ((Opc == BO_Or || Opc == BO_Xor) && 11999 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12000 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12001 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12002 } 12003 12004 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12005 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12006 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12007 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12008 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12009 } 12010 12011 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12012 || Opc == BO_Shr) { 12013 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12014 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12015 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12016 } 12017 12018 // Warn on overloaded shift operators and comparisons, such as: 12019 // cout << 5 == 4; 12020 if (BinaryOperator::isComparisonOp(Opc)) 12021 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12022 } 12023 12024 // Binary Operators. 'Tok' is the token for the operator. 12025 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12026 tok::TokenKind Kind, 12027 Expr *LHSExpr, Expr *RHSExpr) { 12028 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12029 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12030 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12031 12032 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12033 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12034 12035 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12036 } 12037 12038 /// Build an overloaded binary operator expression in the given scope. 12039 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12040 BinaryOperatorKind Opc, 12041 Expr *LHS, Expr *RHS) { 12042 // Find all of the overloaded operators visible from this 12043 // point. We perform both an operator-name lookup from the local 12044 // scope and an argument-dependent lookup based on the types of 12045 // the arguments. 12046 UnresolvedSet<16> Functions; 12047 OverloadedOperatorKind OverOp 12048 = BinaryOperator::getOverloadedOperator(Opc); 12049 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12050 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12051 RHS->getType(), Functions); 12052 12053 // Build the (potentially-overloaded, potentially-dependent) 12054 // binary operation. 12055 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12056 } 12057 12058 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12059 BinaryOperatorKind Opc, 12060 Expr *LHSExpr, Expr *RHSExpr) { 12061 ExprResult LHS, RHS; 12062 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12063 if (!LHS.isUsable() || !RHS.isUsable()) 12064 return ExprError(); 12065 LHSExpr = LHS.get(); 12066 RHSExpr = RHS.get(); 12067 12068 // We want to end up calling one of checkPseudoObjectAssignment 12069 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12070 // both expressions are overloadable or either is type-dependent), 12071 // or CreateBuiltinBinOp (in any other case). We also want to get 12072 // any placeholder types out of the way. 12073 12074 // Handle pseudo-objects in the LHS. 12075 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12076 // Assignments with a pseudo-object l-value need special analysis. 12077 if (pty->getKind() == BuiltinType::PseudoObject && 12078 BinaryOperator::isAssignmentOp(Opc)) 12079 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12080 12081 // Don't resolve overloads if the other type is overloadable. 12082 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12083 // We can't actually test that if we still have a placeholder, 12084 // though. Fortunately, none of the exceptions we see in that 12085 // code below are valid when the LHS is an overload set. Note 12086 // that an overload set can be dependently-typed, but it never 12087 // instantiates to having an overloadable type. 12088 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12089 if (resolvedRHS.isInvalid()) return ExprError(); 12090 RHSExpr = resolvedRHS.get(); 12091 12092 if (RHSExpr->isTypeDependent() || 12093 RHSExpr->getType()->isOverloadableType()) 12094 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12095 } 12096 12097 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12098 // template, diagnose the missing 'template' keyword instead of diagnosing 12099 // an invalid use of a bound member function. 12100 // 12101 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12102 // to C++1z [over.over]/1.4, but we already checked for that case above. 12103 if (Opc == BO_LT && inTemplateInstantiation() && 12104 (pty->getKind() == BuiltinType::BoundMember || 12105 pty->getKind() == BuiltinType::Overload)) { 12106 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12107 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12108 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12109 return isa<FunctionTemplateDecl>(ND); 12110 })) { 12111 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12112 : OE->getNameLoc(), 12113 diag::err_template_kw_missing) 12114 << OE->getName().getAsString() << ""; 12115 return ExprError(); 12116 } 12117 } 12118 12119 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12120 if (LHS.isInvalid()) return ExprError(); 12121 LHSExpr = LHS.get(); 12122 } 12123 12124 // Handle pseudo-objects in the RHS. 12125 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12126 // An overload in the RHS can potentially be resolved by the type 12127 // being assigned to. 12128 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12129 if (getLangOpts().CPlusPlus && 12130 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12131 LHSExpr->getType()->isOverloadableType())) 12132 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12133 12134 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12135 } 12136 12137 // Don't resolve overloads if the other type is overloadable. 12138 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12139 LHSExpr->getType()->isOverloadableType()) 12140 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12141 12142 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12143 if (!resolvedRHS.isUsable()) return ExprError(); 12144 RHSExpr = resolvedRHS.get(); 12145 } 12146 12147 if (getLangOpts().CPlusPlus) { 12148 // If either expression is type-dependent, always build an 12149 // overloaded op. 12150 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12151 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12152 12153 // Otherwise, build an overloaded op if either expression has an 12154 // overloadable type. 12155 if (LHSExpr->getType()->isOverloadableType() || 12156 RHSExpr->getType()->isOverloadableType()) 12157 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12158 } 12159 12160 // Build a built-in binary operation. 12161 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12162 } 12163 12164 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12165 UnaryOperatorKind Opc, 12166 Expr *InputExpr) { 12167 ExprResult Input = InputExpr; 12168 ExprValueKind VK = VK_RValue; 12169 ExprObjectKind OK = OK_Ordinary; 12170 QualType resultType; 12171 bool ConvertHalfVec = false; 12172 if (getLangOpts().OpenCL) { 12173 QualType Ty = InputExpr->getType(); 12174 // The only legal unary operation for atomics is '&'. 12175 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12176 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12177 // only with a builtin functions and therefore should be disallowed here. 12178 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12179 || Ty->isBlockPointerType())) { 12180 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12181 << InputExpr->getType() 12182 << Input.get()->getSourceRange()); 12183 } 12184 } 12185 switch (Opc) { 12186 case UO_PreInc: 12187 case UO_PreDec: 12188 case UO_PostInc: 12189 case UO_PostDec: 12190 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12191 OpLoc, 12192 Opc == UO_PreInc || 12193 Opc == UO_PostInc, 12194 Opc == UO_PreInc || 12195 Opc == UO_PreDec); 12196 break; 12197 case UO_AddrOf: 12198 resultType = CheckAddressOfOperand(Input, OpLoc); 12199 RecordModifiableNonNullParam(*this, InputExpr); 12200 break; 12201 case UO_Deref: { 12202 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12203 if (Input.isInvalid()) return ExprError(); 12204 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12205 break; 12206 } 12207 case UO_Plus: 12208 case UO_Minus: 12209 Input = UsualUnaryConversions(Input.get()); 12210 if (Input.isInvalid()) return ExprError(); 12211 // Unary plus and minus require promoting an operand of half vector to a 12212 // float vector and truncating the result back to a half vector. For now, we 12213 // do this only when HalfArgsAndReturns is set (that is, when the target is 12214 // arm or arm64). 12215 ConvertHalfVec = 12216 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12217 12218 // If the operand is a half vector, promote it to a float vector. 12219 if (ConvertHalfVec) 12220 Input = convertVector(Input.get(), Context.FloatTy, *this); 12221 resultType = Input.get()->getType(); 12222 if (resultType->isDependentType()) 12223 break; 12224 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12225 break; 12226 else if (resultType->isVectorType() && 12227 // The z vector extensions don't allow + or - with bool vectors. 12228 (!Context.getLangOpts().ZVector || 12229 resultType->getAs<VectorType>()->getVectorKind() != 12230 VectorType::AltiVecBool)) 12231 break; 12232 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12233 Opc == UO_Plus && 12234 resultType->isPointerType()) 12235 break; 12236 12237 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12238 << resultType << Input.get()->getSourceRange()); 12239 12240 case UO_Not: // bitwise complement 12241 Input = UsualUnaryConversions(Input.get()); 12242 if (Input.isInvalid()) 12243 return ExprError(); 12244 resultType = Input.get()->getType(); 12245 if (resultType->isDependentType()) 12246 break; 12247 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12248 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12249 // C99 does not support '~' for complex conjugation. 12250 Diag(OpLoc, diag::ext_integer_complement_complex) 12251 << resultType << Input.get()->getSourceRange(); 12252 else if (resultType->hasIntegerRepresentation()) 12253 break; 12254 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12255 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12256 // on vector float types. 12257 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12258 if (!T->isIntegerType()) 12259 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12260 << resultType << Input.get()->getSourceRange()); 12261 } else { 12262 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12263 << resultType << Input.get()->getSourceRange()); 12264 } 12265 break; 12266 12267 case UO_LNot: // logical negation 12268 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12269 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12270 if (Input.isInvalid()) return ExprError(); 12271 resultType = Input.get()->getType(); 12272 12273 // Though we still have to promote half FP to float... 12274 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12275 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12276 resultType = Context.FloatTy; 12277 } 12278 12279 if (resultType->isDependentType()) 12280 break; 12281 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12282 // C99 6.5.3.3p1: ok, fallthrough; 12283 if (Context.getLangOpts().CPlusPlus) { 12284 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12285 // operand contextually converted to bool. 12286 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12287 ScalarTypeToBooleanCastKind(resultType)); 12288 } else if (Context.getLangOpts().OpenCL && 12289 Context.getLangOpts().OpenCLVersion < 120) { 12290 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12291 // operate on scalar float types. 12292 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12293 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12294 << resultType << Input.get()->getSourceRange()); 12295 } 12296 } else if (resultType->isExtVectorType()) { 12297 if (Context.getLangOpts().OpenCL && 12298 Context.getLangOpts().OpenCLVersion < 120) { 12299 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12300 // operate on vector float types. 12301 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12302 if (!T->isIntegerType()) 12303 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12304 << resultType << Input.get()->getSourceRange()); 12305 } 12306 // Vector logical not returns the signed variant of the operand type. 12307 resultType = GetSignedVectorType(resultType); 12308 break; 12309 } else { 12310 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12311 // type in C++. We should allow that here too. 12312 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12313 << resultType << Input.get()->getSourceRange()); 12314 } 12315 12316 // LNot always has type int. C99 6.5.3.3p5. 12317 // In C++, it's bool. C++ 5.3.1p8 12318 resultType = Context.getLogicalOperationType(); 12319 break; 12320 case UO_Real: 12321 case UO_Imag: 12322 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12323 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12324 // complex l-values to ordinary l-values and all other values to r-values. 12325 if (Input.isInvalid()) return ExprError(); 12326 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12327 if (Input.get()->getValueKind() != VK_RValue && 12328 Input.get()->getObjectKind() == OK_Ordinary) 12329 VK = Input.get()->getValueKind(); 12330 } else if (!getLangOpts().CPlusPlus) { 12331 // In C, a volatile scalar is read by __imag. In C++, it is not. 12332 Input = DefaultLvalueConversion(Input.get()); 12333 } 12334 break; 12335 case UO_Extension: 12336 resultType = Input.get()->getType(); 12337 VK = Input.get()->getValueKind(); 12338 OK = Input.get()->getObjectKind(); 12339 break; 12340 case UO_Coawait: 12341 // It's unnessesary to represent the pass-through operator co_await in the 12342 // AST; just return the input expression instead. 12343 assert(!Input.get()->getType()->isDependentType() && 12344 "the co_await expression must be non-dependant before " 12345 "building operator co_await"); 12346 return Input; 12347 } 12348 if (resultType.isNull() || Input.isInvalid()) 12349 return ExprError(); 12350 12351 // Check for array bounds violations in the operand of the UnaryOperator, 12352 // except for the '*' and '&' operators that have to be handled specially 12353 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12354 // that are explicitly defined as valid by the standard). 12355 if (Opc != UO_AddrOf && Opc != UO_Deref) 12356 CheckArrayAccess(Input.get()); 12357 12358 auto *UO = new (Context) 12359 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12360 // Convert the result back to a half vector. 12361 if (ConvertHalfVec) 12362 return convertVector(UO, Context.HalfTy, *this); 12363 return UO; 12364 } 12365 12366 /// \brief Determine whether the given expression is a qualified member 12367 /// access expression, of a form that could be turned into a pointer to member 12368 /// with the address-of operator. 12369 static bool isQualifiedMemberAccess(Expr *E) { 12370 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12371 if (!DRE->getQualifier()) 12372 return false; 12373 12374 ValueDecl *VD = DRE->getDecl(); 12375 if (!VD->isCXXClassMember()) 12376 return false; 12377 12378 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12379 return true; 12380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12381 return Method->isInstance(); 12382 12383 return false; 12384 } 12385 12386 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12387 if (!ULE->getQualifier()) 12388 return false; 12389 12390 for (NamedDecl *D : ULE->decls()) { 12391 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12392 if (Method->isInstance()) 12393 return true; 12394 } else { 12395 // Overload set does not contain methods. 12396 break; 12397 } 12398 } 12399 12400 return false; 12401 } 12402 12403 return false; 12404 } 12405 12406 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12407 UnaryOperatorKind Opc, Expr *Input) { 12408 // First things first: handle placeholders so that the 12409 // overloaded-operator check considers the right type. 12410 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12411 // Increment and decrement of pseudo-object references. 12412 if (pty->getKind() == BuiltinType::PseudoObject && 12413 UnaryOperator::isIncrementDecrementOp(Opc)) 12414 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12415 12416 // extension is always a builtin operator. 12417 if (Opc == UO_Extension) 12418 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12419 12420 // & gets special logic for several kinds of placeholder. 12421 // The builtin code knows what to do. 12422 if (Opc == UO_AddrOf && 12423 (pty->getKind() == BuiltinType::Overload || 12424 pty->getKind() == BuiltinType::UnknownAny || 12425 pty->getKind() == BuiltinType::BoundMember)) 12426 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12427 12428 // Anything else needs to be handled now. 12429 ExprResult Result = CheckPlaceholderExpr(Input); 12430 if (Result.isInvalid()) return ExprError(); 12431 Input = Result.get(); 12432 } 12433 12434 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12435 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12436 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12437 // Find all of the overloaded operators visible from this 12438 // point. We perform both an operator-name lookup from the local 12439 // scope and an argument-dependent lookup based on the types of 12440 // the arguments. 12441 UnresolvedSet<16> Functions; 12442 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12443 if (S && OverOp != OO_None) 12444 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12445 Functions); 12446 12447 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12448 } 12449 12450 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12451 } 12452 12453 // Unary Operators. 'Tok' is the token for the operator. 12454 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12455 tok::TokenKind Op, Expr *Input) { 12456 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12457 } 12458 12459 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12460 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12461 LabelDecl *TheDecl) { 12462 TheDecl->markUsed(Context); 12463 // Create the AST node. The address of a label always has type 'void*'. 12464 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12465 Context.getPointerType(Context.VoidTy)); 12466 } 12467 12468 /// Given the last statement in a statement-expression, check whether 12469 /// the result is a producing expression (like a call to an 12470 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12471 /// release out of the full-expression. Otherwise, return null. 12472 /// Cannot fail. 12473 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12474 // Should always be wrapped with one of these. 12475 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12476 if (!cleanups) return nullptr; 12477 12478 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12479 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12480 return nullptr; 12481 12482 // Splice out the cast. This shouldn't modify any interesting 12483 // features of the statement. 12484 Expr *producer = cast->getSubExpr(); 12485 assert(producer->getType() == cast->getType()); 12486 assert(producer->getValueKind() == cast->getValueKind()); 12487 cleanups->setSubExpr(producer); 12488 return cleanups; 12489 } 12490 12491 void Sema::ActOnStartStmtExpr() { 12492 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12493 } 12494 12495 void Sema::ActOnStmtExprError() { 12496 // Note that function is also called by TreeTransform when leaving a 12497 // StmtExpr scope without rebuilding anything. 12498 12499 DiscardCleanupsInEvaluationContext(); 12500 PopExpressionEvaluationContext(); 12501 } 12502 12503 ExprResult 12504 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12505 SourceLocation RPLoc) { // "({..})" 12506 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12507 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12508 12509 if (hasAnyUnrecoverableErrorsInThisFunction()) 12510 DiscardCleanupsInEvaluationContext(); 12511 assert(!Cleanup.exprNeedsCleanups() && 12512 "cleanups within StmtExpr not correctly bound!"); 12513 PopExpressionEvaluationContext(); 12514 12515 // FIXME: there are a variety of strange constraints to enforce here, for 12516 // example, it is not possible to goto into a stmt expression apparently. 12517 // More semantic analysis is needed. 12518 12519 // If there are sub-stmts in the compound stmt, take the type of the last one 12520 // as the type of the stmtexpr. 12521 QualType Ty = Context.VoidTy; 12522 bool StmtExprMayBindToTemp = false; 12523 if (!Compound->body_empty()) { 12524 Stmt *LastStmt = Compound->body_back(); 12525 LabelStmt *LastLabelStmt = nullptr; 12526 // If LastStmt is a label, skip down through into the body. 12527 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12528 LastLabelStmt = Label; 12529 LastStmt = Label->getSubStmt(); 12530 } 12531 12532 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12533 // Do function/array conversion on the last expression, but not 12534 // lvalue-to-rvalue. However, initialize an unqualified type. 12535 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12536 if (LastExpr.isInvalid()) 12537 return ExprError(); 12538 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12539 12540 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12541 // In ARC, if the final expression ends in a consume, splice 12542 // the consume out and bind it later. In the alternate case 12543 // (when dealing with a retainable type), the result 12544 // initialization will create a produce. In both cases the 12545 // result will be +1, and we'll need to balance that out with 12546 // a bind. 12547 if (Expr *rebuiltLastStmt 12548 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12549 LastExpr = rebuiltLastStmt; 12550 } else { 12551 LastExpr = PerformCopyInitialization( 12552 InitializedEntity::InitializeResult(LPLoc, 12553 Ty, 12554 false), 12555 SourceLocation(), 12556 LastExpr); 12557 } 12558 12559 if (LastExpr.isInvalid()) 12560 return ExprError(); 12561 if (LastExpr.get() != nullptr) { 12562 if (!LastLabelStmt) 12563 Compound->setLastStmt(LastExpr.get()); 12564 else 12565 LastLabelStmt->setSubStmt(LastExpr.get()); 12566 StmtExprMayBindToTemp = true; 12567 } 12568 } 12569 } 12570 } 12571 12572 // FIXME: Check that expression type is complete/non-abstract; statement 12573 // expressions are not lvalues. 12574 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12575 if (StmtExprMayBindToTemp) 12576 return MaybeBindToTemporary(ResStmtExpr); 12577 return ResStmtExpr; 12578 } 12579 12580 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12581 TypeSourceInfo *TInfo, 12582 ArrayRef<OffsetOfComponent> Components, 12583 SourceLocation RParenLoc) { 12584 QualType ArgTy = TInfo->getType(); 12585 bool Dependent = ArgTy->isDependentType(); 12586 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12587 12588 // We must have at least one component that refers to the type, and the first 12589 // one is known to be a field designator. Verify that the ArgTy represents 12590 // a struct/union/class. 12591 if (!Dependent && !ArgTy->isRecordType()) 12592 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12593 << ArgTy << TypeRange); 12594 12595 // Type must be complete per C99 7.17p3 because a declaring a variable 12596 // with an incomplete type would be ill-formed. 12597 if (!Dependent 12598 && RequireCompleteType(BuiltinLoc, ArgTy, 12599 diag::err_offsetof_incomplete_type, TypeRange)) 12600 return ExprError(); 12601 12602 bool DidWarnAboutNonPOD = false; 12603 QualType CurrentType = ArgTy; 12604 SmallVector<OffsetOfNode, 4> Comps; 12605 SmallVector<Expr*, 4> Exprs; 12606 for (const OffsetOfComponent &OC : Components) { 12607 if (OC.isBrackets) { 12608 // Offset of an array sub-field. TODO: Should we allow vector elements? 12609 if (!CurrentType->isDependentType()) { 12610 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12611 if(!AT) 12612 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12613 << CurrentType); 12614 CurrentType = AT->getElementType(); 12615 } else 12616 CurrentType = Context.DependentTy; 12617 12618 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12619 if (IdxRval.isInvalid()) 12620 return ExprError(); 12621 Expr *Idx = IdxRval.get(); 12622 12623 // The expression must be an integral expression. 12624 // FIXME: An integral constant expression? 12625 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12626 !Idx->getType()->isIntegerType()) 12627 return ExprError(Diag(Idx->getLocStart(), 12628 diag::err_typecheck_subscript_not_integer) 12629 << Idx->getSourceRange()); 12630 12631 // Record this array index. 12632 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12633 Exprs.push_back(Idx); 12634 continue; 12635 } 12636 12637 // Offset of a field. 12638 if (CurrentType->isDependentType()) { 12639 // We have the offset of a field, but we can't look into the dependent 12640 // type. Just record the identifier of the field. 12641 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12642 CurrentType = Context.DependentTy; 12643 continue; 12644 } 12645 12646 // We need to have a complete type to look into. 12647 if (RequireCompleteType(OC.LocStart, CurrentType, 12648 diag::err_offsetof_incomplete_type)) 12649 return ExprError(); 12650 12651 // Look for the designated field. 12652 const RecordType *RC = CurrentType->getAs<RecordType>(); 12653 if (!RC) 12654 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12655 << CurrentType); 12656 RecordDecl *RD = RC->getDecl(); 12657 12658 // C++ [lib.support.types]p5: 12659 // The macro offsetof accepts a restricted set of type arguments in this 12660 // International Standard. type shall be a POD structure or a POD union 12661 // (clause 9). 12662 // C++11 [support.types]p4: 12663 // If type is not a standard-layout class (Clause 9), the results are 12664 // undefined. 12665 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12666 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12667 unsigned DiagID = 12668 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12669 : diag::ext_offsetof_non_pod_type; 12670 12671 if (!IsSafe && !DidWarnAboutNonPOD && 12672 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12673 PDiag(DiagID) 12674 << SourceRange(Components[0].LocStart, OC.LocEnd) 12675 << CurrentType)) 12676 DidWarnAboutNonPOD = true; 12677 } 12678 12679 // Look for the field. 12680 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12681 LookupQualifiedName(R, RD); 12682 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12683 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12684 if (!MemberDecl) { 12685 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12686 MemberDecl = IndirectMemberDecl->getAnonField(); 12687 } 12688 12689 if (!MemberDecl) 12690 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12691 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12692 OC.LocEnd)); 12693 12694 // C99 7.17p3: 12695 // (If the specified member is a bit-field, the behavior is undefined.) 12696 // 12697 // We diagnose this as an error. 12698 if (MemberDecl->isBitField()) { 12699 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12700 << MemberDecl->getDeclName() 12701 << SourceRange(BuiltinLoc, RParenLoc); 12702 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12703 return ExprError(); 12704 } 12705 12706 RecordDecl *Parent = MemberDecl->getParent(); 12707 if (IndirectMemberDecl) 12708 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12709 12710 // If the member was found in a base class, introduce OffsetOfNodes for 12711 // the base class indirections. 12712 CXXBasePaths Paths; 12713 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12714 Paths)) { 12715 if (Paths.getDetectedVirtual()) { 12716 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12717 << MemberDecl->getDeclName() 12718 << SourceRange(BuiltinLoc, RParenLoc); 12719 return ExprError(); 12720 } 12721 12722 CXXBasePath &Path = Paths.front(); 12723 for (const CXXBasePathElement &B : Path) 12724 Comps.push_back(OffsetOfNode(B.Base)); 12725 } 12726 12727 if (IndirectMemberDecl) { 12728 for (auto *FI : IndirectMemberDecl->chain()) { 12729 assert(isa<FieldDecl>(FI)); 12730 Comps.push_back(OffsetOfNode(OC.LocStart, 12731 cast<FieldDecl>(FI), OC.LocEnd)); 12732 } 12733 } else 12734 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12735 12736 CurrentType = MemberDecl->getType().getNonReferenceType(); 12737 } 12738 12739 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12740 Comps, Exprs, RParenLoc); 12741 } 12742 12743 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12744 SourceLocation BuiltinLoc, 12745 SourceLocation TypeLoc, 12746 ParsedType ParsedArgTy, 12747 ArrayRef<OffsetOfComponent> Components, 12748 SourceLocation RParenLoc) { 12749 12750 TypeSourceInfo *ArgTInfo; 12751 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12752 if (ArgTy.isNull()) 12753 return ExprError(); 12754 12755 if (!ArgTInfo) 12756 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12757 12758 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12759 } 12760 12761 12762 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12763 Expr *CondExpr, 12764 Expr *LHSExpr, Expr *RHSExpr, 12765 SourceLocation RPLoc) { 12766 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12767 12768 ExprValueKind VK = VK_RValue; 12769 ExprObjectKind OK = OK_Ordinary; 12770 QualType resType; 12771 bool ValueDependent = false; 12772 bool CondIsTrue = false; 12773 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12774 resType = Context.DependentTy; 12775 ValueDependent = true; 12776 } else { 12777 // The conditional expression is required to be a constant expression. 12778 llvm::APSInt condEval(32); 12779 ExprResult CondICE 12780 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12781 diag::err_typecheck_choose_expr_requires_constant, false); 12782 if (CondICE.isInvalid()) 12783 return ExprError(); 12784 CondExpr = CondICE.get(); 12785 CondIsTrue = condEval.getZExtValue(); 12786 12787 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12788 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12789 12790 resType = ActiveExpr->getType(); 12791 ValueDependent = ActiveExpr->isValueDependent(); 12792 VK = ActiveExpr->getValueKind(); 12793 OK = ActiveExpr->getObjectKind(); 12794 } 12795 12796 return new (Context) 12797 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12798 CondIsTrue, resType->isDependentType(), ValueDependent); 12799 } 12800 12801 //===----------------------------------------------------------------------===// 12802 // Clang Extensions. 12803 //===----------------------------------------------------------------------===// 12804 12805 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12806 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12807 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12808 12809 if (LangOpts.CPlusPlus) { 12810 Decl *ManglingContextDecl; 12811 if (MangleNumberingContext *MCtx = 12812 getCurrentMangleNumberContext(Block->getDeclContext(), 12813 ManglingContextDecl)) { 12814 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12815 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12816 } 12817 } 12818 12819 PushBlockScope(CurScope, Block); 12820 CurContext->addDecl(Block); 12821 if (CurScope) 12822 PushDeclContext(CurScope, Block); 12823 else 12824 CurContext = Block; 12825 12826 getCurBlock()->HasImplicitReturnType = true; 12827 12828 // Enter a new evaluation context to insulate the block from any 12829 // cleanups from the enclosing full-expression. 12830 PushExpressionEvaluationContext( 12831 ExpressionEvaluationContext::PotentiallyEvaluated); 12832 } 12833 12834 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12835 Scope *CurScope) { 12836 assert(ParamInfo.getIdentifier() == nullptr && 12837 "block-id should have no identifier!"); 12838 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 12839 BlockScopeInfo *CurBlock = getCurBlock(); 12840 12841 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12842 QualType T = Sig->getType(); 12843 12844 // FIXME: We should allow unexpanded parameter packs here, but that would, 12845 // in turn, make the block expression contain unexpanded parameter packs. 12846 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12847 // Drop the parameters. 12848 FunctionProtoType::ExtProtoInfo EPI; 12849 EPI.HasTrailingReturn = false; 12850 EPI.TypeQuals |= DeclSpec::TQ_const; 12851 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12852 Sig = Context.getTrivialTypeSourceInfo(T); 12853 } 12854 12855 // GetTypeForDeclarator always produces a function type for a block 12856 // literal signature. Furthermore, it is always a FunctionProtoType 12857 // unless the function was written with a typedef. 12858 assert(T->isFunctionType() && 12859 "GetTypeForDeclarator made a non-function block signature"); 12860 12861 // Look for an explicit signature in that function type. 12862 FunctionProtoTypeLoc ExplicitSignature; 12863 12864 if ((ExplicitSignature = 12865 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 12866 12867 // Check whether that explicit signature was synthesized by 12868 // GetTypeForDeclarator. If so, don't save that as part of the 12869 // written signature. 12870 if (ExplicitSignature.getLocalRangeBegin() == 12871 ExplicitSignature.getLocalRangeEnd()) { 12872 // This would be much cheaper if we stored TypeLocs instead of 12873 // TypeSourceInfos. 12874 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12875 unsigned Size = Result.getFullDataSize(); 12876 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12877 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12878 12879 ExplicitSignature = FunctionProtoTypeLoc(); 12880 } 12881 } 12882 12883 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12884 CurBlock->FunctionType = T; 12885 12886 const FunctionType *Fn = T->getAs<FunctionType>(); 12887 QualType RetTy = Fn->getReturnType(); 12888 bool isVariadic = 12889 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12890 12891 CurBlock->TheDecl->setIsVariadic(isVariadic); 12892 12893 // Context.DependentTy is used as a placeholder for a missing block 12894 // return type. TODO: what should we do with declarators like: 12895 // ^ * { ... } 12896 // If the answer is "apply template argument deduction".... 12897 if (RetTy != Context.DependentTy) { 12898 CurBlock->ReturnType = RetTy; 12899 CurBlock->TheDecl->setBlockMissingReturnType(false); 12900 CurBlock->HasImplicitReturnType = false; 12901 } 12902 12903 // Push block parameters from the declarator if we had them. 12904 SmallVector<ParmVarDecl*, 8> Params; 12905 if (ExplicitSignature) { 12906 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12907 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12908 if (Param->getIdentifier() == nullptr && 12909 !Param->isImplicit() && 12910 !Param->isInvalidDecl() && 12911 !getLangOpts().CPlusPlus) 12912 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12913 Params.push_back(Param); 12914 } 12915 12916 // Fake up parameter variables if we have a typedef, like 12917 // ^ fntype { ... } 12918 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12919 for (const auto &I : Fn->param_types()) { 12920 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12921 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12922 Params.push_back(Param); 12923 } 12924 } 12925 12926 // Set the parameters on the block decl. 12927 if (!Params.empty()) { 12928 CurBlock->TheDecl->setParams(Params); 12929 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12930 /*CheckParameterNames=*/false); 12931 } 12932 12933 // Finally we can process decl attributes. 12934 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12935 12936 // Put the parameter variables in scope. 12937 for (auto AI : CurBlock->TheDecl->parameters()) { 12938 AI->setOwningFunction(CurBlock->TheDecl); 12939 12940 // If this has an identifier, add it to the scope stack. 12941 if (AI->getIdentifier()) { 12942 CheckShadow(CurBlock->TheScope, AI); 12943 12944 PushOnScopeChains(AI, CurBlock->TheScope); 12945 } 12946 } 12947 } 12948 12949 /// ActOnBlockError - If there is an error parsing a block, this callback 12950 /// is invoked to pop the information about the block from the action impl. 12951 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12952 // Leave the expression-evaluation context. 12953 DiscardCleanupsInEvaluationContext(); 12954 PopExpressionEvaluationContext(); 12955 12956 // Pop off CurBlock, handle nested blocks. 12957 PopDeclContext(); 12958 PopFunctionScopeInfo(); 12959 } 12960 12961 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12962 /// literal was successfully completed. ^(int x){...} 12963 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12964 Stmt *Body, Scope *CurScope) { 12965 // If blocks are disabled, emit an error. 12966 if (!LangOpts.Blocks) 12967 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12968 12969 // Leave the expression-evaluation context. 12970 if (hasAnyUnrecoverableErrorsInThisFunction()) 12971 DiscardCleanupsInEvaluationContext(); 12972 assert(!Cleanup.exprNeedsCleanups() && 12973 "cleanups within block not correctly bound!"); 12974 PopExpressionEvaluationContext(); 12975 12976 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12977 12978 if (BSI->HasImplicitReturnType) 12979 deduceClosureReturnType(*BSI); 12980 12981 PopDeclContext(); 12982 12983 QualType RetTy = Context.VoidTy; 12984 if (!BSI->ReturnType.isNull()) 12985 RetTy = BSI->ReturnType; 12986 12987 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12988 QualType BlockTy; 12989 12990 // Set the captured variables on the block. 12991 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12992 SmallVector<BlockDecl::Capture, 4> Captures; 12993 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12994 if (Cap.isThisCapture()) 12995 continue; 12996 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12997 Cap.isNested(), Cap.getInitExpr()); 12998 Captures.push_back(NewCap); 12999 } 13000 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13001 13002 // If the user wrote a function type in some form, try to use that. 13003 if (!BSI->FunctionType.isNull()) { 13004 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13005 13006 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13007 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13008 13009 // Turn protoless block types into nullary block types. 13010 if (isa<FunctionNoProtoType>(FTy)) { 13011 FunctionProtoType::ExtProtoInfo EPI; 13012 EPI.ExtInfo = Ext; 13013 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13014 13015 // Otherwise, if we don't need to change anything about the function type, 13016 // preserve its sugar structure. 13017 } else if (FTy->getReturnType() == RetTy && 13018 (!NoReturn || FTy->getNoReturnAttr())) { 13019 BlockTy = BSI->FunctionType; 13020 13021 // Otherwise, make the minimal modifications to the function type. 13022 } else { 13023 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13024 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13025 EPI.TypeQuals = 0; // FIXME: silently? 13026 EPI.ExtInfo = Ext; 13027 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13028 } 13029 13030 // If we don't have a function type, just build one from nothing. 13031 } else { 13032 FunctionProtoType::ExtProtoInfo EPI; 13033 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13034 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13035 } 13036 13037 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13038 BlockTy = Context.getBlockPointerType(BlockTy); 13039 13040 // If needed, diagnose invalid gotos and switches in the block. 13041 if (getCurFunction()->NeedsScopeChecking() && 13042 !PP.isCodeCompletionEnabled()) 13043 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13044 13045 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13046 13047 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13048 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13049 13050 // Try to apply the named return value optimization. We have to check again 13051 // if we can do this, though, because blocks keep return statements around 13052 // to deduce an implicit return type. 13053 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13054 !BSI->TheDecl->isDependentContext()) 13055 computeNRVO(Body, BSI); 13056 13057 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13058 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13059 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13060 13061 // If the block isn't obviously global, i.e. it captures anything at 13062 // all, then we need to do a few things in the surrounding context: 13063 if (Result->getBlockDecl()->hasCaptures()) { 13064 // First, this expression has a new cleanup object. 13065 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13066 Cleanup.setExprNeedsCleanups(true); 13067 13068 // It also gets a branch-protected scope if any of the captured 13069 // variables needs destruction. 13070 for (const auto &CI : Result->getBlockDecl()->captures()) { 13071 const VarDecl *var = CI.getVariable(); 13072 if (var->getType().isDestructedType() != QualType::DK_none) { 13073 getCurFunction()->setHasBranchProtectedScope(); 13074 break; 13075 } 13076 } 13077 } 13078 13079 return Result; 13080 } 13081 13082 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13083 SourceLocation RPLoc) { 13084 TypeSourceInfo *TInfo; 13085 GetTypeFromParser(Ty, &TInfo); 13086 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13087 } 13088 13089 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13090 Expr *E, TypeSourceInfo *TInfo, 13091 SourceLocation RPLoc) { 13092 Expr *OrigExpr = E; 13093 bool IsMS = false; 13094 13095 // CUDA device code does not support varargs. 13096 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13097 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13098 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13099 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13100 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13101 } 13102 } 13103 13104 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13105 // as Microsoft ABI on an actual Microsoft platform, where 13106 // __builtin_ms_va_list and __builtin_va_list are the same.) 13107 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13108 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13109 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13110 if (Context.hasSameType(MSVaListType, E->getType())) { 13111 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13112 return ExprError(); 13113 IsMS = true; 13114 } 13115 } 13116 13117 // Get the va_list type 13118 QualType VaListType = Context.getBuiltinVaListType(); 13119 if (!IsMS) { 13120 if (VaListType->isArrayType()) { 13121 // Deal with implicit array decay; for example, on x86-64, 13122 // va_list is an array, but it's supposed to decay to 13123 // a pointer for va_arg. 13124 VaListType = Context.getArrayDecayedType(VaListType); 13125 // Make sure the input expression also decays appropriately. 13126 ExprResult Result = UsualUnaryConversions(E); 13127 if (Result.isInvalid()) 13128 return ExprError(); 13129 E = Result.get(); 13130 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13131 // If va_list is a record type and we are compiling in C++ mode, 13132 // check the argument using reference binding. 13133 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13134 Context, Context.getLValueReferenceType(VaListType), false); 13135 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13136 if (Init.isInvalid()) 13137 return ExprError(); 13138 E = Init.getAs<Expr>(); 13139 } else { 13140 // Otherwise, the va_list argument must be an l-value because 13141 // it is modified by va_arg. 13142 if (!E->isTypeDependent() && 13143 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13144 return ExprError(); 13145 } 13146 } 13147 13148 if (!IsMS && !E->isTypeDependent() && 13149 !Context.hasSameType(VaListType, E->getType())) 13150 return ExprError(Diag(E->getLocStart(), 13151 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13152 << OrigExpr->getType() << E->getSourceRange()); 13153 13154 if (!TInfo->getType()->isDependentType()) { 13155 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13156 diag::err_second_parameter_to_va_arg_incomplete, 13157 TInfo->getTypeLoc())) 13158 return ExprError(); 13159 13160 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13161 TInfo->getType(), 13162 diag::err_second_parameter_to_va_arg_abstract, 13163 TInfo->getTypeLoc())) 13164 return ExprError(); 13165 13166 if (!TInfo->getType().isPODType(Context)) { 13167 Diag(TInfo->getTypeLoc().getBeginLoc(), 13168 TInfo->getType()->isObjCLifetimeType() 13169 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13170 : diag::warn_second_parameter_to_va_arg_not_pod) 13171 << TInfo->getType() 13172 << TInfo->getTypeLoc().getSourceRange(); 13173 } 13174 13175 // Check for va_arg where arguments of the given type will be promoted 13176 // (i.e. this va_arg is guaranteed to have undefined behavior). 13177 QualType PromoteType; 13178 if (TInfo->getType()->isPromotableIntegerType()) { 13179 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13180 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13181 PromoteType = QualType(); 13182 } 13183 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13184 PromoteType = Context.DoubleTy; 13185 if (!PromoteType.isNull()) 13186 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13187 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13188 << TInfo->getType() 13189 << PromoteType 13190 << TInfo->getTypeLoc().getSourceRange()); 13191 } 13192 13193 QualType T = TInfo->getType().getNonLValueExprType(Context); 13194 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13195 } 13196 13197 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13198 // The type of __null will be int or long, depending on the size of 13199 // pointers on the target. 13200 QualType Ty; 13201 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13202 if (pw == Context.getTargetInfo().getIntWidth()) 13203 Ty = Context.IntTy; 13204 else if (pw == Context.getTargetInfo().getLongWidth()) 13205 Ty = Context.LongTy; 13206 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13207 Ty = Context.LongLongTy; 13208 else { 13209 llvm_unreachable("I don't know size of pointer!"); 13210 } 13211 13212 return new (Context) GNUNullExpr(Ty, TokenLoc); 13213 } 13214 13215 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13216 bool Diagnose) { 13217 if (!getLangOpts().ObjC1) 13218 return false; 13219 13220 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13221 if (!PT) 13222 return false; 13223 13224 if (!PT->isObjCIdType()) { 13225 // Check if the destination is the 'NSString' interface. 13226 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13227 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13228 return false; 13229 } 13230 13231 // Ignore any parens, implicit casts (should only be 13232 // array-to-pointer decays), and not-so-opaque values. The last is 13233 // important for making this trigger for property assignments. 13234 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13235 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13236 if (OV->getSourceExpr()) 13237 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13238 13239 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13240 if (!SL || !SL->isAscii()) 13241 return false; 13242 if (Diagnose) { 13243 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13244 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13245 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13246 } 13247 return true; 13248 } 13249 13250 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13251 const Expr *SrcExpr) { 13252 if (!DstType->isFunctionPointerType() || 13253 !SrcExpr->getType()->isFunctionType()) 13254 return false; 13255 13256 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13257 if (!DRE) 13258 return false; 13259 13260 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13261 if (!FD) 13262 return false; 13263 13264 return !S.checkAddressOfFunctionIsAvailable(FD, 13265 /*Complain=*/true, 13266 SrcExpr->getLocStart()); 13267 } 13268 13269 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13270 SourceLocation Loc, 13271 QualType DstType, QualType SrcType, 13272 Expr *SrcExpr, AssignmentAction Action, 13273 bool *Complained) { 13274 if (Complained) 13275 *Complained = false; 13276 13277 // Decode the result (notice that AST's are still created for extensions). 13278 bool CheckInferredResultType = false; 13279 bool isInvalid = false; 13280 unsigned DiagKind = 0; 13281 FixItHint Hint; 13282 ConversionFixItGenerator ConvHints; 13283 bool MayHaveConvFixit = false; 13284 bool MayHaveFunctionDiff = false; 13285 const ObjCInterfaceDecl *IFace = nullptr; 13286 const ObjCProtocolDecl *PDecl = nullptr; 13287 13288 switch (ConvTy) { 13289 case Compatible: 13290 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13291 return false; 13292 13293 case PointerToInt: 13294 DiagKind = diag::ext_typecheck_convert_pointer_int; 13295 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13296 MayHaveConvFixit = true; 13297 break; 13298 case IntToPointer: 13299 DiagKind = diag::ext_typecheck_convert_int_pointer; 13300 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13301 MayHaveConvFixit = true; 13302 break; 13303 case IncompatiblePointer: 13304 if (Action == AA_Passing_CFAudited) 13305 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13306 else if (SrcType->isFunctionPointerType() && 13307 DstType->isFunctionPointerType()) 13308 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13309 else 13310 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13311 13312 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13313 SrcType->isObjCObjectPointerType(); 13314 if (Hint.isNull() && !CheckInferredResultType) { 13315 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13316 } 13317 else if (CheckInferredResultType) { 13318 SrcType = SrcType.getUnqualifiedType(); 13319 DstType = DstType.getUnqualifiedType(); 13320 } 13321 MayHaveConvFixit = true; 13322 break; 13323 case IncompatiblePointerSign: 13324 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13325 break; 13326 case FunctionVoidPointer: 13327 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13328 break; 13329 case IncompatiblePointerDiscardsQualifiers: { 13330 // Perform array-to-pointer decay if necessary. 13331 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13332 13333 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13334 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13335 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13336 DiagKind = diag::err_typecheck_incompatible_address_space; 13337 break; 13338 13339 13340 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13341 DiagKind = diag::err_typecheck_incompatible_ownership; 13342 break; 13343 } 13344 13345 llvm_unreachable("unknown error case for discarding qualifiers!"); 13346 // fallthrough 13347 } 13348 case CompatiblePointerDiscardsQualifiers: 13349 // If the qualifiers lost were because we were applying the 13350 // (deprecated) C++ conversion from a string literal to a char* 13351 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13352 // Ideally, this check would be performed in 13353 // checkPointerTypesForAssignment. However, that would require a 13354 // bit of refactoring (so that the second argument is an 13355 // expression, rather than a type), which should be done as part 13356 // of a larger effort to fix checkPointerTypesForAssignment for 13357 // C++ semantics. 13358 if (getLangOpts().CPlusPlus && 13359 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13360 return false; 13361 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13362 break; 13363 case IncompatibleNestedPointerQualifiers: 13364 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13365 break; 13366 case IntToBlockPointer: 13367 DiagKind = diag::err_int_to_block_pointer; 13368 break; 13369 case IncompatibleBlockPointer: 13370 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13371 break; 13372 case IncompatibleObjCQualifiedId: { 13373 if (SrcType->isObjCQualifiedIdType()) { 13374 const ObjCObjectPointerType *srcOPT = 13375 SrcType->getAs<ObjCObjectPointerType>(); 13376 for (auto *srcProto : srcOPT->quals()) { 13377 PDecl = srcProto; 13378 break; 13379 } 13380 if (const ObjCInterfaceType *IFaceT = 13381 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13382 IFace = IFaceT->getDecl(); 13383 } 13384 else if (DstType->isObjCQualifiedIdType()) { 13385 const ObjCObjectPointerType *dstOPT = 13386 DstType->getAs<ObjCObjectPointerType>(); 13387 for (auto *dstProto : dstOPT->quals()) { 13388 PDecl = dstProto; 13389 break; 13390 } 13391 if (const ObjCInterfaceType *IFaceT = 13392 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13393 IFace = IFaceT->getDecl(); 13394 } 13395 DiagKind = diag::warn_incompatible_qualified_id; 13396 break; 13397 } 13398 case IncompatibleVectors: 13399 DiagKind = diag::warn_incompatible_vectors; 13400 break; 13401 case IncompatibleObjCWeakRef: 13402 DiagKind = diag::err_arc_weak_unavailable_assign; 13403 break; 13404 case Incompatible: 13405 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13406 if (Complained) 13407 *Complained = true; 13408 return true; 13409 } 13410 13411 DiagKind = diag::err_typecheck_convert_incompatible; 13412 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13413 MayHaveConvFixit = true; 13414 isInvalid = true; 13415 MayHaveFunctionDiff = true; 13416 break; 13417 } 13418 13419 QualType FirstType, SecondType; 13420 switch (Action) { 13421 case AA_Assigning: 13422 case AA_Initializing: 13423 // The destination type comes first. 13424 FirstType = DstType; 13425 SecondType = SrcType; 13426 break; 13427 13428 case AA_Returning: 13429 case AA_Passing: 13430 case AA_Passing_CFAudited: 13431 case AA_Converting: 13432 case AA_Sending: 13433 case AA_Casting: 13434 // The source type comes first. 13435 FirstType = SrcType; 13436 SecondType = DstType; 13437 break; 13438 } 13439 13440 PartialDiagnostic FDiag = PDiag(DiagKind); 13441 if (Action == AA_Passing_CFAudited) 13442 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13443 else 13444 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13445 13446 // If we can fix the conversion, suggest the FixIts. 13447 assert(ConvHints.isNull() || Hint.isNull()); 13448 if (!ConvHints.isNull()) { 13449 for (FixItHint &H : ConvHints.Hints) 13450 FDiag << H; 13451 } else { 13452 FDiag << Hint; 13453 } 13454 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13455 13456 if (MayHaveFunctionDiff) 13457 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13458 13459 Diag(Loc, FDiag); 13460 if (DiagKind == diag::warn_incompatible_qualified_id && 13461 PDecl && IFace && !IFace->hasDefinition()) 13462 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13463 << IFace->getName() << PDecl->getName(); 13464 13465 if (SecondType == Context.OverloadTy) 13466 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13467 FirstType, /*TakingAddress=*/true); 13468 13469 if (CheckInferredResultType) 13470 EmitRelatedResultTypeNote(SrcExpr); 13471 13472 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13473 EmitRelatedResultTypeNoteForReturn(DstType); 13474 13475 if (Complained) 13476 *Complained = true; 13477 return isInvalid; 13478 } 13479 13480 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13481 llvm::APSInt *Result) { 13482 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13483 public: 13484 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13485 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13486 } 13487 } Diagnoser; 13488 13489 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13490 } 13491 13492 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13493 llvm::APSInt *Result, 13494 unsigned DiagID, 13495 bool AllowFold) { 13496 class IDDiagnoser : public VerifyICEDiagnoser { 13497 unsigned DiagID; 13498 13499 public: 13500 IDDiagnoser(unsigned DiagID) 13501 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13502 13503 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13504 S.Diag(Loc, DiagID) << SR; 13505 } 13506 } Diagnoser(DiagID); 13507 13508 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13509 } 13510 13511 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13512 SourceRange SR) { 13513 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13514 } 13515 13516 ExprResult 13517 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13518 VerifyICEDiagnoser &Diagnoser, 13519 bool AllowFold) { 13520 SourceLocation DiagLoc = E->getLocStart(); 13521 13522 if (getLangOpts().CPlusPlus11) { 13523 // C++11 [expr.const]p5: 13524 // If an expression of literal class type is used in a context where an 13525 // integral constant expression is required, then that class type shall 13526 // have a single non-explicit conversion function to an integral or 13527 // unscoped enumeration type 13528 ExprResult Converted; 13529 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13530 public: 13531 CXX11ConvertDiagnoser(bool Silent) 13532 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13533 Silent, true) {} 13534 13535 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13536 QualType T) override { 13537 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13538 } 13539 13540 SemaDiagnosticBuilder diagnoseIncomplete( 13541 Sema &S, SourceLocation Loc, QualType T) override { 13542 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13543 } 13544 13545 SemaDiagnosticBuilder diagnoseExplicitConv( 13546 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13547 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13548 } 13549 13550 SemaDiagnosticBuilder noteExplicitConv( 13551 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13552 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13553 << ConvTy->isEnumeralType() << ConvTy; 13554 } 13555 13556 SemaDiagnosticBuilder diagnoseAmbiguous( 13557 Sema &S, SourceLocation Loc, QualType T) override { 13558 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13559 } 13560 13561 SemaDiagnosticBuilder noteAmbiguous( 13562 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13563 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13564 << ConvTy->isEnumeralType() << ConvTy; 13565 } 13566 13567 SemaDiagnosticBuilder diagnoseConversion( 13568 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13569 llvm_unreachable("conversion functions are permitted"); 13570 } 13571 } ConvertDiagnoser(Diagnoser.Suppress); 13572 13573 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13574 ConvertDiagnoser); 13575 if (Converted.isInvalid()) 13576 return Converted; 13577 E = Converted.get(); 13578 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13579 return ExprError(); 13580 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13581 // An ICE must be of integral or unscoped enumeration type. 13582 if (!Diagnoser.Suppress) 13583 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13584 return ExprError(); 13585 } 13586 13587 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13588 // in the non-ICE case. 13589 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13590 if (Result) 13591 *Result = E->EvaluateKnownConstInt(Context); 13592 return E; 13593 } 13594 13595 Expr::EvalResult EvalResult; 13596 SmallVector<PartialDiagnosticAt, 8> Notes; 13597 EvalResult.Diag = &Notes; 13598 13599 // Try to evaluate the expression, and produce diagnostics explaining why it's 13600 // not a constant expression as a side-effect. 13601 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13602 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13603 13604 // In C++11, we can rely on diagnostics being produced for any expression 13605 // which is not a constant expression. If no diagnostics were produced, then 13606 // this is a constant expression. 13607 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13608 if (Result) 13609 *Result = EvalResult.Val.getInt(); 13610 return E; 13611 } 13612 13613 // If our only note is the usual "invalid subexpression" note, just point 13614 // the caret at its location rather than producing an essentially 13615 // redundant note. 13616 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13617 diag::note_invalid_subexpr_in_const_expr) { 13618 DiagLoc = Notes[0].first; 13619 Notes.clear(); 13620 } 13621 13622 if (!Folded || !AllowFold) { 13623 if (!Diagnoser.Suppress) { 13624 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13625 for (const PartialDiagnosticAt &Note : Notes) 13626 Diag(Note.first, Note.second); 13627 } 13628 13629 return ExprError(); 13630 } 13631 13632 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13633 for (const PartialDiagnosticAt &Note : Notes) 13634 Diag(Note.first, Note.second); 13635 13636 if (Result) 13637 *Result = EvalResult.Val.getInt(); 13638 return E; 13639 } 13640 13641 namespace { 13642 // Handle the case where we conclude a expression which we speculatively 13643 // considered to be unevaluated is actually evaluated. 13644 class TransformToPE : public TreeTransform<TransformToPE> { 13645 typedef TreeTransform<TransformToPE> BaseTransform; 13646 13647 public: 13648 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13649 13650 // Make sure we redo semantic analysis 13651 bool AlwaysRebuild() { return true; } 13652 13653 // Make sure we handle LabelStmts correctly. 13654 // FIXME: This does the right thing, but maybe we need a more general 13655 // fix to TreeTransform? 13656 StmtResult TransformLabelStmt(LabelStmt *S) { 13657 S->getDecl()->setStmt(nullptr); 13658 return BaseTransform::TransformLabelStmt(S); 13659 } 13660 13661 // We need to special-case DeclRefExprs referring to FieldDecls which 13662 // are not part of a member pointer formation; normal TreeTransforming 13663 // doesn't catch this case because of the way we represent them in the AST. 13664 // FIXME: This is a bit ugly; is it really the best way to handle this 13665 // case? 13666 // 13667 // Error on DeclRefExprs referring to FieldDecls. 13668 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13669 if (isa<FieldDecl>(E->getDecl()) && 13670 !SemaRef.isUnevaluatedContext()) 13671 return SemaRef.Diag(E->getLocation(), 13672 diag::err_invalid_non_static_member_use) 13673 << E->getDecl() << E->getSourceRange(); 13674 13675 return BaseTransform::TransformDeclRefExpr(E); 13676 } 13677 13678 // Exception: filter out member pointer formation 13679 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13680 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13681 return E; 13682 13683 return BaseTransform::TransformUnaryOperator(E); 13684 } 13685 13686 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13687 // Lambdas never need to be transformed. 13688 return E; 13689 } 13690 }; 13691 } 13692 13693 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13694 assert(isUnevaluatedContext() && 13695 "Should only transform unevaluated expressions"); 13696 ExprEvalContexts.back().Context = 13697 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13698 if (isUnevaluatedContext()) 13699 return E; 13700 return TransformToPE(*this).TransformExpr(E); 13701 } 13702 13703 void 13704 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13705 Decl *LambdaContextDecl, 13706 bool IsDecltype) { 13707 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13708 LambdaContextDecl, IsDecltype); 13709 Cleanup.reset(); 13710 if (!MaybeODRUseExprs.empty()) 13711 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13712 } 13713 13714 void 13715 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13716 ReuseLambdaContextDecl_t, 13717 bool IsDecltype) { 13718 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13719 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13720 } 13721 13722 void Sema::PopExpressionEvaluationContext() { 13723 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13724 unsigned NumTypos = Rec.NumTypos; 13725 13726 if (!Rec.Lambdas.empty()) { 13727 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13728 unsigned D; 13729 if (Rec.isUnevaluated()) { 13730 // C++11 [expr.prim.lambda]p2: 13731 // A lambda-expression shall not appear in an unevaluated operand 13732 // (Clause 5). 13733 D = diag::err_lambda_unevaluated_operand; 13734 } else { 13735 // C++1y [expr.const]p2: 13736 // A conditional-expression e is a core constant expression unless the 13737 // evaluation of e, following the rules of the abstract machine, would 13738 // evaluate [...] a lambda-expression. 13739 D = diag::err_lambda_in_constant_expression; 13740 } 13741 13742 // C++1z allows lambda expressions as core constant expressions. 13743 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13744 // 1607) from appearing within template-arguments and array-bounds that 13745 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13746 // unevaluated contexts) might lift some of these restrictions in a 13747 // future version. 13748 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 13749 for (const auto *L : Rec.Lambdas) 13750 Diag(L->getLocStart(), D); 13751 } else { 13752 // Mark the capture expressions odr-used. This was deferred 13753 // during lambda expression creation. 13754 for (auto *Lambda : Rec.Lambdas) { 13755 for (auto *C : Lambda->capture_inits()) 13756 MarkDeclarationsReferencedInExpr(C); 13757 } 13758 } 13759 } 13760 13761 // When are coming out of an unevaluated context, clear out any 13762 // temporaries that we may have created as part of the evaluation of 13763 // the expression in that context: they aren't relevant because they 13764 // will never be constructed. 13765 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13766 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13767 ExprCleanupObjects.end()); 13768 Cleanup = Rec.ParentCleanup; 13769 CleanupVarDeclMarking(); 13770 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13771 // Otherwise, merge the contexts together. 13772 } else { 13773 Cleanup.mergeFrom(Rec.ParentCleanup); 13774 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13775 Rec.SavedMaybeODRUseExprs.end()); 13776 } 13777 13778 // Pop the current expression evaluation context off the stack. 13779 ExprEvalContexts.pop_back(); 13780 13781 if (!ExprEvalContexts.empty()) 13782 ExprEvalContexts.back().NumTypos += NumTypos; 13783 else 13784 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13785 "last ExpressionEvaluationContextRecord"); 13786 } 13787 13788 void Sema::DiscardCleanupsInEvaluationContext() { 13789 ExprCleanupObjects.erase( 13790 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13791 ExprCleanupObjects.end()); 13792 Cleanup.reset(); 13793 MaybeODRUseExprs.clear(); 13794 } 13795 13796 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13797 if (!E->getType()->isVariablyModifiedType()) 13798 return E; 13799 return TransformToPotentiallyEvaluated(E); 13800 } 13801 13802 /// Are we within a context in which some evaluation could be performed (be it 13803 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13804 /// captured by C++'s idea of an "unevaluated context". 13805 static bool isEvaluatableContext(Sema &SemaRef) { 13806 switch (SemaRef.ExprEvalContexts.back().Context) { 13807 case Sema::ExpressionEvaluationContext::Unevaluated: 13808 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13809 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13810 // Expressions in this context are never evaluated. 13811 return false; 13812 13813 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13814 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13815 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13816 // Expressions in this context could be evaluated. 13817 return true; 13818 13819 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13820 // Referenced declarations will only be used if the construct in the 13821 // containing expression is used, at which point we'll be given another 13822 // turn to mark them. 13823 return false; 13824 } 13825 llvm_unreachable("Invalid context"); 13826 } 13827 13828 /// Are we within a context in which references to resolved functions or to 13829 /// variables result in odr-use? 13830 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13831 // An expression in a template is not really an expression until it's been 13832 // instantiated, so it doesn't trigger odr-use. 13833 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13834 return false; 13835 13836 switch (SemaRef.ExprEvalContexts.back().Context) { 13837 case Sema::ExpressionEvaluationContext::Unevaluated: 13838 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13839 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13840 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13841 return false; 13842 13843 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13844 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13845 return true; 13846 13847 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13848 return false; 13849 } 13850 llvm_unreachable("Invalid context"); 13851 } 13852 13853 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13854 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13855 return Func->isConstexpr() && 13856 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13857 } 13858 13859 /// \brief Mark a function referenced, and check whether it is odr-used 13860 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13861 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13862 bool MightBeOdrUse) { 13863 assert(Func && "No function?"); 13864 13865 Func->setReferenced(); 13866 13867 // C++11 [basic.def.odr]p3: 13868 // A function whose name appears as a potentially-evaluated expression is 13869 // odr-used if it is the unique lookup result or the selected member of a 13870 // set of overloaded functions [...]. 13871 // 13872 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13873 // can just check that here. 13874 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13875 13876 // Determine whether we require a function definition to exist, per 13877 // C++11 [temp.inst]p3: 13878 // Unless a function template specialization has been explicitly 13879 // instantiated or explicitly specialized, the function template 13880 // specialization is implicitly instantiated when the specialization is 13881 // referenced in a context that requires a function definition to exist. 13882 // 13883 // That is either when this is an odr-use, or when a usage of a constexpr 13884 // function occurs within an evaluatable context. 13885 bool NeedDefinition = 13886 OdrUse || (isEvaluatableContext(*this) && 13887 isImplicitlyDefinableConstexprFunction(Func)); 13888 13889 // C++14 [temp.expl.spec]p6: 13890 // If a template [...] is explicitly specialized then that specialization 13891 // shall be declared before the first use of that specialization that would 13892 // cause an implicit instantiation to take place, in every translation unit 13893 // in which such a use occurs 13894 if (NeedDefinition && 13895 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13896 Func->getMemberSpecializationInfo())) 13897 checkSpecializationVisibility(Loc, Func); 13898 13899 // C++14 [except.spec]p17: 13900 // An exception-specification is considered to be needed when: 13901 // - the function is odr-used or, if it appears in an unevaluated operand, 13902 // would be odr-used if the expression were potentially-evaluated; 13903 // 13904 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13905 // function is a pure virtual function we're calling, and in that case the 13906 // function was selected by overload resolution and we need to resolve its 13907 // exception specification for a different reason. 13908 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13909 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13910 ResolveExceptionSpec(Loc, FPT); 13911 13912 // If we don't need to mark the function as used, and we don't need to 13913 // try to provide a definition, there's nothing more to do. 13914 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13915 (!NeedDefinition || Func->getBody())) 13916 return; 13917 13918 // Note that this declaration has been used. 13919 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13920 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13921 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13922 if (Constructor->isDefaultConstructor()) { 13923 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13924 return; 13925 DefineImplicitDefaultConstructor(Loc, Constructor); 13926 } else if (Constructor->isCopyConstructor()) { 13927 DefineImplicitCopyConstructor(Loc, Constructor); 13928 } else if (Constructor->isMoveConstructor()) { 13929 DefineImplicitMoveConstructor(Loc, Constructor); 13930 } 13931 } else if (Constructor->getInheritedConstructor()) { 13932 DefineInheritingConstructor(Loc, Constructor); 13933 } 13934 } else if (CXXDestructorDecl *Destructor = 13935 dyn_cast<CXXDestructorDecl>(Func)) { 13936 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13937 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13938 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13939 return; 13940 DefineImplicitDestructor(Loc, Destructor); 13941 } 13942 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13943 MarkVTableUsed(Loc, Destructor->getParent()); 13944 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13945 if (MethodDecl->isOverloadedOperator() && 13946 MethodDecl->getOverloadedOperator() == OO_Equal) { 13947 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13948 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13949 if (MethodDecl->isCopyAssignmentOperator()) 13950 DefineImplicitCopyAssignment(Loc, MethodDecl); 13951 else if (MethodDecl->isMoveAssignmentOperator()) 13952 DefineImplicitMoveAssignment(Loc, MethodDecl); 13953 } 13954 } else if (isa<CXXConversionDecl>(MethodDecl) && 13955 MethodDecl->getParent()->isLambda()) { 13956 CXXConversionDecl *Conversion = 13957 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13958 if (Conversion->isLambdaToBlockPointerConversion()) 13959 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13960 else 13961 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13962 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13963 MarkVTableUsed(Loc, MethodDecl->getParent()); 13964 } 13965 13966 // Recursive functions should be marked when used from another function. 13967 // FIXME: Is this really right? 13968 if (CurContext == Func) return; 13969 13970 // Implicit instantiation of function templates and member functions of 13971 // class templates. 13972 if (Func->isImplicitlyInstantiable()) { 13973 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 13974 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 13975 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 13976 if (FirstInstantiation) { 13977 PointOfInstantiation = Loc; 13978 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 13979 } else if (TSK != TSK_ImplicitInstantiation) { 13980 // Use the point of use as the point of instantiation, instead of the 13981 // point of explicit instantiation (which we track as the actual point of 13982 // instantiation). This gives better backtraces in diagnostics. 13983 PointOfInstantiation = Loc; 13984 } 13985 13986 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 13987 Func->isConstexpr()) { 13988 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13989 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13990 CodeSynthesisContexts.size()) 13991 PendingLocalImplicitInstantiations.push_back( 13992 std::make_pair(Func, PointOfInstantiation)); 13993 else if (Func->isConstexpr()) 13994 // Do not defer instantiations of constexpr functions, to avoid the 13995 // expression evaluator needing to call back into Sema if it sees a 13996 // call to such a function. 13997 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13998 else { 13999 Func->setInstantiationIsPending(true); 14000 PendingInstantiations.push_back(std::make_pair(Func, 14001 PointOfInstantiation)); 14002 // Notify the consumer that a function was implicitly instantiated. 14003 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14004 } 14005 } 14006 } else { 14007 // Walk redefinitions, as some of them may be instantiable. 14008 for (auto i : Func->redecls()) { 14009 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14010 MarkFunctionReferenced(Loc, i, OdrUse); 14011 } 14012 } 14013 14014 if (!OdrUse) return; 14015 14016 // Keep track of used but undefined functions. 14017 if (!Func->isDefined()) { 14018 if (mightHaveNonExternalLinkage(Func)) 14019 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14020 else if (Func->getMostRecentDecl()->isInlined() && 14021 !LangOpts.GNUInline && 14022 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14023 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14024 else if (isExternalWithNoLinkageType(Func)) 14025 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14026 } 14027 14028 Func->markUsed(Context); 14029 } 14030 14031 static void 14032 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14033 ValueDecl *var, DeclContext *DC) { 14034 DeclContext *VarDC = var->getDeclContext(); 14035 14036 // If the parameter still belongs to the translation unit, then 14037 // we're actually just using one parameter in the declaration of 14038 // the next. 14039 if (isa<ParmVarDecl>(var) && 14040 isa<TranslationUnitDecl>(VarDC)) 14041 return; 14042 14043 // For C code, don't diagnose about capture if we're not actually in code 14044 // right now; it's impossible to write a non-constant expression outside of 14045 // function context, so we'll get other (more useful) diagnostics later. 14046 // 14047 // For C++, things get a bit more nasty... it would be nice to suppress this 14048 // diagnostic for certain cases like using a local variable in an array bound 14049 // for a member of a local class, but the correct predicate is not obvious. 14050 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14051 return; 14052 14053 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14054 unsigned ContextKind = 3; // unknown 14055 if (isa<CXXMethodDecl>(VarDC) && 14056 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14057 ContextKind = 2; 14058 } else if (isa<FunctionDecl>(VarDC)) { 14059 ContextKind = 0; 14060 } else if (isa<BlockDecl>(VarDC)) { 14061 ContextKind = 1; 14062 } 14063 14064 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14065 << var << ValueKind << ContextKind << VarDC; 14066 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14067 << var; 14068 14069 // FIXME: Add additional diagnostic info about class etc. which prevents 14070 // capture. 14071 } 14072 14073 14074 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14075 bool &SubCapturesAreNested, 14076 QualType &CaptureType, 14077 QualType &DeclRefType) { 14078 // Check whether we've already captured it. 14079 if (CSI->CaptureMap.count(Var)) { 14080 // If we found a capture, any subcaptures are nested. 14081 SubCapturesAreNested = true; 14082 14083 // Retrieve the capture type for this variable. 14084 CaptureType = CSI->getCapture(Var).getCaptureType(); 14085 14086 // Compute the type of an expression that refers to this variable. 14087 DeclRefType = CaptureType.getNonReferenceType(); 14088 14089 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14090 // are mutable in the sense that user can change their value - they are 14091 // private instances of the captured declarations. 14092 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14093 if (Cap.isCopyCapture() && 14094 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14095 !(isa<CapturedRegionScopeInfo>(CSI) && 14096 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14097 DeclRefType.addConst(); 14098 return true; 14099 } 14100 return false; 14101 } 14102 14103 // Only block literals, captured statements, and lambda expressions can 14104 // capture; other scopes don't work. 14105 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14106 SourceLocation Loc, 14107 const bool Diagnose, Sema &S) { 14108 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14109 return getLambdaAwareParentOfDeclContext(DC); 14110 else if (Var->hasLocalStorage()) { 14111 if (Diagnose) 14112 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14113 } 14114 return nullptr; 14115 } 14116 14117 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14118 // certain types of variables (unnamed, variably modified types etc.) 14119 // so check for eligibility. 14120 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14121 SourceLocation Loc, 14122 const bool Diagnose, Sema &S) { 14123 14124 bool IsBlock = isa<BlockScopeInfo>(CSI); 14125 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14126 14127 // Lambdas are not allowed to capture unnamed variables 14128 // (e.g. anonymous unions). 14129 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14130 // assuming that's the intent. 14131 if (IsLambda && !Var->getDeclName()) { 14132 if (Diagnose) { 14133 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14134 S.Diag(Var->getLocation(), diag::note_declared_at); 14135 } 14136 return false; 14137 } 14138 14139 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14140 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14141 if (Diagnose) { 14142 S.Diag(Loc, diag::err_ref_vm_type); 14143 S.Diag(Var->getLocation(), diag::note_previous_decl) 14144 << Var->getDeclName(); 14145 } 14146 return false; 14147 } 14148 // Prohibit structs with flexible array members too. 14149 // We cannot capture what is in the tail end of the struct. 14150 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14151 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14152 if (Diagnose) { 14153 if (IsBlock) 14154 S.Diag(Loc, diag::err_ref_flexarray_type); 14155 else 14156 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14157 << Var->getDeclName(); 14158 S.Diag(Var->getLocation(), diag::note_previous_decl) 14159 << Var->getDeclName(); 14160 } 14161 return false; 14162 } 14163 } 14164 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14165 // Lambdas and captured statements are not allowed to capture __block 14166 // variables; they don't support the expected semantics. 14167 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14168 if (Diagnose) { 14169 S.Diag(Loc, diag::err_capture_block_variable) 14170 << Var->getDeclName() << !IsLambda; 14171 S.Diag(Var->getLocation(), diag::note_previous_decl) 14172 << Var->getDeclName(); 14173 } 14174 return false; 14175 } 14176 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14177 if (S.getLangOpts().OpenCL && IsBlock && 14178 Var->getType()->isBlockPointerType()) { 14179 if (Diagnose) 14180 S.Diag(Loc, diag::err_opencl_block_ref_block); 14181 return false; 14182 } 14183 14184 return true; 14185 } 14186 14187 // Returns true if the capture by block was successful. 14188 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14189 SourceLocation Loc, 14190 const bool BuildAndDiagnose, 14191 QualType &CaptureType, 14192 QualType &DeclRefType, 14193 const bool Nested, 14194 Sema &S) { 14195 Expr *CopyExpr = nullptr; 14196 bool ByRef = false; 14197 14198 // Blocks are not allowed to capture arrays. 14199 if (CaptureType->isArrayType()) { 14200 if (BuildAndDiagnose) { 14201 S.Diag(Loc, diag::err_ref_array_type); 14202 S.Diag(Var->getLocation(), diag::note_previous_decl) 14203 << Var->getDeclName(); 14204 } 14205 return false; 14206 } 14207 14208 // Forbid the block-capture of autoreleasing variables. 14209 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14210 if (BuildAndDiagnose) { 14211 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14212 << /*block*/ 0; 14213 S.Diag(Var->getLocation(), diag::note_previous_decl) 14214 << Var->getDeclName(); 14215 } 14216 return false; 14217 } 14218 14219 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14220 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14221 // This function finds out whether there is an AttributedType of kind 14222 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14223 // attr_objc_ownership implies __autoreleasing was explicitly specified 14224 // rather than being added implicitly by the compiler. 14225 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14226 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14227 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14228 return true; 14229 14230 // Peel off AttributedTypes that are not of kind objc_ownership. 14231 Ty = AttrTy->getModifiedType(); 14232 } 14233 14234 return false; 14235 }; 14236 14237 QualType PointeeTy = PT->getPointeeType(); 14238 14239 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14240 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14241 !IsObjCOwnershipAttributedType(PointeeTy)) { 14242 if (BuildAndDiagnose) { 14243 SourceLocation VarLoc = Var->getLocation(); 14244 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14245 { 14246 auto AddAutoreleaseNote = 14247 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14248 // Provide a fix-it for the '__autoreleasing' keyword at the 14249 // appropriate location in the variable's type. 14250 if (const auto *TSI = Var->getTypeSourceInfo()) { 14251 PointerTypeLoc PTL = 14252 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14253 if (PTL) { 14254 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14255 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14256 S.getLangOpts()); 14257 if (Loc.isValid()) { 14258 StringRef CharAtLoc = Lexer::getSourceText( 14259 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14260 S.getSourceManager(), S.getLangOpts()); 14261 AddAutoreleaseNote << FixItHint::CreateInsertion( 14262 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14263 ? " __autoreleasing " 14264 : " __autoreleasing"); 14265 } 14266 } 14267 } 14268 } 14269 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14270 } 14271 } 14272 } 14273 14274 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14275 if (HasBlocksAttr || CaptureType->isReferenceType() || 14276 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14277 // Block capture by reference does not change the capture or 14278 // declaration reference types. 14279 ByRef = true; 14280 } else { 14281 // Block capture by copy introduces 'const'. 14282 CaptureType = CaptureType.getNonReferenceType().withConst(); 14283 DeclRefType = CaptureType; 14284 14285 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14286 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14287 // The capture logic needs the destructor, so make sure we mark it. 14288 // Usually this is unnecessary because most local variables have 14289 // their destructors marked at declaration time, but parameters are 14290 // an exception because it's technically only the call site that 14291 // actually requires the destructor. 14292 if (isa<ParmVarDecl>(Var)) 14293 S.FinalizeVarWithDestructor(Var, Record); 14294 14295 // Enter a new evaluation context to insulate the copy 14296 // full-expression. 14297 EnterExpressionEvaluationContext scope( 14298 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14299 14300 // According to the blocks spec, the capture of a variable from 14301 // the stack requires a const copy constructor. This is not true 14302 // of the copy/move done to move a __block variable to the heap. 14303 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14304 DeclRefType.withConst(), 14305 VK_LValue, Loc); 14306 14307 ExprResult Result 14308 = S.PerformCopyInitialization( 14309 InitializedEntity::InitializeBlock(Var->getLocation(), 14310 CaptureType, false), 14311 Loc, DeclRef); 14312 14313 // Build a full-expression copy expression if initialization 14314 // succeeded and used a non-trivial constructor. Recover from 14315 // errors by pretending that the copy isn't necessary. 14316 if (!Result.isInvalid() && 14317 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14318 ->isTrivial()) { 14319 Result = S.MaybeCreateExprWithCleanups(Result); 14320 CopyExpr = Result.get(); 14321 } 14322 } 14323 } 14324 } 14325 14326 // Actually capture the variable. 14327 if (BuildAndDiagnose) 14328 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14329 SourceLocation(), CaptureType, CopyExpr); 14330 14331 return true; 14332 14333 } 14334 14335 14336 /// \brief Capture the given variable in the captured region. 14337 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14338 VarDecl *Var, 14339 SourceLocation Loc, 14340 const bool BuildAndDiagnose, 14341 QualType &CaptureType, 14342 QualType &DeclRefType, 14343 const bool RefersToCapturedVariable, 14344 Sema &S) { 14345 // By default, capture variables by reference. 14346 bool ByRef = true; 14347 // Using an LValue reference type is consistent with Lambdas (see below). 14348 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14349 if (S.IsOpenMPCapturedDecl(Var)) { 14350 bool HasConst = DeclRefType.isConstQualified(); 14351 DeclRefType = DeclRefType.getUnqualifiedType(); 14352 // Don't lose diagnostics about assignments to const. 14353 if (HasConst) 14354 DeclRefType.addConst(); 14355 } 14356 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14357 } 14358 14359 if (ByRef) 14360 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14361 else 14362 CaptureType = DeclRefType; 14363 14364 Expr *CopyExpr = nullptr; 14365 if (BuildAndDiagnose) { 14366 // The current implementation assumes that all variables are captured 14367 // by references. Since there is no capture by copy, no expression 14368 // evaluation will be needed. 14369 RecordDecl *RD = RSI->TheRecordDecl; 14370 14371 FieldDecl *Field 14372 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14373 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14374 nullptr, false, ICIS_NoInit); 14375 Field->setImplicit(true); 14376 Field->setAccess(AS_private); 14377 RD->addDecl(Field); 14378 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14379 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14380 14381 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14382 DeclRefType, VK_LValue, Loc); 14383 Var->setReferenced(true); 14384 Var->markUsed(S.Context); 14385 } 14386 14387 // Actually capture the variable. 14388 if (BuildAndDiagnose) 14389 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14390 SourceLocation(), CaptureType, CopyExpr); 14391 14392 14393 return true; 14394 } 14395 14396 /// \brief Create a field within the lambda class for the variable 14397 /// being captured. 14398 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14399 QualType FieldType, QualType DeclRefType, 14400 SourceLocation Loc, 14401 bool RefersToCapturedVariable) { 14402 CXXRecordDecl *Lambda = LSI->Lambda; 14403 14404 // Build the non-static data member. 14405 FieldDecl *Field 14406 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14407 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14408 nullptr, false, ICIS_NoInit); 14409 Field->setImplicit(true); 14410 Field->setAccess(AS_private); 14411 Lambda->addDecl(Field); 14412 } 14413 14414 /// \brief Capture the given variable in the lambda. 14415 static bool captureInLambda(LambdaScopeInfo *LSI, 14416 VarDecl *Var, 14417 SourceLocation Loc, 14418 const bool BuildAndDiagnose, 14419 QualType &CaptureType, 14420 QualType &DeclRefType, 14421 const bool RefersToCapturedVariable, 14422 const Sema::TryCaptureKind Kind, 14423 SourceLocation EllipsisLoc, 14424 const bool IsTopScope, 14425 Sema &S) { 14426 14427 // Determine whether we are capturing by reference or by value. 14428 bool ByRef = false; 14429 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14430 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14431 } else { 14432 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14433 } 14434 14435 // Compute the type of the field that will capture this variable. 14436 if (ByRef) { 14437 // C++11 [expr.prim.lambda]p15: 14438 // An entity is captured by reference if it is implicitly or 14439 // explicitly captured but not captured by copy. It is 14440 // unspecified whether additional unnamed non-static data 14441 // members are declared in the closure type for entities 14442 // captured by reference. 14443 // 14444 // FIXME: It is not clear whether we want to build an lvalue reference 14445 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14446 // to do the former, while EDG does the latter. Core issue 1249 will 14447 // clarify, but for now we follow GCC because it's a more permissive and 14448 // easily defensible position. 14449 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14450 } else { 14451 // C++11 [expr.prim.lambda]p14: 14452 // For each entity captured by copy, an unnamed non-static 14453 // data member is declared in the closure type. The 14454 // declaration order of these members is unspecified. The type 14455 // of such a data member is the type of the corresponding 14456 // captured entity if the entity is not a reference to an 14457 // object, or the referenced type otherwise. [Note: If the 14458 // captured entity is a reference to a function, the 14459 // corresponding data member is also a reference to a 14460 // function. - end note ] 14461 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14462 if (!RefType->getPointeeType()->isFunctionType()) 14463 CaptureType = RefType->getPointeeType(); 14464 } 14465 14466 // Forbid the lambda copy-capture of autoreleasing variables. 14467 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14468 if (BuildAndDiagnose) { 14469 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14470 S.Diag(Var->getLocation(), diag::note_previous_decl) 14471 << Var->getDeclName(); 14472 } 14473 return false; 14474 } 14475 14476 // Make sure that by-copy captures are of a complete and non-abstract type. 14477 if (BuildAndDiagnose) { 14478 if (!CaptureType->isDependentType() && 14479 S.RequireCompleteType(Loc, CaptureType, 14480 diag::err_capture_of_incomplete_type, 14481 Var->getDeclName())) 14482 return false; 14483 14484 if (S.RequireNonAbstractType(Loc, CaptureType, 14485 diag::err_capture_of_abstract_type)) 14486 return false; 14487 } 14488 } 14489 14490 // Capture this variable in the lambda. 14491 if (BuildAndDiagnose) 14492 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14493 RefersToCapturedVariable); 14494 14495 // Compute the type of a reference to this captured variable. 14496 if (ByRef) 14497 DeclRefType = CaptureType.getNonReferenceType(); 14498 else { 14499 // C++ [expr.prim.lambda]p5: 14500 // The closure type for a lambda-expression has a public inline 14501 // function call operator [...]. This function call operator is 14502 // declared const (9.3.1) if and only if the lambda-expression's 14503 // parameter-declaration-clause is not followed by mutable. 14504 DeclRefType = CaptureType.getNonReferenceType(); 14505 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14506 DeclRefType.addConst(); 14507 } 14508 14509 // Add the capture. 14510 if (BuildAndDiagnose) 14511 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14512 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14513 14514 return true; 14515 } 14516 14517 bool Sema::tryCaptureVariable( 14518 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14519 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14520 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14521 // An init-capture is notionally from the context surrounding its 14522 // declaration, but its parent DC is the lambda class. 14523 DeclContext *VarDC = Var->getDeclContext(); 14524 if (Var->isInitCapture()) 14525 VarDC = VarDC->getParent(); 14526 14527 DeclContext *DC = CurContext; 14528 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14529 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14530 // We need to sync up the Declaration Context with the 14531 // FunctionScopeIndexToStopAt 14532 if (FunctionScopeIndexToStopAt) { 14533 unsigned FSIndex = FunctionScopes.size() - 1; 14534 while (FSIndex != MaxFunctionScopesIndex) { 14535 DC = getLambdaAwareParentOfDeclContext(DC); 14536 --FSIndex; 14537 } 14538 } 14539 14540 14541 // If the variable is declared in the current context, there is no need to 14542 // capture it. 14543 if (VarDC == DC) return true; 14544 14545 // Capture global variables if it is required to use private copy of this 14546 // variable. 14547 bool IsGlobal = !Var->hasLocalStorage(); 14548 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14549 return true; 14550 Var = Var->getCanonicalDecl(); 14551 14552 // Walk up the stack to determine whether we can capture the variable, 14553 // performing the "simple" checks that don't depend on type. We stop when 14554 // we've either hit the declared scope of the variable or find an existing 14555 // capture of that variable. We start from the innermost capturing-entity 14556 // (the DC) and ensure that all intervening capturing-entities 14557 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14558 // declcontext can either capture the variable or have already captured 14559 // the variable. 14560 CaptureType = Var->getType(); 14561 DeclRefType = CaptureType.getNonReferenceType(); 14562 bool Nested = false; 14563 bool Explicit = (Kind != TryCapture_Implicit); 14564 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14565 do { 14566 // Only block literals, captured statements, and lambda expressions can 14567 // capture; other scopes don't work. 14568 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14569 ExprLoc, 14570 BuildAndDiagnose, 14571 *this); 14572 // We need to check for the parent *first* because, if we *have* 14573 // private-captured a global variable, we need to recursively capture it in 14574 // intermediate blocks, lambdas, etc. 14575 if (!ParentDC) { 14576 if (IsGlobal) { 14577 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14578 break; 14579 } 14580 return true; 14581 } 14582 14583 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14584 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14585 14586 14587 // Check whether we've already captured it. 14588 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14589 DeclRefType)) { 14590 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14591 break; 14592 } 14593 // If we are instantiating a generic lambda call operator body, 14594 // we do not want to capture new variables. What was captured 14595 // during either a lambdas transformation or initial parsing 14596 // should be used. 14597 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14598 if (BuildAndDiagnose) { 14599 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14600 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14601 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14602 Diag(Var->getLocation(), diag::note_previous_decl) 14603 << Var->getDeclName(); 14604 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14605 } else 14606 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14607 } 14608 return true; 14609 } 14610 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14611 // certain types of variables (unnamed, variably modified types etc.) 14612 // so check for eligibility. 14613 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14614 return true; 14615 14616 // Try to capture variable-length arrays types. 14617 if (Var->getType()->isVariablyModifiedType()) { 14618 // We're going to walk down into the type and look for VLA 14619 // expressions. 14620 QualType QTy = Var->getType(); 14621 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14622 QTy = PVD->getOriginalType(); 14623 captureVariablyModifiedType(Context, QTy, CSI); 14624 } 14625 14626 if (getLangOpts().OpenMP) { 14627 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14628 // OpenMP private variables should not be captured in outer scope, so 14629 // just break here. Similarly, global variables that are captured in a 14630 // target region should not be captured outside the scope of the region. 14631 if (RSI->CapRegionKind == CR_OpenMP) { 14632 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14633 auto IsTargetCap = !IsOpenMPPrivateDecl && 14634 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14635 // When we detect target captures we are looking from inside the 14636 // target region, therefore we need to propagate the capture from the 14637 // enclosing region. Therefore, the capture is not initially nested. 14638 if (IsTargetCap) 14639 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14640 14641 if (IsTargetCap || IsOpenMPPrivateDecl) { 14642 Nested = !IsTargetCap; 14643 DeclRefType = DeclRefType.getUnqualifiedType(); 14644 CaptureType = Context.getLValueReferenceType(DeclRefType); 14645 break; 14646 } 14647 } 14648 } 14649 } 14650 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14651 // No capture-default, and this is not an explicit capture 14652 // so cannot capture this variable. 14653 if (BuildAndDiagnose) { 14654 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14655 Diag(Var->getLocation(), diag::note_previous_decl) 14656 << Var->getDeclName(); 14657 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14658 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14659 diag::note_lambda_decl); 14660 // FIXME: If we error out because an outer lambda can not implicitly 14661 // capture a variable that an inner lambda explicitly captures, we 14662 // should have the inner lambda do the explicit capture - because 14663 // it makes for cleaner diagnostics later. This would purely be done 14664 // so that the diagnostic does not misleadingly claim that a variable 14665 // can not be captured by a lambda implicitly even though it is captured 14666 // explicitly. Suggestion: 14667 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14668 // at the function head 14669 // - cache the StartingDeclContext - this must be a lambda 14670 // - captureInLambda in the innermost lambda the variable. 14671 } 14672 return true; 14673 } 14674 14675 FunctionScopesIndex--; 14676 DC = ParentDC; 14677 Explicit = false; 14678 } while (!VarDC->Equals(DC)); 14679 14680 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14681 // computing the type of the capture at each step, checking type-specific 14682 // requirements, and adding captures if requested. 14683 // If the variable had already been captured previously, we start capturing 14684 // at the lambda nested within that one. 14685 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14686 ++I) { 14687 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14688 14689 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14690 if (!captureInBlock(BSI, Var, ExprLoc, 14691 BuildAndDiagnose, CaptureType, 14692 DeclRefType, Nested, *this)) 14693 return true; 14694 Nested = true; 14695 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14696 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14697 BuildAndDiagnose, CaptureType, 14698 DeclRefType, Nested, *this)) 14699 return true; 14700 Nested = true; 14701 } else { 14702 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14703 if (!captureInLambda(LSI, Var, ExprLoc, 14704 BuildAndDiagnose, CaptureType, 14705 DeclRefType, Nested, Kind, EllipsisLoc, 14706 /*IsTopScope*/I == N - 1, *this)) 14707 return true; 14708 Nested = true; 14709 } 14710 } 14711 return false; 14712 } 14713 14714 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14715 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14716 QualType CaptureType; 14717 QualType DeclRefType; 14718 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14719 /*BuildAndDiagnose=*/true, CaptureType, 14720 DeclRefType, nullptr); 14721 } 14722 14723 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14724 QualType CaptureType; 14725 QualType DeclRefType; 14726 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14727 /*BuildAndDiagnose=*/false, CaptureType, 14728 DeclRefType, nullptr); 14729 } 14730 14731 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14732 QualType CaptureType; 14733 QualType DeclRefType; 14734 14735 // Determine whether we can capture this variable. 14736 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14737 /*BuildAndDiagnose=*/false, CaptureType, 14738 DeclRefType, nullptr)) 14739 return QualType(); 14740 14741 return DeclRefType; 14742 } 14743 14744 14745 14746 // If either the type of the variable or the initializer is dependent, 14747 // return false. Otherwise, determine whether the variable is a constant 14748 // expression. Use this if you need to know if a variable that might or 14749 // might not be dependent is truly a constant expression. 14750 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14751 ASTContext &Context) { 14752 14753 if (Var->getType()->isDependentType()) 14754 return false; 14755 const VarDecl *DefVD = nullptr; 14756 Var->getAnyInitializer(DefVD); 14757 if (!DefVD) 14758 return false; 14759 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14760 Expr *Init = cast<Expr>(Eval->Value); 14761 if (Init->isValueDependent()) 14762 return false; 14763 return IsVariableAConstantExpression(Var, Context); 14764 } 14765 14766 14767 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14768 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14769 // an object that satisfies the requirements for appearing in a 14770 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14771 // is immediately applied." This function handles the lvalue-to-rvalue 14772 // conversion part. 14773 MaybeODRUseExprs.erase(E->IgnoreParens()); 14774 14775 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14776 // to a variable that is a constant expression, and if so, identify it as 14777 // a reference to a variable that does not involve an odr-use of that 14778 // variable. 14779 if (LambdaScopeInfo *LSI = getCurLambda()) { 14780 Expr *SansParensExpr = E->IgnoreParens(); 14781 VarDecl *Var = nullptr; 14782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14783 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14784 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14785 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14786 14787 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14788 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14789 } 14790 } 14791 14792 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14793 Res = CorrectDelayedTyposInExpr(Res); 14794 14795 if (!Res.isUsable()) 14796 return Res; 14797 14798 // If a constant-expression is a reference to a variable where we delay 14799 // deciding whether it is an odr-use, just assume we will apply the 14800 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14801 // (a non-type template argument), we have special handling anyway. 14802 UpdateMarkingForLValueToRValue(Res.get()); 14803 return Res; 14804 } 14805 14806 void Sema::CleanupVarDeclMarking() { 14807 for (Expr *E : MaybeODRUseExprs) { 14808 VarDecl *Var; 14809 SourceLocation Loc; 14810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14811 Var = cast<VarDecl>(DRE->getDecl()); 14812 Loc = DRE->getLocation(); 14813 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14814 Var = cast<VarDecl>(ME->getMemberDecl()); 14815 Loc = ME->getMemberLoc(); 14816 } else { 14817 llvm_unreachable("Unexpected expression"); 14818 } 14819 14820 MarkVarDeclODRUsed(Var, Loc, *this, 14821 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14822 } 14823 14824 MaybeODRUseExprs.clear(); 14825 } 14826 14827 14828 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14829 VarDecl *Var, Expr *E) { 14830 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14831 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14832 Var->setReferenced(); 14833 14834 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14835 14836 bool OdrUseContext = isOdrUseContext(SemaRef); 14837 bool UsableInConstantExpr = 14838 Var->isUsableInConstantExpressions(SemaRef.Context); 14839 bool NeedDefinition = 14840 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14841 14842 VarTemplateSpecializationDecl *VarSpec = 14843 dyn_cast<VarTemplateSpecializationDecl>(Var); 14844 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14845 "Can't instantiate a partial template specialization."); 14846 14847 // If this might be a member specialization of a static data member, check 14848 // the specialization is visible. We already did the checks for variable 14849 // template specializations when we created them. 14850 if (NeedDefinition && TSK != TSK_Undeclared && 14851 !isa<VarTemplateSpecializationDecl>(Var)) 14852 SemaRef.checkSpecializationVisibility(Loc, Var); 14853 14854 // Perform implicit instantiation of static data members, static data member 14855 // templates of class templates, and variable template specializations. Delay 14856 // instantiations of variable templates, except for those that could be used 14857 // in a constant expression. 14858 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14859 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14860 // instantiation declaration if a variable is usable in a constant 14861 // expression (among other cases). 14862 bool TryInstantiating = 14863 TSK == TSK_ImplicitInstantiation || 14864 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14865 14866 if (TryInstantiating) { 14867 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14868 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14869 if (FirstInstantiation) { 14870 PointOfInstantiation = Loc; 14871 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14872 } 14873 14874 bool InstantiationDependent = false; 14875 bool IsNonDependent = 14876 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14877 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14878 : true; 14879 14880 // Do not instantiate specializations that are still type-dependent. 14881 if (IsNonDependent) { 14882 if (UsableInConstantExpr) { 14883 // Do not defer instantiations of variables that could be used in a 14884 // constant expression. 14885 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14886 } else if (FirstInstantiation || 14887 isa<VarTemplateSpecializationDecl>(Var)) { 14888 // FIXME: For a specialization of a variable template, we don't 14889 // distinguish between "declaration and type implicitly instantiated" 14890 // and "implicit instantiation of definition requested", so we have 14891 // no direct way to avoid enqueueing the pending instantiation 14892 // multiple times. 14893 SemaRef.PendingInstantiations 14894 .push_back(std::make_pair(Var, PointOfInstantiation)); 14895 } 14896 } 14897 } 14898 } 14899 14900 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14901 // the requirements for appearing in a constant expression (5.19) and, if 14902 // it is an object, the lvalue-to-rvalue conversion (4.1) 14903 // is immediately applied." We check the first part here, and 14904 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14905 // Note that we use the C++11 definition everywhere because nothing in 14906 // C++03 depends on whether we get the C++03 version correct. The second 14907 // part does not apply to references, since they are not objects. 14908 if (OdrUseContext && E && 14909 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14910 // A reference initialized by a constant expression can never be 14911 // odr-used, so simply ignore it. 14912 if (!Var->getType()->isReferenceType() || 14913 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14914 SemaRef.MaybeODRUseExprs.insert(E); 14915 } else if (OdrUseContext) { 14916 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14917 /*MaxFunctionScopeIndex ptr*/ nullptr); 14918 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14919 // If this is a dependent context, we don't need to mark variables as 14920 // odr-used, but we may still need to track them for lambda capture. 14921 // FIXME: Do we also need to do this inside dependent typeid expressions 14922 // (which are modeled as unevaluated at this point)? 14923 const bool RefersToEnclosingScope = 14924 (SemaRef.CurContext != Var->getDeclContext() && 14925 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14926 if (RefersToEnclosingScope) { 14927 LambdaScopeInfo *const LSI = 14928 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14929 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14930 // If a variable could potentially be odr-used, defer marking it so 14931 // until we finish analyzing the full expression for any 14932 // lvalue-to-rvalue 14933 // or discarded value conversions that would obviate odr-use. 14934 // Add it to the list of potential captures that will be analyzed 14935 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14936 // unless the variable is a reference that was initialized by a constant 14937 // expression (this will never need to be captured or odr-used). 14938 assert(E && "Capture variable should be used in an expression."); 14939 if (!Var->getType()->isReferenceType() || 14940 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14941 LSI->addPotentialCapture(E->IgnoreParens()); 14942 } 14943 } 14944 } 14945 } 14946 14947 /// \brief Mark a variable referenced, and check whether it is odr-used 14948 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14949 /// used directly for normal expressions referring to VarDecl. 14950 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14951 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14952 } 14953 14954 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14955 Decl *D, Expr *E, bool MightBeOdrUse) { 14956 if (SemaRef.isInOpenMPDeclareTargetContext()) 14957 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14958 14959 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14960 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14961 return; 14962 } 14963 14964 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14965 14966 // If this is a call to a method via a cast, also mark the method in the 14967 // derived class used in case codegen can devirtualize the call. 14968 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14969 if (!ME) 14970 return; 14971 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14972 if (!MD) 14973 return; 14974 // Only attempt to devirtualize if this is truly a virtual call. 14975 bool IsVirtualCall = MD->isVirtual() && 14976 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14977 if (!IsVirtualCall) 14978 return; 14979 14980 // If it's possible to devirtualize the call, mark the called function 14981 // referenced. 14982 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14983 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14984 if (DM) 14985 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14986 } 14987 14988 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14989 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14990 // TODO: update this with DR# once a defect report is filed. 14991 // C++11 defect. The address of a pure member should not be an ODR use, even 14992 // if it's a qualified reference. 14993 bool OdrUse = true; 14994 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14995 if (Method->isVirtual() && 14996 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14997 OdrUse = false; 14998 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14999 } 15000 15001 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15002 void Sema::MarkMemberReferenced(MemberExpr *E) { 15003 // C++11 [basic.def.odr]p2: 15004 // A non-overloaded function whose name appears as a potentially-evaluated 15005 // expression or a member of a set of candidate functions, if selected by 15006 // overload resolution when referred to from a potentially-evaluated 15007 // expression, is odr-used, unless it is a pure virtual function and its 15008 // name is not explicitly qualified. 15009 bool MightBeOdrUse = true; 15010 if (E->performsVirtualDispatch(getLangOpts())) { 15011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15012 if (Method->isPure()) 15013 MightBeOdrUse = false; 15014 } 15015 SourceLocation Loc = E->getMemberLoc().isValid() ? 15016 E->getMemberLoc() : E->getLocStart(); 15017 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15018 } 15019 15020 /// \brief Perform marking for a reference to an arbitrary declaration. It 15021 /// marks the declaration referenced, and performs odr-use checking for 15022 /// functions and variables. This method should not be used when building a 15023 /// normal expression which refers to a variable. 15024 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15025 bool MightBeOdrUse) { 15026 if (MightBeOdrUse) { 15027 if (auto *VD = dyn_cast<VarDecl>(D)) { 15028 MarkVariableReferenced(Loc, VD); 15029 return; 15030 } 15031 } 15032 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15033 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15034 return; 15035 } 15036 D->setReferenced(); 15037 } 15038 15039 namespace { 15040 // Mark all of the declarations used by a type as referenced. 15041 // FIXME: Not fully implemented yet! We need to have a better understanding 15042 // of when we're entering a context we should not recurse into. 15043 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15044 // TreeTransforms rebuilding the type in a new context. Rather than 15045 // duplicating the TreeTransform logic, we should consider reusing it here. 15046 // Currently that causes problems when rebuilding LambdaExprs. 15047 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15048 Sema &S; 15049 SourceLocation Loc; 15050 15051 public: 15052 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15053 15054 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15055 15056 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15057 }; 15058 } 15059 15060 bool MarkReferencedDecls::TraverseTemplateArgument( 15061 const TemplateArgument &Arg) { 15062 { 15063 // A non-type template argument is a constant-evaluated context. 15064 EnterExpressionEvaluationContext Evaluated( 15065 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15066 if (Arg.getKind() == TemplateArgument::Declaration) { 15067 if (Decl *D = Arg.getAsDecl()) 15068 S.MarkAnyDeclReferenced(Loc, D, true); 15069 } else if (Arg.getKind() == TemplateArgument::Expression) { 15070 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15071 } 15072 } 15073 15074 return Inherited::TraverseTemplateArgument(Arg); 15075 } 15076 15077 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15078 MarkReferencedDecls Marker(*this, Loc); 15079 Marker.TraverseType(T); 15080 } 15081 15082 namespace { 15083 /// \brief Helper class that marks all of the declarations referenced by 15084 /// potentially-evaluated subexpressions as "referenced". 15085 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15086 Sema &S; 15087 bool SkipLocalVariables; 15088 15089 public: 15090 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15091 15092 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15093 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15094 15095 void VisitDeclRefExpr(DeclRefExpr *E) { 15096 // If we were asked not to visit local variables, don't. 15097 if (SkipLocalVariables) { 15098 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15099 if (VD->hasLocalStorage()) 15100 return; 15101 } 15102 15103 S.MarkDeclRefReferenced(E); 15104 } 15105 15106 void VisitMemberExpr(MemberExpr *E) { 15107 S.MarkMemberReferenced(E); 15108 Inherited::VisitMemberExpr(E); 15109 } 15110 15111 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15112 S.MarkFunctionReferenced(E->getLocStart(), 15113 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15114 Visit(E->getSubExpr()); 15115 } 15116 15117 void VisitCXXNewExpr(CXXNewExpr *E) { 15118 if (E->getOperatorNew()) 15119 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15120 if (E->getOperatorDelete()) 15121 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15122 Inherited::VisitCXXNewExpr(E); 15123 } 15124 15125 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15126 if (E->getOperatorDelete()) 15127 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15128 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15129 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15130 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15131 S.MarkFunctionReferenced(E->getLocStart(), 15132 S.LookupDestructor(Record)); 15133 } 15134 15135 Inherited::VisitCXXDeleteExpr(E); 15136 } 15137 15138 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15139 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15140 Inherited::VisitCXXConstructExpr(E); 15141 } 15142 15143 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15144 Visit(E->getExpr()); 15145 } 15146 15147 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15148 Inherited::VisitImplicitCastExpr(E); 15149 15150 if (E->getCastKind() == CK_LValueToRValue) 15151 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15152 } 15153 }; 15154 } 15155 15156 /// \brief Mark any declarations that appear within this expression or any 15157 /// potentially-evaluated subexpressions as "referenced". 15158 /// 15159 /// \param SkipLocalVariables If true, don't mark local variables as 15160 /// 'referenced'. 15161 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15162 bool SkipLocalVariables) { 15163 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15164 } 15165 15166 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15167 /// of the program being compiled. 15168 /// 15169 /// This routine emits the given diagnostic when the code currently being 15170 /// type-checked is "potentially evaluated", meaning that there is a 15171 /// possibility that the code will actually be executable. Code in sizeof() 15172 /// expressions, code used only during overload resolution, etc., are not 15173 /// potentially evaluated. This routine will suppress such diagnostics or, 15174 /// in the absolutely nutty case of potentially potentially evaluated 15175 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15176 /// later. 15177 /// 15178 /// This routine should be used for all diagnostics that describe the run-time 15179 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15180 /// Failure to do so will likely result in spurious diagnostics or failures 15181 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15182 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15183 const PartialDiagnostic &PD) { 15184 switch (ExprEvalContexts.back().Context) { 15185 case ExpressionEvaluationContext::Unevaluated: 15186 case ExpressionEvaluationContext::UnevaluatedList: 15187 case ExpressionEvaluationContext::UnevaluatedAbstract: 15188 case ExpressionEvaluationContext::DiscardedStatement: 15189 // The argument will never be evaluated, so don't complain. 15190 break; 15191 15192 case ExpressionEvaluationContext::ConstantEvaluated: 15193 // Relevant diagnostics should be produced by constant evaluation. 15194 break; 15195 15196 case ExpressionEvaluationContext::PotentiallyEvaluated: 15197 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15198 if (Statement && getCurFunctionOrMethodDecl()) { 15199 FunctionScopes.back()->PossiblyUnreachableDiags. 15200 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15201 return true; 15202 } 15203 15204 // The initializer of a constexpr variable or of the first declaration of a 15205 // static data member is not syntactically a constant evaluated constant, 15206 // but nonetheless is always required to be a constant expression, so we 15207 // can skip diagnosing. 15208 // FIXME: Using the mangling context here is a hack. 15209 if (auto *VD = dyn_cast_or_null<VarDecl>( 15210 ExprEvalContexts.back().ManglingContextDecl)) { 15211 if (VD->isConstexpr() || 15212 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15213 break; 15214 // FIXME: For any other kind of variable, we should build a CFG for its 15215 // initializer and check whether the context in question is reachable. 15216 } 15217 15218 Diag(Loc, PD); 15219 return true; 15220 } 15221 15222 return false; 15223 } 15224 15225 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15226 CallExpr *CE, FunctionDecl *FD) { 15227 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15228 return false; 15229 15230 // If we're inside a decltype's expression, don't check for a valid return 15231 // type or construct temporaries until we know whether this is the last call. 15232 if (ExprEvalContexts.back().IsDecltype) { 15233 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15234 return false; 15235 } 15236 15237 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15238 FunctionDecl *FD; 15239 CallExpr *CE; 15240 15241 public: 15242 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15243 : FD(FD), CE(CE) { } 15244 15245 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15246 if (!FD) { 15247 S.Diag(Loc, diag::err_call_incomplete_return) 15248 << T << CE->getSourceRange(); 15249 return; 15250 } 15251 15252 S.Diag(Loc, diag::err_call_function_incomplete_return) 15253 << CE->getSourceRange() << FD->getDeclName() << T; 15254 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15255 << FD->getDeclName(); 15256 } 15257 } Diagnoser(FD, CE); 15258 15259 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15260 return true; 15261 15262 return false; 15263 } 15264 15265 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15266 // will prevent this condition from triggering, which is what we want. 15267 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15268 SourceLocation Loc; 15269 15270 unsigned diagnostic = diag::warn_condition_is_assignment; 15271 bool IsOrAssign = false; 15272 15273 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15274 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15275 return; 15276 15277 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15278 15279 // Greylist some idioms by putting them into a warning subcategory. 15280 if (ObjCMessageExpr *ME 15281 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15282 Selector Sel = ME->getSelector(); 15283 15284 // self = [<foo> init...] 15285 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15286 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15287 15288 // <foo> = [<bar> nextObject] 15289 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15290 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15291 } 15292 15293 Loc = Op->getOperatorLoc(); 15294 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15295 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15296 return; 15297 15298 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15299 Loc = Op->getOperatorLoc(); 15300 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15301 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15302 else { 15303 // Not an assignment. 15304 return; 15305 } 15306 15307 Diag(Loc, diagnostic) << E->getSourceRange(); 15308 15309 SourceLocation Open = E->getLocStart(); 15310 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15311 Diag(Loc, diag::note_condition_assign_silence) 15312 << FixItHint::CreateInsertion(Open, "(") 15313 << FixItHint::CreateInsertion(Close, ")"); 15314 15315 if (IsOrAssign) 15316 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15317 << FixItHint::CreateReplacement(Loc, "!="); 15318 else 15319 Diag(Loc, diag::note_condition_assign_to_comparison) 15320 << FixItHint::CreateReplacement(Loc, "=="); 15321 } 15322 15323 /// \brief Redundant parentheses over an equality comparison can indicate 15324 /// that the user intended an assignment used as condition. 15325 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15326 // Don't warn if the parens came from a macro. 15327 SourceLocation parenLoc = ParenE->getLocStart(); 15328 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15329 return; 15330 // Don't warn for dependent expressions. 15331 if (ParenE->isTypeDependent()) 15332 return; 15333 15334 Expr *E = ParenE->IgnoreParens(); 15335 15336 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15337 if (opE->getOpcode() == BO_EQ && 15338 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15339 == Expr::MLV_Valid) { 15340 SourceLocation Loc = opE->getOperatorLoc(); 15341 15342 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15343 SourceRange ParenERange = ParenE->getSourceRange(); 15344 Diag(Loc, diag::note_equality_comparison_silence) 15345 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15346 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15347 Diag(Loc, diag::note_equality_comparison_to_assign) 15348 << FixItHint::CreateReplacement(Loc, "="); 15349 } 15350 } 15351 15352 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15353 bool IsConstexpr) { 15354 DiagnoseAssignmentAsCondition(E); 15355 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15356 DiagnoseEqualityWithExtraParens(parenE); 15357 15358 ExprResult result = CheckPlaceholderExpr(E); 15359 if (result.isInvalid()) return ExprError(); 15360 E = result.get(); 15361 15362 if (!E->isTypeDependent()) { 15363 if (getLangOpts().CPlusPlus) 15364 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15365 15366 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15367 if (ERes.isInvalid()) 15368 return ExprError(); 15369 E = ERes.get(); 15370 15371 QualType T = E->getType(); 15372 if (!T->isScalarType()) { // C99 6.8.4.1p1 15373 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15374 << T << E->getSourceRange(); 15375 return ExprError(); 15376 } 15377 CheckBoolLikeConversion(E, Loc); 15378 } 15379 15380 return E; 15381 } 15382 15383 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15384 Expr *SubExpr, ConditionKind CK) { 15385 // Empty conditions are valid in for-statements. 15386 if (!SubExpr) 15387 return ConditionResult(); 15388 15389 ExprResult Cond; 15390 switch (CK) { 15391 case ConditionKind::Boolean: 15392 Cond = CheckBooleanCondition(Loc, SubExpr); 15393 break; 15394 15395 case ConditionKind::ConstexprIf: 15396 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15397 break; 15398 15399 case ConditionKind::Switch: 15400 Cond = CheckSwitchCondition(Loc, SubExpr); 15401 break; 15402 } 15403 if (Cond.isInvalid()) 15404 return ConditionError(); 15405 15406 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15407 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15408 if (!FullExpr.get()) 15409 return ConditionError(); 15410 15411 return ConditionResult(*this, nullptr, FullExpr, 15412 CK == ConditionKind::ConstexprIf); 15413 } 15414 15415 namespace { 15416 /// A visitor for rebuilding a call to an __unknown_any expression 15417 /// to have an appropriate type. 15418 struct RebuildUnknownAnyFunction 15419 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15420 15421 Sema &S; 15422 15423 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15424 15425 ExprResult VisitStmt(Stmt *S) { 15426 llvm_unreachable("unexpected statement!"); 15427 } 15428 15429 ExprResult VisitExpr(Expr *E) { 15430 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15431 << E->getSourceRange(); 15432 return ExprError(); 15433 } 15434 15435 /// Rebuild an expression which simply semantically wraps another 15436 /// expression which it shares the type and value kind of. 15437 template <class T> ExprResult rebuildSugarExpr(T *E) { 15438 ExprResult SubResult = Visit(E->getSubExpr()); 15439 if (SubResult.isInvalid()) return ExprError(); 15440 15441 Expr *SubExpr = SubResult.get(); 15442 E->setSubExpr(SubExpr); 15443 E->setType(SubExpr->getType()); 15444 E->setValueKind(SubExpr->getValueKind()); 15445 assert(E->getObjectKind() == OK_Ordinary); 15446 return E; 15447 } 15448 15449 ExprResult VisitParenExpr(ParenExpr *E) { 15450 return rebuildSugarExpr(E); 15451 } 15452 15453 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15454 return rebuildSugarExpr(E); 15455 } 15456 15457 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15458 ExprResult SubResult = Visit(E->getSubExpr()); 15459 if (SubResult.isInvalid()) return ExprError(); 15460 15461 Expr *SubExpr = SubResult.get(); 15462 E->setSubExpr(SubExpr); 15463 E->setType(S.Context.getPointerType(SubExpr->getType())); 15464 assert(E->getValueKind() == VK_RValue); 15465 assert(E->getObjectKind() == OK_Ordinary); 15466 return E; 15467 } 15468 15469 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15470 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15471 15472 E->setType(VD->getType()); 15473 15474 assert(E->getValueKind() == VK_RValue); 15475 if (S.getLangOpts().CPlusPlus && 15476 !(isa<CXXMethodDecl>(VD) && 15477 cast<CXXMethodDecl>(VD)->isInstance())) 15478 E->setValueKind(VK_LValue); 15479 15480 return E; 15481 } 15482 15483 ExprResult VisitMemberExpr(MemberExpr *E) { 15484 return resolveDecl(E, E->getMemberDecl()); 15485 } 15486 15487 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15488 return resolveDecl(E, E->getDecl()); 15489 } 15490 }; 15491 } 15492 15493 /// Given a function expression of unknown-any type, try to rebuild it 15494 /// to have a function type. 15495 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15496 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15497 if (Result.isInvalid()) return ExprError(); 15498 return S.DefaultFunctionArrayConversion(Result.get()); 15499 } 15500 15501 namespace { 15502 /// A visitor for rebuilding an expression of type __unknown_anytype 15503 /// into one which resolves the type directly on the referring 15504 /// expression. Strict preservation of the original source 15505 /// structure is not a goal. 15506 struct RebuildUnknownAnyExpr 15507 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15508 15509 Sema &S; 15510 15511 /// The current destination type. 15512 QualType DestType; 15513 15514 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15515 : S(S), DestType(CastType) {} 15516 15517 ExprResult VisitStmt(Stmt *S) { 15518 llvm_unreachable("unexpected statement!"); 15519 } 15520 15521 ExprResult VisitExpr(Expr *E) { 15522 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15523 << E->getSourceRange(); 15524 return ExprError(); 15525 } 15526 15527 ExprResult VisitCallExpr(CallExpr *E); 15528 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15529 15530 /// Rebuild an expression which simply semantically wraps another 15531 /// expression which it shares the type and value kind of. 15532 template <class T> ExprResult rebuildSugarExpr(T *E) { 15533 ExprResult SubResult = Visit(E->getSubExpr()); 15534 if (SubResult.isInvalid()) return ExprError(); 15535 Expr *SubExpr = SubResult.get(); 15536 E->setSubExpr(SubExpr); 15537 E->setType(SubExpr->getType()); 15538 E->setValueKind(SubExpr->getValueKind()); 15539 assert(E->getObjectKind() == OK_Ordinary); 15540 return E; 15541 } 15542 15543 ExprResult VisitParenExpr(ParenExpr *E) { 15544 return rebuildSugarExpr(E); 15545 } 15546 15547 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15548 return rebuildSugarExpr(E); 15549 } 15550 15551 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15552 const PointerType *Ptr = DestType->getAs<PointerType>(); 15553 if (!Ptr) { 15554 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15555 << E->getSourceRange(); 15556 return ExprError(); 15557 } 15558 15559 if (isa<CallExpr>(E->getSubExpr())) { 15560 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15561 << E->getSourceRange(); 15562 return ExprError(); 15563 } 15564 15565 assert(E->getValueKind() == VK_RValue); 15566 assert(E->getObjectKind() == OK_Ordinary); 15567 E->setType(DestType); 15568 15569 // Build the sub-expression as if it were an object of the pointee type. 15570 DestType = Ptr->getPointeeType(); 15571 ExprResult SubResult = Visit(E->getSubExpr()); 15572 if (SubResult.isInvalid()) return ExprError(); 15573 E->setSubExpr(SubResult.get()); 15574 return E; 15575 } 15576 15577 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15578 15579 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15580 15581 ExprResult VisitMemberExpr(MemberExpr *E) { 15582 return resolveDecl(E, E->getMemberDecl()); 15583 } 15584 15585 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15586 return resolveDecl(E, E->getDecl()); 15587 } 15588 }; 15589 } 15590 15591 /// Rebuilds a call expression which yielded __unknown_anytype. 15592 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15593 Expr *CalleeExpr = E->getCallee(); 15594 15595 enum FnKind { 15596 FK_MemberFunction, 15597 FK_FunctionPointer, 15598 FK_BlockPointer 15599 }; 15600 15601 FnKind Kind; 15602 QualType CalleeType = CalleeExpr->getType(); 15603 if (CalleeType == S.Context.BoundMemberTy) { 15604 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15605 Kind = FK_MemberFunction; 15606 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15607 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15608 CalleeType = Ptr->getPointeeType(); 15609 Kind = FK_FunctionPointer; 15610 } else { 15611 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15612 Kind = FK_BlockPointer; 15613 } 15614 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15615 15616 // Verify that this is a legal result type of a function. 15617 if (DestType->isArrayType() || DestType->isFunctionType()) { 15618 unsigned diagID = diag::err_func_returning_array_function; 15619 if (Kind == FK_BlockPointer) 15620 diagID = diag::err_block_returning_array_function; 15621 15622 S.Diag(E->getExprLoc(), diagID) 15623 << DestType->isFunctionType() << DestType; 15624 return ExprError(); 15625 } 15626 15627 // Otherwise, go ahead and set DestType as the call's result. 15628 E->setType(DestType.getNonLValueExprType(S.Context)); 15629 E->setValueKind(Expr::getValueKindForType(DestType)); 15630 assert(E->getObjectKind() == OK_Ordinary); 15631 15632 // Rebuild the function type, replacing the result type with DestType. 15633 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15634 if (Proto) { 15635 // __unknown_anytype(...) is a special case used by the debugger when 15636 // it has no idea what a function's signature is. 15637 // 15638 // We want to build this call essentially under the K&R 15639 // unprototyped rules, but making a FunctionNoProtoType in C++ 15640 // would foul up all sorts of assumptions. However, we cannot 15641 // simply pass all arguments as variadic arguments, nor can we 15642 // portably just call the function under a non-variadic type; see 15643 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15644 // However, it turns out that in practice it is generally safe to 15645 // call a function declared as "A foo(B,C,D);" under the prototype 15646 // "A foo(B,C,D,...);". The only known exception is with the 15647 // Windows ABI, where any variadic function is implicitly cdecl 15648 // regardless of its normal CC. Therefore we change the parameter 15649 // types to match the types of the arguments. 15650 // 15651 // This is a hack, but it is far superior to moving the 15652 // corresponding target-specific code from IR-gen to Sema/AST. 15653 15654 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15655 SmallVector<QualType, 8> ArgTypes; 15656 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15657 ArgTypes.reserve(E->getNumArgs()); 15658 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15659 Expr *Arg = E->getArg(i); 15660 QualType ArgType = Arg->getType(); 15661 if (E->isLValue()) { 15662 ArgType = S.Context.getLValueReferenceType(ArgType); 15663 } else if (E->isXValue()) { 15664 ArgType = S.Context.getRValueReferenceType(ArgType); 15665 } 15666 ArgTypes.push_back(ArgType); 15667 } 15668 ParamTypes = ArgTypes; 15669 } 15670 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15671 Proto->getExtProtoInfo()); 15672 } else { 15673 DestType = S.Context.getFunctionNoProtoType(DestType, 15674 FnType->getExtInfo()); 15675 } 15676 15677 // Rebuild the appropriate pointer-to-function type. 15678 switch (Kind) { 15679 case FK_MemberFunction: 15680 // Nothing to do. 15681 break; 15682 15683 case FK_FunctionPointer: 15684 DestType = S.Context.getPointerType(DestType); 15685 break; 15686 15687 case FK_BlockPointer: 15688 DestType = S.Context.getBlockPointerType(DestType); 15689 break; 15690 } 15691 15692 // Finally, we can recurse. 15693 ExprResult CalleeResult = Visit(CalleeExpr); 15694 if (!CalleeResult.isUsable()) return ExprError(); 15695 E->setCallee(CalleeResult.get()); 15696 15697 // Bind a temporary if necessary. 15698 return S.MaybeBindToTemporary(E); 15699 } 15700 15701 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15702 // Verify that this is a legal result type of a call. 15703 if (DestType->isArrayType() || DestType->isFunctionType()) { 15704 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15705 << DestType->isFunctionType() << DestType; 15706 return ExprError(); 15707 } 15708 15709 // Rewrite the method result type if available. 15710 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15711 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15712 Method->setReturnType(DestType); 15713 } 15714 15715 // Change the type of the message. 15716 E->setType(DestType.getNonReferenceType()); 15717 E->setValueKind(Expr::getValueKindForType(DestType)); 15718 15719 return S.MaybeBindToTemporary(E); 15720 } 15721 15722 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15723 // The only case we should ever see here is a function-to-pointer decay. 15724 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15725 assert(E->getValueKind() == VK_RValue); 15726 assert(E->getObjectKind() == OK_Ordinary); 15727 15728 E->setType(DestType); 15729 15730 // Rebuild the sub-expression as the pointee (function) type. 15731 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15732 15733 ExprResult Result = Visit(E->getSubExpr()); 15734 if (!Result.isUsable()) return ExprError(); 15735 15736 E->setSubExpr(Result.get()); 15737 return E; 15738 } else if (E->getCastKind() == CK_LValueToRValue) { 15739 assert(E->getValueKind() == VK_RValue); 15740 assert(E->getObjectKind() == OK_Ordinary); 15741 15742 assert(isa<BlockPointerType>(E->getType())); 15743 15744 E->setType(DestType); 15745 15746 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15747 DestType = S.Context.getLValueReferenceType(DestType); 15748 15749 ExprResult Result = Visit(E->getSubExpr()); 15750 if (!Result.isUsable()) return ExprError(); 15751 15752 E->setSubExpr(Result.get()); 15753 return E; 15754 } else { 15755 llvm_unreachable("Unhandled cast type!"); 15756 } 15757 } 15758 15759 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15760 ExprValueKind ValueKind = VK_LValue; 15761 QualType Type = DestType; 15762 15763 // We know how to make this work for certain kinds of decls: 15764 15765 // - functions 15766 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15767 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15768 DestType = Ptr->getPointeeType(); 15769 ExprResult Result = resolveDecl(E, VD); 15770 if (Result.isInvalid()) return ExprError(); 15771 return S.ImpCastExprToType(Result.get(), Type, 15772 CK_FunctionToPointerDecay, VK_RValue); 15773 } 15774 15775 if (!Type->isFunctionType()) { 15776 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15777 << VD << E->getSourceRange(); 15778 return ExprError(); 15779 } 15780 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15781 // We must match the FunctionDecl's type to the hack introduced in 15782 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15783 // type. See the lengthy commentary in that routine. 15784 QualType FDT = FD->getType(); 15785 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15786 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15787 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15788 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15789 SourceLocation Loc = FD->getLocation(); 15790 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15791 FD->getDeclContext(), 15792 Loc, Loc, FD->getNameInfo().getName(), 15793 DestType, FD->getTypeSourceInfo(), 15794 SC_None, false/*isInlineSpecified*/, 15795 FD->hasPrototype(), 15796 false/*isConstexprSpecified*/); 15797 15798 if (FD->getQualifier()) 15799 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15800 15801 SmallVector<ParmVarDecl*, 16> Params; 15802 for (const auto &AI : FT->param_types()) { 15803 ParmVarDecl *Param = 15804 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15805 Param->setScopeInfo(0, Params.size()); 15806 Params.push_back(Param); 15807 } 15808 NewFD->setParams(Params); 15809 DRE->setDecl(NewFD); 15810 VD = DRE->getDecl(); 15811 } 15812 } 15813 15814 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15815 if (MD->isInstance()) { 15816 ValueKind = VK_RValue; 15817 Type = S.Context.BoundMemberTy; 15818 } 15819 15820 // Function references aren't l-values in C. 15821 if (!S.getLangOpts().CPlusPlus) 15822 ValueKind = VK_RValue; 15823 15824 // - variables 15825 } else if (isa<VarDecl>(VD)) { 15826 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15827 Type = RefTy->getPointeeType(); 15828 } else if (Type->isFunctionType()) { 15829 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15830 << VD << E->getSourceRange(); 15831 return ExprError(); 15832 } 15833 15834 // - nothing else 15835 } else { 15836 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15837 << VD << E->getSourceRange(); 15838 return ExprError(); 15839 } 15840 15841 // Modifying the declaration like this is friendly to IR-gen but 15842 // also really dangerous. 15843 VD->setType(DestType); 15844 E->setType(Type); 15845 E->setValueKind(ValueKind); 15846 return E; 15847 } 15848 15849 /// Check a cast of an unknown-any type. We intentionally only 15850 /// trigger this for C-style casts. 15851 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15852 Expr *CastExpr, CastKind &CastKind, 15853 ExprValueKind &VK, CXXCastPath &Path) { 15854 // The type we're casting to must be either void or complete. 15855 if (!CastType->isVoidType() && 15856 RequireCompleteType(TypeRange.getBegin(), CastType, 15857 diag::err_typecheck_cast_to_incomplete)) 15858 return ExprError(); 15859 15860 // Rewrite the casted expression from scratch. 15861 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15862 if (!result.isUsable()) return ExprError(); 15863 15864 CastExpr = result.get(); 15865 VK = CastExpr->getValueKind(); 15866 CastKind = CK_NoOp; 15867 15868 return CastExpr; 15869 } 15870 15871 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15872 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15873 } 15874 15875 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15876 Expr *arg, QualType ¶mType) { 15877 // If the syntactic form of the argument is not an explicit cast of 15878 // any sort, just do default argument promotion. 15879 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15880 if (!castArg) { 15881 ExprResult result = DefaultArgumentPromotion(arg); 15882 if (result.isInvalid()) return ExprError(); 15883 paramType = result.get()->getType(); 15884 return result; 15885 } 15886 15887 // Otherwise, use the type that was written in the explicit cast. 15888 assert(!arg->hasPlaceholderType()); 15889 paramType = castArg->getTypeAsWritten(); 15890 15891 // Copy-initialize a parameter of that type. 15892 InitializedEntity entity = 15893 InitializedEntity::InitializeParameter(Context, paramType, 15894 /*consumed*/ false); 15895 return PerformCopyInitialization(entity, callLoc, arg); 15896 } 15897 15898 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15899 Expr *orig = E; 15900 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15901 while (true) { 15902 E = E->IgnoreParenImpCasts(); 15903 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15904 E = call->getCallee(); 15905 diagID = diag::err_uncasted_call_of_unknown_any; 15906 } else { 15907 break; 15908 } 15909 } 15910 15911 SourceLocation loc; 15912 NamedDecl *d; 15913 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15914 loc = ref->getLocation(); 15915 d = ref->getDecl(); 15916 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15917 loc = mem->getMemberLoc(); 15918 d = mem->getMemberDecl(); 15919 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15920 diagID = diag::err_uncasted_call_of_unknown_any; 15921 loc = msg->getSelectorStartLoc(); 15922 d = msg->getMethodDecl(); 15923 if (!d) { 15924 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15925 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15926 << orig->getSourceRange(); 15927 return ExprError(); 15928 } 15929 } else { 15930 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15931 << E->getSourceRange(); 15932 return ExprError(); 15933 } 15934 15935 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15936 15937 // Never recoverable. 15938 return ExprError(); 15939 } 15940 15941 /// Check for operands with placeholder types and complain if found. 15942 /// Returns ExprError() if there was an error and no recovery was possible. 15943 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15944 if (!getLangOpts().CPlusPlus) { 15945 // C cannot handle TypoExpr nodes on either side of a binop because it 15946 // doesn't handle dependent types properly, so make sure any TypoExprs have 15947 // been dealt with before checking the operands. 15948 ExprResult Result = CorrectDelayedTyposInExpr(E); 15949 if (!Result.isUsable()) return ExprError(); 15950 E = Result.get(); 15951 } 15952 15953 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15954 if (!placeholderType) return E; 15955 15956 switch (placeholderType->getKind()) { 15957 15958 // Overloaded expressions. 15959 case BuiltinType::Overload: { 15960 // Try to resolve a single function template specialization. 15961 // This is obligatory. 15962 ExprResult Result = E; 15963 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15964 return Result; 15965 15966 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15967 // leaves Result unchanged on failure. 15968 Result = E; 15969 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15970 return Result; 15971 15972 // If that failed, try to recover with a call. 15973 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15974 /*complain*/ true); 15975 return Result; 15976 } 15977 15978 // Bound member functions. 15979 case BuiltinType::BoundMember: { 15980 ExprResult result = E; 15981 const Expr *BME = E->IgnoreParens(); 15982 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15983 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15984 if (isa<CXXPseudoDestructorExpr>(BME)) { 15985 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15986 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15987 if (ME->getMemberNameInfo().getName().getNameKind() == 15988 DeclarationName::CXXDestructorName) 15989 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15990 } 15991 tryToRecoverWithCall(result, PD, 15992 /*complain*/ true); 15993 return result; 15994 } 15995 15996 // ARC unbridged casts. 15997 case BuiltinType::ARCUnbridgedCast: { 15998 Expr *realCast = stripARCUnbridgedCast(E); 15999 diagnoseARCUnbridgedCast(realCast); 16000 return realCast; 16001 } 16002 16003 // Expressions of unknown type. 16004 case BuiltinType::UnknownAny: 16005 return diagnoseUnknownAnyExpr(*this, E); 16006 16007 // Pseudo-objects. 16008 case BuiltinType::PseudoObject: 16009 return checkPseudoObjectRValue(E); 16010 16011 case BuiltinType::BuiltinFn: { 16012 // Accept __noop without parens by implicitly converting it to a call expr. 16013 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16014 if (DRE) { 16015 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16016 if (FD->getBuiltinID() == Builtin::BI__noop) { 16017 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16018 CK_BuiltinFnToFnPtr).get(); 16019 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16020 VK_RValue, SourceLocation()); 16021 } 16022 } 16023 16024 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16025 return ExprError(); 16026 } 16027 16028 // Expressions of unknown type. 16029 case BuiltinType::OMPArraySection: 16030 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16031 return ExprError(); 16032 16033 // Everything else should be impossible. 16034 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16035 case BuiltinType::Id: 16036 #include "clang/Basic/OpenCLImageTypes.def" 16037 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16038 #define PLACEHOLDER_TYPE(Id, SingletonId) 16039 #include "clang/AST/BuiltinTypes.def" 16040 break; 16041 } 16042 16043 llvm_unreachable("invalid placeholder type!"); 16044 } 16045 16046 bool Sema::CheckCaseExpression(Expr *E) { 16047 if (E->isTypeDependent()) 16048 return true; 16049 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16050 return E->getType()->isIntegralOrEnumerationType(); 16051 return false; 16052 } 16053 16054 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16055 ExprResult 16056 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16057 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16058 "Unknown Objective-C Boolean value!"); 16059 QualType BoolT = Context.ObjCBuiltinBoolTy; 16060 if (!Context.getBOOLDecl()) { 16061 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16062 Sema::LookupOrdinaryName); 16063 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16064 NamedDecl *ND = Result.getFoundDecl(); 16065 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16066 Context.setBOOLDecl(TD); 16067 } 16068 } 16069 if (Context.getBOOLDecl()) 16070 BoolT = Context.getBOOLType(); 16071 return new (Context) 16072 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16073 } 16074 16075 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16076 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16077 SourceLocation RParen) { 16078 16079 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16080 16081 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16082 [&](const AvailabilitySpec &Spec) { 16083 return Spec.getPlatform() == Platform; 16084 }); 16085 16086 VersionTuple Version; 16087 if (Spec != AvailSpecs.end()) 16088 Version = Spec->getVersion(); 16089 16090 // The use of `@available` in the enclosing function should be analyzed to 16091 // warn when it's used inappropriately (i.e. not if(@available)). 16092 if (getCurFunctionOrMethodDecl()) 16093 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16094 else if (getCurBlock() || getCurLambda()) 16095 getCurFunction()->HasPotentialAvailabilityViolations = true; 16096 16097 return new (Context) 16098 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16099 } 16100