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 // Fall through. 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() == UnqualifiedId::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() == UnqualifiedId::IK_ImplicitSelfParam) 2075 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2076 if (TemplateArgs) { 2077 // Lookup the template name again to correctly establish the context in 2078 // which it was found. This is really unfortunate as we already did the 2079 // lookup to determine that it was a template name in the first place. If 2080 // this becomes a performance hit, we can work harder to preserve those 2081 // results until we get here but it's likely not worth it. 2082 bool MemberOfUnknownSpecialization; 2083 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2084 MemberOfUnknownSpecialization); 2085 2086 if (MemberOfUnknownSpecialization || 2087 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2088 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2089 IsAddressOfOperand, TemplateArgs); 2090 } else { 2091 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2092 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2093 2094 // If the result might be in a dependent base class, this is a dependent 2095 // id-expression. 2096 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2097 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2098 IsAddressOfOperand, TemplateArgs); 2099 2100 // If this reference is in an Objective-C method, then we need to do 2101 // some special Objective-C lookup, too. 2102 if (IvarLookupFollowUp) { 2103 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2104 if (E.isInvalid()) 2105 return ExprError(); 2106 2107 if (Expr *Ex = E.getAs<Expr>()) 2108 return Ex; 2109 } 2110 } 2111 2112 if (R.isAmbiguous()) 2113 return ExprError(); 2114 2115 // This could be an implicitly declared function reference (legal in C90, 2116 // extension in C99, forbidden in C++). 2117 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2118 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2119 if (D) R.addDecl(D); 2120 } 2121 2122 // Determine whether this name might be a candidate for 2123 // argument-dependent lookup. 2124 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2125 2126 if (R.empty() && !ADL) { 2127 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2128 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2129 TemplateKWLoc, TemplateArgs)) 2130 return E; 2131 } 2132 2133 // Don't diagnose an empty lookup for inline assembly. 2134 if (IsInlineAsmIdentifier) 2135 return ExprError(); 2136 2137 // If this name wasn't predeclared and if this is not a function 2138 // call, diagnose the problem. 2139 TypoExpr *TE = nullptr; 2140 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2141 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2142 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2143 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2144 "Typo correction callback misconfigured"); 2145 if (CCC) { 2146 // Make sure the callback knows what the typo being diagnosed is. 2147 CCC->setTypoName(II); 2148 if (SS.isValid()) 2149 CCC->setTypoNNS(SS.getScopeRep()); 2150 } 2151 if (DiagnoseEmptyLookup(S, SS, R, 2152 CCC ? std::move(CCC) : std::move(DefaultValidator), 2153 nullptr, None, &TE)) { 2154 if (TE && KeywordReplacement) { 2155 auto &State = getTypoExprState(TE); 2156 auto BestTC = State.Consumer->getNextCorrection(); 2157 if (BestTC.isKeyword()) { 2158 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2159 if (State.DiagHandler) 2160 State.DiagHandler(BestTC); 2161 KeywordReplacement->startToken(); 2162 KeywordReplacement->setKind(II->getTokenID()); 2163 KeywordReplacement->setIdentifierInfo(II); 2164 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2165 // Clean up the state associated with the TypoExpr, since it has 2166 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2167 clearDelayedTypo(TE); 2168 // Signal that a correction to a keyword was performed by returning a 2169 // valid-but-null ExprResult. 2170 return (Expr*)nullptr; 2171 } 2172 State.Consumer->resetCorrectionStream(); 2173 } 2174 return TE ? TE : ExprError(); 2175 } 2176 2177 assert(!R.empty() && 2178 "DiagnoseEmptyLookup returned false but added no results"); 2179 2180 // If we found an Objective-C instance variable, let 2181 // LookupInObjCMethod build the appropriate expression to 2182 // reference the ivar. 2183 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2184 R.clear(); 2185 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2186 // In a hopelessly buggy code, Objective-C instance variable 2187 // lookup fails and no expression will be built to reference it. 2188 if (!E.isInvalid() && !E.get()) 2189 return ExprError(); 2190 return E; 2191 } 2192 } 2193 2194 // This is guaranteed from this point on. 2195 assert(!R.empty() || ADL); 2196 2197 // Check whether this might be a C++ implicit instance member access. 2198 // C++ [class.mfct.non-static]p3: 2199 // When an id-expression that is not part of a class member access 2200 // syntax and not used to form a pointer to member is used in the 2201 // body of a non-static member function of class X, if name lookup 2202 // resolves the name in the id-expression to a non-static non-type 2203 // member of some class C, the id-expression is transformed into a 2204 // class member access expression using (*this) as the 2205 // postfix-expression to the left of the . operator. 2206 // 2207 // But we don't actually need to do this for '&' operands if R 2208 // resolved to a function or overloaded function set, because the 2209 // expression is ill-formed if it actually works out to be a 2210 // non-static member function: 2211 // 2212 // C++ [expr.ref]p4: 2213 // Otherwise, if E1.E2 refers to a non-static member function. . . 2214 // [t]he expression can be used only as the left-hand operand of a 2215 // member function call. 2216 // 2217 // There are other safeguards against such uses, but it's important 2218 // to get this right here so that we don't end up making a 2219 // spuriously dependent expression if we're inside a dependent 2220 // instance method. 2221 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2222 bool MightBeImplicitMember; 2223 if (!IsAddressOfOperand) 2224 MightBeImplicitMember = true; 2225 else if (!SS.isEmpty()) 2226 MightBeImplicitMember = false; 2227 else if (R.isOverloadedResult()) 2228 MightBeImplicitMember = false; 2229 else if (R.isUnresolvableResult()) 2230 MightBeImplicitMember = true; 2231 else 2232 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2233 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2234 isa<MSPropertyDecl>(R.getFoundDecl()); 2235 2236 if (MightBeImplicitMember) 2237 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2238 R, TemplateArgs, S); 2239 } 2240 2241 if (TemplateArgs || TemplateKWLoc.isValid()) { 2242 2243 // In C++1y, if this is a variable template id, then check it 2244 // in BuildTemplateIdExpr(). 2245 // The single lookup result must be a variable template declaration. 2246 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2247 Id.TemplateId->Kind == TNK_Var_template) { 2248 assert(R.getAsSingle<VarTemplateDecl>() && 2249 "There should only be one declaration found."); 2250 } 2251 2252 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2253 } 2254 2255 return BuildDeclarationNameExpr(SS, R, ADL); 2256 } 2257 2258 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2259 /// declaration name, generally during template instantiation. 2260 /// There's a large number of things which don't need to be done along 2261 /// this path. 2262 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2263 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2264 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2265 DeclContext *DC = computeDeclContext(SS, false); 2266 if (!DC) 2267 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2268 NameInfo, /*TemplateArgs=*/nullptr); 2269 2270 if (RequireCompleteDeclContext(SS, DC)) 2271 return ExprError(); 2272 2273 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2274 LookupQualifiedName(R, DC); 2275 2276 if (R.isAmbiguous()) 2277 return ExprError(); 2278 2279 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2280 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2281 NameInfo, /*TemplateArgs=*/nullptr); 2282 2283 if (R.empty()) { 2284 Diag(NameInfo.getLoc(), diag::err_no_member) 2285 << NameInfo.getName() << DC << SS.getRange(); 2286 return ExprError(); 2287 } 2288 2289 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2290 // Diagnose a missing typename if this resolved unambiguously to a type in 2291 // a dependent context. If we can recover with a type, downgrade this to 2292 // a warning in Microsoft compatibility mode. 2293 unsigned DiagID = diag::err_typename_missing; 2294 if (RecoveryTSI && getLangOpts().MSVCCompat) 2295 DiagID = diag::ext_typename_missing; 2296 SourceLocation Loc = SS.getBeginLoc(); 2297 auto D = Diag(Loc, DiagID); 2298 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2299 << SourceRange(Loc, NameInfo.getEndLoc()); 2300 2301 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2302 // context. 2303 if (!RecoveryTSI) 2304 return ExprError(); 2305 2306 // Only issue the fixit if we're prepared to recover. 2307 D << FixItHint::CreateInsertion(Loc, "typename "); 2308 2309 // Recover by pretending this was an elaborated type. 2310 QualType Ty = Context.getTypeDeclType(TD); 2311 TypeLocBuilder TLB; 2312 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2313 2314 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2315 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2316 QTL.setElaboratedKeywordLoc(SourceLocation()); 2317 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2318 2319 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2320 2321 return ExprEmpty(); 2322 } 2323 2324 // Defend against this resolving to an implicit member access. We usually 2325 // won't get here if this might be a legitimate a class member (we end up in 2326 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2327 // a pointer-to-member or in an unevaluated context in C++11. 2328 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2329 return BuildPossibleImplicitMemberExpr(SS, 2330 /*TemplateKWLoc=*/SourceLocation(), 2331 R, /*TemplateArgs=*/nullptr, S); 2332 2333 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2334 } 2335 2336 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2337 /// detected that we're currently inside an ObjC method. Perform some 2338 /// additional lookup. 2339 /// 2340 /// Ideally, most of this would be done by lookup, but there's 2341 /// actually quite a lot of extra work involved. 2342 /// 2343 /// Returns a null sentinel to indicate trivial success. 2344 ExprResult 2345 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2346 IdentifierInfo *II, bool AllowBuiltinCreation) { 2347 SourceLocation Loc = Lookup.getNameLoc(); 2348 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2349 2350 // Check for error condition which is already reported. 2351 if (!CurMethod) 2352 return ExprError(); 2353 2354 // There are two cases to handle here. 1) scoped lookup could have failed, 2355 // in which case we should look for an ivar. 2) scoped lookup could have 2356 // found a decl, but that decl is outside the current instance method (i.e. 2357 // a global variable). In these two cases, we do a lookup for an ivar with 2358 // this name, if the lookup sucedes, we replace it our current decl. 2359 2360 // If we're in a class method, we don't normally want to look for 2361 // ivars. But if we don't find anything else, and there's an 2362 // ivar, that's an error. 2363 bool IsClassMethod = CurMethod->isClassMethod(); 2364 2365 bool LookForIvars; 2366 if (Lookup.empty()) 2367 LookForIvars = true; 2368 else if (IsClassMethod) 2369 LookForIvars = false; 2370 else 2371 LookForIvars = (Lookup.isSingleResult() && 2372 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2373 ObjCInterfaceDecl *IFace = nullptr; 2374 if (LookForIvars) { 2375 IFace = CurMethod->getClassInterface(); 2376 ObjCInterfaceDecl *ClassDeclared; 2377 ObjCIvarDecl *IV = nullptr; 2378 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2379 // Diagnose using an ivar in a class method. 2380 if (IsClassMethod) 2381 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2382 << IV->getDeclName()); 2383 2384 // If we're referencing an invalid decl, just return this as a silent 2385 // error node. The error diagnostic was already emitted on the decl. 2386 if (IV->isInvalidDecl()) 2387 return ExprError(); 2388 2389 // Check if referencing a field with __attribute__((deprecated)). 2390 if (DiagnoseUseOfDecl(IV, Loc)) 2391 return ExprError(); 2392 2393 // Diagnose the use of an ivar outside of the declaring class. 2394 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2395 !declaresSameEntity(ClassDeclared, IFace) && 2396 !getLangOpts().DebuggerSupport) 2397 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2398 2399 // FIXME: This should use a new expr for a direct reference, don't 2400 // turn this into Self->ivar, just return a BareIVarExpr or something. 2401 IdentifierInfo &II = Context.Idents.get("self"); 2402 UnqualifiedId SelfName; 2403 SelfName.setIdentifier(&II, SourceLocation()); 2404 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2405 CXXScopeSpec SelfScopeSpec; 2406 SourceLocation TemplateKWLoc; 2407 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2408 SelfName, false, false); 2409 if (SelfExpr.isInvalid()) 2410 return ExprError(); 2411 2412 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2413 if (SelfExpr.isInvalid()) 2414 return ExprError(); 2415 2416 MarkAnyDeclReferenced(Loc, IV, true); 2417 2418 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2419 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2420 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2421 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2422 2423 ObjCIvarRefExpr *Result = new (Context) 2424 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2425 IV->getLocation(), SelfExpr.get(), true, true); 2426 2427 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2428 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2429 recordUseOfEvaluatedWeak(Result); 2430 } 2431 if (getLangOpts().ObjCAutoRefCount) { 2432 if (CurContext->isClosure()) 2433 Diag(Loc, diag::warn_implicitly_retains_self) 2434 << FixItHint::CreateInsertion(Loc, "self->"); 2435 } 2436 2437 return Result; 2438 } 2439 } else if (CurMethod->isInstanceMethod()) { 2440 // We should warn if a local variable hides an ivar. 2441 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2442 ObjCInterfaceDecl *ClassDeclared; 2443 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2444 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2445 declaresSameEntity(IFace, ClassDeclared)) 2446 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2447 } 2448 } 2449 } else if (Lookup.isSingleResult() && 2450 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2451 // If accessing a stand-alone ivar in a class method, this is an error. 2452 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2453 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2454 << IV->getDeclName()); 2455 } 2456 2457 if (Lookup.empty() && II && AllowBuiltinCreation) { 2458 // FIXME. Consolidate this with similar code in LookupName. 2459 if (unsigned BuiltinID = II->getBuiltinID()) { 2460 if (!(getLangOpts().CPlusPlus && 2461 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2462 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2463 S, Lookup.isForRedeclaration(), 2464 Lookup.getNameLoc()); 2465 if (D) Lookup.addDecl(D); 2466 } 2467 } 2468 } 2469 // Sentinel value saying that we didn't do anything special. 2470 return ExprResult((Expr *)nullptr); 2471 } 2472 2473 /// \brief Cast a base object to a member's actual type. 2474 /// 2475 /// Logically this happens in three phases: 2476 /// 2477 /// * First we cast from the base type to the naming class. 2478 /// The naming class is the class into which we were looking 2479 /// when we found the member; it's the qualifier type if a 2480 /// qualifier was provided, and otherwise it's the base type. 2481 /// 2482 /// * Next we cast from the naming class to the declaring class. 2483 /// If the member we found was brought into a class's scope by 2484 /// a using declaration, this is that class; otherwise it's 2485 /// the class declaring the member. 2486 /// 2487 /// * Finally we cast from the declaring class to the "true" 2488 /// declaring class of the member. This conversion does not 2489 /// obey access control. 2490 ExprResult 2491 Sema::PerformObjectMemberConversion(Expr *From, 2492 NestedNameSpecifier *Qualifier, 2493 NamedDecl *FoundDecl, 2494 NamedDecl *Member) { 2495 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2496 if (!RD) 2497 return From; 2498 2499 QualType DestRecordType; 2500 QualType DestType; 2501 QualType FromRecordType; 2502 QualType FromType = From->getType(); 2503 bool PointerConversions = false; 2504 if (isa<FieldDecl>(Member)) { 2505 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2506 2507 if (FromType->getAs<PointerType>()) { 2508 DestType = Context.getPointerType(DestRecordType); 2509 FromRecordType = FromType->getPointeeType(); 2510 PointerConversions = true; 2511 } else { 2512 DestType = DestRecordType; 2513 FromRecordType = FromType; 2514 } 2515 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2516 if (Method->isStatic()) 2517 return From; 2518 2519 DestType = Method->getThisType(Context); 2520 DestRecordType = DestType->getPointeeType(); 2521 2522 if (FromType->getAs<PointerType>()) { 2523 FromRecordType = FromType->getPointeeType(); 2524 PointerConversions = true; 2525 } else { 2526 FromRecordType = FromType; 2527 DestType = DestRecordType; 2528 } 2529 } else { 2530 // No conversion necessary. 2531 return From; 2532 } 2533 2534 if (DestType->isDependentType() || FromType->isDependentType()) 2535 return From; 2536 2537 // If the unqualified types are the same, no conversion is necessary. 2538 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2539 return From; 2540 2541 SourceRange FromRange = From->getSourceRange(); 2542 SourceLocation FromLoc = FromRange.getBegin(); 2543 2544 ExprValueKind VK = From->getValueKind(); 2545 2546 // C++ [class.member.lookup]p8: 2547 // [...] Ambiguities can often be resolved by qualifying a name with its 2548 // class name. 2549 // 2550 // If the member was a qualified name and the qualified referred to a 2551 // specific base subobject type, we'll cast to that intermediate type 2552 // first and then to the object in which the member is declared. That allows 2553 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2554 // 2555 // class Base { public: int x; }; 2556 // class Derived1 : public Base { }; 2557 // class Derived2 : public Base { }; 2558 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2559 // 2560 // void VeryDerived::f() { 2561 // x = 17; // error: ambiguous base subobjects 2562 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2563 // } 2564 if (Qualifier && Qualifier->getAsType()) { 2565 QualType QType = QualType(Qualifier->getAsType(), 0); 2566 assert(QType->isRecordType() && "lookup done with non-record type"); 2567 2568 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2569 2570 // In C++98, the qualifier type doesn't actually have to be a base 2571 // type of the object type, in which case we just ignore it. 2572 // Otherwise build the appropriate casts. 2573 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2574 CXXCastPath BasePath; 2575 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2576 FromLoc, FromRange, &BasePath)) 2577 return ExprError(); 2578 2579 if (PointerConversions) 2580 QType = Context.getPointerType(QType); 2581 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2582 VK, &BasePath).get(); 2583 2584 FromType = QType; 2585 FromRecordType = QRecordType; 2586 2587 // If the qualifier type was the same as the destination type, 2588 // we're done. 2589 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2590 return From; 2591 } 2592 } 2593 2594 bool IgnoreAccess = false; 2595 2596 // If we actually found the member through a using declaration, cast 2597 // down to the using declaration's type. 2598 // 2599 // Pointer equality is fine here because only one declaration of a 2600 // class ever has member declarations. 2601 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2602 assert(isa<UsingShadowDecl>(FoundDecl)); 2603 QualType URecordType = Context.getTypeDeclType( 2604 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2605 2606 // We only need to do this if the naming-class to declaring-class 2607 // conversion is non-trivial. 2608 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2609 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2610 CXXCastPath BasePath; 2611 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2612 FromLoc, FromRange, &BasePath)) 2613 return ExprError(); 2614 2615 QualType UType = URecordType; 2616 if (PointerConversions) 2617 UType = Context.getPointerType(UType); 2618 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2619 VK, &BasePath).get(); 2620 FromType = UType; 2621 FromRecordType = URecordType; 2622 } 2623 2624 // We don't do access control for the conversion from the 2625 // declaring class to the true declaring class. 2626 IgnoreAccess = true; 2627 } 2628 2629 CXXCastPath BasePath; 2630 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2631 FromLoc, FromRange, &BasePath, 2632 IgnoreAccess)) 2633 return ExprError(); 2634 2635 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2636 VK, &BasePath); 2637 } 2638 2639 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2640 const LookupResult &R, 2641 bool HasTrailingLParen) { 2642 // Only when used directly as the postfix-expression of a call. 2643 if (!HasTrailingLParen) 2644 return false; 2645 2646 // Never if a scope specifier was provided. 2647 if (SS.isSet()) 2648 return false; 2649 2650 // Only in C++ or ObjC++. 2651 if (!getLangOpts().CPlusPlus) 2652 return false; 2653 2654 // Turn off ADL when we find certain kinds of declarations during 2655 // normal lookup: 2656 for (NamedDecl *D : R) { 2657 // C++0x [basic.lookup.argdep]p3: 2658 // -- a declaration of a class member 2659 // Since using decls preserve this property, we check this on the 2660 // original decl. 2661 if (D->isCXXClassMember()) 2662 return false; 2663 2664 // C++0x [basic.lookup.argdep]p3: 2665 // -- a block-scope function declaration that is not a 2666 // using-declaration 2667 // NOTE: we also trigger this for function templates (in fact, we 2668 // don't check the decl type at all, since all other decl types 2669 // turn off ADL anyway). 2670 if (isa<UsingShadowDecl>(D)) 2671 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2672 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2673 return false; 2674 2675 // C++0x [basic.lookup.argdep]p3: 2676 // -- a declaration that is neither a function or a function 2677 // template 2678 // And also for builtin functions. 2679 if (isa<FunctionDecl>(D)) { 2680 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2681 2682 // But also builtin functions. 2683 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2684 return false; 2685 } else if (!isa<FunctionTemplateDecl>(D)) 2686 return false; 2687 } 2688 2689 return true; 2690 } 2691 2692 2693 /// Diagnoses obvious problems with the use of the given declaration 2694 /// as an expression. This is only actually called for lookups that 2695 /// were not overloaded, and it doesn't promise that the declaration 2696 /// will in fact be used. 2697 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2698 if (D->isInvalidDecl()) 2699 return true; 2700 2701 if (isa<TypedefNameDecl>(D)) { 2702 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2703 return true; 2704 } 2705 2706 if (isa<ObjCInterfaceDecl>(D)) { 2707 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2708 return true; 2709 } 2710 2711 if (isa<NamespaceDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 return false; 2717 } 2718 2719 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2720 LookupResult &R, bool NeedsADL, 2721 bool AcceptInvalidDecl) { 2722 // If this is a single, fully-resolved result and we don't need ADL, 2723 // just build an ordinary singleton decl ref. 2724 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2725 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2726 R.getRepresentativeDecl(), nullptr, 2727 AcceptInvalidDecl); 2728 2729 // We only need to check the declaration if there's exactly one 2730 // result, because in the overloaded case the results can only be 2731 // functions and function templates. 2732 if (R.isSingleResult() && 2733 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2734 return ExprError(); 2735 2736 // Otherwise, just build an unresolved lookup expression. Suppress 2737 // any lookup-related diagnostics; we'll hash these out later, when 2738 // we've picked a target. 2739 R.suppressDiagnostics(); 2740 2741 UnresolvedLookupExpr *ULE 2742 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2743 SS.getWithLocInContext(Context), 2744 R.getLookupNameInfo(), 2745 NeedsADL, R.isOverloadedResult(), 2746 R.begin(), R.end()); 2747 2748 return ULE; 2749 } 2750 2751 static void 2752 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2753 ValueDecl *var, DeclContext *DC); 2754 2755 /// \brief Complete semantic analysis for a reference to the given declaration. 2756 ExprResult Sema::BuildDeclarationNameExpr( 2757 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2758 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2759 bool AcceptInvalidDecl) { 2760 assert(D && "Cannot refer to a NULL declaration"); 2761 assert(!isa<FunctionTemplateDecl>(D) && 2762 "Cannot refer unambiguously to a function template"); 2763 2764 SourceLocation Loc = NameInfo.getLoc(); 2765 if (CheckDeclInExpr(*this, Loc, D)) 2766 return ExprError(); 2767 2768 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2769 // Specifically diagnose references to class templates that are missing 2770 // a template argument list. 2771 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2772 << Template << SS.getRange(); 2773 Diag(Template->getLocation(), diag::note_template_decl_here); 2774 return ExprError(); 2775 } 2776 2777 // Make sure that we're referring to a value. 2778 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2779 if (!VD) { 2780 Diag(Loc, diag::err_ref_non_value) 2781 << D << SS.getRange(); 2782 Diag(D->getLocation(), diag::note_declared_at); 2783 return ExprError(); 2784 } 2785 2786 // Check whether this declaration can be used. Note that we suppress 2787 // this check when we're going to perform argument-dependent lookup 2788 // on this function name, because this might not be the function 2789 // that overload resolution actually selects. 2790 if (DiagnoseUseOfDecl(VD, Loc)) 2791 return ExprError(); 2792 2793 // Only create DeclRefExpr's for valid Decl's. 2794 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2795 return ExprError(); 2796 2797 // Handle members of anonymous structs and unions. If we got here, 2798 // and the reference is to a class member indirect field, then this 2799 // must be the subject of a pointer-to-member expression. 2800 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2801 if (!indirectField->isCXXClassMember()) 2802 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2803 indirectField); 2804 2805 { 2806 QualType type = VD->getType(); 2807 if (type.isNull()) 2808 return ExprError(); 2809 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2810 // C++ [except.spec]p17: 2811 // An exception-specification is considered to be needed when: 2812 // - in an expression, the function is the unique lookup result or 2813 // the selected member of a set of overloaded functions. 2814 ResolveExceptionSpec(Loc, FPT); 2815 type = VD->getType(); 2816 } 2817 ExprValueKind valueKind = VK_RValue; 2818 2819 switch (D->getKind()) { 2820 // Ignore all the non-ValueDecl kinds. 2821 #define ABSTRACT_DECL(kind) 2822 #define VALUE(type, base) 2823 #define DECL(type, base) \ 2824 case Decl::type: 2825 #include "clang/AST/DeclNodes.inc" 2826 llvm_unreachable("invalid value decl kind"); 2827 2828 // These shouldn't make it here. 2829 case Decl::ObjCAtDefsField: 2830 case Decl::ObjCIvar: 2831 llvm_unreachable("forming non-member reference to ivar?"); 2832 2833 // Enum constants are always r-values and never references. 2834 // Unresolved using declarations are dependent. 2835 case Decl::EnumConstant: 2836 case Decl::UnresolvedUsingValue: 2837 case Decl::OMPDeclareReduction: 2838 valueKind = VK_RValue; 2839 break; 2840 2841 // Fields and indirect fields that got here must be for 2842 // pointer-to-member expressions; we just call them l-values for 2843 // internal consistency, because this subexpression doesn't really 2844 // exist in the high-level semantics. 2845 case Decl::Field: 2846 case Decl::IndirectField: 2847 assert(getLangOpts().CPlusPlus && 2848 "building reference to field in C?"); 2849 2850 // These can't have reference type in well-formed programs, but 2851 // for internal consistency we do this anyway. 2852 type = type.getNonReferenceType(); 2853 valueKind = VK_LValue; 2854 break; 2855 2856 // Non-type template parameters are either l-values or r-values 2857 // depending on the type. 2858 case Decl::NonTypeTemplateParm: { 2859 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2860 type = reftype->getPointeeType(); 2861 valueKind = VK_LValue; // even if the parameter is an r-value reference 2862 break; 2863 } 2864 2865 // For non-references, we need to strip qualifiers just in case 2866 // the template parameter was declared as 'const int' or whatever. 2867 valueKind = VK_RValue; 2868 type = type.getUnqualifiedType(); 2869 break; 2870 } 2871 2872 case Decl::Var: 2873 case Decl::VarTemplateSpecialization: 2874 case Decl::VarTemplatePartialSpecialization: 2875 case Decl::Decomposition: 2876 case Decl::OMPCapturedExpr: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 // fallthrough 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Binding: { 2905 // These are always lvalues. 2906 valueKind = VK_LValue; 2907 type = type.getNonReferenceType(); 2908 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2909 // decides how that's supposed to work. 2910 auto *BD = cast<BindingDecl>(VD); 2911 if (BD->getDeclContext()->isFunctionOrMethod() && 2912 BD->getDeclContext() != CurContext) 2913 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2914 break; 2915 } 2916 2917 case Decl::Function: { 2918 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2919 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2920 type = Context.BuiltinFnTy; 2921 valueKind = VK_RValue; 2922 break; 2923 } 2924 } 2925 2926 const FunctionType *fty = type->castAs<FunctionType>(); 2927 2928 // If we're referring to a function with an __unknown_anytype 2929 // result type, make the entire expression __unknown_anytype. 2930 if (fty->getReturnType() == Context.UnknownAnyTy) { 2931 type = Context.UnknownAnyTy; 2932 valueKind = VK_RValue; 2933 break; 2934 } 2935 2936 // Functions are l-values in C++. 2937 if (getLangOpts().CPlusPlus) { 2938 valueKind = VK_LValue; 2939 break; 2940 } 2941 2942 // C99 DR 316 says that, if a function type comes from a 2943 // function definition (without a prototype), that type is only 2944 // used for checking compatibility. Therefore, when referencing 2945 // the function, we pretend that we don't have the full function 2946 // type. 2947 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2948 isa<FunctionProtoType>(fty)) 2949 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2950 fty->getExtInfo()); 2951 2952 // Functions are r-values in C. 2953 valueKind = VK_RValue; 2954 break; 2955 } 2956 2957 case Decl::CXXDeductionGuide: 2958 llvm_unreachable("building reference to deduction guide"); 2959 2960 case Decl::MSProperty: 2961 valueKind = VK_LValue; 2962 break; 2963 2964 case Decl::CXXMethod: 2965 // If we're referring to a method with an __unknown_anytype 2966 // result type, make the entire expression __unknown_anytype. 2967 // This should only be possible with a type written directly. 2968 if (const FunctionProtoType *proto 2969 = dyn_cast<FunctionProtoType>(VD->getType())) 2970 if (proto->getReturnType() == Context.UnknownAnyTy) { 2971 type = Context.UnknownAnyTy; 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 2976 // C++ methods are l-values if static, r-values if non-static. 2977 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2978 valueKind = VK_LValue; 2979 break; 2980 } 2981 // fallthrough 2982 2983 case Decl::CXXConversion: 2984 case Decl::CXXDestructor: 2985 case Decl::CXXConstructor: 2986 valueKind = VK_RValue; 2987 break; 2988 } 2989 2990 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2991 TemplateArgs); 2992 } 2993 } 2994 2995 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2996 SmallString<32> &Target) { 2997 Target.resize(CharByteWidth * (Source.size() + 1)); 2998 char *ResultPtr = &Target[0]; 2999 const llvm::UTF8 *ErrorPtr; 3000 bool success = 3001 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3002 (void)success; 3003 assert(success); 3004 Target.resize(ResultPtr - &Target[0]); 3005 } 3006 3007 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3008 PredefinedExpr::IdentType IT) { 3009 // Pick the current block, lambda, captured statement or function. 3010 Decl *currentDecl = nullptr; 3011 if (const BlockScopeInfo *BSI = getCurBlock()) 3012 currentDecl = BSI->TheDecl; 3013 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3014 currentDecl = LSI->CallOperator; 3015 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3016 currentDecl = CSI->TheCapturedDecl; 3017 else 3018 currentDecl = getCurFunctionOrMethodDecl(); 3019 3020 if (!currentDecl) { 3021 Diag(Loc, diag::ext_predef_outside_function); 3022 currentDecl = Context.getTranslationUnitDecl(); 3023 } 3024 3025 QualType ResTy; 3026 StringLiteral *SL = nullptr; 3027 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3028 ResTy = Context.DependentTy; 3029 else { 3030 // Pre-defined identifiers are of type char[x], where x is the length of 3031 // the string. 3032 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3033 unsigned Length = Str.length(); 3034 3035 llvm::APInt LengthI(32, Length + 1); 3036 if (IT == PredefinedExpr::LFunction) { 3037 ResTy = Context.WideCharTy.withConst(); 3038 SmallString<32> RawChars; 3039 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3040 Str, RawChars); 3041 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3042 /*IndexTypeQuals*/ 0); 3043 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3044 /*Pascal*/ false, ResTy, Loc); 3045 } else { 3046 ResTy = Context.CharTy.withConst(); 3047 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3048 /*IndexTypeQuals*/ 0); 3049 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3050 /*Pascal*/ false, ResTy, Loc); 3051 } 3052 } 3053 3054 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3055 } 3056 3057 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3058 PredefinedExpr::IdentType IT; 3059 3060 switch (Kind) { 3061 default: llvm_unreachable("Unknown simple primary expr!"); 3062 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3063 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3064 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3065 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3066 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3067 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3068 } 3069 3070 return BuildPredefinedExpr(Loc, IT); 3071 } 3072 3073 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3074 SmallString<16> CharBuffer; 3075 bool Invalid = false; 3076 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3077 if (Invalid) 3078 return ExprError(); 3079 3080 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3081 PP, Tok.getKind()); 3082 if (Literal.hadError()) 3083 return ExprError(); 3084 3085 QualType Ty; 3086 if (Literal.isWide()) 3087 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3088 else if (Literal.isUTF16()) 3089 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3090 else if (Literal.isUTF32()) 3091 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3092 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3093 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3094 else 3095 Ty = Context.CharTy; // 'x' -> char in C++ 3096 3097 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3098 if (Literal.isWide()) 3099 Kind = CharacterLiteral::Wide; 3100 else if (Literal.isUTF16()) 3101 Kind = CharacterLiteral::UTF16; 3102 else if (Literal.isUTF32()) 3103 Kind = CharacterLiteral::UTF32; 3104 else if (Literal.isUTF8()) 3105 Kind = CharacterLiteral::UTF8; 3106 3107 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3108 Tok.getLocation()); 3109 3110 if (Literal.getUDSuffix().empty()) 3111 return Lit; 3112 3113 // We're building a user-defined literal. 3114 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3115 SourceLocation UDSuffixLoc = 3116 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3117 3118 // Make sure we're allowed user-defined literals here. 3119 if (!UDLScope) 3120 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3121 3122 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3123 // operator "" X (ch) 3124 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3125 Lit, Tok.getLocation()); 3126 } 3127 3128 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3129 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3130 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3131 Context.IntTy, Loc); 3132 } 3133 3134 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3135 QualType Ty, SourceLocation Loc) { 3136 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3137 3138 using llvm::APFloat; 3139 APFloat Val(Format); 3140 3141 APFloat::opStatus result = Literal.GetFloatValue(Val); 3142 3143 // Overflow is always an error, but underflow is only an error if 3144 // we underflowed to zero (APFloat reports denormals as underflow). 3145 if ((result & APFloat::opOverflow) || 3146 ((result & APFloat::opUnderflow) && Val.isZero())) { 3147 unsigned diagnostic; 3148 SmallString<20> buffer; 3149 if (result & APFloat::opOverflow) { 3150 diagnostic = diag::warn_float_overflow; 3151 APFloat::getLargest(Format).toString(buffer); 3152 } else { 3153 diagnostic = diag::warn_float_underflow; 3154 APFloat::getSmallest(Format).toString(buffer); 3155 } 3156 3157 S.Diag(Loc, diagnostic) 3158 << Ty 3159 << StringRef(buffer.data(), buffer.size()); 3160 } 3161 3162 bool isExact = (result == APFloat::opOK); 3163 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3164 } 3165 3166 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3167 assert(E && "Invalid expression"); 3168 3169 if (E->isValueDependent()) 3170 return false; 3171 3172 QualType QT = E->getType(); 3173 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3174 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3175 return true; 3176 } 3177 3178 llvm::APSInt ValueAPS; 3179 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3180 3181 if (R.isInvalid()) 3182 return true; 3183 3184 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3185 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3186 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3187 << ValueAPS.toString(10) << ValueIsPositive; 3188 return true; 3189 } 3190 3191 return false; 3192 } 3193 3194 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3195 // Fast path for a single digit (which is quite common). A single digit 3196 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3197 if (Tok.getLength() == 1) { 3198 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3199 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3200 } 3201 3202 SmallString<128> SpellingBuffer; 3203 // NumericLiteralParser wants to overread by one character. Add padding to 3204 // the buffer in case the token is copied to the buffer. If getSpelling() 3205 // returns a StringRef to the memory buffer, it should have a null char at 3206 // the EOF, so it is also safe. 3207 SpellingBuffer.resize(Tok.getLength() + 1); 3208 3209 // Get the spelling of the token, which eliminates trigraphs, etc. 3210 bool Invalid = false; 3211 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3212 if (Invalid) 3213 return ExprError(); 3214 3215 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3216 if (Literal.hadError) 3217 return ExprError(); 3218 3219 if (Literal.hasUDSuffix()) { 3220 // We're building a user-defined literal. 3221 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3222 SourceLocation UDSuffixLoc = 3223 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3224 3225 // Make sure we're allowed user-defined literals here. 3226 if (!UDLScope) 3227 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3228 3229 QualType CookedTy; 3230 if (Literal.isFloatingLiteral()) { 3231 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3232 // long double, the literal is treated as a call of the form 3233 // operator "" X (f L) 3234 CookedTy = Context.LongDoubleTy; 3235 } else { 3236 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3237 // unsigned long long, the literal is treated as a call of the form 3238 // operator "" X (n ULL) 3239 CookedTy = Context.UnsignedLongLongTy; 3240 } 3241 3242 DeclarationName OpName = 3243 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3244 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3245 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3246 3247 SourceLocation TokLoc = Tok.getLocation(); 3248 3249 // Perform literal operator lookup to determine if we're building a raw 3250 // literal or a cooked one. 3251 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3252 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3253 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3254 /*AllowStringTemplate*/ false, 3255 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3256 case LOLR_ErrorNoDiagnostic: 3257 // Lookup failure for imaginary constants isn't fatal, there's still the 3258 // GNU extension producing _Complex types. 3259 break; 3260 case LOLR_Error: 3261 return ExprError(); 3262 case LOLR_Cooked: { 3263 Expr *Lit; 3264 if (Literal.isFloatingLiteral()) { 3265 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3266 } else { 3267 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3268 if (Literal.GetIntegerValue(ResultVal)) 3269 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3270 << /* Unsigned */ 1; 3271 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3272 Tok.getLocation()); 3273 } 3274 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3275 } 3276 3277 case LOLR_Raw: { 3278 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3279 // literal is treated as a call of the form 3280 // operator "" X ("n") 3281 unsigned Length = Literal.getUDSuffixOffset(); 3282 QualType StrTy = Context.getConstantArrayType( 3283 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3284 ArrayType::Normal, 0); 3285 Expr *Lit = StringLiteral::Create( 3286 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3287 /*Pascal*/false, StrTy, &TokLoc, 1); 3288 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3289 } 3290 3291 case LOLR_Template: { 3292 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3293 // template), L is treated as a call fo the form 3294 // operator "" X <'c1', 'c2', ... 'ck'>() 3295 // where n is the source character sequence c1 c2 ... ck. 3296 TemplateArgumentListInfo ExplicitArgs; 3297 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3298 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3299 llvm::APSInt Value(CharBits, CharIsUnsigned); 3300 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3301 Value = TokSpelling[I]; 3302 TemplateArgument Arg(Context, Value, Context.CharTy); 3303 TemplateArgumentLocInfo ArgInfo; 3304 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3305 } 3306 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3307 &ExplicitArgs); 3308 } 3309 case LOLR_StringTemplate: 3310 llvm_unreachable("unexpected literal operator lookup result"); 3311 } 3312 } 3313 3314 Expr *Res; 3315 3316 if (Literal.isFloatingLiteral()) { 3317 QualType Ty; 3318 if (Literal.isHalf){ 3319 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3320 Ty = Context.HalfTy; 3321 else { 3322 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3323 return ExprError(); 3324 } 3325 } else if (Literal.isFloat) 3326 Ty = Context.FloatTy; 3327 else if (Literal.isLong) 3328 Ty = Context.LongDoubleTy; 3329 else if (Literal.isFloat16) 3330 Ty = Context.Float16Ty; 3331 else if (Literal.isFloat128) 3332 Ty = Context.Float128Ty; 3333 else 3334 Ty = Context.DoubleTy; 3335 3336 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3337 3338 if (Ty == Context.DoubleTy) { 3339 if (getLangOpts().SinglePrecisionConstants) { 3340 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3341 if (BTy->getKind() != BuiltinType::Float) { 3342 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3343 } 3344 } else if (getLangOpts().OpenCL && 3345 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3346 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3347 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3348 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3349 } 3350 } 3351 } else if (!Literal.isIntegerLiteral()) { 3352 return ExprError(); 3353 } else { 3354 QualType Ty; 3355 3356 // 'long long' is a C99 or C++11 feature. 3357 if (!getLangOpts().C99 && Literal.isLongLong) { 3358 if (getLangOpts().CPlusPlus) 3359 Diag(Tok.getLocation(), 3360 getLangOpts().CPlusPlus11 ? 3361 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3362 else 3363 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3364 } 3365 3366 // Get the value in the widest-possible width. 3367 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3368 llvm::APInt ResultVal(MaxWidth, 0); 3369 3370 if (Literal.GetIntegerValue(ResultVal)) { 3371 // If this value didn't fit into uintmax_t, error and force to ull. 3372 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3373 << /* Unsigned */ 1; 3374 Ty = Context.UnsignedLongLongTy; 3375 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3376 "long long is not intmax_t?"); 3377 } else { 3378 // If this value fits into a ULL, try to figure out what else it fits into 3379 // according to the rules of C99 6.4.4.1p5. 3380 3381 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3382 // be an unsigned int. 3383 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3384 3385 // Check from smallest to largest, picking the smallest type we can. 3386 unsigned Width = 0; 3387 3388 // Microsoft specific integer suffixes are explicitly sized. 3389 if (Literal.MicrosoftInteger) { 3390 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3391 Width = 8; 3392 Ty = Context.CharTy; 3393 } else { 3394 Width = Literal.MicrosoftInteger; 3395 Ty = Context.getIntTypeForBitwidth(Width, 3396 /*Signed=*/!Literal.isUnsigned); 3397 } 3398 } 3399 3400 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3401 // Are int/unsigned possibilities? 3402 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3403 3404 // Does it fit in a unsigned int? 3405 if (ResultVal.isIntN(IntSize)) { 3406 // Does it fit in a signed int? 3407 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3408 Ty = Context.IntTy; 3409 else if (AllowUnsigned) 3410 Ty = Context.UnsignedIntTy; 3411 Width = IntSize; 3412 } 3413 } 3414 3415 // Are long/unsigned long possibilities? 3416 if (Ty.isNull() && !Literal.isLongLong) { 3417 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3418 3419 // Does it fit in a unsigned long? 3420 if (ResultVal.isIntN(LongSize)) { 3421 // Does it fit in a signed long? 3422 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3423 Ty = Context.LongTy; 3424 else if (AllowUnsigned) 3425 Ty = Context.UnsignedLongTy; 3426 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3427 // is compatible. 3428 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3429 const unsigned LongLongSize = 3430 Context.getTargetInfo().getLongLongWidth(); 3431 Diag(Tok.getLocation(), 3432 getLangOpts().CPlusPlus 3433 ? Literal.isLong 3434 ? diag::warn_old_implicitly_unsigned_long_cxx 3435 : /*C++98 UB*/ diag:: 3436 ext_old_implicitly_unsigned_long_cxx 3437 : diag::warn_old_implicitly_unsigned_long) 3438 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3439 : /*will be ill-formed*/ 1); 3440 Ty = Context.UnsignedLongTy; 3441 } 3442 Width = LongSize; 3443 } 3444 } 3445 3446 // Check long long if needed. 3447 if (Ty.isNull()) { 3448 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3449 3450 // Does it fit in a unsigned long long? 3451 if (ResultVal.isIntN(LongLongSize)) { 3452 // Does it fit in a signed long long? 3453 // To be compatible with MSVC, hex integer literals ending with the 3454 // LL or i64 suffix are always signed in Microsoft mode. 3455 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3456 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3457 Ty = Context.LongLongTy; 3458 else if (AllowUnsigned) 3459 Ty = Context.UnsignedLongLongTy; 3460 Width = LongLongSize; 3461 } 3462 } 3463 3464 // If we still couldn't decide a type, we probably have something that 3465 // does not fit in a signed long long, but has no U suffix. 3466 if (Ty.isNull()) { 3467 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3468 Ty = Context.UnsignedLongLongTy; 3469 Width = Context.getTargetInfo().getLongLongWidth(); 3470 } 3471 3472 if (ResultVal.getBitWidth() != Width) 3473 ResultVal = ResultVal.trunc(Width); 3474 } 3475 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3476 } 3477 3478 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3479 if (Literal.isImaginary) { 3480 Res = new (Context) ImaginaryLiteral(Res, 3481 Context.getComplexType(Res->getType())); 3482 3483 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3484 } 3485 return Res; 3486 } 3487 3488 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3489 assert(E && "ActOnParenExpr() missing expr"); 3490 return new (Context) ParenExpr(L, R, E); 3491 } 3492 3493 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3494 SourceLocation Loc, 3495 SourceRange ArgRange) { 3496 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3497 // scalar or vector data type argument..." 3498 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3499 // type (C99 6.2.5p18) or void. 3500 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3501 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3502 << T << ArgRange; 3503 return true; 3504 } 3505 3506 assert((T->isVoidType() || !T->isIncompleteType()) && 3507 "Scalar types should always be complete"); 3508 return false; 3509 } 3510 3511 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3512 SourceLocation Loc, 3513 SourceRange ArgRange, 3514 UnaryExprOrTypeTrait TraitKind) { 3515 // Invalid types must be hard errors for SFINAE in C++. 3516 if (S.LangOpts.CPlusPlus) 3517 return true; 3518 3519 // C99 6.5.3.4p1: 3520 if (T->isFunctionType() && 3521 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3522 // sizeof(function)/alignof(function) is allowed as an extension. 3523 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3524 << TraitKind << ArgRange; 3525 return false; 3526 } 3527 3528 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3529 // this is an error (OpenCL v1.1 s6.3.k) 3530 if (T->isVoidType()) { 3531 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3532 : diag::ext_sizeof_alignof_void_type; 3533 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3534 return false; 3535 } 3536 3537 return true; 3538 } 3539 3540 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3541 SourceLocation Loc, 3542 SourceRange ArgRange, 3543 UnaryExprOrTypeTrait TraitKind) { 3544 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3545 // runtime doesn't allow it. 3546 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3547 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3548 << T << (TraitKind == UETT_SizeOf) 3549 << ArgRange; 3550 return true; 3551 } 3552 3553 return false; 3554 } 3555 3556 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3557 /// pointer type is equal to T) and emit a warning if it is. 3558 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3559 Expr *E) { 3560 // Don't warn if the operation changed the type. 3561 if (T != E->getType()) 3562 return; 3563 3564 // Now look for array decays. 3565 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3566 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3567 return; 3568 3569 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3570 << ICE->getType() 3571 << ICE->getSubExpr()->getType(); 3572 } 3573 3574 /// \brief Check the constraints on expression operands to unary type expression 3575 /// and type traits. 3576 /// 3577 /// Completes any types necessary and validates the constraints on the operand 3578 /// expression. The logic mostly mirrors the type-based overload, but may modify 3579 /// the expression as it completes the type for that expression through template 3580 /// instantiation, etc. 3581 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3582 UnaryExprOrTypeTrait ExprKind) { 3583 QualType ExprTy = E->getType(); 3584 assert(!ExprTy->isReferenceType()); 3585 3586 if (ExprKind == UETT_VecStep) 3587 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3588 E->getSourceRange()); 3589 3590 // Whitelist some types as extensions 3591 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3592 E->getSourceRange(), ExprKind)) 3593 return false; 3594 3595 // 'alignof' applied to an expression only requires the base element type of 3596 // the expression to be complete. 'sizeof' requires the expression's type to 3597 // be complete (and will attempt to complete it if it's an array of unknown 3598 // bound). 3599 if (ExprKind == UETT_AlignOf) { 3600 if (RequireCompleteType(E->getExprLoc(), 3601 Context.getBaseElementType(E->getType()), 3602 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3603 E->getSourceRange())) 3604 return true; 3605 } else { 3606 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3607 ExprKind, E->getSourceRange())) 3608 return true; 3609 } 3610 3611 // Completing the expression's type may have changed it. 3612 ExprTy = E->getType(); 3613 assert(!ExprTy->isReferenceType()); 3614 3615 if (ExprTy->isFunctionType()) { 3616 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3617 << ExprKind << E->getSourceRange(); 3618 return true; 3619 } 3620 3621 // The operand for sizeof and alignof is in an unevaluated expression context, 3622 // so side effects could result in unintended consequences. 3623 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3624 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3625 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3626 3627 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3628 E->getSourceRange(), ExprKind)) 3629 return true; 3630 3631 if (ExprKind == UETT_SizeOf) { 3632 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3633 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3634 QualType OType = PVD->getOriginalType(); 3635 QualType Type = PVD->getType(); 3636 if (Type->isPointerType() && OType->isArrayType()) { 3637 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3638 << Type << OType; 3639 Diag(PVD->getLocation(), diag::note_declared_at); 3640 } 3641 } 3642 } 3643 3644 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3645 // decays into a pointer and returns an unintended result. This is most 3646 // likely a typo for "sizeof(array) op x". 3647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3648 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3649 BO->getLHS()); 3650 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3651 BO->getRHS()); 3652 } 3653 } 3654 3655 return false; 3656 } 3657 3658 /// \brief Check the constraints on operands to unary expression and type 3659 /// traits. 3660 /// 3661 /// This will complete any types necessary, and validate the various constraints 3662 /// on those operands. 3663 /// 3664 /// The UsualUnaryConversions() function is *not* called by this routine. 3665 /// C99 6.3.2.1p[2-4] all state: 3666 /// Except when it is the operand of the sizeof operator ... 3667 /// 3668 /// C++ [expr.sizeof]p4 3669 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3670 /// standard conversions are not applied to the operand of sizeof. 3671 /// 3672 /// This policy is followed for all of the unary trait expressions. 3673 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3674 SourceLocation OpLoc, 3675 SourceRange ExprRange, 3676 UnaryExprOrTypeTrait ExprKind) { 3677 if (ExprType->isDependentType()) 3678 return false; 3679 3680 // C++ [expr.sizeof]p2: 3681 // When applied to a reference or a reference type, the result 3682 // is the size of the referenced type. 3683 // C++11 [expr.alignof]p3: 3684 // When alignof is applied to a reference type, the result 3685 // shall be the alignment of the referenced type. 3686 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3687 ExprType = Ref->getPointeeType(); 3688 3689 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3690 // When alignof or _Alignof is applied to an array type, the result 3691 // is the alignment of the element type. 3692 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3693 ExprType = Context.getBaseElementType(ExprType); 3694 3695 if (ExprKind == UETT_VecStep) 3696 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3697 3698 // Whitelist some types as extensions 3699 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3700 ExprKind)) 3701 return false; 3702 3703 if (RequireCompleteType(OpLoc, ExprType, 3704 diag::err_sizeof_alignof_incomplete_type, 3705 ExprKind, ExprRange)) 3706 return true; 3707 3708 if (ExprType->isFunctionType()) { 3709 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3710 << ExprKind << ExprRange; 3711 return true; 3712 } 3713 3714 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3715 ExprKind)) 3716 return true; 3717 3718 return false; 3719 } 3720 3721 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3722 E = E->IgnoreParens(); 3723 3724 // Cannot know anything else if the expression is dependent. 3725 if (E->isTypeDependent()) 3726 return false; 3727 3728 if (E->getObjectKind() == OK_BitField) { 3729 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3730 << 1 << E->getSourceRange(); 3731 return true; 3732 } 3733 3734 ValueDecl *D = nullptr; 3735 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3736 D = DRE->getDecl(); 3737 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3738 D = ME->getMemberDecl(); 3739 } 3740 3741 // If it's a field, require the containing struct to have a 3742 // complete definition so that we can compute the layout. 3743 // 3744 // This can happen in C++11 onwards, either by naming the member 3745 // in a way that is not transformed into a member access expression 3746 // (in an unevaluated operand, for instance), or by naming the member 3747 // in a trailing-return-type. 3748 // 3749 // For the record, since __alignof__ on expressions is a GCC 3750 // extension, GCC seems to permit this but always gives the 3751 // nonsensical answer 0. 3752 // 3753 // We don't really need the layout here --- we could instead just 3754 // directly check for all the appropriate alignment-lowing 3755 // attributes --- but that would require duplicating a lot of 3756 // logic that just isn't worth duplicating for such a marginal 3757 // use-case. 3758 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3759 // Fast path this check, since we at least know the record has a 3760 // definition if we can find a member of it. 3761 if (!FD->getParent()->isCompleteDefinition()) { 3762 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3763 << E->getSourceRange(); 3764 return true; 3765 } 3766 3767 // Otherwise, if it's a field, and the field doesn't have 3768 // reference type, then it must have a complete type (or be a 3769 // flexible array member, which we explicitly want to 3770 // white-list anyway), which makes the following checks trivial. 3771 if (!FD->getType()->isReferenceType()) 3772 return false; 3773 } 3774 3775 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3776 } 3777 3778 bool Sema::CheckVecStepExpr(Expr *E) { 3779 E = E->IgnoreParens(); 3780 3781 // Cannot know anything else if the expression is dependent. 3782 if (E->isTypeDependent()) 3783 return false; 3784 3785 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3786 } 3787 3788 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3789 CapturingScopeInfo *CSI) { 3790 assert(T->isVariablyModifiedType()); 3791 assert(CSI != nullptr); 3792 3793 // We're going to walk down into the type and look for VLA expressions. 3794 do { 3795 const Type *Ty = T.getTypePtr(); 3796 switch (Ty->getTypeClass()) { 3797 #define TYPE(Class, Base) 3798 #define ABSTRACT_TYPE(Class, Base) 3799 #define NON_CANONICAL_TYPE(Class, Base) 3800 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3801 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3802 #include "clang/AST/TypeNodes.def" 3803 T = QualType(); 3804 break; 3805 // These types are never variably-modified. 3806 case Type::Builtin: 3807 case Type::Complex: 3808 case Type::Vector: 3809 case Type::ExtVector: 3810 case Type::Record: 3811 case Type::Enum: 3812 case Type::Elaborated: 3813 case Type::TemplateSpecialization: 3814 case Type::ObjCObject: 3815 case Type::ObjCInterface: 3816 case Type::ObjCObjectPointer: 3817 case Type::ObjCTypeParam: 3818 case Type::Pipe: 3819 llvm_unreachable("type class is never variably-modified!"); 3820 case Type::Adjusted: 3821 T = cast<AdjustedType>(Ty)->getOriginalType(); 3822 break; 3823 case Type::Decayed: 3824 T = cast<DecayedType>(Ty)->getPointeeType(); 3825 break; 3826 case Type::Pointer: 3827 T = cast<PointerType>(Ty)->getPointeeType(); 3828 break; 3829 case Type::BlockPointer: 3830 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3831 break; 3832 case Type::LValueReference: 3833 case Type::RValueReference: 3834 T = cast<ReferenceType>(Ty)->getPointeeType(); 3835 break; 3836 case Type::MemberPointer: 3837 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3838 break; 3839 case Type::ConstantArray: 3840 case Type::IncompleteArray: 3841 // Losing element qualification here is fine. 3842 T = cast<ArrayType>(Ty)->getElementType(); 3843 break; 3844 case Type::VariableArray: { 3845 // Losing element qualification here is fine. 3846 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3847 3848 // Unknown size indication requires no size computation. 3849 // Otherwise, evaluate and record it. 3850 if (auto Size = VAT->getSizeExpr()) { 3851 if (!CSI->isVLATypeCaptured(VAT)) { 3852 RecordDecl *CapRecord = nullptr; 3853 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3854 CapRecord = LSI->Lambda; 3855 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3856 CapRecord = CRSI->TheRecordDecl; 3857 } 3858 if (CapRecord) { 3859 auto ExprLoc = Size->getExprLoc(); 3860 auto SizeType = Context.getSizeType(); 3861 // Build the non-static data member. 3862 auto Field = 3863 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3864 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3865 /*BW*/ nullptr, /*Mutable*/ false, 3866 /*InitStyle*/ ICIS_NoInit); 3867 Field->setImplicit(true); 3868 Field->setAccess(AS_private); 3869 Field->setCapturedVLAType(VAT); 3870 CapRecord->addDecl(Field); 3871 3872 CSI->addVLATypeCapture(ExprLoc, SizeType); 3873 } 3874 } 3875 } 3876 T = VAT->getElementType(); 3877 break; 3878 } 3879 case Type::FunctionProto: 3880 case Type::FunctionNoProto: 3881 T = cast<FunctionType>(Ty)->getReturnType(); 3882 break; 3883 case Type::Paren: 3884 case Type::TypeOf: 3885 case Type::UnaryTransform: 3886 case Type::Attributed: 3887 case Type::SubstTemplateTypeParm: 3888 case Type::PackExpansion: 3889 // Keep walking after single level desugaring. 3890 T = T.getSingleStepDesugaredType(Context); 3891 break; 3892 case Type::Typedef: 3893 T = cast<TypedefType>(Ty)->desugar(); 3894 break; 3895 case Type::Decltype: 3896 T = cast<DecltypeType>(Ty)->desugar(); 3897 break; 3898 case Type::Auto: 3899 case Type::DeducedTemplateSpecialization: 3900 T = cast<DeducedType>(Ty)->getDeducedType(); 3901 break; 3902 case Type::TypeOfExpr: 3903 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3904 break; 3905 case Type::Atomic: 3906 T = cast<AtomicType>(Ty)->getValueType(); 3907 break; 3908 } 3909 } while (!T.isNull() && T->isVariablyModifiedType()); 3910 } 3911 3912 /// \brief Build a sizeof or alignof expression given a type operand. 3913 ExprResult 3914 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3915 SourceLocation OpLoc, 3916 UnaryExprOrTypeTrait ExprKind, 3917 SourceRange R) { 3918 if (!TInfo) 3919 return ExprError(); 3920 3921 QualType T = TInfo->getType(); 3922 3923 if (!T->isDependentType() && 3924 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3925 return ExprError(); 3926 3927 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3928 if (auto *TT = T->getAs<TypedefType>()) { 3929 for (auto I = FunctionScopes.rbegin(), 3930 E = std::prev(FunctionScopes.rend()); 3931 I != E; ++I) { 3932 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3933 if (CSI == nullptr) 3934 break; 3935 DeclContext *DC = nullptr; 3936 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3937 DC = LSI->CallOperator; 3938 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3939 DC = CRSI->TheCapturedDecl; 3940 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3941 DC = BSI->TheDecl; 3942 if (DC) { 3943 if (DC->containsDecl(TT->getDecl())) 3944 break; 3945 captureVariablyModifiedType(Context, T, CSI); 3946 } 3947 } 3948 } 3949 } 3950 3951 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3952 return new (Context) UnaryExprOrTypeTraitExpr( 3953 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3954 } 3955 3956 /// \brief Build a sizeof or alignof expression given an expression 3957 /// operand. 3958 ExprResult 3959 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3960 UnaryExprOrTypeTrait ExprKind) { 3961 ExprResult PE = CheckPlaceholderExpr(E); 3962 if (PE.isInvalid()) 3963 return ExprError(); 3964 3965 E = PE.get(); 3966 3967 // Verify that the operand is valid. 3968 bool isInvalid = false; 3969 if (E->isTypeDependent()) { 3970 // Delay type-checking for type-dependent expressions. 3971 } else if (ExprKind == UETT_AlignOf) { 3972 isInvalid = CheckAlignOfExpr(*this, E); 3973 } else if (ExprKind == UETT_VecStep) { 3974 isInvalid = CheckVecStepExpr(E); 3975 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3976 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3977 isInvalid = true; 3978 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3979 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3980 isInvalid = true; 3981 } else { 3982 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3983 } 3984 3985 if (isInvalid) 3986 return ExprError(); 3987 3988 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3989 PE = TransformToPotentiallyEvaluated(E); 3990 if (PE.isInvalid()) return ExprError(); 3991 E = PE.get(); 3992 } 3993 3994 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3995 return new (Context) UnaryExprOrTypeTraitExpr( 3996 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3997 } 3998 3999 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4000 /// expr and the same for @c alignof and @c __alignof 4001 /// Note that the ArgRange is invalid if isType is false. 4002 ExprResult 4003 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4004 UnaryExprOrTypeTrait ExprKind, bool IsType, 4005 void *TyOrEx, SourceRange ArgRange) { 4006 // If error parsing type, ignore. 4007 if (!TyOrEx) return ExprError(); 4008 4009 if (IsType) { 4010 TypeSourceInfo *TInfo; 4011 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4012 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4013 } 4014 4015 Expr *ArgEx = (Expr *)TyOrEx; 4016 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4017 return Result; 4018 } 4019 4020 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4021 bool IsReal) { 4022 if (V.get()->isTypeDependent()) 4023 return S.Context.DependentTy; 4024 4025 // _Real and _Imag are only l-values for normal l-values. 4026 if (V.get()->getObjectKind() != OK_Ordinary) { 4027 V = S.DefaultLvalueConversion(V.get()); 4028 if (V.isInvalid()) 4029 return QualType(); 4030 } 4031 4032 // These operators return the element type of a complex type. 4033 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4034 return CT->getElementType(); 4035 4036 // Otherwise they pass through real integer and floating point types here. 4037 if (V.get()->getType()->isArithmeticType()) 4038 return V.get()->getType(); 4039 4040 // Test for placeholders. 4041 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4042 if (PR.isInvalid()) return QualType(); 4043 if (PR.get() != V.get()) { 4044 V = PR; 4045 return CheckRealImagOperand(S, V, Loc, IsReal); 4046 } 4047 4048 // Reject anything else. 4049 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4050 << (IsReal ? "__real" : "__imag"); 4051 return QualType(); 4052 } 4053 4054 4055 4056 ExprResult 4057 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4058 tok::TokenKind Kind, Expr *Input) { 4059 UnaryOperatorKind Opc; 4060 switch (Kind) { 4061 default: llvm_unreachable("Unknown unary op!"); 4062 case tok::plusplus: Opc = UO_PostInc; break; 4063 case tok::minusminus: Opc = UO_PostDec; break; 4064 } 4065 4066 // Since this might is a postfix expression, get rid of ParenListExprs. 4067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4068 if (Result.isInvalid()) return ExprError(); 4069 Input = Result.get(); 4070 4071 return BuildUnaryOp(S, OpLoc, Opc, Input); 4072 } 4073 4074 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4075 /// 4076 /// \return true on error 4077 static bool checkArithmeticOnObjCPointer(Sema &S, 4078 SourceLocation opLoc, 4079 Expr *op) { 4080 assert(op->getType()->isObjCObjectPointerType()); 4081 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4082 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4083 return false; 4084 4085 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4086 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4087 << op->getSourceRange(); 4088 return true; 4089 } 4090 4091 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4092 auto *BaseNoParens = Base->IgnoreParens(); 4093 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4094 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4095 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4096 } 4097 4098 ExprResult 4099 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4100 Expr *idx, SourceLocation rbLoc) { 4101 if (base && !base->getType().isNull() && 4102 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4103 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4104 /*Length=*/nullptr, rbLoc); 4105 4106 // Since this might be a postfix expression, get rid of ParenListExprs. 4107 if (isa<ParenListExpr>(base)) { 4108 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4109 if (result.isInvalid()) return ExprError(); 4110 base = result.get(); 4111 } 4112 4113 // Handle any non-overload placeholder types in the base and index 4114 // expressions. We can't handle overloads here because the other 4115 // operand might be an overloadable type, in which case the overload 4116 // resolution for the operator overload should get the first crack 4117 // at the overload. 4118 bool IsMSPropertySubscript = false; 4119 if (base->getType()->isNonOverloadPlaceholderType()) { 4120 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4121 if (!IsMSPropertySubscript) { 4122 ExprResult result = CheckPlaceholderExpr(base); 4123 if (result.isInvalid()) 4124 return ExprError(); 4125 base = result.get(); 4126 } 4127 } 4128 if (idx->getType()->isNonOverloadPlaceholderType()) { 4129 ExprResult result = CheckPlaceholderExpr(idx); 4130 if (result.isInvalid()) return ExprError(); 4131 idx = result.get(); 4132 } 4133 4134 // Build an unanalyzed expression if either operand is type-dependent. 4135 if (getLangOpts().CPlusPlus && 4136 (base->isTypeDependent() || idx->isTypeDependent())) { 4137 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4138 VK_LValue, OK_Ordinary, rbLoc); 4139 } 4140 4141 // MSDN, property (C++) 4142 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4143 // This attribute can also be used in the declaration of an empty array in a 4144 // class or structure definition. For example: 4145 // __declspec(property(get=GetX, put=PutX)) int x[]; 4146 // The above statement indicates that x[] can be used with one or more array 4147 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4148 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4149 if (IsMSPropertySubscript) { 4150 // Build MS property subscript expression if base is MS property reference 4151 // or MS property subscript. 4152 return new (Context) MSPropertySubscriptExpr( 4153 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4154 } 4155 4156 // Use C++ overloaded-operator rules if either operand has record 4157 // type. The spec says to do this if either type is *overloadable*, 4158 // but enum types can't declare subscript operators or conversion 4159 // operators, so there's nothing interesting for overload resolution 4160 // to do if there aren't any record types involved. 4161 // 4162 // ObjC pointers have their own subscripting logic that is not tied 4163 // to overload resolution and so should not take this path. 4164 if (getLangOpts().CPlusPlus && 4165 (base->getType()->isRecordType() || 4166 (!base->getType()->isObjCObjectPointerType() && 4167 idx->getType()->isRecordType()))) { 4168 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4169 } 4170 4171 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4172 } 4173 4174 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4175 Expr *LowerBound, 4176 SourceLocation ColonLoc, Expr *Length, 4177 SourceLocation RBLoc) { 4178 if (Base->getType()->isPlaceholderType() && 4179 !Base->getType()->isSpecificPlaceholderType( 4180 BuiltinType::OMPArraySection)) { 4181 ExprResult Result = CheckPlaceholderExpr(Base); 4182 if (Result.isInvalid()) 4183 return ExprError(); 4184 Base = Result.get(); 4185 } 4186 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4187 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4188 if (Result.isInvalid()) 4189 return ExprError(); 4190 Result = DefaultLvalueConversion(Result.get()); 4191 if (Result.isInvalid()) 4192 return ExprError(); 4193 LowerBound = Result.get(); 4194 } 4195 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4196 ExprResult Result = CheckPlaceholderExpr(Length); 4197 if (Result.isInvalid()) 4198 return ExprError(); 4199 Result = DefaultLvalueConversion(Result.get()); 4200 if (Result.isInvalid()) 4201 return ExprError(); 4202 Length = Result.get(); 4203 } 4204 4205 // Build an unanalyzed expression if either operand is type-dependent. 4206 if (Base->isTypeDependent() || 4207 (LowerBound && 4208 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4209 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4210 return new (Context) 4211 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4212 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4213 } 4214 4215 // Perform default conversions. 4216 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4217 QualType ResultTy; 4218 if (OriginalTy->isAnyPointerType()) { 4219 ResultTy = OriginalTy->getPointeeType(); 4220 } else if (OriginalTy->isArrayType()) { 4221 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4222 } else { 4223 return ExprError( 4224 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4225 << Base->getSourceRange()); 4226 } 4227 // C99 6.5.2.1p1 4228 if (LowerBound) { 4229 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4230 LowerBound); 4231 if (Res.isInvalid()) 4232 return ExprError(Diag(LowerBound->getExprLoc(), 4233 diag::err_omp_typecheck_section_not_integer) 4234 << 0 << LowerBound->getSourceRange()); 4235 LowerBound = Res.get(); 4236 4237 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4238 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4239 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4240 << 0 << LowerBound->getSourceRange(); 4241 } 4242 if (Length) { 4243 auto Res = 4244 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4245 if (Res.isInvalid()) 4246 return ExprError(Diag(Length->getExprLoc(), 4247 diag::err_omp_typecheck_section_not_integer) 4248 << 1 << Length->getSourceRange()); 4249 Length = Res.get(); 4250 4251 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4252 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4253 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4254 << 1 << Length->getSourceRange(); 4255 } 4256 4257 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4258 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4259 // type. Note that functions are not objects, and that (in C99 parlance) 4260 // incomplete types are not object types. 4261 if (ResultTy->isFunctionType()) { 4262 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4263 << ResultTy << Base->getSourceRange(); 4264 return ExprError(); 4265 } 4266 4267 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4268 diag::err_omp_section_incomplete_type, Base)) 4269 return ExprError(); 4270 4271 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4272 llvm::APSInt LowerBoundValue; 4273 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4274 // OpenMP 4.5, [2.4 Array Sections] 4275 // The array section must be a subset of the original array. 4276 if (LowerBoundValue.isNegative()) { 4277 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4278 << LowerBound->getSourceRange(); 4279 return ExprError(); 4280 } 4281 } 4282 } 4283 4284 if (Length) { 4285 llvm::APSInt LengthValue; 4286 if (Length->EvaluateAsInt(LengthValue, Context)) { 4287 // OpenMP 4.5, [2.4 Array Sections] 4288 // The length must evaluate to non-negative integers. 4289 if (LengthValue.isNegative()) { 4290 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4291 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4292 << Length->getSourceRange(); 4293 return ExprError(); 4294 } 4295 } 4296 } else if (ColonLoc.isValid() && 4297 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4298 !OriginalTy->isVariableArrayType()))) { 4299 // OpenMP 4.5, [2.4 Array Sections] 4300 // When the size of the array dimension is not known, the length must be 4301 // specified explicitly. 4302 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4303 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4304 return ExprError(); 4305 } 4306 4307 if (!Base->getType()->isSpecificPlaceholderType( 4308 BuiltinType::OMPArraySection)) { 4309 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4310 if (Result.isInvalid()) 4311 return ExprError(); 4312 Base = Result.get(); 4313 } 4314 return new (Context) 4315 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4316 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4317 } 4318 4319 ExprResult 4320 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4321 Expr *Idx, SourceLocation RLoc) { 4322 Expr *LHSExp = Base; 4323 Expr *RHSExp = Idx; 4324 4325 ExprValueKind VK = VK_LValue; 4326 ExprObjectKind OK = OK_Ordinary; 4327 4328 // Per C++ core issue 1213, the result is an xvalue if either operand is 4329 // a non-lvalue array, and an lvalue otherwise. 4330 if (getLangOpts().CPlusPlus11 && 4331 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4332 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4333 VK = VK_XValue; 4334 4335 // Perform default conversions. 4336 if (!LHSExp->getType()->getAs<VectorType>()) { 4337 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4338 if (Result.isInvalid()) 4339 return ExprError(); 4340 LHSExp = Result.get(); 4341 } 4342 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4343 if (Result.isInvalid()) 4344 return ExprError(); 4345 RHSExp = Result.get(); 4346 4347 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4348 4349 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4350 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4351 // in the subscript position. As a result, we need to derive the array base 4352 // and index from the expression types. 4353 Expr *BaseExpr, *IndexExpr; 4354 QualType ResultType; 4355 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4356 BaseExpr = LHSExp; 4357 IndexExpr = RHSExp; 4358 ResultType = Context.DependentTy; 4359 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4360 BaseExpr = LHSExp; 4361 IndexExpr = RHSExp; 4362 ResultType = PTy->getPointeeType(); 4363 } else if (const ObjCObjectPointerType *PTy = 4364 LHSTy->getAs<ObjCObjectPointerType>()) { 4365 BaseExpr = LHSExp; 4366 IndexExpr = RHSExp; 4367 4368 // Use custom logic if this should be the pseudo-object subscript 4369 // expression. 4370 if (!LangOpts.isSubscriptPointerArithmetic()) 4371 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4372 nullptr); 4373 4374 ResultType = PTy->getPointeeType(); 4375 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4376 // Handle the uncommon case of "123[Ptr]". 4377 BaseExpr = RHSExp; 4378 IndexExpr = LHSExp; 4379 ResultType = PTy->getPointeeType(); 4380 } else if (const ObjCObjectPointerType *PTy = 4381 RHSTy->getAs<ObjCObjectPointerType>()) { 4382 // Handle the uncommon case of "123[Ptr]". 4383 BaseExpr = RHSExp; 4384 IndexExpr = LHSExp; 4385 ResultType = PTy->getPointeeType(); 4386 if (!LangOpts.isSubscriptPointerArithmetic()) { 4387 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4388 << ResultType << BaseExpr->getSourceRange(); 4389 return ExprError(); 4390 } 4391 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4392 BaseExpr = LHSExp; // vectors: V[123] 4393 IndexExpr = RHSExp; 4394 VK = LHSExp->getValueKind(); 4395 if (VK != VK_RValue) 4396 OK = OK_VectorComponent; 4397 4398 // FIXME: need to deal with const... 4399 ResultType = VTy->getElementType(); 4400 } else if (LHSTy->isArrayType()) { 4401 // If we see an array that wasn't promoted by 4402 // DefaultFunctionArrayLvalueConversion, it must be an array that 4403 // wasn't promoted because of the C90 rule that doesn't 4404 // allow promoting non-lvalue arrays. Warn, then 4405 // force the promotion here. 4406 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4407 LHSExp->getSourceRange(); 4408 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4409 CK_ArrayToPointerDecay).get(); 4410 LHSTy = LHSExp->getType(); 4411 4412 BaseExpr = LHSExp; 4413 IndexExpr = RHSExp; 4414 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4415 } else if (RHSTy->isArrayType()) { 4416 // Same as previous, except for 123[f().a] case 4417 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4418 RHSExp->getSourceRange(); 4419 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4420 CK_ArrayToPointerDecay).get(); 4421 RHSTy = RHSExp->getType(); 4422 4423 BaseExpr = RHSExp; 4424 IndexExpr = LHSExp; 4425 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4426 } else { 4427 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4428 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4429 } 4430 // C99 6.5.2.1p1 4431 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4432 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4433 << IndexExpr->getSourceRange()); 4434 4435 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4436 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4437 && !IndexExpr->isTypeDependent()) 4438 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4439 4440 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4441 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4442 // type. Note that Functions are not objects, and that (in C99 parlance) 4443 // incomplete types are not object types. 4444 if (ResultType->isFunctionType()) { 4445 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4446 << ResultType << BaseExpr->getSourceRange(); 4447 return ExprError(); 4448 } 4449 4450 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4451 // GNU extension: subscripting on pointer to void 4452 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4453 << BaseExpr->getSourceRange(); 4454 4455 // C forbids expressions of unqualified void type from being l-values. 4456 // See IsCForbiddenLValueType. 4457 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4458 } else if (!ResultType->isDependentType() && 4459 RequireCompleteType(LLoc, ResultType, 4460 diag::err_subscript_incomplete_type, BaseExpr)) 4461 return ExprError(); 4462 4463 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4464 !ResultType.isCForbiddenLValueType()); 4465 4466 return new (Context) 4467 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4468 } 4469 4470 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4471 ParmVarDecl *Param) { 4472 if (Param->hasUnparsedDefaultArg()) { 4473 Diag(CallLoc, 4474 diag::err_use_of_default_argument_to_function_declared_later) << 4475 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4476 Diag(UnparsedDefaultArgLocs[Param], 4477 diag::note_default_argument_declared_here); 4478 return true; 4479 } 4480 4481 if (Param->hasUninstantiatedDefaultArg()) { 4482 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4483 4484 EnterExpressionEvaluationContext EvalContext( 4485 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4486 4487 // Instantiate the expression. 4488 // 4489 // FIXME: Pass in a correct Pattern argument, otherwise 4490 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4491 // 4492 // template<typename T> 4493 // struct A { 4494 // static int FooImpl(); 4495 // 4496 // template<typename Tp> 4497 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4498 // // template argument list [[T], [Tp]], should be [[Tp]]. 4499 // friend A<Tp> Foo(int a); 4500 // }; 4501 // 4502 // template<typename T> 4503 // A<T> Foo(int a = A<T>::FooImpl()); 4504 MultiLevelTemplateArgumentList MutiLevelArgList 4505 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4506 4507 InstantiatingTemplate Inst(*this, CallLoc, Param, 4508 MutiLevelArgList.getInnermost()); 4509 if (Inst.isInvalid()) 4510 return true; 4511 if (Inst.isAlreadyInstantiating()) { 4512 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4513 Param->setInvalidDecl(); 4514 return true; 4515 } 4516 4517 ExprResult Result; 4518 { 4519 // C++ [dcl.fct.default]p5: 4520 // The names in the [default argument] expression are bound, and 4521 // the semantic constraints are checked, at the point where the 4522 // default argument expression appears. 4523 ContextRAII SavedContext(*this, FD); 4524 LocalInstantiationScope Local(*this); 4525 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4526 /*DirectInit*/false); 4527 } 4528 if (Result.isInvalid()) 4529 return true; 4530 4531 // Check the expression as an initializer for the parameter. 4532 InitializedEntity Entity 4533 = InitializedEntity::InitializeParameter(Context, Param); 4534 InitializationKind Kind 4535 = InitializationKind::CreateCopy(Param->getLocation(), 4536 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4537 Expr *ResultE = Result.getAs<Expr>(); 4538 4539 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4540 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4541 if (Result.isInvalid()) 4542 return true; 4543 4544 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4545 Param->getOuterLocStart()); 4546 if (Result.isInvalid()) 4547 return true; 4548 4549 // Remember the instantiated default argument. 4550 Param->setDefaultArg(Result.getAs<Expr>()); 4551 if (ASTMutationListener *L = getASTMutationListener()) { 4552 L->DefaultArgumentInstantiated(Param); 4553 } 4554 } 4555 4556 // If the default argument expression is not set yet, we are building it now. 4557 if (!Param->hasInit()) { 4558 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4559 Param->setInvalidDecl(); 4560 return true; 4561 } 4562 4563 // If the default expression creates temporaries, we need to 4564 // push them to the current stack of expression temporaries so they'll 4565 // be properly destroyed. 4566 // FIXME: We should really be rebuilding the default argument with new 4567 // bound temporaries; see the comment in PR5810. 4568 // We don't need to do that with block decls, though, because 4569 // blocks in default argument expression can never capture anything. 4570 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4571 // Set the "needs cleanups" bit regardless of whether there are 4572 // any explicit objects. 4573 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4574 4575 // Append all the objects to the cleanup list. Right now, this 4576 // should always be a no-op, because blocks in default argument 4577 // expressions should never be able to capture anything. 4578 assert(!Init->getNumObjects() && 4579 "default argument expression has capturing blocks?"); 4580 } 4581 4582 // We already type-checked the argument, so we know it works. 4583 // Just mark all of the declarations in this potentially-evaluated expression 4584 // as being "referenced". 4585 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4586 /*SkipLocalVariables=*/true); 4587 return false; 4588 } 4589 4590 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4591 FunctionDecl *FD, ParmVarDecl *Param) { 4592 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4593 return ExprError(); 4594 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4595 } 4596 4597 Sema::VariadicCallType 4598 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4599 Expr *Fn) { 4600 if (Proto && Proto->isVariadic()) { 4601 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4602 return VariadicConstructor; 4603 else if (Fn && Fn->getType()->isBlockPointerType()) 4604 return VariadicBlock; 4605 else if (FDecl) { 4606 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4607 if (Method->isInstance()) 4608 return VariadicMethod; 4609 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4610 return VariadicMethod; 4611 return VariadicFunction; 4612 } 4613 return VariadicDoesNotApply; 4614 } 4615 4616 namespace { 4617 class FunctionCallCCC : public FunctionCallFilterCCC { 4618 public: 4619 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4620 unsigned NumArgs, MemberExpr *ME) 4621 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4622 FunctionName(FuncName) {} 4623 4624 bool ValidateCandidate(const TypoCorrection &candidate) override { 4625 if (!candidate.getCorrectionSpecifier() || 4626 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4627 return false; 4628 } 4629 4630 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4631 } 4632 4633 private: 4634 const IdentifierInfo *const FunctionName; 4635 }; 4636 } 4637 4638 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4639 FunctionDecl *FDecl, 4640 ArrayRef<Expr *> Args) { 4641 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4642 DeclarationName FuncName = FDecl->getDeclName(); 4643 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4644 4645 if (TypoCorrection Corrected = S.CorrectTypo( 4646 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4647 S.getScopeForContext(S.CurContext), nullptr, 4648 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4649 Args.size(), ME), 4650 Sema::CTK_ErrorRecovery)) { 4651 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4652 if (Corrected.isOverloaded()) { 4653 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4654 OverloadCandidateSet::iterator Best; 4655 for (NamedDecl *CD : Corrected) { 4656 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4657 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4658 OCS); 4659 } 4660 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4661 case OR_Success: 4662 ND = Best->FoundDecl; 4663 Corrected.setCorrectionDecl(ND); 4664 break; 4665 default: 4666 break; 4667 } 4668 } 4669 ND = ND->getUnderlyingDecl(); 4670 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4671 return Corrected; 4672 } 4673 } 4674 return TypoCorrection(); 4675 } 4676 4677 /// ConvertArgumentsForCall - Converts the arguments specified in 4678 /// Args/NumArgs to the parameter types of the function FDecl with 4679 /// function prototype Proto. Call is the call expression itself, and 4680 /// Fn is the function expression. For a C++ member function, this 4681 /// routine does not attempt to convert the object argument. Returns 4682 /// true if the call is ill-formed. 4683 bool 4684 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4685 FunctionDecl *FDecl, 4686 const FunctionProtoType *Proto, 4687 ArrayRef<Expr *> Args, 4688 SourceLocation RParenLoc, 4689 bool IsExecConfig) { 4690 // Bail out early if calling a builtin with custom typechecking. 4691 if (FDecl) 4692 if (unsigned ID = FDecl->getBuiltinID()) 4693 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4694 return false; 4695 4696 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4697 // assignment, to the types of the corresponding parameter, ... 4698 unsigned NumParams = Proto->getNumParams(); 4699 bool Invalid = false; 4700 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4701 unsigned FnKind = Fn->getType()->isBlockPointerType() 4702 ? 1 /* block */ 4703 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4704 : 0 /* function */); 4705 4706 // If too few arguments are available (and we don't have default 4707 // arguments for the remaining parameters), don't make the call. 4708 if (Args.size() < NumParams) { 4709 if (Args.size() < MinArgs) { 4710 TypoCorrection TC; 4711 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4712 unsigned diag_id = 4713 MinArgs == NumParams && !Proto->isVariadic() 4714 ? diag::err_typecheck_call_too_few_args_suggest 4715 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4716 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4717 << static_cast<unsigned>(Args.size()) 4718 << TC.getCorrectionRange()); 4719 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4720 Diag(RParenLoc, 4721 MinArgs == NumParams && !Proto->isVariadic() 4722 ? diag::err_typecheck_call_too_few_args_one 4723 : diag::err_typecheck_call_too_few_args_at_least_one) 4724 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4725 else 4726 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4727 ? diag::err_typecheck_call_too_few_args 4728 : diag::err_typecheck_call_too_few_args_at_least) 4729 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4730 << Fn->getSourceRange(); 4731 4732 // Emit the location of the prototype. 4733 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4734 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4735 << FDecl; 4736 4737 return true; 4738 } 4739 Call->setNumArgs(Context, NumParams); 4740 } 4741 4742 // If too many are passed and not variadic, error on the extras and drop 4743 // them. 4744 if (Args.size() > NumParams) { 4745 if (!Proto->isVariadic()) { 4746 TypoCorrection TC; 4747 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4748 unsigned diag_id = 4749 MinArgs == NumParams && !Proto->isVariadic() 4750 ? diag::err_typecheck_call_too_many_args_suggest 4751 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4752 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4753 << static_cast<unsigned>(Args.size()) 4754 << TC.getCorrectionRange()); 4755 } else if (NumParams == 1 && FDecl && 4756 FDecl->getParamDecl(0)->getDeclName()) 4757 Diag(Args[NumParams]->getLocStart(), 4758 MinArgs == NumParams 4759 ? diag::err_typecheck_call_too_many_args_one 4760 : diag::err_typecheck_call_too_many_args_at_most_one) 4761 << FnKind << FDecl->getParamDecl(0) 4762 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4763 << SourceRange(Args[NumParams]->getLocStart(), 4764 Args.back()->getLocEnd()); 4765 else 4766 Diag(Args[NumParams]->getLocStart(), 4767 MinArgs == NumParams 4768 ? diag::err_typecheck_call_too_many_args 4769 : diag::err_typecheck_call_too_many_args_at_most) 4770 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4771 << Fn->getSourceRange() 4772 << SourceRange(Args[NumParams]->getLocStart(), 4773 Args.back()->getLocEnd()); 4774 4775 // Emit the location of the prototype. 4776 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4777 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4778 << FDecl; 4779 4780 // This deletes the extra arguments. 4781 Call->setNumArgs(Context, NumParams); 4782 return true; 4783 } 4784 } 4785 SmallVector<Expr *, 8> AllArgs; 4786 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4787 4788 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4789 Proto, 0, Args, AllArgs, CallType); 4790 if (Invalid) 4791 return true; 4792 unsigned TotalNumArgs = AllArgs.size(); 4793 for (unsigned i = 0; i < TotalNumArgs; ++i) 4794 Call->setArg(i, AllArgs[i]); 4795 4796 return false; 4797 } 4798 4799 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4800 const FunctionProtoType *Proto, 4801 unsigned FirstParam, ArrayRef<Expr *> Args, 4802 SmallVectorImpl<Expr *> &AllArgs, 4803 VariadicCallType CallType, bool AllowExplicit, 4804 bool IsListInitialization) { 4805 unsigned NumParams = Proto->getNumParams(); 4806 bool Invalid = false; 4807 size_t ArgIx = 0; 4808 // Continue to check argument types (even if we have too few/many args). 4809 for (unsigned i = FirstParam; i < NumParams; i++) { 4810 QualType ProtoArgType = Proto->getParamType(i); 4811 4812 Expr *Arg; 4813 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4814 if (ArgIx < Args.size()) { 4815 Arg = Args[ArgIx++]; 4816 4817 if (RequireCompleteType(Arg->getLocStart(), 4818 ProtoArgType, 4819 diag::err_call_incomplete_argument, Arg)) 4820 return true; 4821 4822 // Strip the unbridged-cast placeholder expression off, if applicable. 4823 bool CFAudited = false; 4824 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4825 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4826 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4827 Arg = stripARCUnbridgedCast(Arg); 4828 else if (getLangOpts().ObjCAutoRefCount && 4829 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4830 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4831 CFAudited = true; 4832 4833 InitializedEntity Entity = 4834 Param ? InitializedEntity::InitializeParameter(Context, Param, 4835 ProtoArgType) 4836 : InitializedEntity::InitializeParameter( 4837 Context, ProtoArgType, Proto->isParamConsumed(i)); 4838 4839 // Remember that parameter belongs to a CF audited API. 4840 if (CFAudited) 4841 Entity.setParameterCFAudited(); 4842 4843 ExprResult ArgE = PerformCopyInitialization( 4844 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4845 if (ArgE.isInvalid()) 4846 return true; 4847 4848 Arg = ArgE.getAs<Expr>(); 4849 } else { 4850 assert(Param && "can't use default arguments without a known callee"); 4851 4852 ExprResult ArgExpr = 4853 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4854 if (ArgExpr.isInvalid()) 4855 return true; 4856 4857 Arg = ArgExpr.getAs<Expr>(); 4858 } 4859 4860 // Check for array bounds violations for each argument to the call. This 4861 // check only triggers warnings when the argument isn't a more complex Expr 4862 // with its own checking, such as a BinaryOperator. 4863 CheckArrayAccess(Arg); 4864 4865 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4866 CheckStaticArrayArgument(CallLoc, Param, Arg); 4867 4868 AllArgs.push_back(Arg); 4869 } 4870 4871 // If this is a variadic call, handle args passed through "...". 4872 if (CallType != VariadicDoesNotApply) { 4873 // Assume that extern "C" functions with variadic arguments that 4874 // return __unknown_anytype aren't *really* variadic. 4875 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4876 FDecl->isExternC()) { 4877 for (Expr *A : Args.slice(ArgIx)) { 4878 QualType paramType; // ignored 4879 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4880 Invalid |= arg.isInvalid(); 4881 AllArgs.push_back(arg.get()); 4882 } 4883 4884 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4885 } else { 4886 for (Expr *A : Args.slice(ArgIx)) { 4887 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4888 Invalid |= Arg.isInvalid(); 4889 AllArgs.push_back(Arg.get()); 4890 } 4891 } 4892 4893 // Check for array bounds violations. 4894 for (Expr *A : Args.slice(ArgIx)) 4895 CheckArrayAccess(A); 4896 } 4897 return Invalid; 4898 } 4899 4900 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4901 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4902 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4903 TL = DTL.getOriginalLoc(); 4904 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4905 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4906 << ATL.getLocalSourceRange(); 4907 } 4908 4909 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4910 /// array parameter, check that it is non-null, and that if it is formed by 4911 /// array-to-pointer decay, the underlying array is sufficiently large. 4912 /// 4913 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4914 /// array type derivation, then for each call to the function, the value of the 4915 /// corresponding actual argument shall provide access to the first element of 4916 /// an array with at least as many elements as specified by the size expression. 4917 void 4918 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4919 ParmVarDecl *Param, 4920 const Expr *ArgExpr) { 4921 // Static array parameters are not supported in C++. 4922 if (!Param || getLangOpts().CPlusPlus) 4923 return; 4924 4925 QualType OrigTy = Param->getOriginalType(); 4926 4927 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4928 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4929 return; 4930 4931 if (ArgExpr->isNullPointerConstant(Context, 4932 Expr::NPC_NeverValueDependent)) { 4933 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4934 DiagnoseCalleeStaticArrayParam(*this, Param); 4935 return; 4936 } 4937 4938 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4939 if (!CAT) 4940 return; 4941 4942 const ConstantArrayType *ArgCAT = 4943 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4944 if (!ArgCAT) 4945 return; 4946 4947 if (ArgCAT->getSize().ult(CAT->getSize())) { 4948 Diag(CallLoc, diag::warn_static_array_too_small) 4949 << ArgExpr->getSourceRange() 4950 << (unsigned) ArgCAT->getSize().getZExtValue() 4951 << (unsigned) CAT->getSize().getZExtValue(); 4952 DiagnoseCalleeStaticArrayParam(*this, Param); 4953 } 4954 } 4955 4956 /// Given a function expression of unknown-any type, try to rebuild it 4957 /// to have a function type. 4958 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4959 4960 /// Is the given type a placeholder that we need to lower out 4961 /// immediately during argument processing? 4962 static bool isPlaceholderToRemoveAsArg(QualType type) { 4963 // Placeholders are never sugared. 4964 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4965 if (!placeholder) return false; 4966 4967 switch (placeholder->getKind()) { 4968 // Ignore all the non-placeholder types. 4969 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4970 case BuiltinType::Id: 4971 #include "clang/Basic/OpenCLImageTypes.def" 4972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4973 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4974 #include "clang/AST/BuiltinTypes.def" 4975 return false; 4976 4977 // We cannot lower out overload sets; they might validly be resolved 4978 // by the call machinery. 4979 case BuiltinType::Overload: 4980 return false; 4981 4982 // Unbridged casts in ARC can be handled in some call positions and 4983 // should be left in place. 4984 case BuiltinType::ARCUnbridgedCast: 4985 return false; 4986 4987 // Pseudo-objects should be converted as soon as possible. 4988 case BuiltinType::PseudoObject: 4989 return true; 4990 4991 // The debugger mode could theoretically but currently does not try 4992 // to resolve unknown-typed arguments based on known parameter types. 4993 case BuiltinType::UnknownAny: 4994 return true; 4995 4996 // These are always invalid as call arguments and should be reported. 4997 case BuiltinType::BoundMember: 4998 case BuiltinType::BuiltinFn: 4999 case BuiltinType::OMPArraySection: 5000 return true; 5001 5002 } 5003 llvm_unreachable("bad builtin type kind"); 5004 } 5005 5006 /// Check an argument list for placeholders that we won't try to 5007 /// handle later. 5008 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5009 // Apply this processing to all the arguments at once instead of 5010 // dying at the first failure. 5011 bool hasInvalid = false; 5012 for (size_t i = 0, e = args.size(); i != e; i++) { 5013 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5014 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5015 if (result.isInvalid()) hasInvalid = true; 5016 else args[i] = result.get(); 5017 } else if (hasInvalid) { 5018 (void)S.CorrectDelayedTyposInExpr(args[i]); 5019 } 5020 } 5021 return hasInvalid; 5022 } 5023 5024 /// If a builtin function has a pointer argument with no explicit address 5025 /// space, then it should be able to accept a pointer to any address 5026 /// space as input. In order to do this, we need to replace the 5027 /// standard builtin declaration with one that uses the same address space 5028 /// as the call. 5029 /// 5030 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5031 /// it does not contain any pointer arguments without 5032 /// an address space qualifer. Otherwise the rewritten 5033 /// FunctionDecl is returned. 5034 /// TODO: Handle pointer return types. 5035 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5036 const FunctionDecl *FDecl, 5037 MultiExprArg ArgExprs) { 5038 5039 QualType DeclType = FDecl->getType(); 5040 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5041 5042 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5043 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5044 return nullptr; 5045 5046 bool NeedsNewDecl = false; 5047 unsigned i = 0; 5048 SmallVector<QualType, 8> OverloadParams; 5049 5050 for (QualType ParamType : FT->param_types()) { 5051 5052 // Convert array arguments to pointer to simplify type lookup. 5053 ExprResult ArgRes = 5054 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5055 if (ArgRes.isInvalid()) 5056 return nullptr; 5057 Expr *Arg = ArgRes.get(); 5058 QualType ArgType = Arg->getType(); 5059 if (!ParamType->isPointerType() || 5060 ParamType.getQualifiers().hasAddressSpace() || 5061 !ArgType->isPointerType() || 5062 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5063 OverloadParams.push_back(ParamType); 5064 continue; 5065 } 5066 5067 NeedsNewDecl = true; 5068 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5069 5070 QualType PointeeType = ParamType->getPointeeType(); 5071 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5072 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5073 } 5074 5075 if (!NeedsNewDecl) 5076 return nullptr; 5077 5078 FunctionProtoType::ExtProtoInfo EPI; 5079 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5080 OverloadParams, EPI); 5081 DeclContext *Parent = Context.getTranslationUnitDecl(); 5082 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5083 FDecl->getLocation(), 5084 FDecl->getLocation(), 5085 FDecl->getIdentifier(), 5086 OverloadTy, 5087 /*TInfo=*/nullptr, 5088 SC_Extern, false, 5089 /*hasPrototype=*/true); 5090 SmallVector<ParmVarDecl*, 16> Params; 5091 FT = cast<FunctionProtoType>(OverloadTy); 5092 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5093 QualType ParamType = FT->getParamType(i); 5094 ParmVarDecl *Parm = 5095 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5096 SourceLocation(), nullptr, ParamType, 5097 /*TInfo=*/nullptr, SC_None, nullptr); 5098 Parm->setScopeInfo(0, i); 5099 Params.push_back(Parm); 5100 } 5101 OverloadDecl->setParams(Params); 5102 return OverloadDecl; 5103 } 5104 5105 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5106 FunctionDecl *Callee, 5107 MultiExprArg ArgExprs) { 5108 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5109 // similar attributes) really don't like it when functions are called with an 5110 // invalid number of args. 5111 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5112 /*PartialOverloading=*/false) && 5113 !Callee->isVariadic()) 5114 return; 5115 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5116 return; 5117 5118 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5119 S.Diag(Fn->getLocStart(), 5120 isa<CXXMethodDecl>(Callee) 5121 ? diag::err_ovl_no_viable_member_function_in_call 5122 : diag::err_ovl_no_viable_function_in_call) 5123 << Callee << Callee->getSourceRange(); 5124 S.Diag(Callee->getLocation(), 5125 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5126 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5127 return; 5128 } 5129 } 5130 5131 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5132 const UnresolvedMemberExpr *const UME, Sema &S) { 5133 5134 const auto GetFunctionLevelDCIfCXXClass = 5135 [](Sema &S) -> const CXXRecordDecl * { 5136 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5137 if (!DC || !DC->getParent()) 5138 return nullptr; 5139 5140 // If the call to some member function was made from within a member 5141 // function body 'M' return return 'M's parent. 5142 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5143 return MD->getParent()->getCanonicalDecl(); 5144 // else the call was made from within a default member initializer of a 5145 // class, so return the class. 5146 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5147 return RD->getCanonicalDecl(); 5148 return nullptr; 5149 }; 5150 // If our DeclContext is neither a member function nor a class (in the 5151 // case of a lambda in a default member initializer), we can't have an 5152 // enclosing 'this'. 5153 5154 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5155 if (!CurParentClass) 5156 return false; 5157 5158 // The naming class for implicit member functions call is the class in which 5159 // name lookup starts. 5160 const CXXRecordDecl *const NamingClass = 5161 UME->getNamingClass()->getCanonicalDecl(); 5162 assert(NamingClass && "Must have naming class even for implicit access"); 5163 5164 // If the unresolved member functions were found in a 'naming class' that is 5165 // related (either the same or derived from) to the class that contains the 5166 // member function that itself contained the implicit member access. 5167 5168 return CurParentClass == NamingClass || 5169 CurParentClass->isDerivedFrom(NamingClass); 5170 } 5171 5172 static void 5173 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5174 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5175 5176 if (!UME) 5177 return; 5178 5179 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5180 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5181 // already been captured, or if this is an implicit member function call (if 5182 // it isn't, an attempt to capture 'this' should already have been made). 5183 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5184 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5185 return; 5186 5187 // Check if the naming class in which the unresolved members were found is 5188 // related (same as or is a base of) to the enclosing class. 5189 5190 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5191 return; 5192 5193 5194 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5195 // If the enclosing function is not dependent, then this lambda is 5196 // capture ready, so if we can capture this, do so. 5197 if (!EnclosingFunctionCtx->isDependentContext()) { 5198 // If the current lambda and all enclosing lambdas can capture 'this' - 5199 // then go ahead and capture 'this' (since our unresolved overload set 5200 // contains at least one non-static member function). 5201 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5202 S.CheckCXXThisCapture(CallLoc); 5203 } else if (S.CurContext->isDependentContext()) { 5204 // ... since this is an implicit member reference, that might potentially 5205 // involve a 'this' capture, mark 'this' for potential capture in 5206 // enclosing lambdas. 5207 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5208 CurLSI->addPotentialThisCapture(CallLoc); 5209 } 5210 } 5211 5212 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5213 /// This provides the location of the left/right parens and a list of comma 5214 /// locations. 5215 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5216 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5217 Expr *ExecConfig, bool IsExecConfig) { 5218 // Since this might be a postfix expression, get rid of ParenListExprs. 5219 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5220 if (Result.isInvalid()) return ExprError(); 5221 Fn = Result.get(); 5222 5223 if (checkArgsForPlaceholders(*this, ArgExprs)) 5224 return ExprError(); 5225 5226 if (getLangOpts().CPlusPlus) { 5227 // If this is a pseudo-destructor expression, build the call immediately. 5228 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5229 if (!ArgExprs.empty()) { 5230 // Pseudo-destructor calls should not have any arguments. 5231 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5232 << FixItHint::CreateRemoval( 5233 SourceRange(ArgExprs.front()->getLocStart(), 5234 ArgExprs.back()->getLocEnd())); 5235 } 5236 5237 return new (Context) 5238 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5239 } 5240 if (Fn->getType() == Context.PseudoObjectTy) { 5241 ExprResult result = CheckPlaceholderExpr(Fn); 5242 if (result.isInvalid()) return ExprError(); 5243 Fn = result.get(); 5244 } 5245 5246 // Determine whether this is a dependent call inside a C++ template, 5247 // in which case we won't do any semantic analysis now. 5248 bool Dependent = false; 5249 if (Fn->isTypeDependent()) 5250 Dependent = true; 5251 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5252 Dependent = true; 5253 5254 if (Dependent) { 5255 if (ExecConfig) { 5256 return new (Context) CUDAKernelCallExpr( 5257 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5258 Context.DependentTy, VK_RValue, RParenLoc); 5259 } else { 5260 5261 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5262 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5263 Fn->getLocStart()); 5264 5265 return new (Context) CallExpr( 5266 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5267 } 5268 } 5269 5270 // Determine whether this is a call to an object (C++ [over.call.object]). 5271 if (Fn->getType()->isRecordType()) 5272 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5273 RParenLoc); 5274 5275 if (Fn->getType() == Context.UnknownAnyTy) { 5276 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5277 if (result.isInvalid()) return ExprError(); 5278 Fn = result.get(); 5279 } 5280 5281 if (Fn->getType() == Context.BoundMemberTy) { 5282 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5283 RParenLoc); 5284 } 5285 } 5286 5287 // Check for overloaded calls. This can happen even in C due to extensions. 5288 if (Fn->getType() == Context.OverloadTy) { 5289 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5290 5291 // We aren't supposed to apply this logic if there's an '&' involved. 5292 if (!find.HasFormOfMemberPointer) { 5293 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5294 return new (Context) CallExpr( 5295 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5296 OverloadExpr *ovl = find.Expression; 5297 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5298 return BuildOverloadedCallExpr( 5299 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5300 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5301 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5302 RParenLoc); 5303 } 5304 } 5305 5306 // If we're directly calling a function, get the appropriate declaration. 5307 if (Fn->getType() == Context.UnknownAnyTy) { 5308 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5309 if (result.isInvalid()) return ExprError(); 5310 Fn = result.get(); 5311 } 5312 5313 Expr *NakedFn = Fn->IgnoreParens(); 5314 5315 bool CallingNDeclIndirectly = false; 5316 NamedDecl *NDecl = nullptr; 5317 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5318 if (UnOp->getOpcode() == UO_AddrOf) { 5319 CallingNDeclIndirectly = true; 5320 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5321 } 5322 } 5323 5324 if (isa<DeclRefExpr>(NakedFn)) { 5325 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5326 5327 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5328 if (FDecl && FDecl->getBuiltinID()) { 5329 // Rewrite the function decl for this builtin by replacing parameters 5330 // with no explicit address space with the address space of the arguments 5331 // in ArgExprs. 5332 if ((FDecl = 5333 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5334 NDecl = FDecl; 5335 Fn = DeclRefExpr::Create( 5336 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5337 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5338 } 5339 } 5340 } else if (isa<MemberExpr>(NakedFn)) 5341 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5342 5343 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5344 if (CallingNDeclIndirectly && 5345 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5346 Fn->getLocStart())) 5347 return ExprError(); 5348 5349 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5350 return ExprError(); 5351 5352 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5353 } 5354 5355 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5356 ExecConfig, IsExecConfig); 5357 } 5358 5359 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5360 /// 5361 /// __builtin_astype( value, dst type ) 5362 /// 5363 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5364 SourceLocation BuiltinLoc, 5365 SourceLocation RParenLoc) { 5366 ExprValueKind VK = VK_RValue; 5367 ExprObjectKind OK = OK_Ordinary; 5368 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5369 QualType SrcTy = E->getType(); 5370 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5371 return ExprError(Diag(BuiltinLoc, 5372 diag::err_invalid_astype_of_different_size) 5373 << DstTy 5374 << SrcTy 5375 << E->getSourceRange()); 5376 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5377 } 5378 5379 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5380 /// provided arguments. 5381 /// 5382 /// __builtin_convertvector( value, dst type ) 5383 /// 5384 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5385 SourceLocation BuiltinLoc, 5386 SourceLocation RParenLoc) { 5387 TypeSourceInfo *TInfo; 5388 GetTypeFromParser(ParsedDestTy, &TInfo); 5389 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5390 } 5391 5392 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5393 /// i.e. an expression not of \p OverloadTy. The expression should 5394 /// unary-convert to an expression of function-pointer or 5395 /// block-pointer type. 5396 /// 5397 /// \param NDecl the declaration being called, if available 5398 ExprResult 5399 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5400 SourceLocation LParenLoc, 5401 ArrayRef<Expr *> Args, 5402 SourceLocation RParenLoc, 5403 Expr *Config, bool IsExecConfig) { 5404 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5405 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5406 5407 // Functions with 'interrupt' attribute cannot be called directly. 5408 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5409 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5410 return ExprError(); 5411 } 5412 5413 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5414 // so there's some risk when calling out to non-interrupt handler functions 5415 // that the callee might not preserve them. This is easy to diagnose here, 5416 // but can be very challenging to debug. 5417 if (auto *Caller = getCurFunctionDecl()) 5418 if (Caller->hasAttr<ARMInterruptAttr>()) { 5419 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5420 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5421 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5422 } 5423 5424 // Promote the function operand. 5425 // We special-case function promotion here because we only allow promoting 5426 // builtin functions to function pointers in the callee of a call. 5427 ExprResult Result; 5428 if (BuiltinID && 5429 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5430 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5431 CK_BuiltinFnToFnPtr).get(); 5432 } else { 5433 Result = CallExprUnaryConversions(Fn); 5434 } 5435 if (Result.isInvalid()) 5436 return ExprError(); 5437 Fn = Result.get(); 5438 5439 // Make the call expr early, before semantic checks. This guarantees cleanup 5440 // of arguments and function on error. 5441 CallExpr *TheCall; 5442 if (Config) 5443 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5444 cast<CallExpr>(Config), Args, 5445 Context.BoolTy, VK_RValue, 5446 RParenLoc); 5447 else 5448 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5449 VK_RValue, RParenLoc); 5450 5451 if (!getLangOpts().CPlusPlus) { 5452 // C cannot always handle TypoExpr nodes in builtin calls and direct 5453 // function calls as their argument checking don't necessarily handle 5454 // dependent types properly, so make sure any TypoExprs have been 5455 // dealt with. 5456 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5457 if (!Result.isUsable()) return ExprError(); 5458 TheCall = dyn_cast<CallExpr>(Result.get()); 5459 if (!TheCall) return Result; 5460 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5461 } 5462 5463 // Bail out early if calling a builtin with custom typechecking. 5464 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5465 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5466 5467 retry: 5468 const FunctionType *FuncT; 5469 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5470 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5471 // have type pointer to function". 5472 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5473 if (!FuncT) 5474 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5475 << Fn->getType() << Fn->getSourceRange()); 5476 } else if (const BlockPointerType *BPT = 5477 Fn->getType()->getAs<BlockPointerType>()) { 5478 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5479 } else { 5480 // Handle calls to expressions of unknown-any type. 5481 if (Fn->getType() == Context.UnknownAnyTy) { 5482 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5483 if (rewrite.isInvalid()) return ExprError(); 5484 Fn = rewrite.get(); 5485 TheCall->setCallee(Fn); 5486 goto retry; 5487 } 5488 5489 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5490 << Fn->getType() << Fn->getSourceRange()); 5491 } 5492 5493 if (getLangOpts().CUDA) { 5494 if (Config) { 5495 // CUDA: Kernel calls must be to global functions 5496 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5497 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5498 << FDecl->getName() << Fn->getSourceRange()); 5499 5500 // CUDA: Kernel function must have 'void' return type 5501 if (!FuncT->getReturnType()->isVoidType()) 5502 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5503 << Fn->getType() << Fn->getSourceRange()); 5504 } else { 5505 // CUDA: Calls to global functions must be configured 5506 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5507 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5508 << FDecl->getName() << Fn->getSourceRange()); 5509 } 5510 } 5511 5512 // Check for a valid return type 5513 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5514 FDecl)) 5515 return ExprError(); 5516 5517 // We know the result type of the call, set it. 5518 TheCall->setType(FuncT->getCallResultType(Context)); 5519 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5520 5521 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5522 if (Proto) { 5523 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5524 IsExecConfig)) 5525 return ExprError(); 5526 } else { 5527 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5528 5529 if (FDecl) { 5530 // Check if we have too few/too many template arguments, based 5531 // on our knowledge of the function definition. 5532 const FunctionDecl *Def = nullptr; 5533 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5534 Proto = Def->getType()->getAs<FunctionProtoType>(); 5535 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5536 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5537 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5538 } 5539 5540 // If the function we're calling isn't a function prototype, but we have 5541 // a function prototype from a prior declaratiom, use that prototype. 5542 if (!FDecl->hasPrototype()) 5543 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5544 } 5545 5546 // Promote the arguments (C99 6.5.2.2p6). 5547 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5548 Expr *Arg = Args[i]; 5549 5550 if (Proto && i < Proto->getNumParams()) { 5551 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5552 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5553 ExprResult ArgE = 5554 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5555 if (ArgE.isInvalid()) 5556 return true; 5557 5558 Arg = ArgE.getAs<Expr>(); 5559 5560 } else { 5561 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5562 5563 if (ArgE.isInvalid()) 5564 return true; 5565 5566 Arg = ArgE.getAs<Expr>(); 5567 } 5568 5569 if (RequireCompleteType(Arg->getLocStart(), 5570 Arg->getType(), 5571 diag::err_call_incomplete_argument, Arg)) 5572 return ExprError(); 5573 5574 TheCall->setArg(i, Arg); 5575 } 5576 } 5577 5578 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5579 if (!Method->isStatic()) 5580 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5581 << Fn->getSourceRange()); 5582 5583 // Check for sentinels 5584 if (NDecl) 5585 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5586 5587 // Do special checking on direct calls to functions. 5588 if (FDecl) { 5589 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5590 return ExprError(); 5591 5592 if (BuiltinID) 5593 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5594 } else if (NDecl) { 5595 if (CheckPointerCall(NDecl, TheCall, Proto)) 5596 return ExprError(); 5597 } else { 5598 if (CheckOtherCall(TheCall, Proto)) 5599 return ExprError(); 5600 } 5601 5602 return MaybeBindToTemporary(TheCall); 5603 } 5604 5605 ExprResult 5606 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5607 SourceLocation RParenLoc, Expr *InitExpr) { 5608 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5609 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5610 5611 TypeSourceInfo *TInfo; 5612 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5613 if (!TInfo) 5614 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5615 5616 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5617 } 5618 5619 ExprResult 5620 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5621 SourceLocation RParenLoc, Expr *LiteralExpr) { 5622 QualType literalType = TInfo->getType(); 5623 5624 if (literalType->isArrayType()) { 5625 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5626 diag::err_illegal_decl_array_incomplete_type, 5627 SourceRange(LParenLoc, 5628 LiteralExpr->getSourceRange().getEnd()))) 5629 return ExprError(); 5630 if (literalType->isVariableArrayType()) 5631 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5632 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5633 } else if (!literalType->isDependentType() && 5634 RequireCompleteType(LParenLoc, literalType, 5635 diag::err_typecheck_decl_incomplete_type, 5636 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5637 return ExprError(); 5638 5639 InitializedEntity Entity 5640 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5641 InitializationKind Kind 5642 = InitializationKind::CreateCStyleCast(LParenLoc, 5643 SourceRange(LParenLoc, RParenLoc), 5644 /*InitList=*/true); 5645 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5646 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5647 &literalType); 5648 if (Result.isInvalid()) 5649 return ExprError(); 5650 LiteralExpr = Result.get(); 5651 5652 bool isFileScope = !CurContext->isFunctionOrMethod(); 5653 if (isFileScope && 5654 !LiteralExpr->isTypeDependent() && 5655 !LiteralExpr->isValueDependent() && 5656 !literalType->isDependentType()) { // 6.5.2.5p3 5657 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5658 return ExprError(); 5659 } 5660 5661 // In C, compound literals are l-values for some reason. 5662 // For GCC compatibility, in C++, file-scope array compound literals with 5663 // constant initializers are also l-values, and compound literals are 5664 // otherwise prvalues. 5665 // 5666 // (GCC also treats C++ list-initialized file-scope array prvalues with 5667 // constant initializers as l-values, but that's non-conforming, so we don't 5668 // follow it there.) 5669 // 5670 // FIXME: It would be better to handle the lvalue cases as materializing and 5671 // lifetime-extending a temporary object, but our materialized temporaries 5672 // representation only supports lifetime extension from a variable, not "out 5673 // of thin air". 5674 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5675 // is bound to the result of applying array-to-pointer decay to the compound 5676 // literal. 5677 // FIXME: GCC supports compound literals of reference type, which should 5678 // obviously have a value kind derived from the kind of reference involved. 5679 ExprValueKind VK = 5680 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5681 ? VK_RValue 5682 : VK_LValue; 5683 5684 return MaybeBindToTemporary( 5685 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5686 VK, LiteralExpr, isFileScope)); 5687 } 5688 5689 ExprResult 5690 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5691 SourceLocation RBraceLoc) { 5692 // Immediately handle non-overload placeholders. Overloads can be 5693 // resolved contextually, but everything else here can't. 5694 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5695 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5696 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5697 5698 // Ignore failures; dropping the entire initializer list because 5699 // of one failure would be terrible for indexing/etc. 5700 if (result.isInvalid()) continue; 5701 5702 InitArgList[I] = result.get(); 5703 } 5704 } 5705 5706 // Semantic analysis for initializers is done by ActOnDeclarator() and 5707 // CheckInitializer() - it requires knowledge of the object being intialized. 5708 5709 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5710 RBraceLoc); 5711 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5712 return E; 5713 } 5714 5715 /// Do an explicit extend of the given block pointer if we're in ARC. 5716 void Sema::maybeExtendBlockObject(ExprResult &E) { 5717 assert(E.get()->getType()->isBlockPointerType()); 5718 assert(E.get()->isRValue()); 5719 5720 // Only do this in an r-value context. 5721 if (!getLangOpts().ObjCAutoRefCount) return; 5722 5723 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5724 CK_ARCExtendBlockObject, E.get(), 5725 /*base path*/ nullptr, VK_RValue); 5726 Cleanup.setExprNeedsCleanups(true); 5727 } 5728 5729 /// Prepare a conversion of the given expression to an ObjC object 5730 /// pointer type. 5731 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5732 QualType type = E.get()->getType(); 5733 if (type->isObjCObjectPointerType()) { 5734 return CK_BitCast; 5735 } else if (type->isBlockPointerType()) { 5736 maybeExtendBlockObject(E); 5737 return CK_BlockPointerToObjCPointerCast; 5738 } else { 5739 assert(type->isPointerType()); 5740 return CK_CPointerToObjCPointerCast; 5741 } 5742 } 5743 5744 /// Prepares for a scalar cast, performing all the necessary stages 5745 /// except the final cast and returning the kind required. 5746 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5747 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5748 // Also, callers should have filtered out the invalid cases with 5749 // pointers. Everything else should be possible. 5750 5751 QualType SrcTy = Src.get()->getType(); 5752 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5753 return CK_NoOp; 5754 5755 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5756 case Type::STK_MemberPointer: 5757 llvm_unreachable("member pointer type in C"); 5758 5759 case Type::STK_CPointer: 5760 case Type::STK_BlockPointer: 5761 case Type::STK_ObjCObjectPointer: 5762 switch (DestTy->getScalarTypeKind()) { 5763 case Type::STK_CPointer: { 5764 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5765 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5766 if (SrcAS != DestAS) 5767 return CK_AddressSpaceConversion; 5768 return CK_BitCast; 5769 } 5770 case Type::STK_BlockPointer: 5771 return (SrcKind == Type::STK_BlockPointer 5772 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5773 case Type::STK_ObjCObjectPointer: 5774 if (SrcKind == Type::STK_ObjCObjectPointer) 5775 return CK_BitCast; 5776 if (SrcKind == Type::STK_CPointer) 5777 return CK_CPointerToObjCPointerCast; 5778 maybeExtendBlockObject(Src); 5779 return CK_BlockPointerToObjCPointerCast; 5780 case Type::STK_Bool: 5781 return CK_PointerToBoolean; 5782 case Type::STK_Integral: 5783 return CK_PointerToIntegral; 5784 case Type::STK_Floating: 5785 case Type::STK_FloatingComplex: 5786 case Type::STK_IntegralComplex: 5787 case Type::STK_MemberPointer: 5788 llvm_unreachable("illegal cast from pointer"); 5789 } 5790 llvm_unreachable("Should have returned before this"); 5791 5792 case Type::STK_Bool: // casting from bool is like casting from an integer 5793 case Type::STK_Integral: 5794 switch (DestTy->getScalarTypeKind()) { 5795 case Type::STK_CPointer: 5796 case Type::STK_ObjCObjectPointer: 5797 case Type::STK_BlockPointer: 5798 if (Src.get()->isNullPointerConstant(Context, 5799 Expr::NPC_ValueDependentIsNull)) 5800 return CK_NullToPointer; 5801 return CK_IntegralToPointer; 5802 case Type::STK_Bool: 5803 return CK_IntegralToBoolean; 5804 case Type::STK_Integral: 5805 return CK_IntegralCast; 5806 case Type::STK_Floating: 5807 return CK_IntegralToFloating; 5808 case Type::STK_IntegralComplex: 5809 Src = ImpCastExprToType(Src.get(), 5810 DestTy->castAs<ComplexType>()->getElementType(), 5811 CK_IntegralCast); 5812 return CK_IntegralRealToComplex; 5813 case Type::STK_FloatingComplex: 5814 Src = ImpCastExprToType(Src.get(), 5815 DestTy->castAs<ComplexType>()->getElementType(), 5816 CK_IntegralToFloating); 5817 return CK_FloatingRealToComplex; 5818 case Type::STK_MemberPointer: 5819 llvm_unreachable("member pointer type in C"); 5820 } 5821 llvm_unreachable("Should have returned before this"); 5822 5823 case Type::STK_Floating: 5824 switch (DestTy->getScalarTypeKind()) { 5825 case Type::STK_Floating: 5826 return CK_FloatingCast; 5827 case Type::STK_Bool: 5828 return CK_FloatingToBoolean; 5829 case Type::STK_Integral: 5830 return CK_FloatingToIntegral; 5831 case Type::STK_FloatingComplex: 5832 Src = ImpCastExprToType(Src.get(), 5833 DestTy->castAs<ComplexType>()->getElementType(), 5834 CK_FloatingCast); 5835 return CK_FloatingRealToComplex; 5836 case Type::STK_IntegralComplex: 5837 Src = ImpCastExprToType(Src.get(), 5838 DestTy->castAs<ComplexType>()->getElementType(), 5839 CK_FloatingToIntegral); 5840 return CK_IntegralRealToComplex; 5841 case Type::STK_CPointer: 5842 case Type::STK_ObjCObjectPointer: 5843 case Type::STK_BlockPointer: 5844 llvm_unreachable("valid float->pointer cast?"); 5845 case Type::STK_MemberPointer: 5846 llvm_unreachable("member pointer type in C"); 5847 } 5848 llvm_unreachable("Should have returned before this"); 5849 5850 case Type::STK_FloatingComplex: 5851 switch (DestTy->getScalarTypeKind()) { 5852 case Type::STK_FloatingComplex: 5853 return CK_FloatingComplexCast; 5854 case Type::STK_IntegralComplex: 5855 return CK_FloatingComplexToIntegralComplex; 5856 case Type::STK_Floating: { 5857 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5858 if (Context.hasSameType(ET, DestTy)) 5859 return CK_FloatingComplexToReal; 5860 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5861 return CK_FloatingCast; 5862 } 5863 case Type::STK_Bool: 5864 return CK_FloatingComplexToBoolean; 5865 case Type::STK_Integral: 5866 Src = ImpCastExprToType(Src.get(), 5867 SrcTy->castAs<ComplexType>()->getElementType(), 5868 CK_FloatingComplexToReal); 5869 return CK_FloatingToIntegral; 5870 case Type::STK_CPointer: 5871 case Type::STK_ObjCObjectPointer: 5872 case Type::STK_BlockPointer: 5873 llvm_unreachable("valid complex float->pointer cast?"); 5874 case Type::STK_MemberPointer: 5875 llvm_unreachable("member pointer type in C"); 5876 } 5877 llvm_unreachable("Should have returned before this"); 5878 5879 case Type::STK_IntegralComplex: 5880 switch (DestTy->getScalarTypeKind()) { 5881 case Type::STK_FloatingComplex: 5882 return CK_IntegralComplexToFloatingComplex; 5883 case Type::STK_IntegralComplex: 5884 return CK_IntegralComplexCast; 5885 case Type::STK_Integral: { 5886 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5887 if (Context.hasSameType(ET, DestTy)) 5888 return CK_IntegralComplexToReal; 5889 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5890 return CK_IntegralCast; 5891 } 5892 case Type::STK_Bool: 5893 return CK_IntegralComplexToBoolean; 5894 case Type::STK_Floating: 5895 Src = ImpCastExprToType(Src.get(), 5896 SrcTy->castAs<ComplexType>()->getElementType(), 5897 CK_IntegralComplexToReal); 5898 return CK_IntegralToFloating; 5899 case Type::STK_CPointer: 5900 case Type::STK_ObjCObjectPointer: 5901 case Type::STK_BlockPointer: 5902 llvm_unreachable("valid complex int->pointer cast?"); 5903 case Type::STK_MemberPointer: 5904 llvm_unreachable("member pointer type in C"); 5905 } 5906 llvm_unreachable("Should have returned before this"); 5907 } 5908 5909 llvm_unreachable("Unhandled scalar cast"); 5910 } 5911 5912 static bool breakDownVectorType(QualType type, uint64_t &len, 5913 QualType &eltType) { 5914 // Vectors are simple. 5915 if (const VectorType *vecType = type->getAs<VectorType>()) { 5916 len = vecType->getNumElements(); 5917 eltType = vecType->getElementType(); 5918 assert(eltType->isScalarType()); 5919 return true; 5920 } 5921 5922 // We allow lax conversion to and from non-vector types, but only if 5923 // they're real types (i.e. non-complex, non-pointer scalar types). 5924 if (!type->isRealType()) return false; 5925 5926 len = 1; 5927 eltType = type; 5928 return true; 5929 } 5930 5931 /// Are the two types lax-compatible vector types? That is, given 5932 /// that one of them is a vector, do they have equal storage sizes, 5933 /// where the storage size is the number of elements times the element 5934 /// size? 5935 /// 5936 /// This will also return false if either of the types is neither a 5937 /// vector nor a real type. 5938 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5939 assert(destTy->isVectorType() || srcTy->isVectorType()); 5940 5941 // Disallow lax conversions between scalars and ExtVectors (these 5942 // conversions are allowed for other vector types because common headers 5943 // depend on them). Most scalar OP ExtVector cases are handled by the 5944 // splat path anyway, which does what we want (convert, not bitcast). 5945 // What this rules out for ExtVectors is crazy things like char4*float. 5946 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5947 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5948 5949 uint64_t srcLen, destLen; 5950 QualType srcEltTy, destEltTy; 5951 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5952 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5953 5954 // ASTContext::getTypeSize will return the size rounded up to a 5955 // power of 2, so instead of using that, we need to use the raw 5956 // element size multiplied by the element count. 5957 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5958 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5959 5960 return (srcLen * srcEltSize == destLen * destEltSize); 5961 } 5962 5963 /// Is this a legal conversion between two types, one of which is 5964 /// known to be a vector type? 5965 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5966 assert(destTy->isVectorType() || srcTy->isVectorType()); 5967 5968 if (!Context.getLangOpts().LaxVectorConversions) 5969 return false; 5970 return areLaxCompatibleVectorTypes(srcTy, destTy); 5971 } 5972 5973 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5974 CastKind &Kind) { 5975 assert(VectorTy->isVectorType() && "Not a vector type!"); 5976 5977 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5978 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5979 return Diag(R.getBegin(), 5980 Ty->isVectorType() ? 5981 diag::err_invalid_conversion_between_vectors : 5982 diag::err_invalid_conversion_between_vector_and_integer) 5983 << VectorTy << Ty << R; 5984 } else 5985 return Diag(R.getBegin(), 5986 diag::err_invalid_conversion_between_vector_and_scalar) 5987 << VectorTy << Ty << R; 5988 5989 Kind = CK_BitCast; 5990 return false; 5991 } 5992 5993 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5994 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5995 5996 if (DestElemTy == SplattedExpr->getType()) 5997 return SplattedExpr; 5998 5999 assert(DestElemTy->isFloatingType() || 6000 DestElemTy->isIntegralOrEnumerationType()); 6001 6002 CastKind CK; 6003 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6004 // OpenCL requires that we convert `true` boolean expressions to -1, but 6005 // only when splatting vectors. 6006 if (DestElemTy->isFloatingType()) { 6007 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6008 // in two steps: boolean to signed integral, then to floating. 6009 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6010 CK_BooleanToSignedIntegral); 6011 SplattedExpr = CastExprRes.get(); 6012 CK = CK_IntegralToFloating; 6013 } else { 6014 CK = CK_BooleanToSignedIntegral; 6015 } 6016 } else { 6017 ExprResult CastExprRes = SplattedExpr; 6018 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6019 if (CastExprRes.isInvalid()) 6020 return ExprError(); 6021 SplattedExpr = CastExprRes.get(); 6022 } 6023 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6024 } 6025 6026 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6027 Expr *CastExpr, CastKind &Kind) { 6028 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6029 6030 QualType SrcTy = CastExpr->getType(); 6031 6032 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6033 // an ExtVectorType. 6034 // In OpenCL, casts between vectors of different types are not allowed. 6035 // (See OpenCL 6.2). 6036 if (SrcTy->isVectorType()) { 6037 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6038 (getLangOpts().OpenCL && 6039 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6040 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6041 << DestTy << SrcTy << R; 6042 return ExprError(); 6043 } 6044 Kind = CK_BitCast; 6045 return CastExpr; 6046 } 6047 6048 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6049 // conversion will take place first from scalar to elt type, and then 6050 // splat from elt type to vector. 6051 if (SrcTy->isPointerType()) 6052 return Diag(R.getBegin(), 6053 diag::err_invalid_conversion_between_vector_and_scalar) 6054 << DestTy << SrcTy << R; 6055 6056 Kind = CK_VectorSplat; 6057 return prepareVectorSplat(DestTy, CastExpr); 6058 } 6059 6060 ExprResult 6061 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6062 Declarator &D, ParsedType &Ty, 6063 SourceLocation RParenLoc, Expr *CastExpr) { 6064 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6065 "ActOnCastExpr(): missing type or expr"); 6066 6067 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6068 if (D.isInvalidType()) 6069 return ExprError(); 6070 6071 if (getLangOpts().CPlusPlus) { 6072 // Check that there are no default arguments (C++ only). 6073 CheckExtraCXXDefaultArguments(D); 6074 } else { 6075 // Make sure any TypoExprs have been dealt with. 6076 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6077 if (!Res.isUsable()) 6078 return ExprError(); 6079 CastExpr = Res.get(); 6080 } 6081 6082 checkUnusedDeclAttributes(D); 6083 6084 QualType castType = castTInfo->getType(); 6085 Ty = CreateParsedType(castType, castTInfo); 6086 6087 bool isVectorLiteral = false; 6088 6089 // Check for an altivec or OpenCL literal, 6090 // i.e. all the elements are integer constants. 6091 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6092 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6093 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6094 && castType->isVectorType() && (PE || PLE)) { 6095 if (PLE && PLE->getNumExprs() == 0) { 6096 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6097 return ExprError(); 6098 } 6099 if (PE || PLE->getNumExprs() == 1) { 6100 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6101 if (!E->getType()->isVectorType()) 6102 isVectorLiteral = true; 6103 } 6104 else 6105 isVectorLiteral = true; 6106 } 6107 6108 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6109 // then handle it as such. 6110 if (isVectorLiteral) 6111 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6112 6113 // If the Expr being casted is a ParenListExpr, handle it specially. 6114 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6115 // sequence of BinOp comma operators. 6116 if (isa<ParenListExpr>(CastExpr)) { 6117 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6118 if (Result.isInvalid()) return ExprError(); 6119 CastExpr = Result.get(); 6120 } 6121 6122 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6123 !getSourceManager().isInSystemMacro(LParenLoc)) 6124 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6125 6126 CheckTollFreeBridgeCast(castType, CastExpr); 6127 6128 CheckObjCBridgeRelatedCast(castType, CastExpr); 6129 6130 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6131 6132 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6133 } 6134 6135 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6136 SourceLocation RParenLoc, Expr *E, 6137 TypeSourceInfo *TInfo) { 6138 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6139 "Expected paren or paren list expression"); 6140 6141 Expr **exprs; 6142 unsigned numExprs; 6143 Expr *subExpr; 6144 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6145 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6146 LiteralLParenLoc = PE->getLParenLoc(); 6147 LiteralRParenLoc = PE->getRParenLoc(); 6148 exprs = PE->getExprs(); 6149 numExprs = PE->getNumExprs(); 6150 } else { // isa<ParenExpr> by assertion at function entrance 6151 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6152 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6153 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6154 exprs = &subExpr; 6155 numExprs = 1; 6156 } 6157 6158 QualType Ty = TInfo->getType(); 6159 assert(Ty->isVectorType() && "Expected vector type"); 6160 6161 SmallVector<Expr *, 8> initExprs; 6162 const VectorType *VTy = Ty->getAs<VectorType>(); 6163 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6164 6165 // '(...)' form of vector initialization in AltiVec: the number of 6166 // initializers must be one or must match the size of the vector. 6167 // If a single value is specified in the initializer then it will be 6168 // replicated to all the components of the vector 6169 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6170 // The number of initializers must be one or must match the size of the 6171 // vector. If a single value is specified in the initializer then it will 6172 // be replicated to all the components of the vector 6173 if (numExprs == 1) { 6174 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6175 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6176 if (Literal.isInvalid()) 6177 return ExprError(); 6178 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6179 PrepareScalarCast(Literal, ElemTy)); 6180 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6181 } 6182 else if (numExprs < numElems) { 6183 Diag(E->getExprLoc(), 6184 diag::err_incorrect_number_of_vector_initializers); 6185 return ExprError(); 6186 } 6187 else 6188 initExprs.append(exprs, exprs + numExprs); 6189 } 6190 else { 6191 // For OpenCL, when the number of initializers is a single value, 6192 // it will be replicated to all components of the vector. 6193 if (getLangOpts().OpenCL && 6194 VTy->getVectorKind() == VectorType::GenericVector && 6195 numExprs == 1) { 6196 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6197 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6198 if (Literal.isInvalid()) 6199 return ExprError(); 6200 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6201 PrepareScalarCast(Literal, ElemTy)); 6202 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6203 } 6204 6205 initExprs.append(exprs, exprs + numExprs); 6206 } 6207 // FIXME: This means that pretty-printing the final AST will produce curly 6208 // braces instead of the original commas. 6209 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6210 initExprs, LiteralRParenLoc); 6211 initE->setType(Ty); 6212 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6213 } 6214 6215 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6216 /// the ParenListExpr into a sequence of comma binary operators. 6217 ExprResult 6218 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6219 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6220 if (!E) 6221 return OrigExpr; 6222 6223 ExprResult Result(E->getExpr(0)); 6224 6225 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6226 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6227 E->getExpr(i)); 6228 6229 if (Result.isInvalid()) return ExprError(); 6230 6231 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6232 } 6233 6234 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6235 SourceLocation R, 6236 MultiExprArg Val) { 6237 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6238 return expr; 6239 } 6240 6241 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6242 /// constant and the other is not a pointer. Returns true if a diagnostic is 6243 /// emitted. 6244 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6245 SourceLocation QuestionLoc) { 6246 Expr *NullExpr = LHSExpr; 6247 Expr *NonPointerExpr = RHSExpr; 6248 Expr::NullPointerConstantKind NullKind = 6249 NullExpr->isNullPointerConstant(Context, 6250 Expr::NPC_ValueDependentIsNotNull); 6251 6252 if (NullKind == Expr::NPCK_NotNull) { 6253 NullExpr = RHSExpr; 6254 NonPointerExpr = LHSExpr; 6255 NullKind = 6256 NullExpr->isNullPointerConstant(Context, 6257 Expr::NPC_ValueDependentIsNotNull); 6258 } 6259 6260 if (NullKind == Expr::NPCK_NotNull) 6261 return false; 6262 6263 if (NullKind == Expr::NPCK_ZeroExpression) 6264 return false; 6265 6266 if (NullKind == Expr::NPCK_ZeroLiteral) { 6267 // In this case, check to make sure that we got here from a "NULL" 6268 // string in the source code. 6269 NullExpr = NullExpr->IgnoreParenImpCasts(); 6270 SourceLocation loc = NullExpr->getExprLoc(); 6271 if (!findMacroSpelling(loc, "NULL")) 6272 return false; 6273 } 6274 6275 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6276 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6277 << NonPointerExpr->getType() << DiagType 6278 << NonPointerExpr->getSourceRange(); 6279 return true; 6280 } 6281 6282 /// \brief Return false if the condition expression is valid, true otherwise. 6283 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6284 QualType CondTy = Cond->getType(); 6285 6286 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6287 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6288 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6289 << CondTy << Cond->getSourceRange(); 6290 return true; 6291 } 6292 6293 // C99 6.5.15p2 6294 if (CondTy->isScalarType()) return false; 6295 6296 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6297 << CondTy << Cond->getSourceRange(); 6298 return true; 6299 } 6300 6301 /// \brief Handle when one or both operands are void type. 6302 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6303 ExprResult &RHS) { 6304 Expr *LHSExpr = LHS.get(); 6305 Expr *RHSExpr = RHS.get(); 6306 6307 if (!LHSExpr->getType()->isVoidType()) 6308 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6309 << RHSExpr->getSourceRange(); 6310 if (!RHSExpr->getType()->isVoidType()) 6311 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6312 << LHSExpr->getSourceRange(); 6313 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6314 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6315 return S.Context.VoidTy; 6316 } 6317 6318 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6319 /// true otherwise. 6320 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6321 QualType PointerTy) { 6322 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6323 !NullExpr.get()->isNullPointerConstant(S.Context, 6324 Expr::NPC_ValueDependentIsNull)) 6325 return true; 6326 6327 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6328 return false; 6329 } 6330 6331 /// \brief Checks compatibility between two pointers and return the resulting 6332 /// type. 6333 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6334 ExprResult &RHS, 6335 SourceLocation Loc) { 6336 QualType LHSTy = LHS.get()->getType(); 6337 QualType RHSTy = RHS.get()->getType(); 6338 6339 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6340 // Two identical pointers types are always compatible. 6341 return LHSTy; 6342 } 6343 6344 QualType lhptee, rhptee; 6345 6346 // Get the pointee types. 6347 bool IsBlockPointer = false; 6348 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6349 lhptee = LHSBTy->getPointeeType(); 6350 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6351 IsBlockPointer = true; 6352 } else { 6353 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6354 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6355 } 6356 6357 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6358 // differently qualified versions of compatible types, the result type is 6359 // a pointer to an appropriately qualified version of the composite 6360 // type. 6361 6362 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6363 // clause doesn't make sense for our extensions. E.g. address space 2 should 6364 // be incompatible with address space 3: they may live on different devices or 6365 // anything. 6366 Qualifiers lhQual = lhptee.getQualifiers(); 6367 Qualifiers rhQual = rhptee.getQualifiers(); 6368 6369 LangAS ResultAddrSpace = LangAS::Default; 6370 LangAS LAddrSpace = lhQual.getAddressSpace(); 6371 LangAS RAddrSpace = rhQual.getAddressSpace(); 6372 if (S.getLangOpts().OpenCL) { 6373 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6374 // spaces is disallowed. 6375 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6376 ResultAddrSpace = LAddrSpace; 6377 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6378 ResultAddrSpace = RAddrSpace; 6379 else { 6380 S.Diag(Loc, 6381 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6382 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6383 << RHS.get()->getSourceRange(); 6384 return QualType(); 6385 } 6386 } 6387 6388 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6389 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6390 lhQual.removeCVRQualifiers(); 6391 rhQual.removeCVRQualifiers(); 6392 6393 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6394 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6395 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6396 // qual types are compatible iff 6397 // * corresponded types are compatible 6398 // * CVR qualifiers are equal 6399 // * address spaces are equal 6400 // Thus for conditional operator we merge CVR and address space unqualified 6401 // pointees and if there is a composite type we return a pointer to it with 6402 // merged qualifiers. 6403 if (S.getLangOpts().OpenCL) { 6404 LHSCastKind = LAddrSpace == ResultAddrSpace 6405 ? CK_BitCast 6406 : CK_AddressSpaceConversion; 6407 RHSCastKind = RAddrSpace == ResultAddrSpace 6408 ? CK_BitCast 6409 : CK_AddressSpaceConversion; 6410 lhQual.removeAddressSpace(); 6411 rhQual.removeAddressSpace(); 6412 } 6413 6414 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6415 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6416 6417 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6418 6419 if (CompositeTy.isNull()) { 6420 // In this situation, we assume void* type. No especially good 6421 // reason, but this is what gcc does, and we do have to pick 6422 // to get a consistent AST. 6423 QualType incompatTy; 6424 incompatTy = S.Context.getPointerType( 6425 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6426 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6427 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6428 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6429 // for casts between types with incompatible address space qualifiers. 6430 // For the following code the compiler produces casts between global and 6431 // local address spaces of the corresponded innermost pointees: 6432 // local int *global *a; 6433 // global int *global *b; 6434 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6435 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6436 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6437 << RHS.get()->getSourceRange(); 6438 return incompatTy; 6439 } 6440 6441 // The pointer types are compatible. 6442 // In case of OpenCL ResultTy should have the address space qualifier 6443 // which is a superset of address spaces of both the 2nd and the 3rd 6444 // operands of the conditional operator. 6445 QualType ResultTy = [&, ResultAddrSpace]() { 6446 if (S.getLangOpts().OpenCL) { 6447 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6448 CompositeQuals.setAddressSpace(ResultAddrSpace); 6449 return S.Context 6450 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6451 .withCVRQualifiers(MergedCVRQual); 6452 } 6453 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6454 }(); 6455 if (IsBlockPointer) 6456 ResultTy = S.Context.getBlockPointerType(ResultTy); 6457 else 6458 ResultTy = S.Context.getPointerType(ResultTy); 6459 6460 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6461 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6462 return ResultTy; 6463 } 6464 6465 /// \brief Return the resulting type when the operands are both block pointers. 6466 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6467 ExprResult &LHS, 6468 ExprResult &RHS, 6469 SourceLocation Loc) { 6470 QualType LHSTy = LHS.get()->getType(); 6471 QualType RHSTy = RHS.get()->getType(); 6472 6473 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6474 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6475 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6476 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6477 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6478 return destType; 6479 } 6480 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6481 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6482 << RHS.get()->getSourceRange(); 6483 return QualType(); 6484 } 6485 6486 // We have 2 block pointer types. 6487 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6488 } 6489 6490 /// \brief Return the resulting type when the operands are both pointers. 6491 static QualType 6492 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6493 ExprResult &RHS, 6494 SourceLocation Loc) { 6495 // get the pointer types 6496 QualType LHSTy = LHS.get()->getType(); 6497 QualType RHSTy = RHS.get()->getType(); 6498 6499 // get the "pointed to" types 6500 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6501 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6502 6503 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6504 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6505 // Figure out necessary qualifiers (C99 6.5.15p6) 6506 QualType destPointee 6507 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6508 QualType destType = S.Context.getPointerType(destPointee); 6509 // Add qualifiers if necessary. 6510 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6511 // Promote to void*. 6512 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6513 return destType; 6514 } 6515 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6516 QualType destPointee 6517 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6518 QualType destType = S.Context.getPointerType(destPointee); 6519 // Add qualifiers if necessary. 6520 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6521 // Promote to void*. 6522 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6523 return destType; 6524 } 6525 6526 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6527 } 6528 6529 /// \brief Return false if the first expression is not an integer and the second 6530 /// expression is not a pointer, true otherwise. 6531 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6532 Expr* PointerExpr, SourceLocation Loc, 6533 bool IsIntFirstExpr) { 6534 if (!PointerExpr->getType()->isPointerType() || 6535 !Int.get()->getType()->isIntegerType()) 6536 return false; 6537 6538 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6539 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6540 6541 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6542 << Expr1->getType() << Expr2->getType() 6543 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6544 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6545 CK_IntegralToPointer); 6546 return true; 6547 } 6548 6549 /// \brief Simple conversion between integer and floating point types. 6550 /// 6551 /// Used when handling the OpenCL conditional operator where the 6552 /// condition is a vector while the other operands are scalar. 6553 /// 6554 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6555 /// types are either integer or floating type. Between the two 6556 /// operands, the type with the higher rank is defined as the "result 6557 /// type". The other operand needs to be promoted to the same type. No 6558 /// other type promotion is allowed. We cannot use 6559 /// UsualArithmeticConversions() for this purpose, since it always 6560 /// promotes promotable types. 6561 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6562 ExprResult &RHS, 6563 SourceLocation QuestionLoc) { 6564 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6565 if (LHS.isInvalid()) 6566 return QualType(); 6567 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6568 if (RHS.isInvalid()) 6569 return QualType(); 6570 6571 // For conversion purposes, we ignore any qualifiers. 6572 // For example, "const float" and "float" are equivalent. 6573 QualType LHSType = 6574 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6575 QualType RHSType = 6576 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6577 6578 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6579 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6580 << LHSType << LHS.get()->getSourceRange(); 6581 return QualType(); 6582 } 6583 6584 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6585 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6586 << RHSType << RHS.get()->getSourceRange(); 6587 return QualType(); 6588 } 6589 6590 // If both types are identical, no conversion is needed. 6591 if (LHSType == RHSType) 6592 return LHSType; 6593 6594 // Now handle "real" floating types (i.e. float, double, long double). 6595 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6596 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6597 /*IsCompAssign = */ false); 6598 6599 // Finally, we have two differing integer types. 6600 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6601 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6602 } 6603 6604 /// \brief Convert scalar operands to a vector that matches the 6605 /// condition in length. 6606 /// 6607 /// Used when handling the OpenCL conditional operator where the 6608 /// condition is a vector while the other operands are scalar. 6609 /// 6610 /// We first compute the "result type" for the scalar operands 6611 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6612 /// into a vector of that type where the length matches the condition 6613 /// vector type. s6.11.6 requires that the element types of the result 6614 /// and the condition must have the same number of bits. 6615 static QualType 6616 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6617 QualType CondTy, SourceLocation QuestionLoc) { 6618 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6619 if (ResTy.isNull()) return QualType(); 6620 6621 const VectorType *CV = CondTy->getAs<VectorType>(); 6622 assert(CV); 6623 6624 // Determine the vector result type 6625 unsigned NumElements = CV->getNumElements(); 6626 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6627 6628 // Ensure that all types have the same number of bits 6629 if (S.Context.getTypeSize(CV->getElementType()) 6630 != S.Context.getTypeSize(ResTy)) { 6631 // Since VectorTy is created internally, it does not pretty print 6632 // with an OpenCL name. Instead, we just print a description. 6633 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6634 SmallString<64> Str; 6635 llvm::raw_svector_ostream OS(Str); 6636 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6637 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6638 << CondTy << OS.str(); 6639 return QualType(); 6640 } 6641 6642 // Convert operands to the vector result type 6643 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6644 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6645 6646 return VectorTy; 6647 } 6648 6649 /// \brief Return false if this is a valid OpenCL condition vector 6650 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6651 SourceLocation QuestionLoc) { 6652 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6653 // integral type. 6654 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6655 assert(CondTy); 6656 QualType EleTy = CondTy->getElementType(); 6657 if (EleTy->isIntegerType()) return false; 6658 6659 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6660 << Cond->getType() << Cond->getSourceRange(); 6661 return true; 6662 } 6663 6664 /// \brief Return false if the vector condition type and the vector 6665 /// result type are compatible. 6666 /// 6667 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6668 /// number of elements, and their element types have the same number 6669 /// of bits. 6670 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6671 SourceLocation QuestionLoc) { 6672 const VectorType *CV = CondTy->getAs<VectorType>(); 6673 const VectorType *RV = VecResTy->getAs<VectorType>(); 6674 assert(CV && RV); 6675 6676 if (CV->getNumElements() != RV->getNumElements()) { 6677 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6678 << CondTy << VecResTy; 6679 return true; 6680 } 6681 6682 QualType CVE = CV->getElementType(); 6683 QualType RVE = RV->getElementType(); 6684 6685 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6686 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6687 << CondTy << VecResTy; 6688 return true; 6689 } 6690 6691 return false; 6692 } 6693 6694 /// \brief Return the resulting type for the conditional operator in 6695 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6696 /// s6.3.i) when the condition is a vector type. 6697 static QualType 6698 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6699 ExprResult &LHS, ExprResult &RHS, 6700 SourceLocation QuestionLoc) { 6701 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6702 if (Cond.isInvalid()) 6703 return QualType(); 6704 QualType CondTy = Cond.get()->getType(); 6705 6706 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6707 return QualType(); 6708 6709 // If either operand is a vector then find the vector type of the 6710 // result as specified in OpenCL v1.1 s6.3.i. 6711 if (LHS.get()->getType()->isVectorType() || 6712 RHS.get()->getType()->isVectorType()) { 6713 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6714 /*isCompAssign*/false, 6715 /*AllowBothBool*/true, 6716 /*AllowBoolConversions*/false); 6717 if (VecResTy.isNull()) return QualType(); 6718 // The result type must match the condition type as specified in 6719 // OpenCL v1.1 s6.11.6. 6720 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6721 return QualType(); 6722 return VecResTy; 6723 } 6724 6725 // Both operands are scalar. 6726 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6727 } 6728 6729 /// \brief Return true if the Expr is block type 6730 static bool checkBlockType(Sema &S, const Expr *E) { 6731 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6732 QualType Ty = CE->getCallee()->getType(); 6733 if (Ty->isBlockPointerType()) { 6734 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6735 return true; 6736 } 6737 } 6738 return false; 6739 } 6740 6741 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6742 /// In that case, LHS = cond. 6743 /// C99 6.5.15 6744 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6745 ExprResult &RHS, ExprValueKind &VK, 6746 ExprObjectKind &OK, 6747 SourceLocation QuestionLoc) { 6748 6749 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6750 if (!LHSResult.isUsable()) return QualType(); 6751 LHS = LHSResult; 6752 6753 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6754 if (!RHSResult.isUsable()) return QualType(); 6755 RHS = RHSResult; 6756 6757 // C++ is sufficiently different to merit its own checker. 6758 if (getLangOpts().CPlusPlus) 6759 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6760 6761 VK = VK_RValue; 6762 OK = OK_Ordinary; 6763 6764 // The OpenCL operator with a vector condition is sufficiently 6765 // different to merit its own checker. 6766 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6767 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6768 6769 // First, check the condition. 6770 Cond = UsualUnaryConversions(Cond.get()); 6771 if (Cond.isInvalid()) 6772 return QualType(); 6773 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6774 return QualType(); 6775 6776 // Now check the two expressions. 6777 if (LHS.get()->getType()->isVectorType() || 6778 RHS.get()->getType()->isVectorType()) 6779 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6780 /*AllowBothBool*/true, 6781 /*AllowBoolConversions*/false); 6782 6783 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6784 if (LHS.isInvalid() || RHS.isInvalid()) 6785 return QualType(); 6786 6787 QualType LHSTy = LHS.get()->getType(); 6788 QualType RHSTy = RHS.get()->getType(); 6789 6790 // Diagnose attempts to convert between __float128 and long double where 6791 // such conversions currently can't be handled. 6792 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6793 Diag(QuestionLoc, 6794 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6795 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6796 return QualType(); 6797 } 6798 6799 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6800 // selection operator (?:). 6801 if (getLangOpts().OpenCL && 6802 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6803 return QualType(); 6804 } 6805 6806 // If both operands have arithmetic type, do the usual arithmetic conversions 6807 // to find a common type: C99 6.5.15p3,5. 6808 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6809 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6810 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6811 6812 return ResTy; 6813 } 6814 6815 // If both operands are the same structure or union type, the result is that 6816 // type. 6817 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6818 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6819 if (LHSRT->getDecl() == RHSRT->getDecl()) 6820 // "If both the operands have structure or union type, the result has 6821 // that type." This implies that CV qualifiers are dropped. 6822 return LHSTy.getUnqualifiedType(); 6823 // FIXME: Type of conditional expression must be complete in C mode. 6824 } 6825 6826 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6827 // The following || allows only one side to be void (a GCC-ism). 6828 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6829 return checkConditionalVoidType(*this, LHS, RHS); 6830 } 6831 6832 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6833 // the type of the other operand." 6834 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6835 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6836 6837 // All objective-c pointer type analysis is done here. 6838 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6839 QuestionLoc); 6840 if (LHS.isInvalid() || RHS.isInvalid()) 6841 return QualType(); 6842 if (!compositeType.isNull()) 6843 return compositeType; 6844 6845 6846 // Handle block pointer types. 6847 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6848 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6849 QuestionLoc); 6850 6851 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6852 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6853 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6854 QuestionLoc); 6855 6856 // GCC compatibility: soften pointer/integer mismatch. Note that 6857 // null pointers have been filtered out by this point. 6858 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6859 /*isIntFirstExpr=*/true)) 6860 return RHSTy; 6861 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6862 /*isIntFirstExpr=*/false)) 6863 return LHSTy; 6864 6865 // Emit a better diagnostic if one of the expressions is a null pointer 6866 // constant and the other is not a pointer type. In this case, the user most 6867 // likely forgot to take the address of the other expression. 6868 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6869 return QualType(); 6870 6871 // Otherwise, the operands are not compatible. 6872 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6873 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6874 << RHS.get()->getSourceRange(); 6875 return QualType(); 6876 } 6877 6878 /// FindCompositeObjCPointerType - Helper method to find composite type of 6879 /// two objective-c pointer types of the two input expressions. 6880 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6881 SourceLocation QuestionLoc) { 6882 QualType LHSTy = LHS.get()->getType(); 6883 QualType RHSTy = RHS.get()->getType(); 6884 6885 // Handle things like Class and struct objc_class*. Here we case the result 6886 // to the pseudo-builtin, because that will be implicitly cast back to the 6887 // redefinition type if an attempt is made to access its fields. 6888 if (LHSTy->isObjCClassType() && 6889 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6890 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6891 return LHSTy; 6892 } 6893 if (RHSTy->isObjCClassType() && 6894 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6895 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6896 return RHSTy; 6897 } 6898 // And the same for struct objc_object* / id 6899 if (LHSTy->isObjCIdType() && 6900 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6901 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6902 return LHSTy; 6903 } 6904 if (RHSTy->isObjCIdType() && 6905 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6906 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6907 return RHSTy; 6908 } 6909 // And the same for struct objc_selector* / SEL 6910 if (Context.isObjCSelType(LHSTy) && 6911 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6912 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6913 return LHSTy; 6914 } 6915 if (Context.isObjCSelType(RHSTy) && 6916 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6917 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6918 return RHSTy; 6919 } 6920 // Check constraints for Objective-C object pointers types. 6921 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6922 6923 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6924 // Two identical object pointer types are always compatible. 6925 return LHSTy; 6926 } 6927 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6928 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6929 QualType compositeType = LHSTy; 6930 6931 // If both operands are interfaces and either operand can be 6932 // assigned to the other, use that type as the composite 6933 // type. This allows 6934 // xxx ? (A*) a : (B*) b 6935 // where B is a subclass of A. 6936 // 6937 // Additionally, as for assignment, if either type is 'id' 6938 // allow silent coercion. Finally, if the types are 6939 // incompatible then make sure to use 'id' as the composite 6940 // type so the result is acceptable for sending messages to. 6941 6942 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6943 // It could return the composite type. 6944 if (!(compositeType = 6945 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6946 // Nothing more to do. 6947 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6948 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6949 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6950 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6951 } else if ((LHSTy->isObjCQualifiedIdType() || 6952 RHSTy->isObjCQualifiedIdType()) && 6953 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6954 // Need to handle "id<xx>" explicitly. 6955 // GCC allows qualified id and any Objective-C type to devolve to 6956 // id. Currently localizing to here until clear this should be 6957 // part of ObjCQualifiedIdTypesAreCompatible. 6958 compositeType = Context.getObjCIdType(); 6959 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6960 compositeType = Context.getObjCIdType(); 6961 } else { 6962 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6963 << LHSTy << RHSTy 6964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6965 QualType incompatTy = Context.getObjCIdType(); 6966 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6967 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6968 return incompatTy; 6969 } 6970 // The object pointer types are compatible. 6971 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6972 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6973 return compositeType; 6974 } 6975 // Check Objective-C object pointer types and 'void *' 6976 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6977 if (getLangOpts().ObjCAutoRefCount) { 6978 // ARC forbids the implicit conversion of object pointers to 'void *', 6979 // so these types are not compatible. 6980 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6982 LHS = RHS = true; 6983 return QualType(); 6984 } 6985 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6986 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6987 QualType destPointee 6988 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6989 QualType destType = Context.getPointerType(destPointee); 6990 // Add qualifiers if necessary. 6991 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6992 // Promote to void*. 6993 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6994 return destType; 6995 } 6996 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6997 if (getLangOpts().ObjCAutoRefCount) { 6998 // ARC forbids the implicit conversion of object pointers to 'void *', 6999 // so these types are not compatible. 7000 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7002 LHS = RHS = true; 7003 return QualType(); 7004 } 7005 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7006 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7007 QualType destPointee 7008 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7009 QualType destType = Context.getPointerType(destPointee); 7010 // Add qualifiers if necessary. 7011 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7012 // Promote to void*. 7013 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7014 return destType; 7015 } 7016 return QualType(); 7017 } 7018 7019 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7020 /// ParenRange in parentheses. 7021 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7022 const PartialDiagnostic &Note, 7023 SourceRange ParenRange) { 7024 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7025 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7026 EndLoc.isValid()) { 7027 Self.Diag(Loc, Note) 7028 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7029 << FixItHint::CreateInsertion(EndLoc, ")"); 7030 } else { 7031 // We can't display the parentheses, so just show the bare note. 7032 Self.Diag(Loc, Note) << ParenRange; 7033 } 7034 } 7035 7036 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7037 return BinaryOperator::isAdditiveOp(Opc) || 7038 BinaryOperator::isMultiplicativeOp(Opc) || 7039 BinaryOperator::isShiftOp(Opc); 7040 } 7041 7042 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7043 /// expression, either using a built-in or overloaded operator, 7044 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7045 /// expression. 7046 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7047 Expr **RHSExprs) { 7048 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7049 E = E->IgnoreImpCasts(); 7050 E = E->IgnoreConversionOperator(); 7051 E = E->IgnoreImpCasts(); 7052 7053 // Built-in binary operator. 7054 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7055 if (IsArithmeticOp(OP->getOpcode())) { 7056 *Opcode = OP->getOpcode(); 7057 *RHSExprs = OP->getRHS(); 7058 return true; 7059 } 7060 } 7061 7062 // Overloaded operator. 7063 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7064 if (Call->getNumArgs() != 2) 7065 return false; 7066 7067 // Make sure this is really a binary operator that is safe to pass into 7068 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7069 OverloadedOperatorKind OO = Call->getOperator(); 7070 if (OO < OO_Plus || OO > OO_Arrow || 7071 OO == OO_PlusPlus || OO == OO_MinusMinus) 7072 return false; 7073 7074 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7075 if (IsArithmeticOp(OpKind)) { 7076 *Opcode = OpKind; 7077 *RHSExprs = Call->getArg(1); 7078 return true; 7079 } 7080 } 7081 7082 return false; 7083 } 7084 7085 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7086 /// or is a logical expression such as (x==y) which has int type, but is 7087 /// commonly interpreted as boolean. 7088 static bool ExprLooksBoolean(Expr *E) { 7089 E = E->IgnoreParenImpCasts(); 7090 7091 if (E->getType()->isBooleanType()) 7092 return true; 7093 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7094 return OP->isComparisonOp() || OP->isLogicalOp(); 7095 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7096 return OP->getOpcode() == UO_LNot; 7097 if (E->getType()->isPointerType()) 7098 return true; 7099 7100 return false; 7101 } 7102 7103 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7104 /// and binary operator are mixed in a way that suggests the programmer assumed 7105 /// the conditional operator has higher precedence, for example: 7106 /// "int x = a + someBinaryCondition ? 1 : 2". 7107 static void DiagnoseConditionalPrecedence(Sema &Self, 7108 SourceLocation OpLoc, 7109 Expr *Condition, 7110 Expr *LHSExpr, 7111 Expr *RHSExpr) { 7112 BinaryOperatorKind CondOpcode; 7113 Expr *CondRHS; 7114 7115 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7116 return; 7117 if (!ExprLooksBoolean(CondRHS)) 7118 return; 7119 7120 // The condition is an arithmetic binary expression, with a right- 7121 // hand side that looks boolean, so warn. 7122 7123 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7124 << Condition->getSourceRange() 7125 << BinaryOperator::getOpcodeStr(CondOpcode); 7126 7127 SuggestParentheses(Self, OpLoc, 7128 Self.PDiag(diag::note_precedence_silence) 7129 << BinaryOperator::getOpcodeStr(CondOpcode), 7130 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7131 7132 SuggestParentheses(Self, OpLoc, 7133 Self.PDiag(diag::note_precedence_conditional_first), 7134 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7135 } 7136 7137 /// Compute the nullability of a conditional expression. 7138 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7139 QualType LHSTy, QualType RHSTy, 7140 ASTContext &Ctx) { 7141 if (!ResTy->isAnyPointerType()) 7142 return ResTy; 7143 7144 auto GetNullability = [&Ctx](QualType Ty) { 7145 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7146 if (Kind) 7147 return *Kind; 7148 return NullabilityKind::Unspecified; 7149 }; 7150 7151 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7152 NullabilityKind MergedKind; 7153 7154 // Compute nullability of a binary conditional expression. 7155 if (IsBin) { 7156 if (LHSKind == NullabilityKind::NonNull) 7157 MergedKind = NullabilityKind::NonNull; 7158 else 7159 MergedKind = RHSKind; 7160 // Compute nullability of a normal conditional expression. 7161 } else { 7162 if (LHSKind == NullabilityKind::Nullable || 7163 RHSKind == NullabilityKind::Nullable) 7164 MergedKind = NullabilityKind::Nullable; 7165 else if (LHSKind == NullabilityKind::NonNull) 7166 MergedKind = RHSKind; 7167 else if (RHSKind == NullabilityKind::NonNull) 7168 MergedKind = LHSKind; 7169 else 7170 MergedKind = NullabilityKind::Unspecified; 7171 } 7172 7173 // Return if ResTy already has the correct nullability. 7174 if (GetNullability(ResTy) == MergedKind) 7175 return ResTy; 7176 7177 // Strip all nullability from ResTy. 7178 while (ResTy->getNullability(Ctx)) 7179 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7180 7181 // Create a new AttributedType with the new nullability kind. 7182 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7183 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7184 } 7185 7186 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7187 /// in the case of a the GNU conditional expr extension. 7188 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7189 SourceLocation ColonLoc, 7190 Expr *CondExpr, Expr *LHSExpr, 7191 Expr *RHSExpr) { 7192 if (!getLangOpts().CPlusPlus) { 7193 // C cannot handle TypoExpr nodes in the condition because it 7194 // doesn't handle dependent types properly, so make sure any TypoExprs have 7195 // been dealt with before checking the operands. 7196 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7197 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7198 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7199 7200 if (!CondResult.isUsable()) 7201 return ExprError(); 7202 7203 if (LHSExpr) { 7204 if (!LHSResult.isUsable()) 7205 return ExprError(); 7206 } 7207 7208 if (!RHSResult.isUsable()) 7209 return ExprError(); 7210 7211 CondExpr = CondResult.get(); 7212 LHSExpr = LHSResult.get(); 7213 RHSExpr = RHSResult.get(); 7214 } 7215 7216 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7217 // was the condition. 7218 OpaqueValueExpr *opaqueValue = nullptr; 7219 Expr *commonExpr = nullptr; 7220 if (!LHSExpr) { 7221 commonExpr = CondExpr; 7222 // Lower out placeholder types first. This is important so that we don't 7223 // try to capture a placeholder. This happens in few cases in C++; such 7224 // as Objective-C++'s dictionary subscripting syntax. 7225 if (commonExpr->hasPlaceholderType()) { 7226 ExprResult result = CheckPlaceholderExpr(commonExpr); 7227 if (!result.isUsable()) return ExprError(); 7228 commonExpr = result.get(); 7229 } 7230 // We usually want to apply unary conversions *before* saving, except 7231 // in the special case of a C++ l-value conditional. 7232 if (!(getLangOpts().CPlusPlus 7233 && !commonExpr->isTypeDependent() 7234 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7235 && commonExpr->isGLValue() 7236 && commonExpr->isOrdinaryOrBitFieldObject() 7237 && RHSExpr->isOrdinaryOrBitFieldObject() 7238 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7239 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7240 if (commonRes.isInvalid()) 7241 return ExprError(); 7242 commonExpr = commonRes.get(); 7243 } 7244 7245 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7246 commonExpr->getType(), 7247 commonExpr->getValueKind(), 7248 commonExpr->getObjectKind(), 7249 commonExpr); 7250 LHSExpr = CondExpr = opaqueValue; 7251 } 7252 7253 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7254 ExprValueKind VK = VK_RValue; 7255 ExprObjectKind OK = OK_Ordinary; 7256 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7257 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7258 VK, OK, QuestionLoc); 7259 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7260 RHS.isInvalid()) 7261 return ExprError(); 7262 7263 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7264 RHS.get()); 7265 7266 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7267 7268 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7269 Context); 7270 7271 if (!commonExpr) 7272 return new (Context) 7273 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7274 RHS.get(), result, VK, OK); 7275 7276 return new (Context) BinaryConditionalOperator( 7277 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7278 ColonLoc, result, VK, OK); 7279 } 7280 7281 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7282 // being closely modeled after the C99 spec:-). The odd characteristic of this 7283 // routine is it effectively iqnores the qualifiers on the top level pointee. 7284 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7285 // FIXME: add a couple examples in this comment. 7286 static Sema::AssignConvertType 7287 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7288 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7289 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7290 7291 // get the "pointed to" type (ignoring qualifiers at the top level) 7292 const Type *lhptee, *rhptee; 7293 Qualifiers lhq, rhq; 7294 std::tie(lhptee, lhq) = 7295 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7296 std::tie(rhptee, rhq) = 7297 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7298 7299 Sema::AssignConvertType ConvTy = Sema::Compatible; 7300 7301 // C99 6.5.16.1p1: This following citation is common to constraints 7302 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7303 // qualifiers of the type *pointed to* by the right; 7304 7305 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7306 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7307 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7308 // Ignore lifetime for further calculation. 7309 lhq.removeObjCLifetime(); 7310 rhq.removeObjCLifetime(); 7311 } 7312 7313 if (!lhq.compatiblyIncludes(rhq)) { 7314 // Treat address-space mismatches as fatal. TODO: address subspaces 7315 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7316 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7317 7318 // It's okay to add or remove GC or lifetime qualifiers when converting to 7319 // and from void*. 7320 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7321 .compatiblyIncludes( 7322 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7323 && (lhptee->isVoidType() || rhptee->isVoidType())) 7324 ; // keep old 7325 7326 // Treat lifetime mismatches as fatal. 7327 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7328 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7329 7330 // For GCC/MS compatibility, other qualifier mismatches are treated 7331 // as still compatible in C. 7332 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7333 } 7334 7335 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7336 // incomplete type and the other is a pointer to a qualified or unqualified 7337 // version of void... 7338 if (lhptee->isVoidType()) { 7339 if (rhptee->isIncompleteOrObjectType()) 7340 return ConvTy; 7341 7342 // As an extension, we allow cast to/from void* to function pointer. 7343 assert(rhptee->isFunctionType()); 7344 return Sema::FunctionVoidPointer; 7345 } 7346 7347 if (rhptee->isVoidType()) { 7348 if (lhptee->isIncompleteOrObjectType()) 7349 return ConvTy; 7350 7351 // As an extension, we allow cast to/from void* to function pointer. 7352 assert(lhptee->isFunctionType()); 7353 return Sema::FunctionVoidPointer; 7354 } 7355 7356 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7357 // unqualified versions of compatible types, ... 7358 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7359 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7360 // Check if the pointee types are compatible ignoring the sign. 7361 // We explicitly check for char so that we catch "char" vs 7362 // "unsigned char" on systems where "char" is unsigned. 7363 if (lhptee->isCharType()) 7364 ltrans = S.Context.UnsignedCharTy; 7365 else if (lhptee->hasSignedIntegerRepresentation()) 7366 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7367 7368 if (rhptee->isCharType()) 7369 rtrans = S.Context.UnsignedCharTy; 7370 else if (rhptee->hasSignedIntegerRepresentation()) 7371 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7372 7373 if (ltrans == rtrans) { 7374 // Types are compatible ignoring the sign. Qualifier incompatibility 7375 // takes priority over sign incompatibility because the sign 7376 // warning can be disabled. 7377 if (ConvTy != Sema::Compatible) 7378 return ConvTy; 7379 7380 return Sema::IncompatiblePointerSign; 7381 } 7382 7383 // If we are a multi-level pointer, it's possible that our issue is simply 7384 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7385 // the eventual target type is the same and the pointers have the same 7386 // level of indirection, this must be the issue. 7387 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7388 do { 7389 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7390 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7391 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7392 7393 if (lhptee == rhptee) 7394 return Sema::IncompatibleNestedPointerQualifiers; 7395 } 7396 7397 // General pointer incompatibility takes priority over qualifiers. 7398 return Sema::IncompatiblePointer; 7399 } 7400 if (!S.getLangOpts().CPlusPlus && 7401 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7402 return Sema::IncompatiblePointer; 7403 return ConvTy; 7404 } 7405 7406 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7407 /// block pointer types are compatible or whether a block and normal pointer 7408 /// are compatible. It is more restrict than comparing two function pointer 7409 // types. 7410 static Sema::AssignConvertType 7411 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7412 QualType RHSType) { 7413 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7414 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7415 7416 QualType lhptee, rhptee; 7417 7418 // get the "pointed to" type (ignoring qualifiers at the top level) 7419 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7420 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7421 7422 // In C++, the types have to match exactly. 7423 if (S.getLangOpts().CPlusPlus) 7424 return Sema::IncompatibleBlockPointer; 7425 7426 Sema::AssignConvertType ConvTy = Sema::Compatible; 7427 7428 // For blocks we enforce that qualifiers are identical. 7429 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7430 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7431 if (S.getLangOpts().OpenCL) { 7432 LQuals.removeAddressSpace(); 7433 RQuals.removeAddressSpace(); 7434 } 7435 if (LQuals != RQuals) 7436 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7437 7438 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7439 // assignment. 7440 // The current behavior is similar to C++ lambdas. A block might be 7441 // assigned to a variable iff its return type and parameters are compatible 7442 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7443 // an assignment. Presumably it should behave in way that a function pointer 7444 // assignment does in C, so for each parameter and return type: 7445 // * CVR and address space of LHS should be a superset of CVR and address 7446 // space of RHS. 7447 // * unqualified types should be compatible. 7448 if (S.getLangOpts().OpenCL) { 7449 if (!S.Context.typesAreBlockPointerCompatible( 7450 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7451 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7452 return Sema::IncompatibleBlockPointer; 7453 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7454 return Sema::IncompatibleBlockPointer; 7455 7456 return ConvTy; 7457 } 7458 7459 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7460 /// for assignment compatibility. 7461 static Sema::AssignConvertType 7462 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7463 QualType RHSType) { 7464 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7465 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7466 7467 if (LHSType->isObjCBuiltinType()) { 7468 // Class is not compatible with ObjC object pointers. 7469 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7470 !RHSType->isObjCQualifiedClassType()) 7471 return Sema::IncompatiblePointer; 7472 return Sema::Compatible; 7473 } 7474 if (RHSType->isObjCBuiltinType()) { 7475 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7476 !LHSType->isObjCQualifiedClassType()) 7477 return Sema::IncompatiblePointer; 7478 return Sema::Compatible; 7479 } 7480 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7481 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7482 7483 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7484 // make an exception for id<P> 7485 !LHSType->isObjCQualifiedIdType()) 7486 return Sema::CompatiblePointerDiscardsQualifiers; 7487 7488 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7489 return Sema::Compatible; 7490 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7491 return Sema::IncompatibleObjCQualifiedId; 7492 return Sema::IncompatiblePointer; 7493 } 7494 7495 Sema::AssignConvertType 7496 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7497 QualType LHSType, QualType RHSType) { 7498 // Fake up an opaque expression. We don't actually care about what 7499 // cast operations are required, so if CheckAssignmentConstraints 7500 // adds casts to this they'll be wasted, but fortunately that doesn't 7501 // usually happen on valid code. 7502 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7503 ExprResult RHSPtr = &RHSExpr; 7504 CastKind K = CK_Invalid; 7505 7506 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7507 } 7508 7509 /// This helper function returns true if QT is a vector type that has element 7510 /// type ElementType. 7511 static bool isVector(QualType QT, QualType ElementType) { 7512 if (const VectorType *VT = QT->getAs<VectorType>()) 7513 return VT->getElementType() == ElementType; 7514 return false; 7515 } 7516 7517 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7518 /// has code to accommodate several GCC extensions when type checking 7519 /// pointers. Here are some objectionable examples that GCC considers warnings: 7520 /// 7521 /// int a, *pint; 7522 /// short *pshort; 7523 /// struct foo *pfoo; 7524 /// 7525 /// pint = pshort; // warning: assignment from incompatible pointer type 7526 /// a = pint; // warning: assignment makes integer from pointer without a cast 7527 /// pint = a; // warning: assignment makes pointer from integer without a cast 7528 /// pint = pfoo; // warning: assignment from incompatible pointer type 7529 /// 7530 /// As a result, the code for dealing with pointers is more complex than the 7531 /// C99 spec dictates. 7532 /// 7533 /// Sets 'Kind' for any result kind except Incompatible. 7534 Sema::AssignConvertType 7535 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7536 CastKind &Kind, bool ConvertRHS) { 7537 QualType RHSType = RHS.get()->getType(); 7538 QualType OrigLHSType = LHSType; 7539 7540 // Get canonical types. We're not formatting these types, just comparing 7541 // them. 7542 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7543 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7544 7545 // Common case: no conversion required. 7546 if (LHSType == RHSType) { 7547 Kind = CK_NoOp; 7548 return Compatible; 7549 } 7550 7551 // If we have an atomic type, try a non-atomic assignment, then just add an 7552 // atomic qualification step. 7553 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7554 Sema::AssignConvertType result = 7555 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7556 if (result != Compatible) 7557 return result; 7558 if (Kind != CK_NoOp && ConvertRHS) 7559 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7560 Kind = CK_NonAtomicToAtomic; 7561 return Compatible; 7562 } 7563 7564 // If the left-hand side is a reference type, then we are in a 7565 // (rare!) case where we've allowed the use of references in C, 7566 // e.g., as a parameter type in a built-in function. In this case, 7567 // just make sure that the type referenced is compatible with the 7568 // right-hand side type. The caller is responsible for adjusting 7569 // LHSType so that the resulting expression does not have reference 7570 // type. 7571 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7572 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7573 Kind = CK_LValueBitCast; 7574 return Compatible; 7575 } 7576 return Incompatible; 7577 } 7578 7579 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7580 // to the same ExtVector type. 7581 if (LHSType->isExtVectorType()) { 7582 if (RHSType->isExtVectorType()) 7583 return Incompatible; 7584 if (RHSType->isArithmeticType()) { 7585 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7586 if (ConvertRHS) 7587 RHS = prepareVectorSplat(LHSType, RHS.get()); 7588 Kind = CK_VectorSplat; 7589 return Compatible; 7590 } 7591 } 7592 7593 // Conversions to or from vector type. 7594 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7595 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7596 // Allow assignments of an AltiVec vector type to an equivalent GCC 7597 // vector type and vice versa 7598 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7599 Kind = CK_BitCast; 7600 return Compatible; 7601 } 7602 7603 // If we are allowing lax vector conversions, and LHS and RHS are both 7604 // vectors, the total size only needs to be the same. This is a bitcast; 7605 // no bits are changed but the result type is different. 7606 if (isLaxVectorConversion(RHSType, LHSType)) { 7607 Kind = CK_BitCast; 7608 return IncompatibleVectors; 7609 } 7610 } 7611 7612 // When the RHS comes from another lax conversion (e.g. binops between 7613 // scalars and vectors) the result is canonicalized as a vector. When the 7614 // LHS is also a vector, the lax is allowed by the condition above. Handle 7615 // the case where LHS is a scalar. 7616 if (LHSType->isScalarType()) { 7617 const VectorType *VecType = RHSType->getAs<VectorType>(); 7618 if (VecType && VecType->getNumElements() == 1 && 7619 isLaxVectorConversion(RHSType, LHSType)) { 7620 ExprResult *VecExpr = &RHS; 7621 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7622 Kind = CK_BitCast; 7623 return Compatible; 7624 } 7625 } 7626 7627 return Incompatible; 7628 } 7629 7630 // Diagnose attempts to convert between __float128 and long double where 7631 // such conversions currently can't be handled. 7632 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7633 return Incompatible; 7634 7635 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7636 // discards the imaginary part. 7637 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7638 !LHSType->getAs<ComplexType>()) 7639 return Incompatible; 7640 7641 // Arithmetic conversions. 7642 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7643 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7644 if (ConvertRHS) 7645 Kind = PrepareScalarCast(RHS, LHSType); 7646 return Compatible; 7647 } 7648 7649 // Conversions to normal pointers. 7650 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7651 // U* -> T* 7652 if (isa<PointerType>(RHSType)) { 7653 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7654 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7655 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7656 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7657 } 7658 7659 // int -> T* 7660 if (RHSType->isIntegerType()) { 7661 Kind = CK_IntegralToPointer; // FIXME: null? 7662 return IntToPointer; 7663 } 7664 7665 // C pointers are not compatible with ObjC object pointers, 7666 // with two exceptions: 7667 if (isa<ObjCObjectPointerType>(RHSType)) { 7668 // - conversions to void* 7669 if (LHSPointer->getPointeeType()->isVoidType()) { 7670 Kind = CK_BitCast; 7671 return Compatible; 7672 } 7673 7674 // - conversions from 'Class' to the redefinition type 7675 if (RHSType->isObjCClassType() && 7676 Context.hasSameType(LHSType, 7677 Context.getObjCClassRedefinitionType())) { 7678 Kind = CK_BitCast; 7679 return Compatible; 7680 } 7681 7682 Kind = CK_BitCast; 7683 return IncompatiblePointer; 7684 } 7685 7686 // U^ -> void* 7687 if (RHSType->getAs<BlockPointerType>()) { 7688 if (LHSPointer->getPointeeType()->isVoidType()) { 7689 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7690 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7691 ->getPointeeType() 7692 .getAddressSpace(); 7693 Kind = 7694 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7695 return Compatible; 7696 } 7697 } 7698 7699 return Incompatible; 7700 } 7701 7702 // Conversions to block pointers. 7703 if (isa<BlockPointerType>(LHSType)) { 7704 // U^ -> T^ 7705 if (RHSType->isBlockPointerType()) { 7706 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7707 ->getPointeeType() 7708 .getAddressSpace(); 7709 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7710 ->getPointeeType() 7711 .getAddressSpace(); 7712 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7713 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7714 } 7715 7716 // int or null -> T^ 7717 if (RHSType->isIntegerType()) { 7718 Kind = CK_IntegralToPointer; // FIXME: null 7719 return IntToBlockPointer; 7720 } 7721 7722 // id -> T^ 7723 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7724 Kind = CK_AnyPointerToBlockPointerCast; 7725 return Compatible; 7726 } 7727 7728 // void* -> T^ 7729 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7730 if (RHSPT->getPointeeType()->isVoidType()) { 7731 Kind = CK_AnyPointerToBlockPointerCast; 7732 return Compatible; 7733 } 7734 7735 return Incompatible; 7736 } 7737 7738 // Conversions to Objective-C pointers. 7739 if (isa<ObjCObjectPointerType>(LHSType)) { 7740 // A* -> B* 7741 if (RHSType->isObjCObjectPointerType()) { 7742 Kind = CK_BitCast; 7743 Sema::AssignConvertType result = 7744 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7745 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7746 result == Compatible && 7747 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7748 result = IncompatibleObjCWeakRef; 7749 return result; 7750 } 7751 7752 // int or null -> A* 7753 if (RHSType->isIntegerType()) { 7754 Kind = CK_IntegralToPointer; // FIXME: null 7755 return IntToPointer; 7756 } 7757 7758 // In general, C pointers are not compatible with ObjC object pointers, 7759 // with two exceptions: 7760 if (isa<PointerType>(RHSType)) { 7761 Kind = CK_CPointerToObjCPointerCast; 7762 7763 // - conversions from 'void*' 7764 if (RHSType->isVoidPointerType()) { 7765 return Compatible; 7766 } 7767 7768 // - conversions to 'Class' from its redefinition type 7769 if (LHSType->isObjCClassType() && 7770 Context.hasSameType(RHSType, 7771 Context.getObjCClassRedefinitionType())) { 7772 return Compatible; 7773 } 7774 7775 return IncompatiblePointer; 7776 } 7777 7778 // Only under strict condition T^ is compatible with an Objective-C pointer. 7779 if (RHSType->isBlockPointerType() && 7780 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7781 if (ConvertRHS) 7782 maybeExtendBlockObject(RHS); 7783 Kind = CK_BlockPointerToObjCPointerCast; 7784 return Compatible; 7785 } 7786 7787 return Incompatible; 7788 } 7789 7790 // Conversions from pointers that are not covered by the above. 7791 if (isa<PointerType>(RHSType)) { 7792 // T* -> _Bool 7793 if (LHSType == Context.BoolTy) { 7794 Kind = CK_PointerToBoolean; 7795 return Compatible; 7796 } 7797 7798 // T* -> int 7799 if (LHSType->isIntegerType()) { 7800 Kind = CK_PointerToIntegral; 7801 return PointerToInt; 7802 } 7803 7804 return Incompatible; 7805 } 7806 7807 // Conversions from Objective-C pointers that are not covered by the above. 7808 if (isa<ObjCObjectPointerType>(RHSType)) { 7809 // T* -> _Bool 7810 if (LHSType == Context.BoolTy) { 7811 Kind = CK_PointerToBoolean; 7812 return Compatible; 7813 } 7814 7815 // T* -> int 7816 if (LHSType->isIntegerType()) { 7817 Kind = CK_PointerToIntegral; 7818 return PointerToInt; 7819 } 7820 7821 return Incompatible; 7822 } 7823 7824 // struct A -> struct B 7825 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7826 if (Context.typesAreCompatible(LHSType, RHSType)) { 7827 Kind = CK_NoOp; 7828 return Compatible; 7829 } 7830 } 7831 7832 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7833 Kind = CK_IntToOCLSampler; 7834 return Compatible; 7835 } 7836 7837 return Incompatible; 7838 } 7839 7840 /// \brief Constructs a transparent union from an expression that is 7841 /// used to initialize the transparent union. 7842 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7843 ExprResult &EResult, QualType UnionType, 7844 FieldDecl *Field) { 7845 // Build an initializer list that designates the appropriate member 7846 // of the transparent union. 7847 Expr *E = EResult.get(); 7848 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7849 E, SourceLocation()); 7850 Initializer->setType(UnionType); 7851 Initializer->setInitializedFieldInUnion(Field); 7852 7853 // Build a compound literal constructing a value of the transparent 7854 // union type from this initializer list. 7855 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7856 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7857 VK_RValue, Initializer, false); 7858 } 7859 7860 Sema::AssignConvertType 7861 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7862 ExprResult &RHS) { 7863 QualType RHSType = RHS.get()->getType(); 7864 7865 // If the ArgType is a Union type, we want to handle a potential 7866 // transparent_union GCC extension. 7867 const RecordType *UT = ArgType->getAsUnionType(); 7868 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7869 return Incompatible; 7870 7871 // The field to initialize within the transparent union. 7872 RecordDecl *UD = UT->getDecl(); 7873 FieldDecl *InitField = nullptr; 7874 // It's compatible if the expression matches any of the fields. 7875 for (auto *it : UD->fields()) { 7876 if (it->getType()->isPointerType()) { 7877 // If the transparent union contains a pointer type, we allow: 7878 // 1) void pointer 7879 // 2) null pointer constant 7880 if (RHSType->isPointerType()) 7881 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7882 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7883 InitField = it; 7884 break; 7885 } 7886 7887 if (RHS.get()->isNullPointerConstant(Context, 7888 Expr::NPC_ValueDependentIsNull)) { 7889 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7890 CK_NullToPointer); 7891 InitField = it; 7892 break; 7893 } 7894 } 7895 7896 CastKind Kind = CK_Invalid; 7897 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7898 == Compatible) { 7899 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7900 InitField = it; 7901 break; 7902 } 7903 } 7904 7905 if (!InitField) 7906 return Incompatible; 7907 7908 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7909 return Compatible; 7910 } 7911 7912 Sema::AssignConvertType 7913 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7914 bool Diagnose, 7915 bool DiagnoseCFAudited, 7916 bool ConvertRHS) { 7917 // We need to be able to tell the caller whether we diagnosed a problem, if 7918 // they ask us to issue diagnostics. 7919 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7920 7921 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7922 // we can't avoid *all* modifications at the moment, so we need some somewhere 7923 // to put the updated value. 7924 ExprResult LocalRHS = CallerRHS; 7925 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7926 7927 if (getLangOpts().CPlusPlus) { 7928 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7929 // C++ 5.17p3: If the left operand is not of class type, the 7930 // expression is implicitly converted (C++ 4) to the 7931 // cv-unqualified type of the left operand. 7932 QualType RHSType = RHS.get()->getType(); 7933 if (Diagnose) { 7934 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7935 AA_Assigning); 7936 } else { 7937 ImplicitConversionSequence ICS = 7938 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7939 /*SuppressUserConversions=*/false, 7940 /*AllowExplicit=*/false, 7941 /*InOverloadResolution=*/false, 7942 /*CStyle=*/false, 7943 /*AllowObjCWritebackConversion=*/false); 7944 if (ICS.isFailure()) 7945 return Incompatible; 7946 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7947 ICS, AA_Assigning); 7948 } 7949 if (RHS.isInvalid()) 7950 return Incompatible; 7951 Sema::AssignConvertType result = Compatible; 7952 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7953 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7954 result = IncompatibleObjCWeakRef; 7955 return result; 7956 } 7957 7958 // FIXME: Currently, we fall through and treat C++ classes like C 7959 // structures. 7960 // FIXME: We also fall through for atomics; not sure what should 7961 // happen there, though. 7962 } else if (RHS.get()->getType() == Context.OverloadTy) { 7963 // As a set of extensions to C, we support overloading on functions. These 7964 // functions need to be resolved here. 7965 DeclAccessPair DAP; 7966 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7967 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7968 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7969 else 7970 return Incompatible; 7971 } 7972 7973 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7974 // a null pointer constant. 7975 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7976 LHSType->isBlockPointerType()) && 7977 RHS.get()->isNullPointerConstant(Context, 7978 Expr::NPC_ValueDependentIsNull)) { 7979 if (Diagnose || ConvertRHS) { 7980 CastKind Kind; 7981 CXXCastPath Path; 7982 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7983 /*IgnoreBaseAccess=*/false, Diagnose); 7984 if (ConvertRHS) 7985 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7986 } 7987 return Compatible; 7988 } 7989 7990 // This check seems unnatural, however it is necessary to ensure the proper 7991 // conversion of functions/arrays. If the conversion were done for all 7992 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7993 // expressions that suppress this implicit conversion (&, sizeof). 7994 // 7995 // Suppress this for references: C++ 8.5.3p5. 7996 if (!LHSType->isReferenceType()) { 7997 // FIXME: We potentially allocate here even if ConvertRHS is false. 7998 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7999 if (RHS.isInvalid()) 8000 return Incompatible; 8001 } 8002 8003 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8004 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8005 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8006 if (PDecl && !PDecl->hasDefinition()) { 8007 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8008 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8009 } 8010 } 8011 8012 CastKind Kind = CK_Invalid; 8013 Sema::AssignConvertType result = 8014 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8015 8016 // C99 6.5.16.1p2: The value of the right operand is converted to the 8017 // type of the assignment expression. 8018 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8019 // so that we can use references in built-in functions even in C. 8020 // The getNonReferenceType() call makes sure that the resulting expression 8021 // does not have reference type. 8022 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8023 QualType Ty = LHSType.getNonLValueExprType(Context); 8024 Expr *E = RHS.get(); 8025 8026 // Check for various Objective-C errors. If we are not reporting 8027 // diagnostics and just checking for errors, e.g., during overload 8028 // resolution, return Incompatible to indicate the failure. 8029 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8030 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8031 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8032 if (!Diagnose) 8033 return Incompatible; 8034 } 8035 if (getLangOpts().ObjC1 && 8036 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8037 E->getType(), E, Diagnose) || 8038 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8039 if (!Diagnose) 8040 return Incompatible; 8041 // Replace the expression with a corrected version and continue so we 8042 // can find further errors. 8043 RHS = E; 8044 return Compatible; 8045 } 8046 8047 if (ConvertRHS) 8048 RHS = ImpCastExprToType(E, Ty, Kind); 8049 } 8050 return result; 8051 } 8052 8053 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8054 ExprResult &RHS) { 8055 Diag(Loc, diag::err_typecheck_invalid_operands) 8056 << LHS.get()->getType() << RHS.get()->getType() 8057 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8058 return QualType(); 8059 } 8060 8061 // Diagnose cases where a scalar was implicitly converted to a vector and 8062 // diagnose the underlying types. Otherwise, diagnose the error 8063 // as invalid vector logical operands for non-C++ cases. 8064 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8065 ExprResult &RHS) { 8066 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8067 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8068 8069 bool LHSNatVec = LHSType->isVectorType(); 8070 bool RHSNatVec = RHSType->isVectorType(); 8071 8072 if (!(LHSNatVec && RHSNatVec)) { 8073 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8074 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8075 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8076 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8077 << Vector->getSourceRange(); 8078 return QualType(); 8079 } 8080 8081 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8082 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8083 << RHS.get()->getSourceRange(); 8084 8085 return QualType(); 8086 } 8087 8088 /// Try to convert a value of non-vector type to a vector type by converting 8089 /// the type to the element type of the vector and then performing a splat. 8090 /// If the language is OpenCL, we only use conversions that promote scalar 8091 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8092 /// for float->int. 8093 /// 8094 /// OpenCL V2.0 6.2.6.p2: 8095 /// An error shall occur if any scalar operand type has greater rank 8096 /// than the type of the vector element. 8097 /// 8098 /// \param scalar - if non-null, actually perform the conversions 8099 /// \return true if the operation fails (but without diagnosing the failure) 8100 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8101 QualType scalarTy, 8102 QualType vectorEltTy, 8103 QualType vectorTy, 8104 unsigned &DiagID) { 8105 // The conversion to apply to the scalar before splatting it, 8106 // if necessary. 8107 CastKind scalarCast = CK_Invalid; 8108 8109 if (vectorEltTy->isIntegralType(S.Context)) { 8110 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8111 (scalarTy->isIntegerType() && 8112 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8113 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8114 return true; 8115 } 8116 if (!scalarTy->isIntegralType(S.Context)) 8117 return true; 8118 scalarCast = CK_IntegralCast; 8119 } else if (vectorEltTy->isRealFloatingType()) { 8120 if (scalarTy->isRealFloatingType()) { 8121 if (S.getLangOpts().OpenCL && 8122 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8123 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8124 return true; 8125 } 8126 scalarCast = CK_FloatingCast; 8127 } 8128 else if (scalarTy->isIntegralType(S.Context)) 8129 scalarCast = CK_IntegralToFloating; 8130 else 8131 return true; 8132 } else { 8133 return true; 8134 } 8135 8136 // Adjust scalar if desired. 8137 if (scalar) { 8138 if (scalarCast != CK_Invalid) 8139 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8140 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8141 } 8142 return false; 8143 } 8144 8145 /// Convert vector E to a vector with the same number of elements but different 8146 /// element type. 8147 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8148 const auto *VecTy = E->getType()->getAs<VectorType>(); 8149 assert(VecTy && "Expression E must be a vector"); 8150 QualType NewVecTy = S.Context.getVectorType(ElementType, 8151 VecTy->getNumElements(), 8152 VecTy->getVectorKind()); 8153 8154 // Look through the implicit cast. Return the subexpression if its type is 8155 // NewVecTy. 8156 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8157 if (ICE->getSubExpr()->getType() == NewVecTy) 8158 return ICE->getSubExpr(); 8159 8160 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8161 return S.ImpCastExprToType(E, NewVecTy, Cast); 8162 } 8163 8164 /// Test if a (constant) integer Int can be casted to another integer type 8165 /// IntTy without losing precision. 8166 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8167 QualType OtherIntTy) { 8168 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8169 8170 // Reject cases where the value of the Int is unknown as that would 8171 // possibly cause truncation, but accept cases where the scalar can be 8172 // demoted without loss of precision. 8173 llvm::APSInt Result; 8174 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8175 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8176 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8177 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8178 8179 if (CstInt) { 8180 // If the scalar is constant and is of a higher order and has more active 8181 // bits that the vector element type, reject it. 8182 unsigned NumBits = IntSigned 8183 ? (Result.isNegative() ? Result.getMinSignedBits() 8184 : Result.getActiveBits()) 8185 : Result.getActiveBits(); 8186 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8187 return true; 8188 8189 // If the signedness of the scalar type and the vector element type 8190 // differs and the number of bits is greater than that of the vector 8191 // element reject it. 8192 return (IntSigned != OtherIntSigned && 8193 NumBits > S.Context.getIntWidth(OtherIntTy)); 8194 } 8195 8196 // Reject cases where the value of the scalar is not constant and it's 8197 // order is greater than that of the vector element type. 8198 return (Order < 0); 8199 } 8200 8201 /// Test if a (constant) integer Int can be casted to floating point type 8202 /// FloatTy without losing precision. 8203 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8204 QualType FloatTy) { 8205 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8206 8207 // Determine if the integer constant can be expressed as a floating point 8208 // number of the appropiate type. 8209 llvm::APSInt Result; 8210 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8211 uint64_t Bits = 0; 8212 if (CstInt) { 8213 // Reject constants that would be truncated if they were converted to 8214 // the floating point type. Test by simple to/from conversion. 8215 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8216 // could be avoided if there was a convertFromAPInt method 8217 // which could signal back if implicit truncation occurred. 8218 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8219 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8220 llvm::APFloat::rmTowardZero); 8221 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8222 !IntTy->hasSignedIntegerRepresentation()); 8223 bool Ignored = false; 8224 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8225 &Ignored); 8226 if (Result != ConvertBack) 8227 return true; 8228 } else { 8229 // Reject types that cannot be fully encoded into the mantissa of 8230 // the float. 8231 Bits = S.Context.getTypeSize(IntTy); 8232 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8233 S.Context.getFloatTypeSemantics(FloatTy)); 8234 if (Bits > FloatPrec) 8235 return true; 8236 } 8237 8238 return false; 8239 } 8240 8241 /// Attempt to convert and splat Scalar into a vector whose types matches 8242 /// Vector following GCC conversion rules. The rule is that implicit 8243 /// conversion can occur when Scalar can be casted to match Vector's element 8244 /// type without causing truncation of Scalar. 8245 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8246 ExprResult *Vector) { 8247 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8248 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8249 const VectorType *VT = VectorTy->getAs<VectorType>(); 8250 8251 assert(!isa<ExtVectorType>(VT) && 8252 "ExtVectorTypes should not be handled here!"); 8253 8254 QualType VectorEltTy = VT->getElementType(); 8255 8256 // Reject cases where the vector element type or the scalar element type are 8257 // not integral or floating point types. 8258 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8259 return true; 8260 8261 // The conversion to apply to the scalar before splatting it, 8262 // if necessary. 8263 CastKind ScalarCast = CK_NoOp; 8264 8265 // Accept cases where the vector elements are integers and the scalar is 8266 // an integer. 8267 // FIXME: Notionally if the scalar was a floating point value with a precise 8268 // integral representation, we could cast it to an appropriate integer 8269 // type and then perform the rest of the checks here. GCC will perform 8270 // this conversion in some cases as determined by the input language. 8271 // We should accept it on a language independent basis. 8272 if (VectorEltTy->isIntegralType(S.Context) && 8273 ScalarTy->isIntegralType(S.Context) && 8274 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8275 8276 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8277 return true; 8278 8279 ScalarCast = CK_IntegralCast; 8280 } else if (VectorEltTy->isRealFloatingType()) { 8281 if (ScalarTy->isRealFloatingType()) { 8282 8283 // Reject cases where the scalar type is not a constant and has a higher 8284 // Order than the vector element type. 8285 llvm::APFloat Result(0.0); 8286 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8287 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8288 if (!CstScalar && Order < 0) 8289 return true; 8290 8291 // If the scalar cannot be safely casted to the vector element type, 8292 // reject it. 8293 if (CstScalar) { 8294 bool Truncated = false; 8295 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8296 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8297 if (Truncated) 8298 return true; 8299 } 8300 8301 ScalarCast = CK_FloatingCast; 8302 } else if (ScalarTy->isIntegralType(S.Context)) { 8303 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8304 return true; 8305 8306 ScalarCast = CK_IntegralToFloating; 8307 } else 8308 return true; 8309 } 8310 8311 // Adjust scalar if desired. 8312 if (Scalar) { 8313 if (ScalarCast != CK_NoOp) 8314 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8315 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8316 } 8317 return false; 8318 } 8319 8320 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8321 SourceLocation Loc, bool IsCompAssign, 8322 bool AllowBothBool, 8323 bool AllowBoolConversions) { 8324 if (!IsCompAssign) { 8325 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8326 if (LHS.isInvalid()) 8327 return QualType(); 8328 } 8329 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8330 if (RHS.isInvalid()) 8331 return QualType(); 8332 8333 // For conversion purposes, we ignore any qualifiers. 8334 // For example, "const float" and "float" are equivalent. 8335 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8336 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8337 8338 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8339 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8340 assert(LHSVecType || RHSVecType); 8341 8342 // AltiVec-style "vector bool op vector bool" combinations are allowed 8343 // for some operators but not others. 8344 if (!AllowBothBool && 8345 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8346 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8347 return InvalidOperands(Loc, LHS, RHS); 8348 8349 // If the vector types are identical, return. 8350 if (Context.hasSameType(LHSType, RHSType)) 8351 return LHSType; 8352 8353 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8354 if (LHSVecType && RHSVecType && 8355 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8356 if (isa<ExtVectorType>(LHSVecType)) { 8357 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8358 return LHSType; 8359 } 8360 8361 if (!IsCompAssign) 8362 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8363 return RHSType; 8364 } 8365 8366 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8367 // can be mixed, with the result being the non-bool type. The non-bool 8368 // operand must have integer element type. 8369 if (AllowBoolConversions && LHSVecType && RHSVecType && 8370 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8371 (Context.getTypeSize(LHSVecType->getElementType()) == 8372 Context.getTypeSize(RHSVecType->getElementType()))) { 8373 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8374 LHSVecType->getElementType()->isIntegerType() && 8375 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8376 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8377 return LHSType; 8378 } 8379 if (!IsCompAssign && 8380 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8381 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8382 RHSVecType->getElementType()->isIntegerType()) { 8383 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8384 return RHSType; 8385 } 8386 } 8387 8388 // If there's a vector type and a scalar, try to convert the scalar to 8389 // the vector element type and splat. 8390 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8391 if (!RHSVecType) { 8392 if (isa<ExtVectorType>(LHSVecType)) { 8393 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8394 LHSVecType->getElementType(), LHSType, 8395 DiagID)) 8396 return LHSType; 8397 } else { 8398 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8399 return LHSType; 8400 } 8401 } 8402 if (!LHSVecType) { 8403 if (isa<ExtVectorType>(RHSVecType)) { 8404 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8405 LHSType, RHSVecType->getElementType(), 8406 RHSType, DiagID)) 8407 return RHSType; 8408 } else { 8409 if (LHS.get()->getValueKind() == VK_LValue || 8410 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8411 return RHSType; 8412 } 8413 } 8414 8415 // FIXME: The code below also handles conversion between vectors and 8416 // non-scalars, we should break this down into fine grained specific checks 8417 // and emit proper diagnostics. 8418 QualType VecType = LHSVecType ? LHSType : RHSType; 8419 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8420 QualType OtherType = LHSVecType ? RHSType : LHSType; 8421 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8422 if (isLaxVectorConversion(OtherType, VecType)) { 8423 // If we're allowing lax vector conversions, only the total (data) size 8424 // needs to be the same. For non compound assignment, if one of the types is 8425 // scalar, the result is always the vector type. 8426 if (!IsCompAssign) { 8427 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8428 return VecType; 8429 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8430 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8431 // type. Note that this is already done by non-compound assignments in 8432 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8433 // <1 x T> -> T. The result is also a vector type. 8434 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8435 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8436 ExprResult *RHSExpr = &RHS; 8437 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8438 return VecType; 8439 } 8440 } 8441 8442 // Okay, the expression is invalid. 8443 8444 // If there's a non-vector, non-real operand, diagnose that. 8445 if ((!RHSVecType && !RHSType->isRealType()) || 8446 (!LHSVecType && !LHSType->isRealType())) { 8447 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8448 << LHSType << RHSType 8449 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8450 return QualType(); 8451 } 8452 8453 // OpenCL V1.1 6.2.6.p1: 8454 // If the operands are of more than one vector type, then an error shall 8455 // occur. Implicit conversions between vector types are not permitted, per 8456 // section 6.2.1. 8457 if (getLangOpts().OpenCL && 8458 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8459 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8460 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8461 << RHSType; 8462 return QualType(); 8463 } 8464 8465 8466 // If there is a vector type that is not a ExtVector and a scalar, we reach 8467 // this point if scalar could not be converted to the vector's element type 8468 // without truncation. 8469 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8470 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8471 QualType Scalar = LHSVecType ? RHSType : LHSType; 8472 QualType Vector = LHSVecType ? LHSType : RHSType; 8473 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8474 Diag(Loc, 8475 diag::err_typecheck_vector_not_convertable_implict_truncation) 8476 << ScalarOrVector << Scalar << Vector; 8477 8478 return QualType(); 8479 } 8480 8481 // Otherwise, use the generic diagnostic. 8482 Diag(Loc, DiagID) 8483 << LHSType << RHSType 8484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8485 return QualType(); 8486 } 8487 8488 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8489 // expression. These are mainly cases where the null pointer is used as an 8490 // integer instead of a pointer. 8491 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8492 SourceLocation Loc, bool IsCompare) { 8493 // The canonical way to check for a GNU null is with isNullPointerConstant, 8494 // but we use a bit of a hack here for speed; this is a relatively 8495 // hot path, and isNullPointerConstant is slow. 8496 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8497 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8498 8499 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8500 8501 // Avoid analyzing cases where the result will either be invalid (and 8502 // diagnosed as such) or entirely valid and not something to warn about. 8503 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8504 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8505 return; 8506 8507 // Comparison operations would not make sense with a null pointer no matter 8508 // what the other expression is. 8509 if (!IsCompare) { 8510 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8511 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8512 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8513 return; 8514 } 8515 8516 // The rest of the operations only make sense with a null pointer 8517 // if the other expression is a pointer. 8518 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8519 NonNullType->canDecayToPointerType()) 8520 return; 8521 8522 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8523 << LHSNull /* LHS is NULL */ << NonNullType 8524 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8525 } 8526 8527 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8528 ExprResult &RHS, 8529 SourceLocation Loc, bool IsDiv) { 8530 // Check for division/remainder by zero. 8531 llvm::APSInt RHSValue; 8532 if (!RHS.get()->isValueDependent() && 8533 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8534 S.DiagRuntimeBehavior(Loc, RHS.get(), 8535 S.PDiag(diag::warn_remainder_division_by_zero) 8536 << IsDiv << RHS.get()->getSourceRange()); 8537 } 8538 8539 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8540 SourceLocation Loc, 8541 bool IsCompAssign, bool IsDiv) { 8542 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8543 8544 if (LHS.get()->getType()->isVectorType() || 8545 RHS.get()->getType()->isVectorType()) 8546 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8547 /*AllowBothBool*/getLangOpts().AltiVec, 8548 /*AllowBoolConversions*/false); 8549 8550 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8551 if (LHS.isInvalid() || RHS.isInvalid()) 8552 return QualType(); 8553 8554 8555 if (compType.isNull() || !compType->isArithmeticType()) 8556 return InvalidOperands(Loc, LHS, RHS); 8557 if (IsDiv) 8558 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8559 return compType; 8560 } 8561 8562 QualType Sema::CheckRemainderOperands( 8563 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8564 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8565 8566 if (LHS.get()->getType()->isVectorType() || 8567 RHS.get()->getType()->isVectorType()) { 8568 if (LHS.get()->getType()->hasIntegerRepresentation() && 8569 RHS.get()->getType()->hasIntegerRepresentation()) 8570 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8571 /*AllowBothBool*/getLangOpts().AltiVec, 8572 /*AllowBoolConversions*/false); 8573 return InvalidOperands(Loc, LHS, RHS); 8574 } 8575 8576 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8577 if (LHS.isInvalid() || RHS.isInvalid()) 8578 return QualType(); 8579 8580 if (compType.isNull() || !compType->isIntegerType()) 8581 return InvalidOperands(Loc, LHS, RHS); 8582 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8583 return compType; 8584 } 8585 8586 /// \brief Diagnose invalid arithmetic on two void pointers. 8587 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8588 Expr *LHSExpr, Expr *RHSExpr) { 8589 S.Diag(Loc, S.getLangOpts().CPlusPlus 8590 ? diag::err_typecheck_pointer_arith_void_type 8591 : diag::ext_gnu_void_ptr) 8592 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8593 << RHSExpr->getSourceRange(); 8594 } 8595 8596 /// \brief Diagnose invalid arithmetic on a void pointer. 8597 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8598 Expr *Pointer) { 8599 S.Diag(Loc, S.getLangOpts().CPlusPlus 8600 ? diag::err_typecheck_pointer_arith_void_type 8601 : diag::ext_gnu_void_ptr) 8602 << 0 /* one pointer */ << Pointer->getSourceRange(); 8603 } 8604 8605 /// \brief Diagnose invalid arithmetic on a null pointer. 8606 /// 8607 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8608 /// idiom, which we recognize as a GNU extension. 8609 /// 8610 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8611 Expr *Pointer, bool IsGNUIdiom) { 8612 if (IsGNUIdiom) 8613 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8614 << Pointer->getSourceRange(); 8615 else 8616 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8617 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8618 } 8619 8620 /// \brief Diagnose invalid arithmetic on two function pointers. 8621 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8622 Expr *LHS, Expr *RHS) { 8623 assert(LHS->getType()->isAnyPointerType()); 8624 assert(RHS->getType()->isAnyPointerType()); 8625 S.Diag(Loc, S.getLangOpts().CPlusPlus 8626 ? diag::err_typecheck_pointer_arith_function_type 8627 : diag::ext_gnu_ptr_func_arith) 8628 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8629 // We only show the second type if it differs from the first. 8630 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8631 RHS->getType()) 8632 << RHS->getType()->getPointeeType() 8633 << LHS->getSourceRange() << RHS->getSourceRange(); 8634 } 8635 8636 /// \brief Diagnose invalid arithmetic on a function pointer. 8637 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8638 Expr *Pointer) { 8639 assert(Pointer->getType()->isAnyPointerType()); 8640 S.Diag(Loc, S.getLangOpts().CPlusPlus 8641 ? diag::err_typecheck_pointer_arith_function_type 8642 : diag::ext_gnu_ptr_func_arith) 8643 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8644 << 0 /* one pointer, so only one type */ 8645 << Pointer->getSourceRange(); 8646 } 8647 8648 /// \brief Emit error if Operand is incomplete pointer type 8649 /// 8650 /// \returns True if pointer has incomplete type 8651 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8652 Expr *Operand) { 8653 QualType ResType = Operand->getType(); 8654 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8655 ResType = ResAtomicType->getValueType(); 8656 8657 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8658 QualType PointeeTy = ResType->getPointeeType(); 8659 return S.RequireCompleteType(Loc, PointeeTy, 8660 diag::err_typecheck_arithmetic_incomplete_type, 8661 PointeeTy, Operand->getSourceRange()); 8662 } 8663 8664 /// \brief Check the validity of an arithmetic pointer operand. 8665 /// 8666 /// If the operand has pointer type, this code will check for pointer types 8667 /// which are invalid in arithmetic operations. These will be diagnosed 8668 /// appropriately, including whether or not the use is supported as an 8669 /// extension. 8670 /// 8671 /// \returns True when the operand is valid to use (even if as an extension). 8672 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8673 Expr *Operand) { 8674 QualType ResType = Operand->getType(); 8675 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8676 ResType = ResAtomicType->getValueType(); 8677 8678 if (!ResType->isAnyPointerType()) return true; 8679 8680 QualType PointeeTy = ResType->getPointeeType(); 8681 if (PointeeTy->isVoidType()) { 8682 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8683 return !S.getLangOpts().CPlusPlus; 8684 } 8685 if (PointeeTy->isFunctionType()) { 8686 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8687 return !S.getLangOpts().CPlusPlus; 8688 } 8689 8690 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8691 8692 return true; 8693 } 8694 8695 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8696 /// operands. 8697 /// 8698 /// This routine will diagnose any invalid arithmetic on pointer operands much 8699 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8700 /// for emitting a single diagnostic even for operations where both LHS and RHS 8701 /// are (potentially problematic) pointers. 8702 /// 8703 /// \returns True when the operand is valid to use (even if as an extension). 8704 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8705 Expr *LHSExpr, Expr *RHSExpr) { 8706 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8707 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8708 if (!isLHSPointer && !isRHSPointer) return true; 8709 8710 QualType LHSPointeeTy, RHSPointeeTy; 8711 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8712 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8713 8714 // if both are pointers check if operation is valid wrt address spaces 8715 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8716 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8717 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8718 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8719 S.Diag(Loc, 8720 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8721 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8722 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8723 return false; 8724 } 8725 } 8726 8727 // Check for arithmetic on pointers to incomplete types. 8728 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8729 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8730 if (isLHSVoidPtr || isRHSVoidPtr) { 8731 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8732 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8733 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8734 8735 return !S.getLangOpts().CPlusPlus; 8736 } 8737 8738 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8739 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8740 if (isLHSFuncPtr || isRHSFuncPtr) { 8741 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8742 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8743 RHSExpr); 8744 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8745 8746 return !S.getLangOpts().CPlusPlus; 8747 } 8748 8749 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8750 return false; 8751 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8752 return false; 8753 8754 return true; 8755 } 8756 8757 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8758 /// literal. 8759 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8760 Expr *LHSExpr, Expr *RHSExpr) { 8761 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8762 Expr* IndexExpr = RHSExpr; 8763 if (!StrExpr) { 8764 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8765 IndexExpr = LHSExpr; 8766 } 8767 8768 bool IsStringPlusInt = StrExpr && 8769 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8770 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8771 return; 8772 8773 llvm::APSInt index; 8774 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8775 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8776 if (index.isNonNegative() && 8777 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8778 index.isUnsigned())) 8779 return; 8780 } 8781 8782 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8783 Self.Diag(OpLoc, diag::warn_string_plus_int) 8784 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8785 8786 // Only print a fixit for "str" + int, not for int + "str". 8787 if (IndexExpr == RHSExpr) { 8788 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8789 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8790 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8791 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8792 << FixItHint::CreateInsertion(EndLoc, "]"); 8793 } else 8794 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8795 } 8796 8797 /// \brief Emit a warning when adding a char literal to a string. 8798 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8799 Expr *LHSExpr, Expr *RHSExpr) { 8800 const Expr *StringRefExpr = LHSExpr; 8801 const CharacterLiteral *CharExpr = 8802 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8803 8804 if (!CharExpr) { 8805 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8806 StringRefExpr = RHSExpr; 8807 } 8808 8809 if (!CharExpr || !StringRefExpr) 8810 return; 8811 8812 const QualType StringType = StringRefExpr->getType(); 8813 8814 // Return if not a PointerType. 8815 if (!StringType->isAnyPointerType()) 8816 return; 8817 8818 // Return if not a CharacterType. 8819 if (!StringType->getPointeeType()->isAnyCharacterType()) 8820 return; 8821 8822 ASTContext &Ctx = Self.getASTContext(); 8823 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8824 8825 const QualType CharType = CharExpr->getType(); 8826 if (!CharType->isAnyCharacterType() && 8827 CharType->isIntegerType() && 8828 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8829 Self.Diag(OpLoc, diag::warn_string_plus_char) 8830 << DiagRange << Ctx.CharTy; 8831 } else { 8832 Self.Diag(OpLoc, diag::warn_string_plus_char) 8833 << DiagRange << CharExpr->getType(); 8834 } 8835 8836 // Only print a fixit for str + char, not for char + str. 8837 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8838 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8839 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8840 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8841 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8842 << FixItHint::CreateInsertion(EndLoc, "]"); 8843 } else { 8844 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8845 } 8846 } 8847 8848 /// \brief Emit error when two pointers are incompatible. 8849 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8850 Expr *LHSExpr, Expr *RHSExpr) { 8851 assert(LHSExpr->getType()->isAnyPointerType()); 8852 assert(RHSExpr->getType()->isAnyPointerType()); 8853 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8854 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8855 << RHSExpr->getSourceRange(); 8856 } 8857 8858 // C99 6.5.6 8859 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8860 SourceLocation Loc, BinaryOperatorKind Opc, 8861 QualType* CompLHSTy) { 8862 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8863 8864 if (LHS.get()->getType()->isVectorType() || 8865 RHS.get()->getType()->isVectorType()) { 8866 QualType compType = CheckVectorOperands( 8867 LHS, RHS, Loc, CompLHSTy, 8868 /*AllowBothBool*/getLangOpts().AltiVec, 8869 /*AllowBoolConversions*/getLangOpts().ZVector); 8870 if (CompLHSTy) *CompLHSTy = compType; 8871 return compType; 8872 } 8873 8874 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8875 if (LHS.isInvalid() || RHS.isInvalid()) 8876 return QualType(); 8877 8878 // Diagnose "string literal" '+' int and string '+' "char literal". 8879 if (Opc == BO_Add) { 8880 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8881 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8882 } 8883 8884 // handle the common case first (both operands are arithmetic). 8885 if (!compType.isNull() && compType->isArithmeticType()) { 8886 if (CompLHSTy) *CompLHSTy = compType; 8887 return compType; 8888 } 8889 8890 // Type-checking. Ultimately the pointer's going to be in PExp; 8891 // note that we bias towards the LHS being the pointer. 8892 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8893 8894 bool isObjCPointer; 8895 if (PExp->getType()->isPointerType()) { 8896 isObjCPointer = false; 8897 } else if (PExp->getType()->isObjCObjectPointerType()) { 8898 isObjCPointer = true; 8899 } else { 8900 std::swap(PExp, IExp); 8901 if (PExp->getType()->isPointerType()) { 8902 isObjCPointer = false; 8903 } else if (PExp->getType()->isObjCObjectPointerType()) { 8904 isObjCPointer = true; 8905 } else { 8906 return InvalidOperands(Loc, LHS, RHS); 8907 } 8908 } 8909 assert(PExp->getType()->isAnyPointerType()); 8910 8911 if (!IExp->getType()->isIntegerType()) 8912 return InvalidOperands(Loc, LHS, RHS); 8913 8914 // Adding to a null pointer results in undefined behavior. 8915 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8916 Context, Expr::NPC_ValueDependentIsNotNull)) { 8917 // In C++ adding zero to a null pointer is defined. 8918 llvm::APSInt KnownVal; 8919 if (!getLangOpts().CPlusPlus || 8920 (!IExp->isValueDependent() && 8921 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8922 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8923 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8924 Context, BO_Add, PExp, IExp); 8925 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8926 } 8927 } 8928 8929 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8930 return QualType(); 8931 8932 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8933 return QualType(); 8934 8935 // Check array bounds for pointer arithemtic 8936 CheckArrayAccess(PExp, IExp); 8937 8938 if (CompLHSTy) { 8939 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8940 if (LHSTy.isNull()) { 8941 LHSTy = LHS.get()->getType(); 8942 if (LHSTy->isPromotableIntegerType()) 8943 LHSTy = Context.getPromotedIntegerType(LHSTy); 8944 } 8945 *CompLHSTy = LHSTy; 8946 } 8947 8948 return PExp->getType(); 8949 } 8950 8951 // C99 6.5.6 8952 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8953 SourceLocation Loc, 8954 QualType* CompLHSTy) { 8955 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8956 8957 if (LHS.get()->getType()->isVectorType() || 8958 RHS.get()->getType()->isVectorType()) { 8959 QualType compType = CheckVectorOperands( 8960 LHS, RHS, Loc, CompLHSTy, 8961 /*AllowBothBool*/getLangOpts().AltiVec, 8962 /*AllowBoolConversions*/getLangOpts().ZVector); 8963 if (CompLHSTy) *CompLHSTy = compType; 8964 return compType; 8965 } 8966 8967 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8968 if (LHS.isInvalid() || RHS.isInvalid()) 8969 return QualType(); 8970 8971 // Enforce type constraints: C99 6.5.6p3. 8972 8973 // Handle the common case first (both operands are arithmetic). 8974 if (!compType.isNull() && compType->isArithmeticType()) { 8975 if (CompLHSTy) *CompLHSTy = compType; 8976 return compType; 8977 } 8978 8979 // Either ptr - int or ptr - ptr. 8980 if (LHS.get()->getType()->isAnyPointerType()) { 8981 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8982 8983 // Diagnose bad cases where we step over interface counts. 8984 if (LHS.get()->getType()->isObjCObjectPointerType() && 8985 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8986 return QualType(); 8987 8988 // The result type of a pointer-int computation is the pointer type. 8989 if (RHS.get()->getType()->isIntegerType()) { 8990 // Subtracting from a null pointer should produce a warning. 8991 // The last argument to the diagnose call says this doesn't match the 8992 // GNU int-to-pointer idiom. 8993 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 8994 Expr::NPC_ValueDependentIsNotNull)) { 8995 // In C++ adding zero to a null pointer is defined. 8996 llvm::APSInt KnownVal; 8997 if (!getLangOpts().CPlusPlus || 8998 (!RHS.get()->isValueDependent() && 8999 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9000 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9001 } 9002 } 9003 9004 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9005 return QualType(); 9006 9007 // Check array bounds for pointer arithemtic 9008 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9009 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9010 9011 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9012 return LHS.get()->getType(); 9013 } 9014 9015 // Handle pointer-pointer subtractions. 9016 if (const PointerType *RHSPTy 9017 = RHS.get()->getType()->getAs<PointerType>()) { 9018 QualType rpointee = RHSPTy->getPointeeType(); 9019 9020 if (getLangOpts().CPlusPlus) { 9021 // Pointee types must be the same: C++ [expr.add] 9022 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9023 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9024 } 9025 } else { 9026 // Pointee types must be compatible C99 6.5.6p3 9027 if (!Context.typesAreCompatible( 9028 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9029 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9030 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9031 return QualType(); 9032 } 9033 } 9034 9035 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9036 LHS.get(), RHS.get())) 9037 return QualType(); 9038 9039 // FIXME: Add warnings for nullptr - ptr. 9040 9041 // The pointee type may have zero size. As an extension, a structure or 9042 // union may have zero size or an array may have zero length. In this 9043 // case subtraction does not make sense. 9044 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9045 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9046 if (ElementSize.isZero()) { 9047 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9048 << rpointee.getUnqualifiedType() 9049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9050 } 9051 } 9052 9053 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9054 return Context.getPointerDiffType(); 9055 } 9056 } 9057 9058 return InvalidOperands(Loc, LHS, RHS); 9059 } 9060 9061 static bool isScopedEnumerationType(QualType T) { 9062 if (const EnumType *ET = T->getAs<EnumType>()) 9063 return ET->getDecl()->isScoped(); 9064 return false; 9065 } 9066 9067 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9068 SourceLocation Loc, BinaryOperatorKind Opc, 9069 QualType LHSType) { 9070 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9071 // so skip remaining warnings as we don't want to modify values within Sema. 9072 if (S.getLangOpts().OpenCL) 9073 return; 9074 9075 llvm::APSInt Right; 9076 // Check right/shifter operand 9077 if (RHS.get()->isValueDependent() || 9078 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9079 return; 9080 9081 if (Right.isNegative()) { 9082 S.DiagRuntimeBehavior(Loc, RHS.get(), 9083 S.PDiag(diag::warn_shift_negative) 9084 << RHS.get()->getSourceRange()); 9085 return; 9086 } 9087 llvm::APInt LeftBits(Right.getBitWidth(), 9088 S.Context.getTypeSize(LHS.get()->getType())); 9089 if (Right.uge(LeftBits)) { 9090 S.DiagRuntimeBehavior(Loc, RHS.get(), 9091 S.PDiag(diag::warn_shift_gt_typewidth) 9092 << RHS.get()->getSourceRange()); 9093 return; 9094 } 9095 if (Opc != BO_Shl) 9096 return; 9097 9098 // When left shifting an ICE which is signed, we can check for overflow which 9099 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9100 // integers have defined behavior modulo one more than the maximum value 9101 // representable in the result type, so never warn for those. 9102 llvm::APSInt Left; 9103 if (LHS.get()->isValueDependent() || 9104 LHSType->hasUnsignedIntegerRepresentation() || 9105 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9106 return; 9107 9108 // If LHS does not have a signed type and non-negative value 9109 // then, the behavior is undefined. Warn about it. 9110 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9111 S.DiagRuntimeBehavior(Loc, LHS.get(), 9112 S.PDiag(diag::warn_shift_lhs_negative) 9113 << LHS.get()->getSourceRange()); 9114 return; 9115 } 9116 9117 llvm::APInt ResultBits = 9118 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9119 if (LeftBits.uge(ResultBits)) 9120 return; 9121 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9122 Result = Result.shl(Right); 9123 9124 // Print the bit representation of the signed integer as an unsigned 9125 // hexadecimal number. 9126 SmallString<40> HexResult; 9127 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9128 9129 // If we are only missing a sign bit, this is less likely to result in actual 9130 // bugs -- if the result is cast back to an unsigned type, it will have the 9131 // expected value. Thus we place this behind a different warning that can be 9132 // turned off separately if needed. 9133 if (LeftBits == ResultBits - 1) { 9134 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9135 << HexResult << LHSType 9136 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9137 return; 9138 } 9139 9140 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9141 << HexResult.str() << Result.getMinSignedBits() << LHSType 9142 << Left.getBitWidth() << LHS.get()->getSourceRange() 9143 << RHS.get()->getSourceRange(); 9144 } 9145 9146 /// \brief Return the resulting type when a vector is shifted 9147 /// by a scalar or vector shift amount. 9148 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9149 SourceLocation Loc, bool IsCompAssign) { 9150 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9151 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9152 !LHS.get()->getType()->isVectorType()) { 9153 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9154 << RHS.get()->getType() << LHS.get()->getType() 9155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9156 return QualType(); 9157 } 9158 9159 if (!IsCompAssign) { 9160 LHS = S.UsualUnaryConversions(LHS.get()); 9161 if (LHS.isInvalid()) return QualType(); 9162 } 9163 9164 RHS = S.UsualUnaryConversions(RHS.get()); 9165 if (RHS.isInvalid()) return QualType(); 9166 9167 QualType LHSType = LHS.get()->getType(); 9168 // Note that LHS might be a scalar because the routine calls not only in 9169 // OpenCL case. 9170 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9171 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9172 9173 // Note that RHS might not be a vector. 9174 QualType RHSType = RHS.get()->getType(); 9175 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9176 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9177 9178 // The operands need to be integers. 9179 if (!LHSEleType->isIntegerType()) { 9180 S.Diag(Loc, diag::err_typecheck_expect_int) 9181 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9182 return QualType(); 9183 } 9184 9185 if (!RHSEleType->isIntegerType()) { 9186 S.Diag(Loc, diag::err_typecheck_expect_int) 9187 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9188 return QualType(); 9189 } 9190 9191 if (!LHSVecTy) { 9192 assert(RHSVecTy); 9193 if (IsCompAssign) 9194 return RHSType; 9195 if (LHSEleType != RHSEleType) { 9196 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9197 LHSEleType = RHSEleType; 9198 } 9199 QualType VecTy = 9200 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9201 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9202 LHSType = VecTy; 9203 } else if (RHSVecTy) { 9204 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9205 // are applied component-wise. So if RHS is a vector, then ensure 9206 // that the number of elements is the same as LHS... 9207 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9208 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9209 << LHS.get()->getType() << RHS.get()->getType() 9210 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9211 return QualType(); 9212 } 9213 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9214 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9215 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9216 if (LHSBT != RHSBT && 9217 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9218 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9219 << LHS.get()->getType() << RHS.get()->getType() 9220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9221 } 9222 } 9223 } else { 9224 // ...else expand RHS to match the number of elements in LHS. 9225 QualType VecTy = 9226 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9227 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9228 } 9229 9230 return LHSType; 9231 } 9232 9233 // C99 6.5.7 9234 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9235 SourceLocation Loc, BinaryOperatorKind Opc, 9236 bool IsCompAssign) { 9237 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9238 9239 // Vector shifts promote their scalar inputs to vector type. 9240 if (LHS.get()->getType()->isVectorType() || 9241 RHS.get()->getType()->isVectorType()) { 9242 if (LangOpts.ZVector) { 9243 // The shift operators for the z vector extensions work basically 9244 // like general shifts, except that neither the LHS nor the RHS is 9245 // allowed to be a "vector bool". 9246 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9247 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9248 return InvalidOperands(Loc, LHS, RHS); 9249 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9250 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9251 return InvalidOperands(Loc, LHS, RHS); 9252 } 9253 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9254 } 9255 9256 // Shifts don't perform usual arithmetic conversions, they just do integer 9257 // promotions on each operand. C99 6.5.7p3 9258 9259 // For the LHS, do usual unary conversions, but then reset them away 9260 // if this is a compound assignment. 9261 ExprResult OldLHS = LHS; 9262 LHS = UsualUnaryConversions(LHS.get()); 9263 if (LHS.isInvalid()) 9264 return QualType(); 9265 QualType LHSType = LHS.get()->getType(); 9266 if (IsCompAssign) LHS = OldLHS; 9267 9268 // The RHS is simpler. 9269 RHS = UsualUnaryConversions(RHS.get()); 9270 if (RHS.isInvalid()) 9271 return QualType(); 9272 QualType RHSType = RHS.get()->getType(); 9273 9274 // C99 6.5.7p2: Each of the operands shall have integer type. 9275 if (!LHSType->hasIntegerRepresentation() || 9276 !RHSType->hasIntegerRepresentation()) 9277 return InvalidOperands(Loc, LHS, RHS); 9278 9279 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9280 // hasIntegerRepresentation() above instead of this. 9281 if (isScopedEnumerationType(LHSType) || 9282 isScopedEnumerationType(RHSType)) { 9283 return InvalidOperands(Loc, LHS, RHS); 9284 } 9285 // Sanity-check shift operands 9286 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9287 9288 // "The type of the result is that of the promoted left operand." 9289 return LHSType; 9290 } 9291 9292 static bool IsWithinTemplateSpecialization(Decl *D) { 9293 if (DeclContext *DC = D->getDeclContext()) { 9294 if (isa<ClassTemplateSpecializationDecl>(DC)) 9295 return true; 9296 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9297 return FD->isFunctionTemplateSpecialization(); 9298 } 9299 return false; 9300 } 9301 9302 /// If two different enums are compared, raise a warning. 9303 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9304 Expr *RHS) { 9305 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9306 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9307 9308 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9309 if (!LHSEnumType) 9310 return; 9311 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9312 if (!RHSEnumType) 9313 return; 9314 9315 // Ignore anonymous enums. 9316 if (!LHSEnumType->getDecl()->getIdentifier() && 9317 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9318 return; 9319 if (!RHSEnumType->getDecl()->getIdentifier() && 9320 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9321 return; 9322 9323 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9324 return; 9325 9326 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9327 << LHSStrippedType << RHSStrippedType 9328 << LHS->getSourceRange() << RHS->getSourceRange(); 9329 } 9330 9331 /// \brief Diagnose bad pointer comparisons. 9332 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9333 ExprResult &LHS, ExprResult &RHS, 9334 bool IsError) { 9335 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9336 : diag::ext_typecheck_comparison_of_distinct_pointers) 9337 << LHS.get()->getType() << RHS.get()->getType() 9338 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9339 } 9340 9341 /// \brief Returns false if the pointers are converted to a composite type, 9342 /// true otherwise. 9343 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9344 ExprResult &LHS, ExprResult &RHS) { 9345 // C++ [expr.rel]p2: 9346 // [...] Pointer conversions (4.10) and qualification 9347 // conversions (4.4) are performed on pointer operands (or on 9348 // a pointer operand and a null pointer constant) to bring 9349 // them to their composite pointer type. [...] 9350 // 9351 // C++ [expr.eq]p1 uses the same notion for (in)equality 9352 // comparisons of pointers. 9353 9354 QualType LHSType = LHS.get()->getType(); 9355 QualType RHSType = RHS.get()->getType(); 9356 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9357 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9358 9359 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9360 if (T.isNull()) { 9361 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9362 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9363 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9364 else 9365 S.InvalidOperands(Loc, LHS, RHS); 9366 return true; 9367 } 9368 9369 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9370 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9371 return false; 9372 } 9373 9374 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9375 ExprResult &LHS, 9376 ExprResult &RHS, 9377 bool IsError) { 9378 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9379 : diag::ext_typecheck_comparison_of_fptr_to_void) 9380 << LHS.get()->getType() << RHS.get()->getType() 9381 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9382 } 9383 9384 static bool isObjCObjectLiteral(ExprResult &E) { 9385 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9386 case Stmt::ObjCArrayLiteralClass: 9387 case Stmt::ObjCDictionaryLiteralClass: 9388 case Stmt::ObjCStringLiteralClass: 9389 case Stmt::ObjCBoxedExprClass: 9390 return true; 9391 default: 9392 // Note that ObjCBoolLiteral is NOT an object literal! 9393 return false; 9394 } 9395 } 9396 9397 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9398 const ObjCObjectPointerType *Type = 9399 LHS->getType()->getAs<ObjCObjectPointerType>(); 9400 9401 // If this is not actually an Objective-C object, bail out. 9402 if (!Type) 9403 return false; 9404 9405 // Get the LHS object's interface type. 9406 QualType InterfaceType = Type->getPointeeType(); 9407 9408 // If the RHS isn't an Objective-C object, bail out. 9409 if (!RHS->getType()->isObjCObjectPointerType()) 9410 return false; 9411 9412 // Try to find the -isEqual: method. 9413 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9414 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9415 InterfaceType, 9416 /*instance=*/true); 9417 if (!Method) { 9418 if (Type->isObjCIdType()) { 9419 // For 'id', just check the global pool. 9420 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9421 /*receiverId=*/true); 9422 } else { 9423 // Check protocols. 9424 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9425 /*instance=*/true); 9426 } 9427 } 9428 9429 if (!Method) 9430 return false; 9431 9432 QualType T = Method->parameters()[0]->getType(); 9433 if (!T->isObjCObjectPointerType()) 9434 return false; 9435 9436 QualType R = Method->getReturnType(); 9437 if (!R->isScalarType()) 9438 return false; 9439 9440 return true; 9441 } 9442 9443 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9444 FromE = FromE->IgnoreParenImpCasts(); 9445 switch (FromE->getStmtClass()) { 9446 default: 9447 break; 9448 case Stmt::ObjCStringLiteralClass: 9449 // "string literal" 9450 return LK_String; 9451 case Stmt::ObjCArrayLiteralClass: 9452 // "array literal" 9453 return LK_Array; 9454 case Stmt::ObjCDictionaryLiteralClass: 9455 // "dictionary literal" 9456 return LK_Dictionary; 9457 case Stmt::BlockExprClass: 9458 return LK_Block; 9459 case Stmt::ObjCBoxedExprClass: { 9460 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9461 switch (Inner->getStmtClass()) { 9462 case Stmt::IntegerLiteralClass: 9463 case Stmt::FloatingLiteralClass: 9464 case Stmt::CharacterLiteralClass: 9465 case Stmt::ObjCBoolLiteralExprClass: 9466 case Stmt::CXXBoolLiteralExprClass: 9467 // "numeric literal" 9468 return LK_Numeric; 9469 case Stmt::ImplicitCastExprClass: { 9470 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9471 // Boolean literals can be represented by implicit casts. 9472 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9473 return LK_Numeric; 9474 break; 9475 } 9476 default: 9477 break; 9478 } 9479 return LK_Boxed; 9480 } 9481 } 9482 return LK_None; 9483 } 9484 9485 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9486 ExprResult &LHS, ExprResult &RHS, 9487 BinaryOperator::Opcode Opc){ 9488 Expr *Literal; 9489 Expr *Other; 9490 if (isObjCObjectLiteral(LHS)) { 9491 Literal = LHS.get(); 9492 Other = RHS.get(); 9493 } else { 9494 Literal = RHS.get(); 9495 Other = LHS.get(); 9496 } 9497 9498 // Don't warn on comparisons against nil. 9499 Other = Other->IgnoreParenCasts(); 9500 if (Other->isNullPointerConstant(S.getASTContext(), 9501 Expr::NPC_ValueDependentIsNotNull)) 9502 return; 9503 9504 // This should be kept in sync with warn_objc_literal_comparison. 9505 // LK_String should always be after the other literals, since it has its own 9506 // warning flag. 9507 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9508 assert(LiteralKind != Sema::LK_Block); 9509 if (LiteralKind == Sema::LK_None) { 9510 llvm_unreachable("Unknown Objective-C object literal kind"); 9511 } 9512 9513 if (LiteralKind == Sema::LK_String) 9514 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9515 << Literal->getSourceRange(); 9516 else 9517 S.Diag(Loc, diag::warn_objc_literal_comparison) 9518 << LiteralKind << Literal->getSourceRange(); 9519 9520 if (BinaryOperator::isEqualityOp(Opc) && 9521 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9522 SourceLocation Start = LHS.get()->getLocStart(); 9523 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9524 CharSourceRange OpRange = 9525 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9526 9527 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9528 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9529 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9530 << FixItHint::CreateInsertion(End, "]"); 9531 } 9532 } 9533 9534 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9535 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9536 ExprResult &RHS, SourceLocation Loc, 9537 BinaryOperatorKind Opc) { 9538 // Check that left hand side is !something. 9539 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9540 if (!UO || UO->getOpcode() != UO_LNot) return; 9541 9542 // Only check if the right hand side is non-bool arithmetic type. 9543 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9544 9545 // Make sure that the something in !something is not bool. 9546 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9547 if (SubExpr->isKnownToHaveBooleanValue()) return; 9548 9549 // Emit warning. 9550 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9551 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9552 << Loc << IsBitwiseOp; 9553 9554 // First note suggest !(x < y) 9555 SourceLocation FirstOpen = SubExpr->getLocStart(); 9556 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9557 FirstClose = S.getLocForEndOfToken(FirstClose); 9558 if (FirstClose.isInvalid()) 9559 FirstOpen = SourceLocation(); 9560 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9561 << IsBitwiseOp 9562 << FixItHint::CreateInsertion(FirstOpen, "(") 9563 << FixItHint::CreateInsertion(FirstClose, ")"); 9564 9565 // Second note suggests (!x) < y 9566 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9567 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9568 SecondClose = S.getLocForEndOfToken(SecondClose); 9569 if (SecondClose.isInvalid()) 9570 SecondOpen = SourceLocation(); 9571 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9572 << FixItHint::CreateInsertion(SecondOpen, "(") 9573 << FixItHint::CreateInsertion(SecondClose, ")"); 9574 } 9575 9576 // Get the decl for a simple expression: a reference to a variable, 9577 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9578 static ValueDecl *getCompareDecl(Expr *E) { 9579 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9580 return DR->getDecl(); 9581 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9582 if (Ivar->isFreeIvar()) 9583 return Ivar->getDecl(); 9584 } 9585 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9586 if (Mem->isImplicitAccess()) 9587 return Mem->getMemberDecl(); 9588 } 9589 return nullptr; 9590 } 9591 9592 // C99 6.5.8, C++ [expr.rel] 9593 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9594 SourceLocation Loc, BinaryOperatorKind Opc, 9595 bool IsRelational) { 9596 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9597 9598 // Handle vector comparisons separately. 9599 if (LHS.get()->getType()->isVectorType() || 9600 RHS.get()->getType()->isVectorType()) 9601 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9602 9603 QualType LHSType = LHS.get()->getType(); 9604 QualType RHSType = RHS.get()->getType(); 9605 9606 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9607 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9608 9609 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9610 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9611 9612 if (!LHSType->hasFloatingRepresentation() && 9613 !(LHSType->isBlockPointerType() && IsRelational) && 9614 !LHS.get()->getLocStart().isMacroID() && 9615 !RHS.get()->getLocStart().isMacroID() && 9616 !inTemplateInstantiation()) { 9617 // For non-floating point types, check for self-comparisons of the form 9618 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9619 // often indicate logic errors in the program. 9620 // 9621 // NOTE: Don't warn about comparison expressions resulting from macro 9622 // expansion. Also don't warn about comparisons which are only self 9623 // comparisons within a template specialization. The warnings should catch 9624 // obvious cases in the definition of the template anyways. The idea is to 9625 // warn when the typed comparison operator will always evaluate to the same 9626 // result. 9627 ValueDecl *DL = getCompareDecl(LHSStripped); 9628 ValueDecl *DR = getCompareDecl(RHSStripped); 9629 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9630 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9631 << 0 // self- 9632 << (Opc == BO_EQ 9633 || Opc == BO_LE 9634 || Opc == BO_GE)); 9635 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9636 !DL->getType()->isReferenceType() && 9637 !DR->getType()->isReferenceType()) { 9638 // what is it always going to eval to? 9639 char always_evals_to; 9640 switch(Opc) { 9641 case BO_EQ: // e.g. array1 == array2 9642 always_evals_to = 0; // false 9643 break; 9644 case BO_NE: // e.g. array1 != array2 9645 always_evals_to = 1; // true 9646 break; 9647 default: 9648 // best we can say is 'a constant' 9649 always_evals_to = 2; // e.g. array1 <= array2 9650 break; 9651 } 9652 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9653 << 1 // array 9654 << always_evals_to); 9655 } 9656 9657 if (isa<CastExpr>(LHSStripped)) 9658 LHSStripped = LHSStripped->IgnoreParenCasts(); 9659 if (isa<CastExpr>(RHSStripped)) 9660 RHSStripped = RHSStripped->IgnoreParenCasts(); 9661 9662 // Warn about comparisons against a string constant (unless the other 9663 // operand is null), the user probably wants strcmp. 9664 Expr *literalString = nullptr; 9665 Expr *literalStringStripped = nullptr; 9666 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9667 !RHSStripped->isNullPointerConstant(Context, 9668 Expr::NPC_ValueDependentIsNull)) { 9669 literalString = LHS.get(); 9670 literalStringStripped = LHSStripped; 9671 } else if ((isa<StringLiteral>(RHSStripped) || 9672 isa<ObjCEncodeExpr>(RHSStripped)) && 9673 !LHSStripped->isNullPointerConstant(Context, 9674 Expr::NPC_ValueDependentIsNull)) { 9675 literalString = RHS.get(); 9676 literalStringStripped = RHSStripped; 9677 } 9678 9679 if (literalString) { 9680 DiagRuntimeBehavior(Loc, nullptr, 9681 PDiag(diag::warn_stringcompare) 9682 << isa<ObjCEncodeExpr>(literalStringStripped) 9683 << literalString->getSourceRange()); 9684 } 9685 } 9686 9687 // C99 6.5.8p3 / C99 6.5.9p4 9688 UsualArithmeticConversions(LHS, RHS); 9689 if (LHS.isInvalid() || RHS.isInvalid()) 9690 return QualType(); 9691 9692 LHSType = LHS.get()->getType(); 9693 RHSType = RHS.get()->getType(); 9694 9695 // The result of comparisons is 'bool' in C++, 'int' in C. 9696 QualType ResultTy = Context.getLogicalOperationType(); 9697 9698 if (IsRelational) { 9699 if (LHSType->isRealType() && RHSType->isRealType()) 9700 return ResultTy; 9701 } else { 9702 // Check for comparisons of floating point operands using != and ==. 9703 if (LHSType->hasFloatingRepresentation()) 9704 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9705 9706 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9707 return ResultTy; 9708 } 9709 9710 const Expr::NullPointerConstantKind LHSNullKind = 9711 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9712 const Expr::NullPointerConstantKind RHSNullKind = 9713 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9714 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9715 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9716 9717 if (!IsRelational && LHSIsNull != RHSIsNull) { 9718 bool IsEquality = Opc == BO_EQ; 9719 if (RHSIsNull) 9720 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9721 RHS.get()->getSourceRange()); 9722 else 9723 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9724 LHS.get()->getSourceRange()); 9725 } 9726 9727 if ((LHSType->isIntegerType() && !LHSIsNull) || 9728 (RHSType->isIntegerType() && !RHSIsNull)) { 9729 // Skip normal pointer conversion checks in this case; we have better 9730 // diagnostics for this below. 9731 } else if (getLangOpts().CPlusPlus) { 9732 // Equality comparison of a function pointer to a void pointer is invalid, 9733 // but we allow it as an extension. 9734 // FIXME: If we really want to allow this, should it be part of composite 9735 // pointer type computation so it works in conditionals too? 9736 if (!IsRelational && 9737 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9738 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9739 // This is a gcc extension compatibility comparison. 9740 // In a SFINAE context, we treat this as a hard error to maintain 9741 // conformance with the C++ standard. 9742 diagnoseFunctionPointerToVoidComparison( 9743 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9744 9745 if (isSFINAEContext()) 9746 return QualType(); 9747 9748 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9749 return ResultTy; 9750 } 9751 9752 // C++ [expr.eq]p2: 9753 // If at least one operand is a pointer [...] bring them to their 9754 // composite pointer type. 9755 // C++ [expr.rel]p2: 9756 // If both operands are pointers, [...] bring them to their composite 9757 // pointer type. 9758 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9759 (IsRelational ? 2 : 1) && 9760 (!LangOpts.ObjCAutoRefCount || 9761 !(LHSType->isObjCObjectPointerType() || 9762 RHSType->isObjCObjectPointerType()))) { 9763 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9764 return QualType(); 9765 else 9766 return ResultTy; 9767 } 9768 } else if (LHSType->isPointerType() && 9769 RHSType->isPointerType()) { // C99 6.5.8p2 9770 // All of the following pointer-related warnings are GCC extensions, except 9771 // when handling null pointer constants. 9772 QualType LCanPointeeTy = 9773 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9774 QualType RCanPointeeTy = 9775 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9776 9777 // C99 6.5.9p2 and C99 6.5.8p2 9778 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9779 RCanPointeeTy.getUnqualifiedType())) { 9780 // Valid unless a relational comparison of function pointers 9781 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9782 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9783 << LHSType << RHSType << LHS.get()->getSourceRange() 9784 << RHS.get()->getSourceRange(); 9785 } 9786 } else if (!IsRelational && 9787 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9788 // Valid unless comparison between non-null pointer and function pointer 9789 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9790 && !LHSIsNull && !RHSIsNull) 9791 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9792 /*isError*/false); 9793 } else { 9794 // Invalid 9795 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9796 } 9797 if (LCanPointeeTy != RCanPointeeTy) { 9798 // Treat NULL constant as a special case in OpenCL. 9799 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9800 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9801 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9802 Diag(Loc, 9803 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9804 << LHSType << RHSType << 0 /* comparison */ 9805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9806 } 9807 } 9808 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9809 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9810 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9811 : CK_BitCast; 9812 if (LHSIsNull && !RHSIsNull) 9813 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9814 else 9815 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9816 } 9817 return ResultTy; 9818 } 9819 9820 if (getLangOpts().CPlusPlus) { 9821 // C++ [expr.eq]p4: 9822 // Two operands of type std::nullptr_t or one operand of type 9823 // std::nullptr_t and the other a null pointer constant compare equal. 9824 if (!IsRelational && LHSIsNull && RHSIsNull) { 9825 if (LHSType->isNullPtrType()) { 9826 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9827 return ResultTy; 9828 } 9829 if (RHSType->isNullPtrType()) { 9830 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9831 return ResultTy; 9832 } 9833 } 9834 9835 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9836 // These aren't covered by the composite pointer type rules. 9837 if (!IsRelational && RHSType->isNullPtrType() && 9838 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9839 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9840 return ResultTy; 9841 } 9842 if (!IsRelational && LHSType->isNullPtrType() && 9843 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9844 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9845 return ResultTy; 9846 } 9847 9848 if (IsRelational && 9849 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9850 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9851 // HACK: Relational comparison of nullptr_t against a pointer type is 9852 // invalid per DR583, but we allow it within std::less<> and friends, 9853 // since otherwise common uses of it break. 9854 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9855 // friends to have std::nullptr_t overload candidates. 9856 DeclContext *DC = CurContext; 9857 if (isa<FunctionDecl>(DC)) 9858 DC = DC->getParent(); 9859 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9860 if (CTSD->isInStdNamespace() && 9861 llvm::StringSwitch<bool>(CTSD->getName()) 9862 .Cases("less", "less_equal", "greater", "greater_equal", true) 9863 .Default(false)) { 9864 if (RHSType->isNullPtrType()) 9865 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9866 else 9867 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9868 return ResultTy; 9869 } 9870 } 9871 } 9872 9873 // C++ [expr.eq]p2: 9874 // If at least one operand is a pointer to member, [...] bring them to 9875 // their composite pointer type. 9876 if (!IsRelational && 9877 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9878 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9879 return QualType(); 9880 else 9881 return ResultTy; 9882 } 9883 9884 // Handle scoped enumeration types specifically, since they don't promote 9885 // to integers. 9886 if (LHS.get()->getType()->isEnumeralType() && 9887 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9888 RHS.get()->getType())) 9889 return ResultTy; 9890 } 9891 9892 // Handle block pointer types. 9893 if (!IsRelational && LHSType->isBlockPointerType() && 9894 RHSType->isBlockPointerType()) { 9895 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9896 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9897 9898 if (!LHSIsNull && !RHSIsNull && 9899 !Context.typesAreCompatible(lpointee, rpointee)) { 9900 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9901 << LHSType << RHSType << LHS.get()->getSourceRange() 9902 << RHS.get()->getSourceRange(); 9903 } 9904 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9905 return ResultTy; 9906 } 9907 9908 // Allow block pointers to be compared with null pointer constants. 9909 if (!IsRelational 9910 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9911 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9912 if (!LHSIsNull && !RHSIsNull) { 9913 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9914 ->getPointeeType()->isVoidType()) 9915 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9916 ->getPointeeType()->isVoidType()))) 9917 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9918 << LHSType << RHSType << LHS.get()->getSourceRange() 9919 << RHS.get()->getSourceRange(); 9920 } 9921 if (LHSIsNull && !RHSIsNull) 9922 LHS = ImpCastExprToType(LHS.get(), RHSType, 9923 RHSType->isPointerType() ? CK_BitCast 9924 : CK_AnyPointerToBlockPointerCast); 9925 else 9926 RHS = ImpCastExprToType(RHS.get(), LHSType, 9927 LHSType->isPointerType() ? CK_BitCast 9928 : CK_AnyPointerToBlockPointerCast); 9929 return ResultTy; 9930 } 9931 9932 if (LHSType->isObjCObjectPointerType() || 9933 RHSType->isObjCObjectPointerType()) { 9934 const PointerType *LPT = LHSType->getAs<PointerType>(); 9935 const PointerType *RPT = RHSType->getAs<PointerType>(); 9936 if (LPT || RPT) { 9937 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9938 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9939 9940 if (!LPtrToVoid && !RPtrToVoid && 9941 !Context.typesAreCompatible(LHSType, RHSType)) { 9942 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9943 /*isError*/false); 9944 } 9945 if (LHSIsNull && !RHSIsNull) { 9946 Expr *E = LHS.get(); 9947 if (getLangOpts().ObjCAutoRefCount) 9948 CheckObjCConversion(SourceRange(), RHSType, E, 9949 CCK_ImplicitConversion); 9950 LHS = ImpCastExprToType(E, RHSType, 9951 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9952 } 9953 else { 9954 Expr *E = RHS.get(); 9955 if (getLangOpts().ObjCAutoRefCount) 9956 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9957 /*Diagnose=*/true, 9958 /*DiagnoseCFAudited=*/false, Opc); 9959 RHS = ImpCastExprToType(E, LHSType, 9960 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9961 } 9962 return ResultTy; 9963 } 9964 if (LHSType->isObjCObjectPointerType() && 9965 RHSType->isObjCObjectPointerType()) { 9966 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9967 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9968 /*isError*/false); 9969 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9970 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9971 9972 if (LHSIsNull && !RHSIsNull) 9973 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9974 else 9975 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9976 return ResultTy; 9977 } 9978 } 9979 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9980 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9981 unsigned DiagID = 0; 9982 bool isError = false; 9983 if (LangOpts.DebuggerSupport) { 9984 // Under a debugger, allow the comparison of pointers to integers, 9985 // since users tend to want to compare addresses. 9986 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9987 (RHSIsNull && RHSType->isIntegerType())) { 9988 if (IsRelational) { 9989 isError = getLangOpts().CPlusPlus; 9990 DiagID = 9991 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9992 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9993 } 9994 } else if (getLangOpts().CPlusPlus) { 9995 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9996 isError = true; 9997 } else if (IsRelational) 9998 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9999 else 10000 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10001 10002 if (DiagID) { 10003 Diag(Loc, DiagID) 10004 << LHSType << RHSType << LHS.get()->getSourceRange() 10005 << RHS.get()->getSourceRange(); 10006 if (isError) 10007 return QualType(); 10008 } 10009 10010 if (LHSType->isIntegerType()) 10011 LHS = ImpCastExprToType(LHS.get(), RHSType, 10012 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10013 else 10014 RHS = ImpCastExprToType(RHS.get(), LHSType, 10015 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10016 return ResultTy; 10017 } 10018 10019 // Handle block pointers. 10020 if (!IsRelational && RHSIsNull 10021 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10022 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10023 return ResultTy; 10024 } 10025 if (!IsRelational && LHSIsNull 10026 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10027 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10028 return ResultTy; 10029 } 10030 10031 if (getLangOpts().OpenCLVersion >= 200) { 10032 if (LHSIsNull && RHSType->isQueueT()) { 10033 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10034 return ResultTy; 10035 } 10036 10037 if (LHSType->isQueueT() && RHSIsNull) { 10038 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10039 return ResultTy; 10040 } 10041 } 10042 10043 return InvalidOperands(Loc, LHS, RHS); 10044 } 10045 10046 // Return a signed ext_vector_type that is of identical size and number of 10047 // elements. For floating point vectors, return an integer type of identical 10048 // size and number of elements. In the non ext_vector_type case, search from 10049 // the largest type to the smallest type to avoid cases where long long == long, 10050 // where long gets picked over long long. 10051 QualType Sema::GetSignedVectorType(QualType V) { 10052 const VectorType *VTy = V->getAs<VectorType>(); 10053 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10054 10055 if (isa<ExtVectorType>(VTy)) { 10056 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10057 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10058 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10059 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10060 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10061 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10062 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10063 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10064 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10065 "Unhandled vector element size in vector compare"); 10066 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10067 } 10068 10069 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10070 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10071 VectorType::GenericVector); 10072 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10073 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10074 VectorType::GenericVector); 10075 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10076 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10077 VectorType::GenericVector); 10078 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10079 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10080 VectorType::GenericVector); 10081 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10082 "Unhandled vector element size in vector compare"); 10083 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10084 VectorType::GenericVector); 10085 } 10086 10087 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10088 /// operates on extended vector types. Instead of producing an IntTy result, 10089 /// like a scalar comparison, a vector comparison produces a vector of integer 10090 /// types. 10091 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10092 SourceLocation Loc, 10093 bool IsRelational) { 10094 // Check to make sure we're operating on vectors of the same type and width, 10095 // Allowing one side to be a scalar of element type. 10096 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10097 /*AllowBothBool*/true, 10098 /*AllowBoolConversions*/getLangOpts().ZVector); 10099 if (vType.isNull()) 10100 return vType; 10101 10102 QualType LHSType = LHS.get()->getType(); 10103 10104 // If AltiVec, the comparison results in a numeric type, i.e. 10105 // bool for C++, int for C 10106 if (getLangOpts().AltiVec && 10107 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10108 return Context.getLogicalOperationType(); 10109 10110 // For non-floating point types, check for self-comparisons of the form 10111 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10112 // often indicate logic errors in the program. 10113 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10114 if (DeclRefExpr* DRL 10115 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10116 if (DeclRefExpr* DRR 10117 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10118 if (DRL->getDecl() == DRR->getDecl()) 10119 DiagRuntimeBehavior(Loc, nullptr, 10120 PDiag(diag::warn_comparison_always) 10121 << 0 // self- 10122 << 2 // "a constant" 10123 ); 10124 } 10125 10126 // Check for comparisons of floating point operands using != and ==. 10127 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10128 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10129 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10130 } 10131 10132 // Return a signed type for the vector. 10133 return GetSignedVectorType(vType); 10134 } 10135 10136 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10137 SourceLocation Loc) { 10138 // Ensure that either both operands are of the same vector type, or 10139 // one operand is of a vector type and the other is of its element type. 10140 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10141 /*AllowBothBool*/true, 10142 /*AllowBoolConversions*/false); 10143 if (vType.isNull()) 10144 return InvalidOperands(Loc, LHS, RHS); 10145 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10146 vType->hasFloatingRepresentation()) 10147 return InvalidOperands(Loc, LHS, RHS); 10148 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10149 // usage of the logical operators && and || with vectors in C. This 10150 // check could be notionally dropped. 10151 if (!getLangOpts().CPlusPlus && 10152 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10153 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10154 10155 return GetSignedVectorType(LHS.get()->getType()); 10156 } 10157 10158 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10159 SourceLocation Loc, 10160 BinaryOperatorKind Opc) { 10161 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10162 10163 bool IsCompAssign = 10164 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10165 10166 if (LHS.get()->getType()->isVectorType() || 10167 RHS.get()->getType()->isVectorType()) { 10168 if (LHS.get()->getType()->hasIntegerRepresentation() && 10169 RHS.get()->getType()->hasIntegerRepresentation()) 10170 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10171 /*AllowBothBool*/true, 10172 /*AllowBoolConversions*/getLangOpts().ZVector); 10173 return InvalidOperands(Loc, LHS, RHS); 10174 } 10175 10176 if (Opc == BO_And) 10177 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10178 10179 ExprResult LHSResult = LHS, RHSResult = RHS; 10180 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10181 IsCompAssign); 10182 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10183 return QualType(); 10184 LHS = LHSResult.get(); 10185 RHS = RHSResult.get(); 10186 10187 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10188 return compType; 10189 return InvalidOperands(Loc, LHS, RHS); 10190 } 10191 10192 // C99 6.5.[13,14] 10193 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10194 SourceLocation Loc, 10195 BinaryOperatorKind Opc) { 10196 // Check vector operands differently. 10197 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10198 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10199 10200 // Diagnose cases where the user write a logical and/or but probably meant a 10201 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10202 // is a constant. 10203 if (LHS.get()->getType()->isIntegerType() && 10204 !LHS.get()->getType()->isBooleanType() && 10205 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10206 // Don't warn in macros or template instantiations. 10207 !Loc.isMacroID() && !inTemplateInstantiation()) { 10208 // If the RHS can be constant folded, and if it constant folds to something 10209 // that isn't 0 or 1 (which indicate a potential logical operation that 10210 // happened to fold to true/false) then warn. 10211 // Parens on the RHS are ignored. 10212 llvm::APSInt Result; 10213 if (RHS.get()->EvaluateAsInt(Result, Context)) 10214 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10215 !RHS.get()->getExprLoc().isMacroID()) || 10216 (Result != 0 && Result != 1)) { 10217 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10218 << RHS.get()->getSourceRange() 10219 << (Opc == BO_LAnd ? "&&" : "||"); 10220 // Suggest replacing the logical operator with the bitwise version 10221 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10222 << (Opc == BO_LAnd ? "&" : "|") 10223 << FixItHint::CreateReplacement(SourceRange( 10224 Loc, getLocForEndOfToken(Loc)), 10225 Opc == BO_LAnd ? "&" : "|"); 10226 if (Opc == BO_LAnd) 10227 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10228 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10229 << FixItHint::CreateRemoval( 10230 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10231 RHS.get()->getLocEnd())); 10232 } 10233 } 10234 10235 if (!Context.getLangOpts().CPlusPlus) { 10236 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10237 // not operate on the built-in scalar and vector float types. 10238 if (Context.getLangOpts().OpenCL && 10239 Context.getLangOpts().OpenCLVersion < 120) { 10240 if (LHS.get()->getType()->isFloatingType() || 10241 RHS.get()->getType()->isFloatingType()) 10242 return InvalidOperands(Loc, LHS, RHS); 10243 } 10244 10245 LHS = UsualUnaryConversions(LHS.get()); 10246 if (LHS.isInvalid()) 10247 return QualType(); 10248 10249 RHS = UsualUnaryConversions(RHS.get()); 10250 if (RHS.isInvalid()) 10251 return QualType(); 10252 10253 if (!LHS.get()->getType()->isScalarType() || 10254 !RHS.get()->getType()->isScalarType()) 10255 return InvalidOperands(Loc, LHS, RHS); 10256 10257 return Context.IntTy; 10258 } 10259 10260 // The following is safe because we only use this method for 10261 // non-overloadable operands. 10262 10263 // C++ [expr.log.and]p1 10264 // C++ [expr.log.or]p1 10265 // The operands are both contextually converted to type bool. 10266 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10267 if (LHSRes.isInvalid()) 10268 return InvalidOperands(Loc, LHS, RHS); 10269 LHS = LHSRes; 10270 10271 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10272 if (RHSRes.isInvalid()) 10273 return InvalidOperands(Loc, LHS, RHS); 10274 RHS = RHSRes; 10275 10276 // C++ [expr.log.and]p2 10277 // C++ [expr.log.or]p2 10278 // The result is a bool. 10279 return Context.BoolTy; 10280 } 10281 10282 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10283 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10284 if (!ME) return false; 10285 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10286 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10287 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10288 if (!Base) return false; 10289 return Base->getMethodDecl() != nullptr; 10290 } 10291 10292 /// Is the given expression (which must be 'const') a reference to a 10293 /// variable which was originally non-const, but which has become 10294 /// 'const' due to being captured within a block? 10295 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10296 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10297 assert(E->isLValue() && E->getType().isConstQualified()); 10298 E = E->IgnoreParens(); 10299 10300 // Must be a reference to a declaration from an enclosing scope. 10301 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10302 if (!DRE) return NCCK_None; 10303 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10304 10305 // The declaration must be a variable which is not declared 'const'. 10306 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10307 if (!var) return NCCK_None; 10308 if (var->getType().isConstQualified()) return NCCK_None; 10309 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10310 10311 // Decide whether the first capture was for a block or a lambda. 10312 DeclContext *DC = S.CurContext, *Prev = nullptr; 10313 // Decide whether the first capture was for a block or a lambda. 10314 while (DC) { 10315 // For init-capture, it is possible that the variable belongs to the 10316 // template pattern of the current context. 10317 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10318 if (var->isInitCapture() && 10319 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10320 break; 10321 if (DC == var->getDeclContext()) 10322 break; 10323 Prev = DC; 10324 DC = DC->getParent(); 10325 } 10326 // Unless we have an init-capture, we've gone one step too far. 10327 if (!var->isInitCapture()) 10328 DC = Prev; 10329 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10330 } 10331 10332 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10333 Ty = Ty.getNonReferenceType(); 10334 if (IsDereference && Ty->isPointerType()) 10335 Ty = Ty->getPointeeType(); 10336 return !Ty.isConstQualified(); 10337 } 10338 10339 // Update err_typecheck_assign_const and note_typecheck_assign_const 10340 // when this enum is changed. 10341 enum { 10342 ConstFunction, 10343 ConstVariable, 10344 ConstMember, 10345 ConstMethod, 10346 NestedConstMember, 10347 ConstUnknown, // Keep as last element 10348 }; 10349 10350 /// Emit the "read-only variable not assignable" error and print notes to give 10351 /// more information about why the variable is not assignable, such as pointing 10352 /// to the declaration of a const variable, showing that a method is const, or 10353 /// that the function is returning a const reference. 10354 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10355 SourceLocation Loc) { 10356 SourceRange ExprRange = E->getSourceRange(); 10357 10358 // Only emit one error on the first const found. All other consts will emit 10359 // a note to the error. 10360 bool DiagnosticEmitted = false; 10361 10362 // Track if the current expression is the result of a dereference, and if the 10363 // next checked expression is the result of a dereference. 10364 bool IsDereference = false; 10365 bool NextIsDereference = false; 10366 10367 // Loop to process MemberExpr chains. 10368 while (true) { 10369 IsDereference = NextIsDereference; 10370 10371 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10372 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10373 NextIsDereference = ME->isArrow(); 10374 const ValueDecl *VD = ME->getMemberDecl(); 10375 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10376 // Mutable fields can be modified even if the class is const. 10377 if (Field->isMutable()) { 10378 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10379 break; 10380 } 10381 10382 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10383 if (!DiagnosticEmitted) { 10384 S.Diag(Loc, diag::err_typecheck_assign_const) 10385 << ExprRange << ConstMember << false /*static*/ << Field 10386 << Field->getType(); 10387 DiagnosticEmitted = true; 10388 } 10389 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10390 << ConstMember << false /*static*/ << Field << Field->getType() 10391 << Field->getSourceRange(); 10392 } 10393 E = ME->getBase(); 10394 continue; 10395 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10396 if (VDecl->getType().isConstQualified()) { 10397 if (!DiagnosticEmitted) { 10398 S.Diag(Loc, diag::err_typecheck_assign_const) 10399 << ExprRange << ConstMember << true /*static*/ << VDecl 10400 << VDecl->getType(); 10401 DiagnosticEmitted = true; 10402 } 10403 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10404 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10405 << VDecl->getSourceRange(); 10406 } 10407 // Static fields do not inherit constness from parents. 10408 break; 10409 } 10410 break; 10411 } // End MemberExpr 10412 break; 10413 } 10414 10415 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10416 // Function calls 10417 const FunctionDecl *FD = CE->getDirectCallee(); 10418 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10419 if (!DiagnosticEmitted) { 10420 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10421 << ConstFunction << FD; 10422 DiagnosticEmitted = true; 10423 } 10424 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10425 diag::note_typecheck_assign_const) 10426 << ConstFunction << FD << FD->getReturnType() 10427 << FD->getReturnTypeSourceRange(); 10428 } 10429 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10430 // Point to variable declaration. 10431 if (const ValueDecl *VD = DRE->getDecl()) { 10432 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10433 if (!DiagnosticEmitted) { 10434 S.Diag(Loc, diag::err_typecheck_assign_const) 10435 << ExprRange << ConstVariable << VD << VD->getType(); 10436 DiagnosticEmitted = true; 10437 } 10438 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10439 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10440 } 10441 } 10442 } else if (isa<CXXThisExpr>(E)) { 10443 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10444 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10445 if (MD->isConst()) { 10446 if (!DiagnosticEmitted) { 10447 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10448 << ConstMethod << MD; 10449 DiagnosticEmitted = true; 10450 } 10451 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10452 << ConstMethod << MD << MD->getSourceRange(); 10453 } 10454 } 10455 } 10456 } 10457 10458 if (DiagnosticEmitted) 10459 return; 10460 10461 // Can't determine a more specific message, so display the generic error. 10462 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10463 } 10464 10465 enum OriginalExprKind { 10466 OEK_Variable, 10467 OEK_Member, 10468 OEK_LValue 10469 }; 10470 10471 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10472 const RecordType *Ty, 10473 SourceLocation Loc, SourceRange Range, 10474 OriginalExprKind OEK, 10475 bool &DiagnosticEmitted, 10476 bool IsNested = false) { 10477 // We walk the record hierarchy breadth-first to ensure that we print 10478 // diagnostics in field nesting order. 10479 // First, check every field for constness. 10480 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10481 if (Field->getType().isConstQualified()) { 10482 if (!DiagnosticEmitted) { 10483 S.Diag(Loc, diag::err_typecheck_assign_const) 10484 << Range << NestedConstMember << OEK << VD 10485 << IsNested << Field; 10486 DiagnosticEmitted = true; 10487 } 10488 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10489 << NestedConstMember << IsNested << Field 10490 << Field->getType() << Field->getSourceRange(); 10491 } 10492 } 10493 // Then, recurse. 10494 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10495 QualType FTy = Field->getType(); 10496 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10497 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10498 OEK, DiagnosticEmitted, true); 10499 } 10500 } 10501 10502 /// Emit an error for the case where a record we are trying to assign to has a 10503 /// const-qualified field somewhere in its hierarchy. 10504 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10505 SourceLocation Loc) { 10506 QualType Ty = E->getType(); 10507 assert(Ty->isRecordType() && "lvalue was not record?"); 10508 SourceRange Range = E->getSourceRange(); 10509 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10510 bool DiagEmitted = false; 10511 10512 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10513 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10514 Range, OEK_Member, DiagEmitted); 10515 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10516 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10517 Range, OEK_Variable, DiagEmitted); 10518 else 10519 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10520 Range, OEK_LValue, DiagEmitted); 10521 if (!DiagEmitted) 10522 DiagnoseConstAssignment(S, E, Loc); 10523 } 10524 10525 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10526 /// emit an error and return true. If so, return false. 10527 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10528 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10529 10530 S.CheckShadowingDeclModification(E, Loc); 10531 10532 SourceLocation OrigLoc = Loc; 10533 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10534 &Loc); 10535 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10536 IsLV = Expr::MLV_InvalidMessageExpression; 10537 if (IsLV == Expr::MLV_Valid) 10538 return false; 10539 10540 unsigned DiagID = 0; 10541 bool NeedType = false; 10542 switch (IsLV) { // C99 6.5.16p2 10543 case Expr::MLV_ConstQualified: 10544 // Use a specialized diagnostic when we're assigning to an object 10545 // from an enclosing function or block. 10546 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10547 if (NCCK == NCCK_Block) 10548 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10549 else 10550 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10551 break; 10552 } 10553 10554 // In ARC, use some specialized diagnostics for occasions where we 10555 // infer 'const'. These are always pseudo-strong variables. 10556 if (S.getLangOpts().ObjCAutoRefCount) { 10557 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10558 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10559 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10560 10561 // Use the normal diagnostic if it's pseudo-__strong but the 10562 // user actually wrote 'const'. 10563 if (var->isARCPseudoStrong() && 10564 (!var->getTypeSourceInfo() || 10565 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10566 // There are two pseudo-strong cases: 10567 // - self 10568 ObjCMethodDecl *method = S.getCurMethodDecl(); 10569 if (method && var == method->getSelfDecl()) 10570 DiagID = method->isClassMethod() 10571 ? diag::err_typecheck_arc_assign_self_class_method 10572 : diag::err_typecheck_arc_assign_self; 10573 10574 // - fast enumeration variables 10575 else 10576 DiagID = diag::err_typecheck_arr_assign_enumeration; 10577 10578 SourceRange Assign; 10579 if (Loc != OrigLoc) 10580 Assign = SourceRange(OrigLoc, OrigLoc); 10581 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10582 // We need to preserve the AST regardless, so migration tool 10583 // can do its job. 10584 return false; 10585 } 10586 } 10587 } 10588 10589 // If none of the special cases above are triggered, then this is a 10590 // simple const assignment. 10591 if (DiagID == 0) { 10592 DiagnoseConstAssignment(S, E, Loc); 10593 return true; 10594 } 10595 10596 break; 10597 case Expr::MLV_ConstAddrSpace: 10598 DiagnoseConstAssignment(S, E, Loc); 10599 return true; 10600 case Expr::MLV_ConstQualifiedField: 10601 DiagnoseRecursiveConstFields(S, E, Loc); 10602 return true; 10603 case Expr::MLV_ArrayType: 10604 case Expr::MLV_ArrayTemporary: 10605 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10606 NeedType = true; 10607 break; 10608 case Expr::MLV_NotObjectType: 10609 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10610 NeedType = true; 10611 break; 10612 case Expr::MLV_LValueCast: 10613 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10614 break; 10615 case Expr::MLV_Valid: 10616 llvm_unreachable("did not take early return for MLV_Valid"); 10617 case Expr::MLV_InvalidExpression: 10618 case Expr::MLV_MemberFunction: 10619 case Expr::MLV_ClassTemporary: 10620 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10621 break; 10622 case Expr::MLV_IncompleteType: 10623 case Expr::MLV_IncompleteVoidType: 10624 return S.RequireCompleteType(Loc, E->getType(), 10625 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10626 case Expr::MLV_DuplicateVectorComponents: 10627 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10628 break; 10629 case Expr::MLV_NoSetterProperty: 10630 llvm_unreachable("readonly properties should be processed differently"); 10631 case Expr::MLV_InvalidMessageExpression: 10632 DiagID = diag::err_readonly_message_assignment; 10633 break; 10634 case Expr::MLV_SubObjCPropertySetting: 10635 DiagID = diag::err_no_subobject_property_setting; 10636 break; 10637 } 10638 10639 SourceRange Assign; 10640 if (Loc != OrigLoc) 10641 Assign = SourceRange(OrigLoc, OrigLoc); 10642 if (NeedType) 10643 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10644 else 10645 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10646 return true; 10647 } 10648 10649 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10650 SourceLocation Loc, 10651 Sema &Sema) { 10652 // C / C++ fields 10653 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10654 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10655 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10656 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10657 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10658 } 10659 10660 // Objective-C instance variables 10661 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10662 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10663 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10664 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10665 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10666 if (RL && RR && RL->getDecl() == RR->getDecl()) 10667 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10668 } 10669 } 10670 10671 // C99 6.5.16.1 10672 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10673 SourceLocation Loc, 10674 QualType CompoundType) { 10675 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10676 10677 // Verify that LHS is a modifiable lvalue, and emit error if not. 10678 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10679 return QualType(); 10680 10681 QualType LHSType = LHSExpr->getType(); 10682 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10683 CompoundType; 10684 // OpenCL v1.2 s6.1.1.1 p2: 10685 // The half data type can only be used to declare a pointer to a buffer that 10686 // contains half values 10687 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10688 LHSType->isHalfType()) { 10689 Diag(Loc, diag::err_opencl_half_load_store) << 1 10690 << LHSType.getUnqualifiedType(); 10691 return QualType(); 10692 } 10693 10694 AssignConvertType ConvTy; 10695 if (CompoundType.isNull()) { 10696 Expr *RHSCheck = RHS.get(); 10697 10698 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10699 10700 QualType LHSTy(LHSType); 10701 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10702 if (RHS.isInvalid()) 10703 return QualType(); 10704 // Special case of NSObject attributes on c-style pointer types. 10705 if (ConvTy == IncompatiblePointer && 10706 ((Context.isObjCNSObjectType(LHSType) && 10707 RHSType->isObjCObjectPointerType()) || 10708 (Context.isObjCNSObjectType(RHSType) && 10709 LHSType->isObjCObjectPointerType()))) 10710 ConvTy = Compatible; 10711 10712 if (ConvTy == Compatible && 10713 LHSType->isObjCObjectType()) 10714 Diag(Loc, diag::err_objc_object_assignment) 10715 << LHSType; 10716 10717 // If the RHS is a unary plus or minus, check to see if they = and + are 10718 // right next to each other. If so, the user may have typo'd "x =+ 4" 10719 // instead of "x += 4". 10720 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10721 RHSCheck = ICE->getSubExpr(); 10722 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10723 if ((UO->getOpcode() == UO_Plus || 10724 UO->getOpcode() == UO_Minus) && 10725 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10726 // Only if the two operators are exactly adjacent. 10727 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10728 // And there is a space or other character before the subexpr of the 10729 // unary +/-. We don't want to warn on "x=-1". 10730 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10731 UO->getSubExpr()->getLocStart().isFileID()) { 10732 Diag(Loc, diag::warn_not_compound_assign) 10733 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10734 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10735 } 10736 } 10737 10738 if (ConvTy == Compatible) { 10739 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10740 // Warn about retain cycles where a block captures the LHS, but 10741 // not if the LHS is a simple variable into which the block is 10742 // being stored...unless that variable can be captured by reference! 10743 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10744 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10745 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10746 checkRetainCycles(LHSExpr, RHS.get()); 10747 } 10748 10749 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10750 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10751 // It is safe to assign a weak reference into a strong variable. 10752 // Although this code can still have problems: 10753 // id x = self.weakProp; 10754 // id y = self.weakProp; 10755 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10756 // paths through the function. This should be revisited if 10757 // -Wrepeated-use-of-weak is made flow-sensitive. 10758 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10759 // variable, which will be valid for the current autorelease scope. 10760 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10761 RHS.get()->getLocStart())) 10762 getCurFunction()->markSafeWeakUse(RHS.get()); 10763 10764 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10765 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10766 } 10767 } 10768 } else { 10769 // Compound assignment "x += y" 10770 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10771 } 10772 10773 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10774 RHS.get(), AA_Assigning)) 10775 return QualType(); 10776 10777 CheckForNullPointerDereference(*this, LHSExpr); 10778 10779 // C99 6.5.16p3: The type of an assignment expression is the type of the 10780 // left operand unless the left operand has qualified type, in which case 10781 // it is the unqualified version of the type of the left operand. 10782 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10783 // is converted to the type of the assignment expression (above). 10784 // C++ 5.17p1: the type of the assignment expression is that of its left 10785 // operand. 10786 return (getLangOpts().CPlusPlus 10787 ? LHSType : LHSType.getUnqualifiedType()); 10788 } 10789 10790 // Only ignore explicit casts to void. 10791 static bool IgnoreCommaOperand(const Expr *E) { 10792 E = E->IgnoreParens(); 10793 10794 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10795 if (CE->getCastKind() == CK_ToVoid) { 10796 return true; 10797 } 10798 } 10799 10800 return false; 10801 } 10802 10803 // Look for instances where it is likely the comma operator is confused with 10804 // another operator. There is a whitelist of acceptable expressions for the 10805 // left hand side of the comma operator, otherwise emit a warning. 10806 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10807 // No warnings in macros 10808 if (Loc.isMacroID()) 10809 return; 10810 10811 // Don't warn in template instantiations. 10812 if (inTemplateInstantiation()) 10813 return; 10814 10815 // Scope isn't fine-grained enough to whitelist the specific cases, so 10816 // instead, skip more than needed, then call back into here with the 10817 // CommaVisitor in SemaStmt.cpp. 10818 // The whitelisted locations are the initialization and increment portions 10819 // of a for loop. The additional checks are on the condition of 10820 // if statements, do/while loops, and for loops. 10821 const unsigned ForIncrementFlags = 10822 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10823 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10824 const unsigned ScopeFlags = getCurScope()->getFlags(); 10825 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10826 (ScopeFlags & ForInitFlags) == ForInitFlags) 10827 return; 10828 10829 // If there are multiple comma operators used together, get the RHS of the 10830 // of the comma operator as the LHS. 10831 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10832 if (BO->getOpcode() != BO_Comma) 10833 break; 10834 LHS = BO->getRHS(); 10835 } 10836 10837 // Only allow some expressions on LHS to not warn. 10838 if (IgnoreCommaOperand(LHS)) 10839 return; 10840 10841 Diag(Loc, diag::warn_comma_operator); 10842 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10843 << LHS->getSourceRange() 10844 << FixItHint::CreateInsertion(LHS->getLocStart(), 10845 LangOpts.CPlusPlus ? "static_cast<void>(" 10846 : "(void)(") 10847 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10848 ")"); 10849 } 10850 10851 // C99 6.5.17 10852 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10853 SourceLocation Loc) { 10854 LHS = S.CheckPlaceholderExpr(LHS.get()); 10855 RHS = S.CheckPlaceholderExpr(RHS.get()); 10856 if (LHS.isInvalid() || RHS.isInvalid()) 10857 return QualType(); 10858 10859 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10860 // operands, but not unary promotions. 10861 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10862 10863 // So we treat the LHS as a ignored value, and in C++ we allow the 10864 // containing site to determine what should be done with the RHS. 10865 LHS = S.IgnoredValueConversions(LHS.get()); 10866 if (LHS.isInvalid()) 10867 return QualType(); 10868 10869 S.DiagnoseUnusedExprResult(LHS.get()); 10870 10871 if (!S.getLangOpts().CPlusPlus) { 10872 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10873 if (RHS.isInvalid()) 10874 return QualType(); 10875 if (!RHS.get()->getType()->isVoidType()) 10876 S.RequireCompleteType(Loc, RHS.get()->getType(), 10877 diag::err_incomplete_type); 10878 } 10879 10880 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10881 S.DiagnoseCommaOperator(LHS.get(), Loc); 10882 10883 return RHS.get()->getType(); 10884 } 10885 10886 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10887 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10888 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10889 ExprValueKind &VK, 10890 ExprObjectKind &OK, 10891 SourceLocation OpLoc, 10892 bool IsInc, bool IsPrefix) { 10893 if (Op->isTypeDependent()) 10894 return S.Context.DependentTy; 10895 10896 QualType ResType = Op->getType(); 10897 // Atomic types can be used for increment / decrement where the non-atomic 10898 // versions can, so ignore the _Atomic() specifier for the purpose of 10899 // checking. 10900 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10901 ResType = ResAtomicType->getValueType(); 10902 10903 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10904 10905 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10906 // Decrement of bool is not allowed. 10907 if (!IsInc) { 10908 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10909 return QualType(); 10910 } 10911 // Increment of bool sets it to true, but is deprecated. 10912 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10913 : diag::warn_increment_bool) 10914 << Op->getSourceRange(); 10915 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10916 // Error on enum increments and decrements in C++ mode 10917 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10918 return QualType(); 10919 } else if (ResType->isRealType()) { 10920 // OK! 10921 } else if (ResType->isPointerType()) { 10922 // C99 6.5.2.4p2, 6.5.6p2 10923 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10924 return QualType(); 10925 } else if (ResType->isObjCObjectPointerType()) { 10926 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10927 // Otherwise, we just need a complete type. 10928 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10929 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10930 return QualType(); 10931 } else if (ResType->isAnyComplexType()) { 10932 // C99 does not support ++/-- on complex types, we allow as an extension. 10933 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10934 << ResType << Op->getSourceRange(); 10935 } else if (ResType->isPlaceholderType()) { 10936 ExprResult PR = S.CheckPlaceholderExpr(Op); 10937 if (PR.isInvalid()) return QualType(); 10938 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10939 IsInc, IsPrefix); 10940 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10941 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10942 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10943 (ResType->getAs<VectorType>()->getVectorKind() != 10944 VectorType::AltiVecBool)) { 10945 // The z vector extensions allow ++ and -- for non-bool vectors. 10946 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10947 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10948 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10949 } else { 10950 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10951 << ResType << int(IsInc) << Op->getSourceRange(); 10952 return QualType(); 10953 } 10954 // At this point, we know we have a real, complex or pointer type. 10955 // Now make sure the operand is a modifiable lvalue. 10956 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10957 return QualType(); 10958 // In C++, a prefix increment is the same type as the operand. Otherwise 10959 // (in C or with postfix), the increment is the unqualified type of the 10960 // operand. 10961 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10962 VK = VK_LValue; 10963 OK = Op->getObjectKind(); 10964 return ResType; 10965 } else { 10966 VK = VK_RValue; 10967 return ResType.getUnqualifiedType(); 10968 } 10969 } 10970 10971 10972 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10973 /// This routine allows us to typecheck complex/recursive expressions 10974 /// where the declaration is needed for type checking. We only need to 10975 /// handle cases when the expression references a function designator 10976 /// or is an lvalue. Here are some examples: 10977 /// - &(x) => x 10978 /// - &*****f => f for f a function designator. 10979 /// - &s.xx => s 10980 /// - &s.zz[1].yy -> s, if zz is an array 10981 /// - *(x + 1) -> x, if x is an array 10982 /// - &"123"[2] -> 0 10983 /// - & __real__ x -> x 10984 static ValueDecl *getPrimaryDecl(Expr *E) { 10985 switch (E->getStmtClass()) { 10986 case Stmt::DeclRefExprClass: 10987 return cast<DeclRefExpr>(E)->getDecl(); 10988 case Stmt::MemberExprClass: 10989 // If this is an arrow operator, the address is an offset from 10990 // the base's value, so the object the base refers to is 10991 // irrelevant. 10992 if (cast<MemberExpr>(E)->isArrow()) 10993 return nullptr; 10994 // Otherwise, the expression refers to a part of the base 10995 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10996 case Stmt::ArraySubscriptExprClass: { 10997 // FIXME: This code shouldn't be necessary! We should catch the implicit 10998 // promotion of register arrays earlier. 10999 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11000 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11001 if (ICE->getSubExpr()->getType()->isArrayType()) 11002 return getPrimaryDecl(ICE->getSubExpr()); 11003 } 11004 return nullptr; 11005 } 11006 case Stmt::UnaryOperatorClass: { 11007 UnaryOperator *UO = cast<UnaryOperator>(E); 11008 11009 switch(UO->getOpcode()) { 11010 case UO_Real: 11011 case UO_Imag: 11012 case UO_Extension: 11013 return getPrimaryDecl(UO->getSubExpr()); 11014 default: 11015 return nullptr; 11016 } 11017 } 11018 case Stmt::ParenExprClass: 11019 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11020 case Stmt::ImplicitCastExprClass: 11021 // If the result of an implicit cast is an l-value, we care about 11022 // the sub-expression; otherwise, the result here doesn't matter. 11023 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11024 default: 11025 return nullptr; 11026 } 11027 } 11028 11029 namespace { 11030 enum { 11031 AO_Bit_Field = 0, 11032 AO_Vector_Element = 1, 11033 AO_Property_Expansion = 2, 11034 AO_Register_Variable = 3, 11035 AO_No_Error = 4 11036 }; 11037 } 11038 /// \brief Diagnose invalid operand for address of operations. 11039 /// 11040 /// \param Type The type of operand which cannot have its address taken. 11041 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11042 Expr *E, unsigned Type) { 11043 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11044 } 11045 11046 /// CheckAddressOfOperand - The operand of & must be either a function 11047 /// designator or an lvalue designating an object. If it is an lvalue, the 11048 /// object cannot be declared with storage class register or be a bit field. 11049 /// Note: The usual conversions are *not* applied to the operand of the & 11050 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11051 /// In C++, the operand might be an overloaded function name, in which case 11052 /// we allow the '&' but retain the overloaded-function type. 11053 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11054 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11055 if (PTy->getKind() == BuiltinType::Overload) { 11056 Expr *E = OrigOp.get()->IgnoreParens(); 11057 if (!isa<OverloadExpr>(E)) { 11058 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11059 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11060 << OrigOp.get()->getSourceRange(); 11061 return QualType(); 11062 } 11063 11064 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11065 if (isa<UnresolvedMemberExpr>(Ovl)) 11066 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11067 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11068 << OrigOp.get()->getSourceRange(); 11069 return QualType(); 11070 } 11071 11072 return Context.OverloadTy; 11073 } 11074 11075 if (PTy->getKind() == BuiltinType::UnknownAny) 11076 return Context.UnknownAnyTy; 11077 11078 if (PTy->getKind() == BuiltinType::BoundMember) { 11079 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11080 << OrigOp.get()->getSourceRange(); 11081 return QualType(); 11082 } 11083 11084 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11085 if (OrigOp.isInvalid()) return QualType(); 11086 } 11087 11088 if (OrigOp.get()->isTypeDependent()) 11089 return Context.DependentTy; 11090 11091 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11092 11093 // Make sure to ignore parentheses in subsequent checks 11094 Expr *op = OrigOp.get()->IgnoreParens(); 11095 11096 // In OpenCL captures for blocks called as lambda functions 11097 // are located in the private address space. Blocks used in 11098 // enqueue_kernel can be located in a different address space 11099 // depending on a vendor implementation. Thus preventing 11100 // taking an address of the capture to avoid invalid AS casts. 11101 if (LangOpts.OpenCL) { 11102 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11103 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11104 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11105 return QualType(); 11106 } 11107 } 11108 11109 if (getLangOpts().C99) { 11110 // Implement C99-only parts of addressof rules. 11111 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11112 if (uOp->getOpcode() == UO_Deref) 11113 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11114 // (assuming the deref expression is valid). 11115 return uOp->getSubExpr()->getType(); 11116 } 11117 // Technically, there should be a check for array subscript 11118 // expressions here, but the result of one is always an lvalue anyway. 11119 } 11120 ValueDecl *dcl = getPrimaryDecl(op); 11121 11122 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11123 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11124 op->getLocStart())) 11125 return QualType(); 11126 11127 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11128 unsigned AddressOfError = AO_No_Error; 11129 11130 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11131 bool sfinae = (bool)isSFINAEContext(); 11132 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11133 : diag::ext_typecheck_addrof_temporary) 11134 << op->getType() << op->getSourceRange(); 11135 if (sfinae) 11136 return QualType(); 11137 // Materialize the temporary as an lvalue so that we can take its address. 11138 OrigOp = op = 11139 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11140 } else if (isa<ObjCSelectorExpr>(op)) { 11141 return Context.getPointerType(op->getType()); 11142 } else if (lval == Expr::LV_MemberFunction) { 11143 // If it's an instance method, make a member pointer. 11144 // The expression must have exactly the form &A::foo. 11145 11146 // If the underlying expression isn't a decl ref, give up. 11147 if (!isa<DeclRefExpr>(op)) { 11148 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11149 << OrigOp.get()->getSourceRange(); 11150 return QualType(); 11151 } 11152 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11153 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11154 11155 // The id-expression was parenthesized. 11156 if (OrigOp.get() != DRE) { 11157 Diag(OpLoc, diag::err_parens_pointer_member_function) 11158 << OrigOp.get()->getSourceRange(); 11159 11160 // The method was named without a qualifier. 11161 } else if (!DRE->getQualifier()) { 11162 if (MD->getParent()->getName().empty()) 11163 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11164 << op->getSourceRange(); 11165 else { 11166 SmallString<32> Str; 11167 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11168 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11169 << op->getSourceRange() 11170 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11171 } 11172 } 11173 11174 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11175 if (isa<CXXDestructorDecl>(MD)) 11176 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11177 11178 QualType MPTy = Context.getMemberPointerType( 11179 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11180 // Under the MS ABI, lock down the inheritance model now. 11181 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11182 (void)isCompleteType(OpLoc, MPTy); 11183 return MPTy; 11184 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11185 // C99 6.5.3.2p1 11186 // The operand must be either an l-value or a function designator 11187 if (!op->getType()->isFunctionType()) { 11188 // Use a special diagnostic for loads from property references. 11189 if (isa<PseudoObjectExpr>(op)) { 11190 AddressOfError = AO_Property_Expansion; 11191 } else { 11192 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11193 << op->getType() << op->getSourceRange(); 11194 return QualType(); 11195 } 11196 } 11197 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11198 // The operand cannot be a bit-field 11199 AddressOfError = AO_Bit_Field; 11200 } else if (op->getObjectKind() == OK_VectorComponent) { 11201 // The operand cannot be an element of a vector 11202 AddressOfError = AO_Vector_Element; 11203 } else if (dcl) { // C99 6.5.3.2p1 11204 // We have an lvalue with a decl. Make sure the decl is not declared 11205 // with the register storage-class specifier. 11206 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11207 // in C++ it is not error to take address of a register 11208 // variable (c++03 7.1.1P3) 11209 if (vd->getStorageClass() == SC_Register && 11210 !getLangOpts().CPlusPlus) { 11211 AddressOfError = AO_Register_Variable; 11212 } 11213 } else if (isa<MSPropertyDecl>(dcl)) { 11214 AddressOfError = AO_Property_Expansion; 11215 } else if (isa<FunctionTemplateDecl>(dcl)) { 11216 return Context.OverloadTy; 11217 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11218 // Okay: we can take the address of a field. 11219 // Could be a pointer to member, though, if there is an explicit 11220 // scope qualifier for the class. 11221 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11222 DeclContext *Ctx = dcl->getDeclContext(); 11223 if (Ctx && Ctx->isRecord()) { 11224 if (dcl->getType()->isReferenceType()) { 11225 Diag(OpLoc, 11226 diag::err_cannot_form_pointer_to_member_of_reference_type) 11227 << dcl->getDeclName() << dcl->getType(); 11228 return QualType(); 11229 } 11230 11231 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11232 Ctx = Ctx->getParent(); 11233 11234 QualType MPTy = Context.getMemberPointerType( 11235 op->getType(), 11236 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11237 // Under the MS ABI, lock down the inheritance model now. 11238 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11239 (void)isCompleteType(OpLoc, MPTy); 11240 return MPTy; 11241 } 11242 } 11243 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11244 !isa<BindingDecl>(dcl)) 11245 llvm_unreachable("Unknown/unexpected decl type"); 11246 } 11247 11248 if (AddressOfError != AO_No_Error) { 11249 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11250 return QualType(); 11251 } 11252 11253 if (lval == Expr::LV_IncompleteVoidType) { 11254 // Taking the address of a void variable is technically illegal, but we 11255 // allow it in cases which are otherwise valid. 11256 // Example: "extern void x; void* y = &x;". 11257 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11258 } 11259 11260 // If the operand has type "type", the result has type "pointer to type". 11261 if (op->getType()->isObjCObjectType()) 11262 return Context.getObjCObjectPointerType(op->getType()); 11263 11264 CheckAddressOfPackedMember(op); 11265 11266 return Context.getPointerType(op->getType()); 11267 } 11268 11269 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11270 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11271 if (!DRE) 11272 return; 11273 const Decl *D = DRE->getDecl(); 11274 if (!D) 11275 return; 11276 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11277 if (!Param) 11278 return; 11279 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11280 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11281 return; 11282 if (FunctionScopeInfo *FD = S.getCurFunction()) 11283 if (!FD->ModifiedNonNullParams.count(Param)) 11284 FD->ModifiedNonNullParams.insert(Param); 11285 } 11286 11287 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11288 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11289 SourceLocation OpLoc) { 11290 if (Op->isTypeDependent()) 11291 return S.Context.DependentTy; 11292 11293 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11294 if (ConvResult.isInvalid()) 11295 return QualType(); 11296 Op = ConvResult.get(); 11297 QualType OpTy = Op->getType(); 11298 QualType Result; 11299 11300 if (isa<CXXReinterpretCastExpr>(Op)) { 11301 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11302 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11303 Op->getSourceRange()); 11304 } 11305 11306 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11307 { 11308 Result = PT->getPointeeType(); 11309 } 11310 else if (const ObjCObjectPointerType *OPT = 11311 OpTy->getAs<ObjCObjectPointerType>()) 11312 Result = OPT->getPointeeType(); 11313 else { 11314 ExprResult PR = S.CheckPlaceholderExpr(Op); 11315 if (PR.isInvalid()) return QualType(); 11316 if (PR.get() != Op) 11317 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11318 } 11319 11320 if (Result.isNull()) { 11321 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11322 << OpTy << Op->getSourceRange(); 11323 return QualType(); 11324 } 11325 11326 // Note that per both C89 and C99, indirection is always legal, even if Result 11327 // is an incomplete type or void. It would be possible to warn about 11328 // dereferencing a void pointer, but it's completely well-defined, and such a 11329 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11330 // for pointers to 'void' but is fine for any other pointer type: 11331 // 11332 // C++ [expr.unary.op]p1: 11333 // [...] the expression to which [the unary * operator] is applied shall 11334 // be a pointer to an object type, or a pointer to a function type 11335 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11336 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11337 << OpTy << Op->getSourceRange(); 11338 11339 // Dereferences are usually l-values... 11340 VK = VK_LValue; 11341 11342 // ...except that certain expressions are never l-values in C. 11343 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11344 VK = VK_RValue; 11345 11346 return Result; 11347 } 11348 11349 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11350 BinaryOperatorKind Opc; 11351 switch (Kind) { 11352 default: llvm_unreachable("Unknown binop!"); 11353 case tok::periodstar: Opc = BO_PtrMemD; break; 11354 case tok::arrowstar: Opc = BO_PtrMemI; break; 11355 case tok::star: Opc = BO_Mul; break; 11356 case tok::slash: Opc = BO_Div; break; 11357 case tok::percent: Opc = BO_Rem; break; 11358 case tok::plus: Opc = BO_Add; break; 11359 case tok::minus: Opc = BO_Sub; break; 11360 case tok::lessless: Opc = BO_Shl; break; 11361 case tok::greatergreater: Opc = BO_Shr; break; 11362 case tok::lessequal: Opc = BO_LE; break; 11363 case tok::less: Opc = BO_LT; break; 11364 case tok::greaterequal: Opc = BO_GE; break; 11365 case tok::greater: Opc = BO_GT; break; 11366 case tok::exclaimequal: Opc = BO_NE; break; 11367 case tok::equalequal: Opc = BO_EQ; break; 11368 case tok::amp: Opc = BO_And; break; 11369 case tok::caret: Opc = BO_Xor; break; 11370 case tok::pipe: Opc = BO_Or; break; 11371 case tok::ampamp: Opc = BO_LAnd; break; 11372 case tok::pipepipe: Opc = BO_LOr; break; 11373 case tok::equal: Opc = BO_Assign; break; 11374 case tok::starequal: Opc = BO_MulAssign; break; 11375 case tok::slashequal: Opc = BO_DivAssign; break; 11376 case tok::percentequal: Opc = BO_RemAssign; break; 11377 case tok::plusequal: Opc = BO_AddAssign; break; 11378 case tok::minusequal: Opc = BO_SubAssign; break; 11379 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11380 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11381 case tok::ampequal: Opc = BO_AndAssign; break; 11382 case tok::caretequal: Opc = BO_XorAssign; break; 11383 case tok::pipeequal: Opc = BO_OrAssign; break; 11384 case tok::comma: Opc = BO_Comma; break; 11385 } 11386 return Opc; 11387 } 11388 11389 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11390 tok::TokenKind Kind) { 11391 UnaryOperatorKind Opc; 11392 switch (Kind) { 11393 default: llvm_unreachable("Unknown unary op!"); 11394 case tok::plusplus: Opc = UO_PreInc; break; 11395 case tok::minusminus: Opc = UO_PreDec; break; 11396 case tok::amp: Opc = UO_AddrOf; break; 11397 case tok::star: Opc = UO_Deref; break; 11398 case tok::plus: Opc = UO_Plus; break; 11399 case tok::minus: Opc = UO_Minus; break; 11400 case tok::tilde: Opc = UO_Not; break; 11401 case tok::exclaim: Opc = UO_LNot; break; 11402 case tok::kw___real: Opc = UO_Real; break; 11403 case tok::kw___imag: Opc = UO_Imag; break; 11404 case tok::kw___extension__: Opc = UO_Extension; break; 11405 } 11406 return Opc; 11407 } 11408 11409 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11410 /// This warning is only emitted for builtin assignment operations. It is also 11411 /// suppressed in the event of macro expansions. 11412 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11413 SourceLocation OpLoc) { 11414 if (S.inTemplateInstantiation()) 11415 return; 11416 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11417 return; 11418 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11419 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11420 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11421 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11422 if (!LHSDeclRef || !RHSDeclRef || 11423 LHSDeclRef->getLocation().isMacroID() || 11424 RHSDeclRef->getLocation().isMacroID()) 11425 return; 11426 const ValueDecl *LHSDecl = 11427 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11428 const ValueDecl *RHSDecl = 11429 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11430 if (LHSDecl != RHSDecl) 11431 return; 11432 if (LHSDecl->getType().isVolatileQualified()) 11433 return; 11434 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11435 if (RefTy->getPointeeType().isVolatileQualified()) 11436 return; 11437 11438 S.Diag(OpLoc, diag::warn_self_assignment) 11439 << LHSDeclRef->getType() 11440 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11441 } 11442 11443 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11444 /// is usually indicative of introspection within the Objective-C pointer. 11445 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11446 SourceLocation OpLoc) { 11447 if (!S.getLangOpts().ObjC1) 11448 return; 11449 11450 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11451 const Expr *LHS = L.get(); 11452 const Expr *RHS = R.get(); 11453 11454 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11455 ObjCPointerExpr = LHS; 11456 OtherExpr = RHS; 11457 } 11458 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11459 ObjCPointerExpr = RHS; 11460 OtherExpr = LHS; 11461 } 11462 11463 // This warning is deliberately made very specific to reduce false 11464 // positives with logic that uses '&' for hashing. This logic mainly 11465 // looks for code trying to introspect into tagged pointers, which 11466 // code should generally never do. 11467 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11468 unsigned Diag = diag::warn_objc_pointer_masking; 11469 // Determine if we are introspecting the result of performSelectorXXX. 11470 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11471 // Special case messages to -performSelector and friends, which 11472 // can return non-pointer values boxed in a pointer value. 11473 // Some clients may wish to silence warnings in this subcase. 11474 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11475 Selector S = ME->getSelector(); 11476 StringRef SelArg0 = S.getNameForSlot(0); 11477 if (SelArg0.startswith("performSelector")) 11478 Diag = diag::warn_objc_pointer_masking_performSelector; 11479 } 11480 11481 S.Diag(OpLoc, Diag) 11482 << ObjCPointerExpr->getSourceRange(); 11483 } 11484 } 11485 11486 static NamedDecl *getDeclFromExpr(Expr *E) { 11487 if (!E) 11488 return nullptr; 11489 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11490 return DRE->getDecl(); 11491 if (auto *ME = dyn_cast<MemberExpr>(E)) 11492 return ME->getMemberDecl(); 11493 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11494 return IRE->getDecl(); 11495 return nullptr; 11496 } 11497 11498 // This helper function promotes a binary operator's operands (which are of a 11499 // half vector type) to a vector of floats and then truncates the result to 11500 // a vector of either half or short. 11501 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11502 BinaryOperatorKind Opc, QualType ResultTy, 11503 ExprValueKind VK, ExprObjectKind OK, 11504 bool IsCompAssign, SourceLocation OpLoc, 11505 FPOptions FPFeatures) { 11506 auto &Context = S.getASTContext(); 11507 assert((isVector(ResultTy, Context.HalfTy) || 11508 isVector(ResultTy, Context.ShortTy)) && 11509 "Result must be a vector of half or short"); 11510 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11511 isVector(RHS.get()->getType(), Context.HalfTy) && 11512 "both operands expected to be a half vector"); 11513 11514 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11515 QualType BinOpResTy = RHS.get()->getType(); 11516 11517 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11518 // change BinOpResTy to a vector of ints. 11519 if (isVector(ResultTy, Context.ShortTy)) 11520 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11521 11522 if (IsCompAssign) 11523 return new (Context) CompoundAssignOperator( 11524 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11525 OpLoc, FPFeatures); 11526 11527 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11528 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11529 VK, OK, OpLoc, FPFeatures); 11530 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11531 } 11532 11533 static std::pair<ExprResult, ExprResult> 11534 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11535 Expr *RHSExpr) { 11536 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11537 if (!S.getLangOpts().CPlusPlus) { 11538 // C cannot handle TypoExpr nodes on either side of a binop because it 11539 // doesn't handle dependent types properly, so make sure any TypoExprs have 11540 // been dealt with before checking the operands. 11541 LHS = S.CorrectDelayedTyposInExpr(LHS); 11542 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11543 if (Opc != BO_Assign) 11544 return ExprResult(E); 11545 // Avoid correcting the RHS to the same Expr as the LHS. 11546 Decl *D = getDeclFromExpr(E); 11547 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11548 }); 11549 } 11550 return std::make_pair(LHS, RHS); 11551 } 11552 11553 /// Returns true if conversion between vectors of halfs and vectors of floats 11554 /// is needed. 11555 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11556 QualType SrcType) { 11557 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11558 Ctx.getLangOpts().HalfArgsAndReturns && isVector(SrcType, Ctx.HalfTy); 11559 } 11560 11561 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11562 /// operator @p Opc at location @c TokLoc. This routine only supports 11563 /// built-in operations; ActOnBinOp handles overloaded operators. 11564 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11565 BinaryOperatorKind Opc, 11566 Expr *LHSExpr, Expr *RHSExpr) { 11567 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11568 // The syntax only allows initializer lists on the RHS of assignment, 11569 // so we don't need to worry about accepting invalid code for 11570 // non-assignment operators. 11571 // C++11 5.17p9: 11572 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11573 // of x = {} is x = T(). 11574 InitializationKind Kind = 11575 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11576 InitializedEntity Entity = 11577 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11578 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11579 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11580 if (Init.isInvalid()) 11581 return Init; 11582 RHSExpr = Init.get(); 11583 } 11584 11585 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11586 QualType ResultTy; // Result type of the binary operator. 11587 // The following two variables are used for compound assignment operators 11588 QualType CompLHSTy; // Type of LHS after promotions for computation 11589 QualType CompResultTy; // Type of computation result 11590 ExprValueKind VK = VK_RValue; 11591 ExprObjectKind OK = OK_Ordinary; 11592 bool ConvertHalfVec = false; 11593 11594 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11595 if (!LHS.isUsable() || !RHS.isUsable()) 11596 return ExprError(); 11597 11598 if (getLangOpts().OpenCL) { 11599 QualType LHSTy = LHSExpr->getType(); 11600 QualType RHSTy = RHSExpr->getType(); 11601 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11602 // the ATOMIC_VAR_INIT macro. 11603 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11604 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11605 if (BO_Assign == Opc) 11606 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11607 else 11608 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11609 return ExprError(); 11610 } 11611 11612 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11613 // only with a builtin functions and therefore should be disallowed here. 11614 if (LHSTy->isImageType() || RHSTy->isImageType() || 11615 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11616 LHSTy->isPipeType() || RHSTy->isPipeType() || 11617 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11618 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11619 return ExprError(); 11620 } 11621 } 11622 11623 switch (Opc) { 11624 case BO_Assign: 11625 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11626 if (getLangOpts().CPlusPlus && 11627 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11628 VK = LHS.get()->getValueKind(); 11629 OK = LHS.get()->getObjectKind(); 11630 } 11631 if (!ResultTy.isNull()) { 11632 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11633 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11634 } 11635 RecordModifiableNonNullParam(*this, LHS.get()); 11636 break; 11637 case BO_PtrMemD: 11638 case BO_PtrMemI: 11639 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11640 Opc == BO_PtrMemI); 11641 break; 11642 case BO_Mul: 11643 case BO_Div: 11644 ConvertHalfVec = true; 11645 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11646 Opc == BO_Div); 11647 break; 11648 case BO_Rem: 11649 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11650 break; 11651 case BO_Add: 11652 ConvertHalfVec = true; 11653 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11654 break; 11655 case BO_Sub: 11656 ConvertHalfVec = true; 11657 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11658 break; 11659 case BO_Shl: 11660 case BO_Shr: 11661 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11662 break; 11663 case BO_LE: 11664 case BO_LT: 11665 case BO_GE: 11666 case BO_GT: 11667 ConvertHalfVec = true; 11668 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11669 break; 11670 case BO_EQ: 11671 case BO_NE: 11672 ConvertHalfVec = true; 11673 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11674 break; 11675 case BO_And: 11676 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11677 LLVM_FALLTHROUGH; 11678 case BO_Xor: 11679 case BO_Or: 11680 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11681 break; 11682 case BO_LAnd: 11683 case BO_LOr: 11684 ConvertHalfVec = true; 11685 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11686 break; 11687 case BO_MulAssign: 11688 case BO_DivAssign: 11689 ConvertHalfVec = true; 11690 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11691 Opc == BO_DivAssign); 11692 CompLHSTy = CompResultTy; 11693 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11694 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11695 break; 11696 case BO_RemAssign: 11697 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11698 CompLHSTy = CompResultTy; 11699 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11700 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11701 break; 11702 case BO_AddAssign: 11703 ConvertHalfVec = true; 11704 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11705 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11706 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11707 break; 11708 case BO_SubAssign: 11709 ConvertHalfVec = true; 11710 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11711 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11712 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11713 break; 11714 case BO_ShlAssign: 11715 case BO_ShrAssign: 11716 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11717 CompLHSTy = CompResultTy; 11718 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11719 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11720 break; 11721 case BO_AndAssign: 11722 case BO_OrAssign: // fallthrough 11723 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11724 LLVM_FALLTHROUGH; 11725 case BO_XorAssign: 11726 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11727 CompLHSTy = CompResultTy; 11728 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11729 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11730 break; 11731 case BO_Comma: 11732 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11733 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11734 VK = RHS.get()->getValueKind(); 11735 OK = RHS.get()->getObjectKind(); 11736 } 11737 break; 11738 } 11739 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11740 return ExprError(); 11741 11742 // Some of the binary operations require promoting operands of half vector to 11743 // float vectors and truncating the result back to half vector. For now, we do 11744 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11745 // arm64). 11746 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11747 isVector(LHS.get()->getType(), Context.HalfTy) && 11748 "both sides are half vectors or neither sides are"); 11749 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11750 LHS.get()->getType()); 11751 11752 // Check for array bounds violations for both sides of the BinaryOperator 11753 CheckArrayAccess(LHS.get()); 11754 CheckArrayAccess(RHS.get()); 11755 11756 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11757 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11758 &Context.Idents.get("object_setClass"), 11759 SourceLocation(), LookupOrdinaryName); 11760 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11761 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11762 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11763 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11764 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11765 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11766 } 11767 else 11768 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11769 } 11770 else if (const ObjCIvarRefExpr *OIRE = 11771 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11772 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11773 11774 // Opc is not a compound assignment if CompResultTy is null. 11775 if (CompResultTy.isNull()) { 11776 if (ConvertHalfVec) 11777 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11778 OpLoc, FPFeatures); 11779 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11780 OK, OpLoc, FPFeatures); 11781 } 11782 11783 // Handle compound assignments. 11784 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11785 OK_ObjCProperty) { 11786 VK = VK_LValue; 11787 OK = LHS.get()->getObjectKind(); 11788 } 11789 11790 if (ConvertHalfVec) 11791 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11792 OpLoc, FPFeatures); 11793 11794 return new (Context) CompoundAssignOperator( 11795 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11796 OpLoc, FPFeatures); 11797 } 11798 11799 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11800 /// operators are mixed in a way that suggests that the programmer forgot that 11801 /// comparison operators have higher precedence. The most typical example of 11802 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11803 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11804 SourceLocation OpLoc, Expr *LHSExpr, 11805 Expr *RHSExpr) { 11806 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11807 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11808 11809 // Check that one of the sides is a comparison operator and the other isn't. 11810 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11811 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11812 if (isLeftComp == isRightComp) 11813 return; 11814 11815 // Bitwise operations are sometimes used as eager logical ops. 11816 // Don't diagnose this. 11817 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11818 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11819 if (isLeftBitwise || isRightBitwise) 11820 return; 11821 11822 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11823 OpLoc) 11824 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11825 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11826 SourceRange ParensRange = isLeftComp ? 11827 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11828 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11829 11830 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11831 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11832 SuggestParentheses(Self, OpLoc, 11833 Self.PDiag(diag::note_precedence_silence) << OpStr, 11834 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11835 SuggestParentheses(Self, OpLoc, 11836 Self.PDiag(diag::note_precedence_bitwise_first) 11837 << BinaryOperator::getOpcodeStr(Opc), 11838 ParensRange); 11839 } 11840 11841 /// \brief It accepts a '&&' expr that is inside a '||' one. 11842 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11843 /// in parentheses. 11844 static void 11845 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11846 BinaryOperator *Bop) { 11847 assert(Bop->getOpcode() == BO_LAnd); 11848 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11849 << Bop->getSourceRange() << OpLoc; 11850 SuggestParentheses(Self, Bop->getOperatorLoc(), 11851 Self.PDiag(diag::note_precedence_silence) 11852 << Bop->getOpcodeStr(), 11853 Bop->getSourceRange()); 11854 } 11855 11856 /// \brief Returns true if the given expression can be evaluated as a constant 11857 /// 'true'. 11858 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11859 bool Res; 11860 return !E->isValueDependent() && 11861 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11862 } 11863 11864 /// \brief Returns true if the given expression can be evaluated as a constant 11865 /// 'false'. 11866 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11867 bool Res; 11868 return !E->isValueDependent() && 11869 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11870 } 11871 11872 /// \brief Look for '&&' in the left hand of a '||' expr. 11873 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11874 Expr *LHSExpr, Expr *RHSExpr) { 11875 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11876 if (Bop->getOpcode() == BO_LAnd) { 11877 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11878 if (EvaluatesAsFalse(S, RHSExpr)) 11879 return; 11880 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11881 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11882 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11883 } else if (Bop->getOpcode() == BO_LOr) { 11884 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11885 // If it's "a || b && 1 || c" we didn't warn earlier for 11886 // "a || b && 1", but warn now. 11887 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11888 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11889 } 11890 } 11891 } 11892 } 11893 11894 /// \brief Look for '&&' in the right hand of a '||' expr. 11895 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11896 Expr *LHSExpr, Expr *RHSExpr) { 11897 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11898 if (Bop->getOpcode() == BO_LAnd) { 11899 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11900 if (EvaluatesAsFalse(S, LHSExpr)) 11901 return; 11902 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11903 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11904 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11905 } 11906 } 11907 } 11908 11909 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11910 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11911 /// the '&' expression in parentheses. 11912 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11913 SourceLocation OpLoc, Expr *SubExpr) { 11914 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11915 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11916 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11917 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11918 << Bop->getSourceRange() << OpLoc; 11919 SuggestParentheses(S, Bop->getOperatorLoc(), 11920 S.PDiag(diag::note_precedence_silence) 11921 << Bop->getOpcodeStr(), 11922 Bop->getSourceRange()); 11923 } 11924 } 11925 } 11926 11927 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11928 Expr *SubExpr, StringRef Shift) { 11929 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11930 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11931 StringRef Op = Bop->getOpcodeStr(); 11932 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11933 << Bop->getSourceRange() << OpLoc << Shift << Op; 11934 SuggestParentheses(S, Bop->getOperatorLoc(), 11935 S.PDiag(diag::note_precedence_silence) << Op, 11936 Bop->getSourceRange()); 11937 } 11938 } 11939 } 11940 11941 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11942 Expr *LHSExpr, Expr *RHSExpr) { 11943 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11944 if (!OCE) 11945 return; 11946 11947 FunctionDecl *FD = OCE->getDirectCallee(); 11948 if (!FD || !FD->isOverloadedOperator()) 11949 return; 11950 11951 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11952 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11953 return; 11954 11955 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11956 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11957 << (Kind == OO_LessLess); 11958 SuggestParentheses(S, OCE->getOperatorLoc(), 11959 S.PDiag(diag::note_precedence_silence) 11960 << (Kind == OO_LessLess ? "<<" : ">>"), 11961 OCE->getSourceRange()); 11962 SuggestParentheses(S, OpLoc, 11963 S.PDiag(diag::note_evaluate_comparison_first), 11964 SourceRange(OCE->getArg(1)->getLocStart(), 11965 RHSExpr->getLocEnd())); 11966 } 11967 11968 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11969 /// precedence. 11970 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11971 SourceLocation OpLoc, Expr *LHSExpr, 11972 Expr *RHSExpr){ 11973 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11974 if (BinaryOperator::isBitwiseOp(Opc)) 11975 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11976 11977 // Diagnose "arg1 & arg2 | arg3" 11978 if ((Opc == BO_Or || Opc == BO_Xor) && 11979 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11980 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11981 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11982 } 11983 11984 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11985 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11986 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11987 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11988 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11989 } 11990 11991 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11992 || Opc == BO_Shr) { 11993 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11994 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11995 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11996 } 11997 11998 // Warn on overloaded shift operators and comparisons, such as: 11999 // cout << 5 == 4; 12000 if (BinaryOperator::isComparisonOp(Opc)) 12001 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12002 } 12003 12004 // Binary Operators. 'Tok' is the token for the operator. 12005 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12006 tok::TokenKind Kind, 12007 Expr *LHSExpr, Expr *RHSExpr) { 12008 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12009 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12010 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12011 12012 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12013 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12014 12015 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12016 } 12017 12018 /// Build an overloaded binary operator expression in the given scope. 12019 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12020 BinaryOperatorKind Opc, 12021 Expr *LHS, Expr *RHS) { 12022 // Find all of the overloaded operators visible from this 12023 // point. We perform both an operator-name lookup from the local 12024 // scope and an argument-dependent lookup based on the types of 12025 // the arguments. 12026 UnresolvedSet<16> Functions; 12027 OverloadedOperatorKind OverOp 12028 = BinaryOperator::getOverloadedOperator(Opc); 12029 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12030 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12031 RHS->getType(), Functions); 12032 12033 // Build the (potentially-overloaded, potentially-dependent) 12034 // binary operation. 12035 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12036 } 12037 12038 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12039 BinaryOperatorKind Opc, 12040 Expr *LHSExpr, Expr *RHSExpr) { 12041 ExprResult LHS, RHS; 12042 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12043 if (!LHS.isUsable() || !RHS.isUsable()) 12044 return ExprError(); 12045 LHSExpr = LHS.get(); 12046 RHSExpr = RHS.get(); 12047 12048 // We want to end up calling one of checkPseudoObjectAssignment 12049 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12050 // both expressions are overloadable or either is type-dependent), 12051 // or CreateBuiltinBinOp (in any other case). We also want to get 12052 // any placeholder types out of the way. 12053 12054 // Handle pseudo-objects in the LHS. 12055 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12056 // Assignments with a pseudo-object l-value need special analysis. 12057 if (pty->getKind() == BuiltinType::PseudoObject && 12058 BinaryOperator::isAssignmentOp(Opc)) 12059 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12060 12061 // Don't resolve overloads if the other type is overloadable. 12062 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12063 // We can't actually test that if we still have a placeholder, 12064 // though. Fortunately, none of the exceptions we see in that 12065 // code below are valid when the LHS is an overload set. Note 12066 // that an overload set can be dependently-typed, but it never 12067 // instantiates to having an overloadable type. 12068 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12069 if (resolvedRHS.isInvalid()) return ExprError(); 12070 RHSExpr = resolvedRHS.get(); 12071 12072 if (RHSExpr->isTypeDependent() || 12073 RHSExpr->getType()->isOverloadableType()) 12074 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12075 } 12076 12077 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12078 // template, diagnose the missing 'template' keyword instead of diagnosing 12079 // an invalid use of a bound member function. 12080 // 12081 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12082 // to C++1z [over.over]/1.4, but we already checked for that case above. 12083 if (Opc == BO_LT && inTemplateInstantiation() && 12084 (pty->getKind() == BuiltinType::BoundMember || 12085 pty->getKind() == BuiltinType::Overload)) { 12086 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12087 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12088 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12089 return isa<FunctionTemplateDecl>(ND); 12090 })) { 12091 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12092 : OE->getNameLoc(), 12093 diag::err_template_kw_missing) 12094 << OE->getName().getAsString() << ""; 12095 return ExprError(); 12096 } 12097 } 12098 12099 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12100 if (LHS.isInvalid()) return ExprError(); 12101 LHSExpr = LHS.get(); 12102 } 12103 12104 // Handle pseudo-objects in the RHS. 12105 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12106 // An overload in the RHS can potentially be resolved by the type 12107 // being assigned to. 12108 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12109 if (getLangOpts().CPlusPlus && 12110 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12111 LHSExpr->getType()->isOverloadableType())) 12112 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12113 12114 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12115 } 12116 12117 // Don't resolve overloads if the other type is overloadable. 12118 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12119 LHSExpr->getType()->isOverloadableType()) 12120 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12121 12122 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12123 if (!resolvedRHS.isUsable()) return ExprError(); 12124 RHSExpr = resolvedRHS.get(); 12125 } 12126 12127 if (getLangOpts().CPlusPlus) { 12128 // If either expression is type-dependent, always build an 12129 // overloaded op. 12130 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12131 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12132 12133 // Otherwise, build an overloaded op if either expression has an 12134 // overloadable type. 12135 if (LHSExpr->getType()->isOverloadableType() || 12136 RHSExpr->getType()->isOverloadableType()) 12137 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12138 } 12139 12140 // Build a built-in binary operation. 12141 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12142 } 12143 12144 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12145 UnaryOperatorKind Opc, 12146 Expr *InputExpr) { 12147 ExprResult Input = InputExpr; 12148 ExprValueKind VK = VK_RValue; 12149 ExprObjectKind OK = OK_Ordinary; 12150 QualType resultType; 12151 bool ConvertHalfVec = false; 12152 if (getLangOpts().OpenCL) { 12153 QualType Ty = InputExpr->getType(); 12154 // The only legal unary operation for atomics is '&'. 12155 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12156 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12157 // only with a builtin functions and therefore should be disallowed here. 12158 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12159 || Ty->isBlockPointerType())) { 12160 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12161 << InputExpr->getType() 12162 << Input.get()->getSourceRange()); 12163 } 12164 } 12165 switch (Opc) { 12166 case UO_PreInc: 12167 case UO_PreDec: 12168 case UO_PostInc: 12169 case UO_PostDec: 12170 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12171 OpLoc, 12172 Opc == UO_PreInc || 12173 Opc == UO_PostInc, 12174 Opc == UO_PreInc || 12175 Opc == UO_PreDec); 12176 break; 12177 case UO_AddrOf: 12178 resultType = CheckAddressOfOperand(Input, OpLoc); 12179 RecordModifiableNonNullParam(*this, InputExpr); 12180 break; 12181 case UO_Deref: { 12182 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12183 if (Input.isInvalid()) return ExprError(); 12184 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12185 break; 12186 } 12187 case UO_Plus: 12188 case UO_Minus: 12189 Input = UsualUnaryConversions(Input.get()); 12190 if (Input.isInvalid()) return ExprError(); 12191 // Unary plus and minus require promoting an operand of half vector to a 12192 // float vector and truncating the result back to a half vector. For now, we 12193 // do this only when HalfArgsAndReturns is set (that is, when the target is 12194 // arm or arm64). 12195 ConvertHalfVec = 12196 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12197 12198 // If the operand is a half vector, promote it to a float vector. 12199 if (ConvertHalfVec) 12200 Input = convertVector(Input.get(), Context.FloatTy, *this); 12201 resultType = Input.get()->getType(); 12202 if (resultType->isDependentType()) 12203 break; 12204 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12205 break; 12206 else if (resultType->isVectorType() && 12207 // The z vector extensions don't allow + or - with bool vectors. 12208 (!Context.getLangOpts().ZVector || 12209 resultType->getAs<VectorType>()->getVectorKind() != 12210 VectorType::AltiVecBool)) 12211 break; 12212 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12213 Opc == UO_Plus && 12214 resultType->isPointerType()) 12215 break; 12216 12217 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12218 << resultType << Input.get()->getSourceRange()); 12219 12220 case UO_Not: // bitwise complement 12221 Input = UsualUnaryConversions(Input.get()); 12222 if (Input.isInvalid()) 12223 return ExprError(); 12224 resultType = Input.get()->getType(); 12225 if (resultType->isDependentType()) 12226 break; 12227 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12228 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12229 // C99 does not support '~' for complex conjugation. 12230 Diag(OpLoc, diag::ext_integer_complement_complex) 12231 << resultType << Input.get()->getSourceRange(); 12232 else if (resultType->hasIntegerRepresentation()) 12233 break; 12234 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12235 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12236 // on vector float types. 12237 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12238 if (!T->isIntegerType()) 12239 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12240 << resultType << Input.get()->getSourceRange()); 12241 } else { 12242 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12243 << resultType << Input.get()->getSourceRange()); 12244 } 12245 break; 12246 12247 case UO_LNot: // logical negation 12248 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12249 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12250 if (Input.isInvalid()) return ExprError(); 12251 resultType = Input.get()->getType(); 12252 12253 // Though we still have to promote half FP to float... 12254 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12255 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12256 resultType = Context.FloatTy; 12257 } 12258 12259 if (resultType->isDependentType()) 12260 break; 12261 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12262 // C99 6.5.3.3p1: ok, fallthrough; 12263 if (Context.getLangOpts().CPlusPlus) { 12264 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12265 // operand contextually converted to bool. 12266 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12267 ScalarTypeToBooleanCastKind(resultType)); 12268 } else if (Context.getLangOpts().OpenCL && 12269 Context.getLangOpts().OpenCLVersion < 120) { 12270 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12271 // operate on scalar float types. 12272 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12273 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12274 << resultType << Input.get()->getSourceRange()); 12275 } 12276 } else if (resultType->isExtVectorType()) { 12277 if (Context.getLangOpts().OpenCL && 12278 Context.getLangOpts().OpenCLVersion < 120) { 12279 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12280 // operate on vector float types. 12281 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12282 if (!T->isIntegerType()) 12283 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12284 << resultType << Input.get()->getSourceRange()); 12285 } 12286 // Vector logical not returns the signed variant of the operand type. 12287 resultType = GetSignedVectorType(resultType); 12288 break; 12289 } else { 12290 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12291 // type in C++. We should allow that here too. 12292 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12293 << resultType << Input.get()->getSourceRange()); 12294 } 12295 12296 // LNot always has type int. C99 6.5.3.3p5. 12297 // In C++, it's bool. C++ 5.3.1p8 12298 resultType = Context.getLogicalOperationType(); 12299 break; 12300 case UO_Real: 12301 case UO_Imag: 12302 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12303 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12304 // complex l-values to ordinary l-values and all other values to r-values. 12305 if (Input.isInvalid()) return ExprError(); 12306 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12307 if (Input.get()->getValueKind() != VK_RValue && 12308 Input.get()->getObjectKind() == OK_Ordinary) 12309 VK = Input.get()->getValueKind(); 12310 } else if (!getLangOpts().CPlusPlus) { 12311 // In C, a volatile scalar is read by __imag. In C++, it is not. 12312 Input = DefaultLvalueConversion(Input.get()); 12313 } 12314 break; 12315 case UO_Extension: 12316 resultType = Input.get()->getType(); 12317 VK = Input.get()->getValueKind(); 12318 OK = Input.get()->getObjectKind(); 12319 break; 12320 case UO_Coawait: 12321 // It's unnessesary to represent the pass-through operator co_await in the 12322 // AST; just return the input expression instead. 12323 assert(!Input.get()->getType()->isDependentType() && 12324 "the co_await expression must be non-dependant before " 12325 "building operator co_await"); 12326 return Input; 12327 } 12328 if (resultType.isNull() || Input.isInvalid()) 12329 return ExprError(); 12330 12331 // Check for array bounds violations in the operand of the UnaryOperator, 12332 // except for the '*' and '&' operators that have to be handled specially 12333 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12334 // that are explicitly defined as valid by the standard). 12335 if (Opc != UO_AddrOf && Opc != UO_Deref) 12336 CheckArrayAccess(Input.get()); 12337 12338 auto *UO = new (Context) 12339 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12340 // Convert the result back to a half vector. 12341 if (ConvertHalfVec) 12342 return convertVector(UO, Context.HalfTy, *this); 12343 return UO; 12344 } 12345 12346 /// \brief Determine whether the given expression is a qualified member 12347 /// access expression, of a form that could be turned into a pointer to member 12348 /// with the address-of operator. 12349 static bool isQualifiedMemberAccess(Expr *E) { 12350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12351 if (!DRE->getQualifier()) 12352 return false; 12353 12354 ValueDecl *VD = DRE->getDecl(); 12355 if (!VD->isCXXClassMember()) 12356 return false; 12357 12358 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12359 return true; 12360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12361 return Method->isInstance(); 12362 12363 return false; 12364 } 12365 12366 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12367 if (!ULE->getQualifier()) 12368 return false; 12369 12370 for (NamedDecl *D : ULE->decls()) { 12371 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12372 if (Method->isInstance()) 12373 return true; 12374 } else { 12375 // Overload set does not contain methods. 12376 break; 12377 } 12378 } 12379 12380 return false; 12381 } 12382 12383 return false; 12384 } 12385 12386 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12387 UnaryOperatorKind Opc, Expr *Input) { 12388 // First things first: handle placeholders so that the 12389 // overloaded-operator check considers the right type. 12390 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12391 // Increment and decrement of pseudo-object references. 12392 if (pty->getKind() == BuiltinType::PseudoObject && 12393 UnaryOperator::isIncrementDecrementOp(Opc)) 12394 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12395 12396 // extension is always a builtin operator. 12397 if (Opc == UO_Extension) 12398 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12399 12400 // & gets special logic for several kinds of placeholder. 12401 // The builtin code knows what to do. 12402 if (Opc == UO_AddrOf && 12403 (pty->getKind() == BuiltinType::Overload || 12404 pty->getKind() == BuiltinType::UnknownAny || 12405 pty->getKind() == BuiltinType::BoundMember)) 12406 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12407 12408 // Anything else needs to be handled now. 12409 ExprResult Result = CheckPlaceholderExpr(Input); 12410 if (Result.isInvalid()) return ExprError(); 12411 Input = Result.get(); 12412 } 12413 12414 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12415 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12416 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12417 // Find all of the overloaded operators visible from this 12418 // point. We perform both an operator-name lookup from the local 12419 // scope and an argument-dependent lookup based on the types of 12420 // the arguments. 12421 UnresolvedSet<16> Functions; 12422 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12423 if (S && OverOp != OO_None) 12424 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12425 Functions); 12426 12427 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12428 } 12429 12430 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12431 } 12432 12433 // Unary Operators. 'Tok' is the token for the operator. 12434 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12435 tok::TokenKind Op, Expr *Input) { 12436 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12437 } 12438 12439 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12440 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12441 LabelDecl *TheDecl) { 12442 TheDecl->markUsed(Context); 12443 // Create the AST node. The address of a label always has type 'void*'. 12444 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12445 Context.getPointerType(Context.VoidTy)); 12446 } 12447 12448 /// Given the last statement in a statement-expression, check whether 12449 /// the result is a producing expression (like a call to an 12450 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12451 /// release out of the full-expression. Otherwise, return null. 12452 /// Cannot fail. 12453 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12454 // Should always be wrapped with one of these. 12455 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12456 if (!cleanups) return nullptr; 12457 12458 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12459 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12460 return nullptr; 12461 12462 // Splice out the cast. This shouldn't modify any interesting 12463 // features of the statement. 12464 Expr *producer = cast->getSubExpr(); 12465 assert(producer->getType() == cast->getType()); 12466 assert(producer->getValueKind() == cast->getValueKind()); 12467 cleanups->setSubExpr(producer); 12468 return cleanups; 12469 } 12470 12471 void Sema::ActOnStartStmtExpr() { 12472 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12473 } 12474 12475 void Sema::ActOnStmtExprError() { 12476 // Note that function is also called by TreeTransform when leaving a 12477 // StmtExpr scope without rebuilding anything. 12478 12479 DiscardCleanupsInEvaluationContext(); 12480 PopExpressionEvaluationContext(); 12481 } 12482 12483 ExprResult 12484 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12485 SourceLocation RPLoc) { // "({..})" 12486 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12487 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12488 12489 if (hasAnyUnrecoverableErrorsInThisFunction()) 12490 DiscardCleanupsInEvaluationContext(); 12491 assert(!Cleanup.exprNeedsCleanups() && 12492 "cleanups within StmtExpr not correctly bound!"); 12493 PopExpressionEvaluationContext(); 12494 12495 // FIXME: there are a variety of strange constraints to enforce here, for 12496 // example, it is not possible to goto into a stmt expression apparently. 12497 // More semantic analysis is needed. 12498 12499 // If there are sub-stmts in the compound stmt, take the type of the last one 12500 // as the type of the stmtexpr. 12501 QualType Ty = Context.VoidTy; 12502 bool StmtExprMayBindToTemp = false; 12503 if (!Compound->body_empty()) { 12504 Stmt *LastStmt = Compound->body_back(); 12505 LabelStmt *LastLabelStmt = nullptr; 12506 // If LastStmt is a label, skip down through into the body. 12507 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12508 LastLabelStmt = Label; 12509 LastStmt = Label->getSubStmt(); 12510 } 12511 12512 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12513 // Do function/array conversion on the last expression, but not 12514 // lvalue-to-rvalue. However, initialize an unqualified type. 12515 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12516 if (LastExpr.isInvalid()) 12517 return ExprError(); 12518 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12519 12520 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12521 // In ARC, if the final expression ends in a consume, splice 12522 // the consume out and bind it later. In the alternate case 12523 // (when dealing with a retainable type), the result 12524 // initialization will create a produce. In both cases the 12525 // result will be +1, and we'll need to balance that out with 12526 // a bind. 12527 if (Expr *rebuiltLastStmt 12528 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12529 LastExpr = rebuiltLastStmt; 12530 } else { 12531 LastExpr = PerformCopyInitialization( 12532 InitializedEntity::InitializeResult(LPLoc, 12533 Ty, 12534 false), 12535 SourceLocation(), 12536 LastExpr); 12537 } 12538 12539 if (LastExpr.isInvalid()) 12540 return ExprError(); 12541 if (LastExpr.get() != nullptr) { 12542 if (!LastLabelStmt) 12543 Compound->setLastStmt(LastExpr.get()); 12544 else 12545 LastLabelStmt->setSubStmt(LastExpr.get()); 12546 StmtExprMayBindToTemp = true; 12547 } 12548 } 12549 } 12550 } 12551 12552 // FIXME: Check that expression type is complete/non-abstract; statement 12553 // expressions are not lvalues. 12554 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12555 if (StmtExprMayBindToTemp) 12556 return MaybeBindToTemporary(ResStmtExpr); 12557 return ResStmtExpr; 12558 } 12559 12560 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12561 TypeSourceInfo *TInfo, 12562 ArrayRef<OffsetOfComponent> Components, 12563 SourceLocation RParenLoc) { 12564 QualType ArgTy = TInfo->getType(); 12565 bool Dependent = ArgTy->isDependentType(); 12566 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12567 12568 // We must have at least one component that refers to the type, and the first 12569 // one is known to be a field designator. Verify that the ArgTy represents 12570 // a struct/union/class. 12571 if (!Dependent && !ArgTy->isRecordType()) 12572 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12573 << ArgTy << TypeRange); 12574 12575 // Type must be complete per C99 7.17p3 because a declaring a variable 12576 // with an incomplete type would be ill-formed. 12577 if (!Dependent 12578 && RequireCompleteType(BuiltinLoc, ArgTy, 12579 diag::err_offsetof_incomplete_type, TypeRange)) 12580 return ExprError(); 12581 12582 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12583 // GCC extension, diagnose them. 12584 // FIXME: This diagnostic isn't actually visible because the location is in 12585 // a system header! 12586 if (Components.size() != 1) 12587 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12588 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12589 12590 bool DidWarnAboutNonPOD = false; 12591 QualType CurrentType = ArgTy; 12592 SmallVector<OffsetOfNode, 4> Comps; 12593 SmallVector<Expr*, 4> Exprs; 12594 for (const OffsetOfComponent &OC : Components) { 12595 if (OC.isBrackets) { 12596 // Offset of an array sub-field. TODO: Should we allow vector elements? 12597 if (!CurrentType->isDependentType()) { 12598 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12599 if(!AT) 12600 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12601 << CurrentType); 12602 CurrentType = AT->getElementType(); 12603 } else 12604 CurrentType = Context.DependentTy; 12605 12606 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12607 if (IdxRval.isInvalid()) 12608 return ExprError(); 12609 Expr *Idx = IdxRval.get(); 12610 12611 // The expression must be an integral expression. 12612 // FIXME: An integral constant expression? 12613 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12614 !Idx->getType()->isIntegerType()) 12615 return ExprError(Diag(Idx->getLocStart(), 12616 diag::err_typecheck_subscript_not_integer) 12617 << Idx->getSourceRange()); 12618 12619 // Record this array index. 12620 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12621 Exprs.push_back(Idx); 12622 continue; 12623 } 12624 12625 // Offset of a field. 12626 if (CurrentType->isDependentType()) { 12627 // We have the offset of a field, but we can't look into the dependent 12628 // type. Just record the identifier of the field. 12629 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12630 CurrentType = Context.DependentTy; 12631 continue; 12632 } 12633 12634 // We need to have a complete type to look into. 12635 if (RequireCompleteType(OC.LocStart, CurrentType, 12636 diag::err_offsetof_incomplete_type)) 12637 return ExprError(); 12638 12639 // Look for the designated field. 12640 const RecordType *RC = CurrentType->getAs<RecordType>(); 12641 if (!RC) 12642 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12643 << CurrentType); 12644 RecordDecl *RD = RC->getDecl(); 12645 12646 // C++ [lib.support.types]p5: 12647 // The macro offsetof accepts a restricted set of type arguments in this 12648 // International Standard. type shall be a POD structure or a POD union 12649 // (clause 9). 12650 // C++11 [support.types]p4: 12651 // If type is not a standard-layout class (Clause 9), the results are 12652 // undefined. 12653 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12654 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12655 unsigned DiagID = 12656 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12657 : diag::ext_offsetof_non_pod_type; 12658 12659 if (!IsSafe && !DidWarnAboutNonPOD && 12660 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12661 PDiag(DiagID) 12662 << SourceRange(Components[0].LocStart, OC.LocEnd) 12663 << CurrentType)) 12664 DidWarnAboutNonPOD = true; 12665 } 12666 12667 // Look for the field. 12668 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12669 LookupQualifiedName(R, RD); 12670 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12671 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12672 if (!MemberDecl) { 12673 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12674 MemberDecl = IndirectMemberDecl->getAnonField(); 12675 } 12676 12677 if (!MemberDecl) 12678 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12679 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12680 OC.LocEnd)); 12681 12682 // C99 7.17p3: 12683 // (If the specified member is a bit-field, the behavior is undefined.) 12684 // 12685 // We diagnose this as an error. 12686 if (MemberDecl->isBitField()) { 12687 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12688 << MemberDecl->getDeclName() 12689 << SourceRange(BuiltinLoc, RParenLoc); 12690 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12691 return ExprError(); 12692 } 12693 12694 RecordDecl *Parent = MemberDecl->getParent(); 12695 if (IndirectMemberDecl) 12696 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12697 12698 // If the member was found in a base class, introduce OffsetOfNodes for 12699 // the base class indirections. 12700 CXXBasePaths Paths; 12701 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12702 Paths)) { 12703 if (Paths.getDetectedVirtual()) { 12704 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12705 << MemberDecl->getDeclName() 12706 << SourceRange(BuiltinLoc, RParenLoc); 12707 return ExprError(); 12708 } 12709 12710 CXXBasePath &Path = Paths.front(); 12711 for (const CXXBasePathElement &B : Path) 12712 Comps.push_back(OffsetOfNode(B.Base)); 12713 } 12714 12715 if (IndirectMemberDecl) { 12716 for (auto *FI : IndirectMemberDecl->chain()) { 12717 assert(isa<FieldDecl>(FI)); 12718 Comps.push_back(OffsetOfNode(OC.LocStart, 12719 cast<FieldDecl>(FI), OC.LocEnd)); 12720 } 12721 } else 12722 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12723 12724 CurrentType = MemberDecl->getType().getNonReferenceType(); 12725 } 12726 12727 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12728 Comps, Exprs, RParenLoc); 12729 } 12730 12731 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12732 SourceLocation BuiltinLoc, 12733 SourceLocation TypeLoc, 12734 ParsedType ParsedArgTy, 12735 ArrayRef<OffsetOfComponent> Components, 12736 SourceLocation RParenLoc) { 12737 12738 TypeSourceInfo *ArgTInfo; 12739 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12740 if (ArgTy.isNull()) 12741 return ExprError(); 12742 12743 if (!ArgTInfo) 12744 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12745 12746 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12747 } 12748 12749 12750 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12751 Expr *CondExpr, 12752 Expr *LHSExpr, Expr *RHSExpr, 12753 SourceLocation RPLoc) { 12754 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12755 12756 ExprValueKind VK = VK_RValue; 12757 ExprObjectKind OK = OK_Ordinary; 12758 QualType resType; 12759 bool ValueDependent = false; 12760 bool CondIsTrue = false; 12761 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12762 resType = Context.DependentTy; 12763 ValueDependent = true; 12764 } else { 12765 // The conditional expression is required to be a constant expression. 12766 llvm::APSInt condEval(32); 12767 ExprResult CondICE 12768 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12769 diag::err_typecheck_choose_expr_requires_constant, false); 12770 if (CondICE.isInvalid()) 12771 return ExprError(); 12772 CondExpr = CondICE.get(); 12773 CondIsTrue = condEval.getZExtValue(); 12774 12775 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12776 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12777 12778 resType = ActiveExpr->getType(); 12779 ValueDependent = ActiveExpr->isValueDependent(); 12780 VK = ActiveExpr->getValueKind(); 12781 OK = ActiveExpr->getObjectKind(); 12782 } 12783 12784 return new (Context) 12785 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12786 CondIsTrue, resType->isDependentType(), ValueDependent); 12787 } 12788 12789 //===----------------------------------------------------------------------===// 12790 // Clang Extensions. 12791 //===----------------------------------------------------------------------===// 12792 12793 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12794 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12795 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12796 12797 if (LangOpts.CPlusPlus) { 12798 Decl *ManglingContextDecl; 12799 if (MangleNumberingContext *MCtx = 12800 getCurrentMangleNumberContext(Block->getDeclContext(), 12801 ManglingContextDecl)) { 12802 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12803 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12804 } 12805 } 12806 12807 PushBlockScope(CurScope, Block); 12808 CurContext->addDecl(Block); 12809 if (CurScope) 12810 PushDeclContext(CurScope, Block); 12811 else 12812 CurContext = Block; 12813 12814 getCurBlock()->HasImplicitReturnType = true; 12815 12816 // Enter a new evaluation context to insulate the block from any 12817 // cleanups from the enclosing full-expression. 12818 PushExpressionEvaluationContext( 12819 ExpressionEvaluationContext::PotentiallyEvaluated); 12820 } 12821 12822 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12823 Scope *CurScope) { 12824 assert(ParamInfo.getIdentifier() == nullptr && 12825 "block-id should have no identifier!"); 12826 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12827 BlockScopeInfo *CurBlock = getCurBlock(); 12828 12829 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12830 QualType T = Sig->getType(); 12831 12832 // FIXME: We should allow unexpanded parameter packs here, but that would, 12833 // in turn, make the block expression contain unexpanded parameter packs. 12834 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12835 // Drop the parameters. 12836 FunctionProtoType::ExtProtoInfo EPI; 12837 EPI.HasTrailingReturn = false; 12838 EPI.TypeQuals |= DeclSpec::TQ_const; 12839 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12840 Sig = Context.getTrivialTypeSourceInfo(T); 12841 } 12842 12843 // GetTypeForDeclarator always produces a function type for a block 12844 // literal signature. Furthermore, it is always a FunctionProtoType 12845 // unless the function was written with a typedef. 12846 assert(T->isFunctionType() && 12847 "GetTypeForDeclarator made a non-function block signature"); 12848 12849 // Look for an explicit signature in that function type. 12850 FunctionProtoTypeLoc ExplicitSignature; 12851 12852 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12853 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12854 12855 // Check whether that explicit signature was synthesized by 12856 // GetTypeForDeclarator. If so, don't save that as part of the 12857 // written signature. 12858 if (ExplicitSignature.getLocalRangeBegin() == 12859 ExplicitSignature.getLocalRangeEnd()) { 12860 // This would be much cheaper if we stored TypeLocs instead of 12861 // TypeSourceInfos. 12862 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12863 unsigned Size = Result.getFullDataSize(); 12864 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12865 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12866 12867 ExplicitSignature = FunctionProtoTypeLoc(); 12868 } 12869 } 12870 12871 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12872 CurBlock->FunctionType = T; 12873 12874 const FunctionType *Fn = T->getAs<FunctionType>(); 12875 QualType RetTy = Fn->getReturnType(); 12876 bool isVariadic = 12877 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12878 12879 CurBlock->TheDecl->setIsVariadic(isVariadic); 12880 12881 // Context.DependentTy is used as a placeholder for a missing block 12882 // return type. TODO: what should we do with declarators like: 12883 // ^ * { ... } 12884 // If the answer is "apply template argument deduction".... 12885 if (RetTy != Context.DependentTy) { 12886 CurBlock->ReturnType = RetTy; 12887 CurBlock->TheDecl->setBlockMissingReturnType(false); 12888 CurBlock->HasImplicitReturnType = false; 12889 } 12890 12891 // Push block parameters from the declarator if we had them. 12892 SmallVector<ParmVarDecl*, 8> Params; 12893 if (ExplicitSignature) { 12894 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12895 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12896 if (Param->getIdentifier() == nullptr && 12897 !Param->isImplicit() && 12898 !Param->isInvalidDecl() && 12899 !getLangOpts().CPlusPlus) 12900 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12901 Params.push_back(Param); 12902 } 12903 12904 // Fake up parameter variables if we have a typedef, like 12905 // ^ fntype { ... } 12906 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12907 for (const auto &I : Fn->param_types()) { 12908 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12909 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12910 Params.push_back(Param); 12911 } 12912 } 12913 12914 // Set the parameters on the block decl. 12915 if (!Params.empty()) { 12916 CurBlock->TheDecl->setParams(Params); 12917 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12918 /*CheckParameterNames=*/false); 12919 } 12920 12921 // Finally we can process decl attributes. 12922 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12923 12924 // Put the parameter variables in scope. 12925 for (auto AI : CurBlock->TheDecl->parameters()) { 12926 AI->setOwningFunction(CurBlock->TheDecl); 12927 12928 // If this has an identifier, add it to the scope stack. 12929 if (AI->getIdentifier()) { 12930 CheckShadow(CurBlock->TheScope, AI); 12931 12932 PushOnScopeChains(AI, CurBlock->TheScope); 12933 } 12934 } 12935 } 12936 12937 /// ActOnBlockError - If there is an error parsing a block, this callback 12938 /// is invoked to pop the information about the block from the action impl. 12939 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12940 // Leave the expression-evaluation context. 12941 DiscardCleanupsInEvaluationContext(); 12942 PopExpressionEvaluationContext(); 12943 12944 // Pop off CurBlock, handle nested blocks. 12945 PopDeclContext(); 12946 PopFunctionScopeInfo(); 12947 } 12948 12949 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12950 /// literal was successfully completed. ^(int x){...} 12951 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12952 Stmt *Body, Scope *CurScope) { 12953 // If blocks are disabled, emit an error. 12954 if (!LangOpts.Blocks) 12955 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12956 12957 // Leave the expression-evaluation context. 12958 if (hasAnyUnrecoverableErrorsInThisFunction()) 12959 DiscardCleanupsInEvaluationContext(); 12960 assert(!Cleanup.exprNeedsCleanups() && 12961 "cleanups within block not correctly bound!"); 12962 PopExpressionEvaluationContext(); 12963 12964 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12965 12966 if (BSI->HasImplicitReturnType) 12967 deduceClosureReturnType(*BSI); 12968 12969 PopDeclContext(); 12970 12971 QualType RetTy = Context.VoidTy; 12972 if (!BSI->ReturnType.isNull()) 12973 RetTy = BSI->ReturnType; 12974 12975 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12976 QualType BlockTy; 12977 12978 // Set the captured variables on the block. 12979 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12980 SmallVector<BlockDecl::Capture, 4> Captures; 12981 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12982 if (Cap.isThisCapture()) 12983 continue; 12984 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12985 Cap.isNested(), Cap.getInitExpr()); 12986 Captures.push_back(NewCap); 12987 } 12988 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12989 12990 // If the user wrote a function type in some form, try to use that. 12991 if (!BSI->FunctionType.isNull()) { 12992 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12993 12994 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12995 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12996 12997 // Turn protoless block types into nullary block types. 12998 if (isa<FunctionNoProtoType>(FTy)) { 12999 FunctionProtoType::ExtProtoInfo EPI; 13000 EPI.ExtInfo = Ext; 13001 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13002 13003 // Otherwise, if we don't need to change anything about the function type, 13004 // preserve its sugar structure. 13005 } else if (FTy->getReturnType() == RetTy && 13006 (!NoReturn || FTy->getNoReturnAttr())) { 13007 BlockTy = BSI->FunctionType; 13008 13009 // Otherwise, make the minimal modifications to the function type. 13010 } else { 13011 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13012 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13013 EPI.TypeQuals = 0; // FIXME: silently? 13014 EPI.ExtInfo = Ext; 13015 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13016 } 13017 13018 // If we don't have a function type, just build one from nothing. 13019 } else { 13020 FunctionProtoType::ExtProtoInfo EPI; 13021 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13022 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13023 } 13024 13025 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13026 BlockTy = Context.getBlockPointerType(BlockTy); 13027 13028 // If needed, diagnose invalid gotos and switches in the block. 13029 if (getCurFunction()->NeedsScopeChecking() && 13030 !PP.isCodeCompletionEnabled()) 13031 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13032 13033 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13034 13035 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13036 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13037 13038 // Try to apply the named return value optimization. We have to check again 13039 // if we can do this, though, because blocks keep return statements around 13040 // to deduce an implicit return type. 13041 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13042 !BSI->TheDecl->isDependentContext()) 13043 computeNRVO(Body, BSI); 13044 13045 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13046 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13047 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13048 13049 // If the block isn't obviously global, i.e. it captures anything at 13050 // all, then we need to do a few things in the surrounding context: 13051 if (Result->getBlockDecl()->hasCaptures()) { 13052 // First, this expression has a new cleanup object. 13053 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13054 Cleanup.setExprNeedsCleanups(true); 13055 13056 // It also gets a branch-protected scope if any of the captured 13057 // variables needs destruction. 13058 for (const auto &CI : Result->getBlockDecl()->captures()) { 13059 const VarDecl *var = CI.getVariable(); 13060 if (var->getType().isDestructedType() != QualType::DK_none) { 13061 getCurFunction()->setHasBranchProtectedScope(); 13062 break; 13063 } 13064 } 13065 } 13066 13067 return Result; 13068 } 13069 13070 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13071 SourceLocation RPLoc) { 13072 TypeSourceInfo *TInfo; 13073 GetTypeFromParser(Ty, &TInfo); 13074 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13075 } 13076 13077 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13078 Expr *E, TypeSourceInfo *TInfo, 13079 SourceLocation RPLoc) { 13080 Expr *OrigExpr = E; 13081 bool IsMS = false; 13082 13083 // CUDA device code does not support varargs. 13084 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13085 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13086 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13087 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13088 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13089 } 13090 } 13091 13092 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13093 // as Microsoft ABI on an actual Microsoft platform, where 13094 // __builtin_ms_va_list and __builtin_va_list are the same.) 13095 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13096 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13097 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13098 if (Context.hasSameType(MSVaListType, E->getType())) { 13099 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13100 return ExprError(); 13101 IsMS = true; 13102 } 13103 } 13104 13105 // Get the va_list type 13106 QualType VaListType = Context.getBuiltinVaListType(); 13107 if (!IsMS) { 13108 if (VaListType->isArrayType()) { 13109 // Deal with implicit array decay; for example, on x86-64, 13110 // va_list is an array, but it's supposed to decay to 13111 // a pointer for va_arg. 13112 VaListType = Context.getArrayDecayedType(VaListType); 13113 // Make sure the input expression also decays appropriately. 13114 ExprResult Result = UsualUnaryConversions(E); 13115 if (Result.isInvalid()) 13116 return ExprError(); 13117 E = Result.get(); 13118 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13119 // If va_list is a record type and we are compiling in C++ mode, 13120 // check the argument using reference binding. 13121 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13122 Context, Context.getLValueReferenceType(VaListType), false); 13123 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13124 if (Init.isInvalid()) 13125 return ExprError(); 13126 E = Init.getAs<Expr>(); 13127 } else { 13128 // Otherwise, the va_list argument must be an l-value because 13129 // it is modified by va_arg. 13130 if (!E->isTypeDependent() && 13131 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13132 return ExprError(); 13133 } 13134 } 13135 13136 if (!IsMS && !E->isTypeDependent() && 13137 !Context.hasSameType(VaListType, E->getType())) 13138 return ExprError(Diag(E->getLocStart(), 13139 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13140 << OrigExpr->getType() << E->getSourceRange()); 13141 13142 if (!TInfo->getType()->isDependentType()) { 13143 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13144 diag::err_second_parameter_to_va_arg_incomplete, 13145 TInfo->getTypeLoc())) 13146 return ExprError(); 13147 13148 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13149 TInfo->getType(), 13150 diag::err_second_parameter_to_va_arg_abstract, 13151 TInfo->getTypeLoc())) 13152 return ExprError(); 13153 13154 if (!TInfo->getType().isPODType(Context)) { 13155 Diag(TInfo->getTypeLoc().getBeginLoc(), 13156 TInfo->getType()->isObjCLifetimeType() 13157 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13158 : diag::warn_second_parameter_to_va_arg_not_pod) 13159 << TInfo->getType() 13160 << TInfo->getTypeLoc().getSourceRange(); 13161 } 13162 13163 // Check for va_arg where arguments of the given type will be promoted 13164 // (i.e. this va_arg is guaranteed to have undefined behavior). 13165 QualType PromoteType; 13166 if (TInfo->getType()->isPromotableIntegerType()) { 13167 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13168 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13169 PromoteType = QualType(); 13170 } 13171 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13172 PromoteType = Context.DoubleTy; 13173 if (!PromoteType.isNull()) 13174 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13175 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13176 << TInfo->getType() 13177 << PromoteType 13178 << TInfo->getTypeLoc().getSourceRange()); 13179 } 13180 13181 QualType T = TInfo->getType().getNonLValueExprType(Context); 13182 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13183 } 13184 13185 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13186 // The type of __null will be int or long, depending on the size of 13187 // pointers on the target. 13188 QualType Ty; 13189 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13190 if (pw == Context.getTargetInfo().getIntWidth()) 13191 Ty = Context.IntTy; 13192 else if (pw == Context.getTargetInfo().getLongWidth()) 13193 Ty = Context.LongTy; 13194 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13195 Ty = Context.LongLongTy; 13196 else { 13197 llvm_unreachable("I don't know size of pointer!"); 13198 } 13199 13200 return new (Context) GNUNullExpr(Ty, TokenLoc); 13201 } 13202 13203 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13204 bool Diagnose) { 13205 if (!getLangOpts().ObjC1) 13206 return false; 13207 13208 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13209 if (!PT) 13210 return false; 13211 13212 if (!PT->isObjCIdType()) { 13213 // Check if the destination is the 'NSString' interface. 13214 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13215 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13216 return false; 13217 } 13218 13219 // Ignore any parens, implicit casts (should only be 13220 // array-to-pointer decays), and not-so-opaque values. The last is 13221 // important for making this trigger for property assignments. 13222 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13223 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13224 if (OV->getSourceExpr()) 13225 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13226 13227 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13228 if (!SL || !SL->isAscii()) 13229 return false; 13230 if (Diagnose) { 13231 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13232 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13233 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13234 } 13235 return true; 13236 } 13237 13238 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13239 const Expr *SrcExpr) { 13240 if (!DstType->isFunctionPointerType() || 13241 !SrcExpr->getType()->isFunctionType()) 13242 return false; 13243 13244 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13245 if (!DRE) 13246 return false; 13247 13248 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13249 if (!FD) 13250 return false; 13251 13252 return !S.checkAddressOfFunctionIsAvailable(FD, 13253 /*Complain=*/true, 13254 SrcExpr->getLocStart()); 13255 } 13256 13257 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13258 SourceLocation Loc, 13259 QualType DstType, QualType SrcType, 13260 Expr *SrcExpr, AssignmentAction Action, 13261 bool *Complained) { 13262 if (Complained) 13263 *Complained = false; 13264 13265 // Decode the result (notice that AST's are still created for extensions). 13266 bool CheckInferredResultType = false; 13267 bool isInvalid = false; 13268 unsigned DiagKind = 0; 13269 FixItHint Hint; 13270 ConversionFixItGenerator ConvHints; 13271 bool MayHaveConvFixit = false; 13272 bool MayHaveFunctionDiff = false; 13273 const ObjCInterfaceDecl *IFace = nullptr; 13274 const ObjCProtocolDecl *PDecl = nullptr; 13275 13276 switch (ConvTy) { 13277 case Compatible: 13278 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13279 return false; 13280 13281 case PointerToInt: 13282 DiagKind = diag::ext_typecheck_convert_pointer_int; 13283 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13284 MayHaveConvFixit = true; 13285 break; 13286 case IntToPointer: 13287 DiagKind = diag::ext_typecheck_convert_int_pointer; 13288 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13289 MayHaveConvFixit = true; 13290 break; 13291 case IncompatiblePointer: 13292 if (Action == AA_Passing_CFAudited) 13293 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13294 else if (SrcType->isFunctionPointerType() && 13295 DstType->isFunctionPointerType()) 13296 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13297 else 13298 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13299 13300 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13301 SrcType->isObjCObjectPointerType(); 13302 if (Hint.isNull() && !CheckInferredResultType) { 13303 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13304 } 13305 else if (CheckInferredResultType) { 13306 SrcType = SrcType.getUnqualifiedType(); 13307 DstType = DstType.getUnqualifiedType(); 13308 } 13309 MayHaveConvFixit = true; 13310 break; 13311 case IncompatiblePointerSign: 13312 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13313 break; 13314 case FunctionVoidPointer: 13315 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13316 break; 13317 case IncompatiblePointerDiscardsQualifiers: { 13318 // Perform array-to-pointer decay if necessary. 13319 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13320 13321 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13322 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13323 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13324 DiagKind = diag::err_typecheck_incompatible_address_space; 13325 break; 13326 13327 13328 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13329 DiagKind = diag::err_typecheck_incompatible_ownership; 13330 break; 13331 } 13332 13333 llvm_unreachable("unknown error case for discarding qualifiers!"); 13334 // fallthrough 13335 } 13336 case CompatiblePointerDiscardsQualifiers: 13337 // If the qualifiers lost were because we were applying the 13338 // (deprecated) C++ conversion from a string literal to a char* 13339 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13340 // Ideally, this check would be performed in 13341 // checkPointerTypesForAssignment. However, that would require a 13342 // bit of refactoring (so that the second argument is an 13343 // expression, rather than a type), which should be done as part 13344 // of a larger effort to fix checkPointerTypesForAssignment for 13345 // C++ semantics. 13346 if (getLangOpts().CPlusPlus && 13347 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13348 return false; 13349 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13350 break; 13351 case IncompatibleNestedPointerQualifiers: 13352 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13353 break; 13354 case IntToBlockPointer: 13355 DiagKind = diag::err_int_to_block_pointer; 13356 break; 13357 case IncompatibleBlockPointer: 13358 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13359 break; 13360 case IncompatibleObjCQualifiedId: { 13361 if (SrcType->isObjCQualifiedIdType()) { 13362 const ObjCObjectPointerType *srcOPT = 13363 SrcType->getAs<ObjCObjectPointerType>(); 13364 for (auto *srcProto : srcOPT->quals()) { 13365 PDecl = srcProto; 13366 break; 13367 } 13368 if (const ObjCInterfaceType *IFaceT = 13369 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13370 IFace = IFaceT->getDecl(); 13371 } 13372 else if (DstType->isObjCQualifiedIdType()) { 13373 const ObjCObjectPointerType *dstOPT = 13374 DstType->getAs<ObjCObjectPointerType>(); 13375 for (auto *dstProto : dstOPT->quals()) { 13376 PDecl = dstProto; 13377 break; 13378 } 13379 if (const ObjCInterfaceType *IFaceT = 13380 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13381 IFace = IFaceT->getDecl(); 13382 } 13383 DiagKind = diag::warn_incompatible_qualified_id; 13384 break; 13385 } 13386 case IncompatibleVectors: 13387 DiagKind = diag::warn_incompatible_vectors; 13388 break; 13389 case IncompatibleObjCWeakRef: 13390 DiagKind = diag::err_arc_weak_unavailable_assign; 13391 break; 13392 case Incompatible: 13393 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13394 if (Complained) 13395 *Complained = true; 13396 return true; 13397 } 13398 13399 DiagKind = diag::err_typecheck_convert_incompatible; 13400 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13401 MayHaveConvFixit = true; 13402 isInvalid = true; 13403 MayHaveFunctionDiff = true; 13404 break; 13405 } 13406 13407 QualType FirstType, SecondType; 13408 switch (Action) { 13409 case AA_Assigning: 13410 case AA_Initializing: 13411 // The destination type comes first. 13412 FirstType = DstType; 13413 SecondType = SrcType; 13414 break; 13415 13416 case AA_Returning: 13417 case AA_Passing: 13418 case AA_Passing_CFAudited: 13419 case AA_Converting: 13420 case AA_Sending: 13421 case AA_Casting: 13422 // The source type comes first. 13423 FirstType = SrcType; 13424 SecondType = DstType; 13425 break; 13426 } 13427 13428 PartialDiagnostic FDiag = PDiag(DiagKind); 13429 if (Action == AA_Passing_CFAudited) 13430 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13431 else 13432 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13433 13434 // If we can fix the conversion, suggest the FixIts. 13435 assert(ConvHints.isNull() || Hint.isNull()); 13436 if (!ConvHints.isNull()) { 13437 for (FixItHint &H : ConvHints.Hints) 13438 FDiag << H; 13439 } else { 13440 FDiag << Hint; 13441 } 13442 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13443 13444 if (MayHaveFunctionDiff) 13445 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13446 13447 Diag(Loc, FDiag); 13448 if (DiagKind == diag::warn_incompatible_qualified_id && 13449 PDecl && IFace && !IFace->hasDefinition()) 13450 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13451 << IFace->getName() << PDecl->getName(); 13452 13453 if (SecondType == Context.OverloadTy) 13454 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13455 FirstType, /*TakingAddress=*/true); 13456 13457 if (CheckInferredResultType) 13458 EmitRelatedResultTypeNote(SrcExpr); 13459 13460 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13461 EmitRelatedResultTypeNoteForReturn(DstType); 13462 13463 if (Complained) 13464 *Complained = true; 13465 return isInvalid; 13466 } 13467 13468 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13469 llvm::APSInt *Result) { 13470 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13471 public: 13472 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13473 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13474 } 13475 } Diagnoser; 13476 13477 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13478 } 13479 13480 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13481 llvm::APSInt *Result, 13482 unsigned DiagID, 13483 bool AllowFold) { 13484 class IDDiagnoser : public VerifyICEDiagnoser { 13485 unsigned DiagID; 13486 13487 public: 13488 IDDiagnoser(unsigned DiagID) 13489 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13490 13491 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13492 S.Diag(Loc, DiagID) << SR; 13493 } 13494 } Diagnoser(DiagID); 13495 13496 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13497 } 13498 13499 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13500 SourceRange SR) { 13501 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13502 } 13503 13504 ExprResult 13505 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13506 VerifyICEDiagnoser &Diagnoser, 13507 bool AllowFold) { 13508 SourceLocation DiagLoc = E->getLocStart(); 13509 13510 if (getLangOpts().CPlusPlus11) { 13511 // C++11 [expr.const]p5: 13512 // If an expression of literal class type is used in a context where an 13513 // integral constant expression is required, then that class type shall 13514 // have a single non-explicit conversion function to an integral or 13515 // unscoped enumeration type 13516 ExprResult Converted; 13517 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13518 public: 13519 CXX11ConvertDiagnoser(bool Silent) 13520 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13521 Silent, true) {} 13522 13523 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13524 QualType T) override { 13525 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13526 } 13527 13528 SemaDiagnosticBuilder diagnoseIncomplete( 13529 Sema &S, SourceLocation Loc, QualType T) override { 13530 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13531 } 13532 13533 SemaDiagnosticBuilder diagnoseExplicitConv( 13534 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13535 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13536 } 13537 13538 SemaDiagnosticBuilder noteExplicitConv( 13539 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13540 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13541 << ConvTy->isEnumeralType() << ConvTy; 13542 } 13543 13544 SemaDiagnosticBuilder diagnoseAmbiguous( 13545 Sema &S, SourceLocation Loc, QualType T) override { 13546 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13547 } 13548 13549 SemaDiagnosticBuilder noteAmbiguous( 13550 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13551 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13552 << ConvTy->isEnumeralType() << ConvTy; 13553 } 13554 13555 SemaDiagnosticBuilder diagnoseConversion( 13556 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13557 llvm_unreachable("conversion functions are permitted"); 13558 } 13559 } ConvertDiagnoser(Diagnoser.Suppress); 13560 13561 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13562 ConvertDiagnoser); 13563 if (Converted.isInvalid()) 13564 return Converted; 13565 E = Converted.get(); 13566 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13567 return ExprError(); 13568 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13569 // An ICE must be of integral or unscoped enumeration type. 13570 if (!Diagnoser.Suppress) 13571 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13572 return ExprError(); 13573 } 13574 13575 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13576 // in the non-ICE case. 13577 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13578 if (Result) 13579 *Result = E->EvaluateKnownConstInt(Context); 13580 return E; 13581 } 13582 13583 Expr::EvalResult EvalResult; 13584 SmallVector<PartialDiagnosticAt, 8> Notes; 13585 EvalResult.Diag = &Notes; 13586 13587 // Try to evaluate the expression, and produce diagnostics explaining why it's 13588 // not a constant expression as a side-effect. 13589 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13590 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13591 13592 // In C++11, we can rely on diagnostics being produced for any expression 13593 // which is not a constant expression. If no diagnostics were produced, then 13594 // this is a constant expression. 13595 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13596 if (Result) 13597 *Result = EvalResult.Val.getInt(); 13598 return E; 13599 } 13600 13601 // If our only note is the usual "invalid subexpression" note, just point 13602 // the caret at its location rather than producing an essentially 13603 // redundant note. 13604 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13605 diag::note_invalid_subexpr_in_const_expr) { 13606 DiagLoc = Notes[0].first; 13607 Notes.clear(); 13608 } 13609 13610 if (!Folded || !AllowFold) { 13611 if (!Diagnoser.Suppress) { 13612 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13613 for (const PartialDiagnosticAt &Note : Notes) 13614 Diag(Note.first, Note.second); 13615 } 13616 13617 return ExprError(); 13618 } 13619 13620 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13621 for (const PartialDiagnosticAt &Note : Notes) 13622 Diag(Note.first, Note.second); 13623 13624 if (Result) 13625 *Result = EvalResult.Val.getInt(); 13626 return E; 13627 } 13628 13629 namespace { 13630 // Handle the case where we conclude a expression which we speculatively 13631 // considered to be unevaluated is actually evaluated. 13632 class TransformToPE : public TreeTransform<TransformToPE> { 13633 typedef TreeTransform<TransformToPE> BaseTransform; 13634 13635 public: 13636 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13637 13638 // Make sure we redo semantic analysis 13639 bool AlwaysRebuild() { return true; } 13640 13641 // Make sure we handle LabelStmts correctly. 13642 // FIXME: This does the right thing, but maybe we need a more general 13643 // fix to TreeTransform? 13644 StmtResult TransformLabelStmt(LabelStmt *S) { 13645 S->getDecl()->setStmt(nullptr); 13646 return BaseTransform::TransformLabelStmt(S); 13647 } 13648 13649 // We need to special-case DeclRefExprs referring to FieldDecls which 13650 // are not part of a member pointer formation; normal TreeTransforming 13651 // doesn't catch this case because of the way we represent them in the AST. 13652 // FIXME: This is a bit ugly; is it really the best way to handle this 13653 // case? 13654 // 13655 // Error on DeclRefExprs referring to FieldDecls. 13656 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13657 if (isa<FieldDecl>(E->getDecl()) && 13658 !SemaRef.isUnevaluatedContext()) 13659 return SemaRef.Diag(E->getLocation(), 13660 diag::err_invalid_non_static_member_use) 13661 << E->getDecl() << E->getSourceRange(); 13662 13663 return BaseTransform::TransformDeclRefExpr(E); 13664 } 13665 13666 // Exception: filter out member pointer formation 13667 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13668 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13669 return E; 13670 13671 return BaseTransform::TransformUnaryOperator(E); 13672 } 13673 13674 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13675 // Lambdas never need to be transformed. 13676 return E; 13677 } 13678 }; 13679 } 13680 13681 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13682 assert(isUnevaluatedContext() && 13683 "Should only transform unevaluated expressions"); 13684 ExprEvalContexts.back().Context = 13685 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13686 if (isUnevaluatedContext()) 13687 return E; 13688 return TransformToPE(*this).TransformExpr(E); 13689 } 13690 13691 void 13692 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13693 Decl *LambdaContextDecl, 13694 bool IsDecltype) { 13695 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13696 LambdaContextDecl, IsDecltype); 13697 Cleanup.reset(); 13698 if (!MaybeODRUseExprs.empty()) 13699 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13700 } 13701 13702 void 13703 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13704 ReuseLambdaContextDecl_t, 13705 bool IsDecltype) { 13706 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13707 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13708 } 13709 13710 void Sema::PopExpressionEvaluationContext() { 13711 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13712 unsigned NumTypos = Rec.NumTypos; 13713 13714 if (!Rec.Lambdas.empty()) { 13715 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13716 unsigned D; 13717 if (Rec.isUnevaluated()) { 13718 // C++11 [expr.prim.lambda]p2: 13719 // A lambda-expression shall not appear in an unevaluated operand 13720 // (Clause 5). 13721 D = diag::err_lambda_unevaluated_operand; 13722 } else { 13723 // C++1y [expr.const]p2: 13724 // A conditional-expression e is a core constant expression unless the 13725 // evaluation of e, following the rules of the abstract machine, would 13726 // evaluate [...] a lambda-expression. 13727 D = diag::err_lambda_in_constant_expression; 13728 } 13729 13730 // C++1z allows lambda expressions as core constant expressions. 13731 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13732 // 1607) from appearing within template-arguments and array-bounds that 13733 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13734 // unevaluated contexts) might lift some of these restrictions in a 13735 // future version. 13736 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13737 for (const auto *L : Rec.Lambdas) 13738 Diag(L->getLocStart(), D); 13739 } else { 13740 // Mark the capture expressions odr-used. This was deferred 13741 // during lambda expression creation. 13742 for (auto *Lambda : Rec.Lambdas) { 13743 for (auto *C : Lambda->capture_inits()) 13744 MarkDeclarationsReferencedInExpr(C); 13745 } 13746 } 13747 } 13748 13749 // When are coming out of an unevaluated context, clear out any 13750 // temporaries that we may have created as part of the evaluation of 13751 // the expression in that context: they aren't relevant because they 13752 // will never be constructed. 13753 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13754 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13755 ExprCleanupObjects.end()); 13756 Cleanup = Rec.ParentCleanup; 13757 CleanupVarDeclMarking(); 13758 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13759 // Otherwise, merge the contexts together. 13760 } else { 13761 Cleanup.mergeFrom(Rec.ParentCleanup); 13762 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13763 Rec.SavedMaybeODRUseExprs.end()); 13764 } 13765 13766 // Pop the current expression evaluation context off the stack. 13767 ExprEvalContexts.pop_back(); 13768 13769 if (!ExprEvalContexts.empty()) 13770 ExprEvalContexts.back().NumTypos += NumTypos; 13771 else 13772 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13773 "last ExpressionEvaluationContextRecord"); 13774 } 13775 13776 void Sema::DiscardCleanupsInEvaluationContext() { 13777 ExprCleanupObjects.erase( 13778 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13779 ExprCleanupObjects.end()); 13780 Cleanup.reset(); 13781 MaybeODRUseExprs.clear(); 13782 } 13783 13784 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13785 if (!E->getType()->isVariablyModifiedType()) 13786 return E; 13787 return TransformToPotentiallyEvaluated(E); 13788 } 13789 13790 /// Are we within a context in which some evaluation could be performed (be it 13791 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13792 /// captured by C++'s idea of an "unevaluated context". 13793 static bool isEvaluatableContext(Sema &SemaRef) { 13794 switch (SemaRef.ExprEvalContexts.back().Context) { 13795 case Sema::ExpressionEvaluationContext::Unevaluated: 13796 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13797 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13798 // Expressions in this context are never evaluated. 13799 return false; 13800 13801 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13802 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13803 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13804 // Expressions in this context could be evaluated. 13805 return true; 13806 13807 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13808 // Referenced declarations will only be used if the construct in the 13809 // containing expression is used, at which point we'll be given another 13810 // turn to mark them. 13811 return false; 13812 } 13813 llvm_unreachable("Invalid context"); 13814 } 13815 13816 /// Are we within a context in which references to resolved functions or to 13817 /// variables result in odr-use? 13818 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13819 // An expression in a template is not really an expression until it's been 13820 // instantiated, so it doesn't trigger odr-use. 13821 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13822 return false; 13823 13824 switch (SemaRef.ExprEvalContexts.back().Context) { 13825 case Sema::ExpressionEvaluationContext::Unevaluated: 13826 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13827 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13828 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13829 return false; 13830 13831 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13832 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13833 return true; 13834 13835 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13836 return false; 13837 } 13838 llvm_unreachable("Invalid context"); 13839 } 13840 13841 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13842 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13843 return Func->isConstexpr() && 13844 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13845 } 13846 13847 /// \brief Mark a function referenced, and check whether it is odr-used 13848 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13849 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13850 bool MightBeOdrUse) { 13851 assert(Func && "No function?"); 13852 13853 Func->setReferenced(); 13854 13855 // C++11 [basic.def.odr]p3: 13856 // A function whose name appears as a potentially-evaluated expression is 13857 // odr-used if it is the unique lookup result or the selected member of a 13858 // set of overloaded functions [...]. 13859 // 13860 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13861 // can just check that here. 13862 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13863 13864 // Determine whether we require a function definition to exist, per 13865 // C++11 [temp.inst]p3: 13866 // Unless a function template specialization has been explicitly 13867 // instantiated or explicitly specialized, the function template 13868 // specialization is implicitly instantiated when the specialization is 13869 // referenced in a context that requires a function definition to exist. 13870 // 13871 // That is either when this is an odr-use, or when a usage of a constexpr 13872 // function occurs within an evaluatable context. 13873 bool NeedDefinition = 13874 OdrUse || (isEvaluatableContext(*this) && 13875 isImplicitlyDefinableConstexprFunction(Func)); 13876 13877 // C++14 [temp.expl.spec]p6: 13878 // If a template [...] is explicitly specialized then that specialization 13879 // shall be declared before the first use of that specialization that would 13880 // cause an implicit instantiation to take place, in every translation unit 13881 // in which such a use occurs 13882 if (NeedDefinition && 13883 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13884 Func->getMemberSpecializationInfo())) 13885 checkSpecializationVisibility(Loc, Func); 13886 13887 // C++14 [except.spec]p17: 13888 // An exception-specification is considered to be needed when: 13889 // - the function is odr-used or, if it appears in an unevaluated operand, 13890 // would be odr-used if the expression were potentially-evaluated; 13891 // 13892 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13893 // function is a pure virtual function we're calling, and in that case the 13894 // function was selected by overload resolution and we need to resolve its 13895 // exception specification for a different reason. 13896 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13897 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13898 ResolveExceptionSpec(Loc, FPT); 13899 13900 // If we don't need to mark the function as used, and we don't need to 13901 // try to provide a definition, there's nothing more to do. 13902 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13903 (!NeedDefinition || Func->getBody())) 13904 return; 13905 13906 // Note that this declaration has been used. 13907 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13908 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13909 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13910 if (Constructor->isDefaultConstructor()) { 13911 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13912 return; 13913 DefineImplicitDefaultConstructor(Loc, Constructor); 13914 } else if (Constructor->isCopyConstructor()) { 13915 DefineImplicitCopyConstructor(Loc, Constructor); 13916 } else if (Constructor->isMoveConstructor()) { 13917 DefineImplicitMoveConstructor(Loc, Constructor); 13918 } 13919 } else if (Constructor->getInheritedConstructor()) { 13920 DefineInheritingConstructor(Loc, Constructor); 13921 } 13922 } else if (CXXDestructorDecl *Destructor = 13923 dyn_cast<CXXDestructorDecl>(Func)) { 13924 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13925 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13926 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13927 return; 13928 DefineImplicitDestructor(Loc, Destructor); 13929 } 13930 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13931 MarkVTableUsed(Loc, Destructor->getParent()); 13932 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13933 if (MethodDecl->isOverloadedOperator() && 13934 MethodDecl->getOverloadedOperator() == OO_Equal) { 13935 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13936 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13937 if (MethodDecl->isCopyAssignmentOperator()) 13938 DefineImplicitCopyAssignment(Loc, MethodDecl); 13939 else if (MethodDecl->isMoveAssignmentOperator()) 13940 DefineImplicitMoveAssignment(Loc, MethodDecl); 13941 } 13942 } else if (isa<CXXConversionDecl>(MethodDecl) && 13943 MethodDecl->getParent()->isLambda()) { 13944 CXXConversionDecl *Conversion = 13945 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13946 if (Conversion->isLambdaToBlockPointerConversion()) 13947 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13948 else 13949 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13950 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13951 MarkVTableUsed(Loc, MethodDecl->getParent()); 13952 } 13953 13954 // Recursive functions should be marked when used from another function. 13955 // FIXME: Is this really right? 13956 if (CurContext == Func) return; 13957 13958 // Implicit instantiation of function templates and member functions of 13959 // class templates. 13960 if (Func->isImplicitlyInstantiable()) { 13961 bool AlreadyInstantiated = false; 13962 SourceLocation PointOfInstantiation = Loc; 13963 if (FunctionTemplateSpecializationInfo *SpecInfo 13964 = Func->getTemplateSpecializationInfo()) { 13965 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13966 SpecInfo->setPointOfInstantiation(Loc); 13967 else if (SpecInfo->getTemplateSpecializationKind() 13968 == TSK_ImplicitInstantiation) { 13969 AlreadyInstantiated = true; 13970 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13971 } 13972 } else if (MemberSpecializationInfo *MSInfo 13973 = Func->getMemberSpecializationInfo()) { 13974 if (MSInfo->getPointOfInstantiation().isInvalid()) 13975 MSInfo->setPointOfInstantiation(Loc); 13976 else if (MSInfo->getTemplateSpecializationKind() 13977 == TSK_ImplicitInstantiation) { 13978 AlreadyInstantiated = true; 13979 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13980 } 13981 } 13982 13983 if (!AlreadyInstantiated || Func->isConstexpr()) { 13984 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13985 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13986 CodeSynthesisContexts.size()) 13987 PendingLocalImplicitInstantiations.push_back( 13988 std::make_pair(Func, PointOfInstantiation)); 13989 else if (Func->isConstexpr()) 13990 // Do not defer instantiations of constexpr functions, to avoid the 13991 // expression evaluator needing to call back into Sema if it sees a 13992 // call to such a function. 13993 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13994 else { 13995 Func->setInstantiationIsPending(true); 13996 PendingInstantiations.push_back(std::make_pair(Func, 13997 PointOfInstantiation)); 13998 // Notify the consumer that a function was implicitly instantiated. 13999 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14000 } 14001 } 14002 } else { 14003 // Walk redefinitions, as some of them may be instantiable. 14004 for (auto i : Func->redecls()) { 14005 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14006 MarkFunctionReferenced(Loc, i, OdrUse); 14007 } 14008 } 14009 14010 if (!OdrUse) return; 14011 14012 // Keep track of used but undefined functions. 14013 if (!Func->isDefined()) { 14014 if (mightHaveNonExternalLinkage(Func)) 14015 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14016 else if (Func->getMostRecentDecl()->isInlined() && 14017 !LangOpts.GNUInline && 14018 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14019 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14020 else if (isExternalWithNoLinkageType(Func)) 14021 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14022 } 14023 14024 Func->markUsed(Context); 14025 } 14026 14027 static void 14028 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14029 ValueDecl *var, DeclContext *DC) { 14030 DeclContext *VarDC = var->getDeclContext(); 14031 14032 // If the parameter still belongs to the translation unit, then 14033 // we're actually just using one parameter in the declaration of 14034 // the next. 14035 if (isa<ParmVarDecl>(var) && 14036 isa<TranslationUnitDecl>(VarDC)) 14037 return; 14038 14039 // For C code, don't diagnose about capture if we're not actually in code 14040 // right now; it's impossible to write a non-constant expression outside of 14041 // function context, so we'll get other (more useful) diagnostics later. 14042 // 14043 // For C++, things get a bit more nasty... it would be nice to suppress this 14044 // diagnostic for certain cases like using a local variable in an array bound 14045 // for a member of a local class, but the correct predicate is not obvious. 14046 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14047 return; 14048 14049 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14050 unsigned ContextKind = 3; // unknown 14051 if (isa<CXXMethodDecl>(VarDC) && 14052 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14053 ContextKind = 2; 14054 } else if (isa<FunctionDecl>(VarDC)) { 14055 ContextKind = 0; 14056 } else if (isa<BlockDecl>(VarDC)) { 14057 ContextKind = 1; 14058 } 14059 14060 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14061 << var << ValueKind << ContextKind << VarDC; 14062 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14063 << var; 14064 14065 // FIXME: Add additional diagnostic info about class etc. which prevents 14066 // capture. 14067 } 14068 14069 14070 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14071 bool &SubCapturesAreNested, 14072 QualType &CaptureType, 14073 QualType &DeclRefType) { 14074 // Check whether we've already captured it. 14075 if (CSI->CaptureMap.count(Var)) { 14076 // If we found a capture, any subcaptures are nested. 14077 SubCapturesAreNested = true; 14078 14079 // Retrieve the capture type for this variable. 14080 CaptureType = CSI->getCapture(Var).getCaptureType(); 14081 14082 // Compute the type of an expression that refers to this variable. 14083 DeclRefType = CaptureType.getNonReferenceType(); 14084 14085 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14086 // are mutable in the sense that user can change their value - they are 14087 // private instances of the captured declarations. 14088 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14089 if (Cap.isCopyCapture() && 14090 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14091 !(isa<CapturedRegionScopeInfo>(CSI) && 14092 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14093 DeclRefType.addConst(); 14094 return true; 14095 } 14096 return false; 14097 } 14098 14099 // Only block literals, captured statements, and lambda expressions can 14100 // capture; other scopes don't work. 14101 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14102 SourceLocation Loc, 14103 const bool Diagnose, Sema &S) { 14104 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14105 return getLambdaAwareParentOfDeclContext(DC); 14106 else if (Var->hasLocalStorage()) { 14107 if (Diagnose) 14108 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14109 } 14110 return nullptr; 14111 } 14112 14113 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14114 // certain types of variables (unnamed, variably modified types etc.) 14115 // so check for eligibility. 14116 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14117 SourceLocation Loc, 14118 const bool Diagnose, Sema &S) { 14119 14120 bool IsBlock = isa<BlockScopeInfo>(CSI); 14121 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14122 14123 // Lambdas are not allowed to capture unnamed variables 14124 // (e.g. anonymous unions). 14125 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14126 // assuming that's the intent. 14127 if (IsLambda && !Var->getDeclName()) { 14128 if (Diagnose) { 14129 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14130 S.Diag(Var->getLocation(), diag::note_declared_at); 14131 } 14132 return false; 14133 } 14134 14135 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14136 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14137 if (Diagnose) { 14138 S.Diag(Loc, diag::err_ref_vm_type); 14139 S.Diag(Var->getLocation(), diag::note_previous_decl) 14140 << Var->getDeclName(); 14141 } 14142 return false; 14143 } 14144 // Prohibit structs with flexible array members too. 14145 // We cannot capture what is in the tail end of the struct. 14146 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14147 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14148 if (Diagnose) { 14149 if (IsBlock) 14150 S.Diag(Loc, diag::err_ref_flexarray_type); 14151 else 14152 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14153 << Var->getDeclName(); 14154 S.Diag(Var->getLocation(), diag::note_previous_decl) 14155 << Var->getDeclName(); 14156 } 14157 return false; 14158 } 14159 } 14160 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14161 // Lambdas and captured statements are not allowed to capture __block 14162 // variables; they don't support the expected semantics. 14163 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14164 if (Diagnose) { 14165 S.Diag(Loc, diag::err_capture_block_variable) 14166 << Var->getDeclName() << !IsLambda; 14167 S.Diag(Var->getLocation(), diag::note_previous_decl) 14168 << Var->getDeclName(); 14169 } 14170 return false; 14171 } 14172 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14173 if (S.getLangOpts().OpenCL && IsBlock && 14174 Var->getType()->isBlockPointerType()) { 14175 if (Diagnose) 14176 S.Diag(Loc, diag::err_opencl_block_ref_block); 14177 return false; 14178 } 14179 14180 return true; 14181 } 14182 14183 // Returns true if the capture by block was successful. 14184 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14185 SourceLocation Loc, 14186 const bool BuildAndDiagnose, 14187 QualType &CaptureType, 14188 QualType &DeclRefType, 14189 const bool Nested, 14190 Sema &S) { 14191 Expr *CopyExpr = nullptr; 14192 bool ByRef = false; 14193 14194 // Blocks are not allowed to capture arrays. 14195 if (CaptureType->isArrayType()) { 14196 if (BuildAndDiagnose) { 14197 S.Diag(Loc, diag::err_ref_array_type); 14198 S.Diag(Var->getLocation(), diag::note_previous_decl) 14199 << Var->getDeclName(); 14200 } 14201 return false; 14202 } 14203 14204 // Forbid the block-capture of autoreleasing variables. 14205 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14206 if (BuildAndDiagnose) { 14207 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14208 << /*block*/ 0; 14209 S.Diag(Var->getLocation(), diag::note_previous_decl) 14210 << Var->getDeclName(); 14211 } 14212 return false; 14213 } 14214 14215 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14216 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14217 // This function finds out whether there is an AttributedType of kind 14218 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14219 // attr_objc_ownership implies __autoreleasing was explicitly specified 14220 // rather than being added implicitly by the compiler. 14221 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14222 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14223 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14224 return true; 14225 14226 // Peel off AttributedTypes that are not of kind objc_ownership. 14227 Ty = AttrTy->getModifiedType(); 14228 } 14229 14230 return false; 14231 }; 14232 14233 QualType PointeeTy = PT->getPointeeType(); 14234 14235 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14236 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14237 !IsObjCOwnershipAttributedType(PointeeTy)) { 14238 if (BuildAndDiagnose) { 14239 SourceLocation VarLoc = Var->getLocation(); 14240 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14241 { 14242 auto AddAutoreleaseNote = 14243 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14244 // Provide a fix-it for the '__autoreleasing' keyword at the 14245 // appropriate location in the variable's type. 14246 if (const auto *TSI = Var->getTypeSourceInfo()) { 14247 PointerTypeLoc PTL = 14248 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14249 if (PTL) { 14250 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14251 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14252 S.getLangOpts()); 14253 if (Loc.isValid()) { 14254 StringRef CharAtLoc = Lexer::getSourceText( 14255 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14256 S.getSourceManager(), S.getLangOpts()); 14257 AddAutoreleaseNote << FixItHint::CreateInsertion( 14258 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14259 ? " __autoreleasing " 14260 : " __autoreleasing"); 14261 } 14262 } 14263 } 14264 } 14265 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14266 } 14267 } 14268 } 14269 14270 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14271 if (HasBlocksAttr || CaptureType->isReferenceType() || 14272 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14273 // Block capture by reference does not change the capture or 14274 // declaration reference types. 14275 ByRef = true; 14276 } else { 14277 // Block capture by copy introduces 'const'. 14278 CaptureType = CaptureType.getNonReferenceType().withConst(); 14279 DeclRefType = CaptureType; 14280 14281 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14282 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14283 // The capture logic needs the destructor, so make sure we mark it. 14284 // Usually this is unnecessary because most local variables have 14285 // their destructors marked at declaration time, but parameters are 14286 // an exception because it's technically only the call site that 14287 // actually requires the destructor. 14288 if (isa<ParmVarDecl>(Var)) 14289 S.FinalizeVarWithDestructor(Var, Record); 14290 14291 // Enter a new evaluation context to insulate the copy 14292 // full-expression. 14293 EnterExpressionEvaluationContext scope( 14294 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14295 14296 // According to the blocks spec, the capture of a variable from 14297 // the stack requires a const copy constructor. This is not true 14298 // of the copy/move done to move a __block variable to the heap. 14299 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14300 DeclRefType.withConst(), 14301 VK_LValue, Loc); 14302 14303 ExprResult Result 14304 = S.PerformCopyInitialization( 14305 InitializedEntity::InitializeBlock(Var->getLocation(), 14306 CaptureType, false), 14307 Loc, DeclRef); 14308 14309 // Build a full-expression copy expression if initialization 14310 // succeeded and used a non-trivial constructor. Recover from 14311 // errors by pretending that the copy isn't necessary. 14312 if (!Result.isInvalid() && 14313 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14314 ->isTrivial()) { 14315 Result = S.MaybeCreateExprWithCleanups(Result); 14316 CopyExpr = Result.get(); 14317 } 14318 } 14319 } 14320 } 14321 14322 // Actually capture the variable. 14323 if (BuildAndDiagnose) 14324 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14325 SourceLocation(), CaptureType, CopyExpr); 14326 14327 return true; 14328 14329 } 14330 14331 14332 /// \brief Capture the given variable in the captured region. 14333 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14334 VarDecl *Var, 14335 SourceLocation Loc, 14336 const bool BuildAndDiagnose, 14337 QualType &CaptureType, 14338 QualType &DeclRefType, 14339 const bool RefersToCapturedVariable, 14340 Sema &S) { 14341 // By default, capture variables by reference. 14342 bool ByRef = true; 14343 // Using an LValue reference type is consistent with Lambdas (see below). 14344 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14345 if (S.IsOpenMPCapturedDecl(Var)) 14346 DeclRefType = DeclRefType.getUnqualifiedType(); 14347 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14348 } 14349 14350 if (ByRef) 14351 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14352 else 14353 CaptureType = DeclRefType; 14354 14355 Expr *CopyExpr = nullptr; 14356 if (BuildAndDiagnose) { 14357 // The current implementation assumes that all variables are captured 14358 // by references. Since there is no capture by copy, no expression 14359 // evaluation will be needed. 14360 RecordDecl *RD = RSI->TheRecordDecl; 14361 14362 FieldDecl *Field 14363 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14364 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14365 nullptr, false, ICIS_NoInit); 14366 Field->setImplicit(true); 14367 Field->setAccess(AS_private); 14368 RD->addDecl(Field); 14369 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14370 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14371 14372 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14373 DeclRefType, VK_LValue, Loc); 14374 Var->setReferenced(true); 14375 Var->markUsed(S.Context); 14376 } 14377 14378 // Actually capture the variable. 14379 if (BuildAndDiagnose) 14380 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14381 SourceLocation(), CaptureType, CopyExpr); 14382 14383 14384 return true; 14385 } 14386 14387 /// \brief Create a field within the lambda class for the variable 14388 /// being captured. 14389 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14390 QualType FieldType, QualType DeclRefType, 14391 SourceLocation Loc, 14392 bool RefersToCapturedVariable) { 14393 CXXRecordDecl *Lambda = LSI->Lambda; 14394 14395 // Build the non-static data member. 14396 FieldDecl *Field 14397 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14398 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14399 nullptr, false, ICIS_NoInit); 14400 Field->setImplicit(true); 14401 Field->setAccess(AS_private); 14402 Lambda->addDecl(Field); 14403 } 14404 14405 /// \brief Capture the given variable in the lambda. 14406 static bool captureInLambda(LambdaScopeInfo *LSI, 14407 VarDecl *Var, 14408 SourceLocation Loc, 14409 const bool BuildAndDiagnose, 14410 QualType &CaptureType, 14411 QualType &DeclRefType, 14412 const bool RefersToCapturedVariable, 14413 const Sema::TryCaptureKind Kind, 14414 SourceLocation EllipsisLoc, 14415 const bool IsTopScope, 14416 Sema &S) { 14417 14418 // Determine whether we are capturing by reference or by value. 14419 bool ByRef = false; 14420 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14421 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14422 } else { 14423 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14424 } 14425 14426 // Compute the type of the field that will capture this variable. 14427 if (ByRef) { 14428 // C++11 [expr.prim.lambda]p15: 14429 // An entity is captured by reference if it is implicitly or 14430 // explicitly captured but not captured by copy. It is 14431 // unspecified whether additional unnamed non-static data 14432 // members are declared in the closure type for entities 14433 // captured by reference. 14434 // 14435 // FIXME: It is not clear whether we want to build an lvalue reference 14436 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14437 // to do the former, while EDG does the latter. Core issue 1249 will 14438 // clarify, but for now we follow GCC because it's a more permissive and 14439 // easily defensible position. 14440 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14441 } else { 14442 // C++11 [expr.prim.lambda]p14: 14443 // For each entity captured by copy, an unnamed non-static 14444 // data member is declared in the closure type. The 14445 // declaration order of these members is unspecified. The type 14446 // of such a data member is the type of the corresponding 14447 // captured entity if the entity is not a reference to an 14448 // object, or the referenced type otherwise. [Note: If the 14449 // captured entity is a reference to a function, the 14450 // corresponding data member is also a reference to a 14451 // function. - end note ] 14452 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14453 if (!RefType->getPointeeType()->isFunctionType()) 14454 CaptureType = RefType->getPointeeType(); 14455 } 14456 14457 // Forbid the lambda copy-capture of autoreleasing variables. 14458 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14459 if (BuildAndDiagnose) { 14460 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14461 S.Diag(Var->getLocation(), diag::note_previous_decl) 14462 << Var->getDeclName(); 14463 } 14464 return false; 14465 } 14466 14467 // Make sure that by-copy captures are of a complete and non-abstract type. 14468 if (BuildAndDiagnose) { 14469 if (!CaptureType->isDependentType() && 14470 S.RequireCompleteType(Loc, CaptureType, 14471 diag::err_capture_of_incomplete_type, 14472 Var->getDeclName())) 14473 return false; 14474 14475 if (S.RequireNonAbstractType(Loc, CaptureType, 14476 diag::err_capture_of_abstract_type)) 14477 return false; 14478 } 14479 } 14480 14481 // Capture this variable in the lambda. 14482 if (BuildAndDiagnose) 14483 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14484 RefersToCapturedVariable); 14485 14486 // Compute the type of a reference to this captured variable. 14487 if (ByRef) 14488 DeclRefType = CaptureType.getNonReferenceType(); 14489 else { 14490 // C++ [expr.prim.lambda]p5: 14491 // The closure type for a lambda-expression has a public inline 14492 // function call operator [...]. This function call operator is 14493 // declared const (9.3.1) if and only if the lambda-expression's 14494 // parameter-declaration-clause is not followed by mutable. 14495 DeclRefType = CaptureType.getNonReferenceType(); 14496 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14497 DeclRefType.addConst(); 14498 } 14499 14500 // Add the capture. 14501 if (BuildAndDiagnose) 14502 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14503 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14504 14505 return true; 14506 } 14507 14508 bool Sema::tryCaptureVariable( 14509 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14510 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14511 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14512 // An init-capture is notionally from the context surrounding its 14513 // declaration, but its parent DC is the lambda class. 14514 DeclContext *VarDC = Var->getDeclContext(); 14515 if (Var->isInitCapture()) 14516 VarDC = VarDC->getParent(); 14517 14518 DeclContext *DC = CurContext; 14519 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14520 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14521 // We need to sync up the Declaration Context with the 14522 // FunctionScopeIndexToStopAt 14523 if (FunctionScopeIndexToStopAt) { 14524 unsigned FSIndex = FunctionScopes.size() - 1; 14525 while (FSIndex != MaxFunctionScopesIndex) { 14526 DC = getLambdaAwareParentOfDeclContext(DC); 14527 --FSIndex; 14528 } 14529 } 14530 14531 14532 // If the variable is declared in the current context, there is no need to 14533 // capture it. 14534 if (VarDC == DC) return true; 14535 14536 // Capture global variables if it is required to use private copy of this 14537 // variable. 14538 bool IsGlobal = !Var->hasLocalStorage(); 14539 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14540 return true; 14541 Var = Var->getCanonicalDecl(); 14542 14543 // Walk up the stack to determine whether we can capture the variable, 14544 // performing the "simple" checks that don't depend on type. We stop when 14545 // we've either hit the declared scope of the variable or find an existing 14546 // capture of that variable. We start from the innermost capturing-entity 14547 // (the DC) and ensure that all intervening capturing-entities 14548 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14549 // declcontext can either capture the variable or have already captured 14550 // the variable. 14551 CaptureType = Var->getType(); 14552 DeclRefType = CaptureType.getNonReferenceType(); 14553 bool Nested = false; 14554 bool Explicit = (Kind != TryCapture_Implicit); 14555 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14556 do { 14557 // Only block literals, captured statements, and lambda expressions can 14558 // capture; other scopes don't work. 14559 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14560 ExprLoc, 14561 BuildAndDiagnose, 14562 *this); 14563 // We need to check for the parent *first* because, if we *have* 14564 // private-captured a global variable, we need to recursively capture it in 14565 // intermediate blocks, lambdas, etc. 14566 if (!ParentDC) { 14567 if (IsGlobal) { 14568 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14569 break; 14570 } 14571 return true; 14572 } 14573 14574 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14575 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14576 14577 14578 // Check whether we've already captured it. 14579 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14580 DeclRefType)) { 14581 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14582 break; 14583 } 14584 // If we are instantiating a generic lambda call operator body, 14585 // we do not want to capture new variables. What was captured 14586 // during either a lambdas transformation or initial parsing 14587 // should be used. 14588 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14589 if (BuildAndDiagnose) { 14590 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14591 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14592 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14593 Diag(Var->getLocation(), diag::note_previous_decl) 14594 << Var->getDeclName(); 14595 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14596 } else 14597 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14598 } 14599 return true; 14600 } 14601 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14602 // certain types of variables (unnamed, variably modified types etc.) 14603 // so check for eligibility. 14604 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14605 return true; 14606 14607 // Try to capture variable-length arrays types. 14608 if (Var->getType()->isVariablyModifiedType()) { 14609 // We're going to walk down into the type and look for VLA 14610 // expressions. 14611 QualType QTy = Var->getType(); 14612 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14613 QTy = PVD->getOriginalType(); 14614 captureVariablyModifiedType(Context, QTy, CSI); 14615 } 14616 14617 if (getLangOpts().OpenMP) { 14618 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14619 // OpenMP private variables should not be captured in outer scope, so 14620 // just break here. Similarly, global variables that are captured in a 14621 // target region should not be captured outside the scope of the region. 14622 if (RSI->CapRegionKind == CR_OpenMP) { 14623 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14624 // When we detect target captures we are looking from inside the 14625 // target region, therefore we need to propagate the capture from the 14626 // enclosing region. Therefore, the capture is not initially nested. 14627 if (IsTargetCap) 14628 FunctionScopesIndex--; 14629 14630 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14631 Nested = !IsTargetCap; 14632 DeclRefType = DeclRefType.getUnqualifiedType(); 14633 CaptureType = Context.getLValueReferenceType(DeclRefType); 14634 break; 14635 } 14636 } 14637 } 14638 } 14639 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14640 // No capture-default, and this is not an explicit capture 14641 // so cannot capture this variable. 14642 if (BuildAndDiagnose) { 14643 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14644 Diag(Var->getLocation(), diag::note_previous_decl) 14645 << Var->getDeclName(); 14646 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14647 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14648 diag::note_lambda_decl); 14649 // FIXME: If we error out because an outer lambda can not implicitly 14650 // capture a variable that an inner lambda explicitly captures, we 14651 // should have the inner lambda do the explicit capture - because 14652 // it makes for cleaner diagnostics later. This would purely be done 14653 // so that the diagnostic does not misleadingly claim that a variable 14654 // can not be captured by a lambda implicitly even though it is captured 14655 // explicitly. Suggestion: 14656 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14657 // at the function head 14658 // - cache the StartingDeclContext - this must be a lambda 14659 // - captureInLambda in the innermost lambda the variable. 14660 } 14661 return true; 14662 } 14663 14664 FunctionScopesIndex--; 14665 DC = ParentDC; 14666 Explicit = false; 14667 } while (!VarDC->Equals(DC)); 14668 14669 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14670 // computing the type of the capture at each step, checking type-specific 14671 // requirements, and adding captures if requested. 14672 // If the variable had already been captured previously, we start capturing 14673 // at the lambda nested within that one. 14674 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14675 ++I) { 14676 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14677 14678 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14679 if (!captureInBlock(BSI, Var, ExprLoc, 14680 BuildAndDiagnose, CaptureType, 14681 DeclRefType, Nested, *this)) 14682 return true; 14683 Nested = true; 14684 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14685 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14686 BuildAndDiagnose, CaptureType, 14687 DeclRefType, Nested, *this)) 14688 return true; 14689 Nested = true; 14690 } else { 14691 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14692 if (!captureInLambda(LSI, Var, ExprLoc, 14693 BuildAndDiagnose, CaptureType, 14694 DeclRefType, Nested, Kind, EllipsisLoc, 14695 /*IsTopScope*/I == N - 1, *this)) 14696 return true; 14697 Nested = true; 14698 } 14699 } 14700 return false; 14701 } 14702 14703 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14704 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14705 QualType CaptureType; 14706 QualType DeclRefType; 14707 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14708 /*BuildAndDiagnose=*/true, CaptureType, 14709 DeclRefType, nullptr); 14710 } 14711 14712 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14713 QualType CaptureType; 14714 QualType DeclRefType; 14715 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14716 /*BuildAndDiagnose=*/false, CaptureType, 14717 DeclRefType, nullptr); 14718 } 14719 14720 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14721 QualType CaptureType; 14722 QualType DeclRefType; 14723 14724 // Determine whether we can capture this variable. 14725 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14726 /*BuildAndDiagnose=*/false, CaptureType, 14727 DeclRefType, nullptr)) 14728 return QualType(); 14729 14730 return DeclRefType; 14731 } 14732 14733 14734 14735 // If either the type of the variable or the initializer is dependent, 14736 // return false. Otherwise, determine whether the variable is a constant 14737 // expression. Use this if you need to know if a variable that might or 14738 // might not be dependent is truly a constant expression. 14739 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14740 ASTContext &Context) { 14741 14742 if (Var->getType()->isDependentType()) 14743 return false; 14744 const VarDecl *DefVD = nullptr; 14745 Var->getAnyInitializer(DefVD); 14746 if (!DefVD) 14747 return false; 14748 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14749 Expr *Init = cast<Expr>(Eval->Value); 14750 if (Init->isValueDependent()) 14751 return false; 14752 return IsVariableAConstantExpression(Var, Context); 14753 } 14754 14755 14756 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14757 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14758 // an object that satisfies the requirements for appearing in a 14759 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14760 // is immediately applied." This function handles the lvalue-to-rvalue 14761 // conversion part. 14762 MaybeODRUseExprs.erase(E->IgnoreParens()); 14763 14764 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14765 // to a variable that is a constant expression, and if so, identify it as 14766 // a reference to a variable that does not involve an odr-use of that 14767 // variable. 14768 if (LambdaScopeInfo *LSI = getCurLambda()) { 14769 Expr *SansParensExpr = E->IgnoreParens(); 14770 VarDecl *Var = nullptr; 14771 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14772 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14773 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14774 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14775 14776 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14777 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14778 } 14779 } 14780 14781 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14782 Res = CorrectDelayedTyposInExpr(Res); 14783 14784 if (!Res.isUsable()) 14785 return Res; 14786 14787 // If a constant-expression is a reference to a variable where we delay 14788 // deciding whether it is an odr-use, just assume we will apply the 14789 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14790 // (a non-type template argument), we have special handling anyway. 14791 UpdateMarkingForLValueToRValue(Res.get()); 14792 return Res; 14793 } 14794 14795 void Sema::CleanupVarDeclMarking() { 14796 for (Expr *E : MaybeODRUseExprs) { 14797 VarDecl *Var; 14798 SourceLocation Loc; 14799 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14800 Var = cast<VarDecl>(DRE->getDecl()); 14801 Loc = DRE->getLocation(); 14802 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14803 Var = cast<VarDecl>(ME->getMemberDecl()); 14804 Loc = ME->getMemberLoc(); 14805 } else { 14806 llvm_unreachable("Unexpected expression"); 14807 } 14808 14809 MarkVarDeclODRUsed(Var, Loc, *this, 14810 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14811 } 14812 14813 MaybeODRUseExprs.clear(); 14814 } 14815 14816 14817 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14818 VarDecl *Var, Expr *E) { 14819 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14820 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14821 Var->setReferenced(); 14822 14823 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14824 14825 bool OdrUseContext = isOdrUseContext(SemaRef); 14826 bool UsableInConstantExpr = 14827 Var->isUsableInConstantExpressions(SemaRef.Context); 14828 bool NeedDefinition = 14829 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14830 14831 VarTemplateSpecializationDecl *VarSpec = 14832 dyn_cast<VarTemplateSpecializationDecl>(Var); 14833 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14834 "Can't instantiate a partial template specialization."); 14835 14836 // If this might be a member specialization of a static data member, check 14837 // the specialization is visible. We already did the checks for variable 14838 // template specializations when we created them. 14839 if (NeedDefinition && TSK != TSK_Undeclared && 14840 !isa<VarTemplateSpecializationDecl>(Var)) 14841 SemaRef.checkSpecializationVisibility(Loc, Var); 14842 14843 // Perform implicit instantiation of static data members, static data member 14844 // templates of class templates, and variable template specializations. Delay 14845 // instantiations of variable templates, except for those that could be used 14846 // in a constant expression. 14847 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14848 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14849 // instantiation declaration if a variable is usable in a constant 14850 // expression (among other cases). 14851 bool TryInstantiating = 14852 TSK == TSK_ImplicitInstantiation || 14853 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14854 14855 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14856 if (Var->getPointOfInstantiation().isInvalid()) { 14857 // This is a modification of an existing AST node. Notify listeners. 14858 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14859 L->StaticDataMemberInstantiated(Var); 14860 } else if (!UsableInConstantExpr) 14861 // Don't bother trying to instantiate it again, unless we might need 14862 // its initializer before we get to the end of the TU. 14863 TryInstantiating = false; 14864 } 14865 14866 if (Var->getPointOfInstantiation().isInvalid()) 14867 Var->setTemplateSpecializationKind(TSK, Loc); 14868 14869 if (TryInstantiating) { 14870 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14871 bool InstantiationDependent = false; 14872 bool IsNonDependent = 14873 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14874 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14875 : true; 14876 14877 // Do not instantiate specializations that are still type-dependent. 14878 if (IsNonDependent) { 14879 if (UsableInConstantExpr) { 14880 // Do not defer instantiations of variables which could be used in a 14881 // constant expression. 14882 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14883 } else { 14884 SemaRef.PendingInstantiations 14885 .push_back(std::make_pair(Var, PointOfInstantiation)); 14886 } 14887 } 14888 } 14889 } 14890 14891 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14892 // the requirements for appearing in a constant expression (5.19) and, if 14893 // it is an object, the lvalue-to-rvalue conversion (4.1) 14894 // is immediately applied." We check the first part here, and 14895 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14896 // Note that we use the C++11 definition everywhere because nothing in 14897 // C++03 depends on whether we get the C++03 version correct. The second 14898 // part does not apply to references, since they are not objects. 14899 if (OdrUseContext && E && 14900 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14901 // A reference initialized by a constant expression can never be 14902 // odr-used, so simply ignore it. 14903 if (!Var->getType()->isReferenceType() || 14904 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14905 SemaRef.MaybeODRUseExprs.insert(E); 14906 } else if (OdrUseContext) { 14907 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14908 /*MaxFunctionScopeIndex ptr*/ nullptr); 14909 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14910 // If this is a dependent context, we don't need to mark variables as 14911 // odr-used, but we may still need to track them for lambda capture. 14912 // FIXME: Do we also need to do this inside dependent typeid expressions 14913 // (which are modeled as unevaluated at this point)? 14914 const bool RefersToEnclosingScope = 14915 (SemaRef.CurContext != Var->getDeclContext() && 14916 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14917 if (RefersToEnclosingScope) { 14918 LambdaScopeInfo *const LSI = 14919 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14920 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14921 // If a variable could potentially be odr-used, defer marking it so 14922 // until we finish analyzing the full expression for any 14923 // lvalue-to-rvalue 14924 // or discarded value conversions that would obviate odr-use. 14925 // Add it to the list of potential captures that will be analyzed 14926 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14927 // unless the variable is a reference that was initialized by a constant 14928 // expression (this will never need to be captured or odr-used). 14929 assert(E && "Capture variable should be used in an expression."); 14930 if (!Var->getType()->isReferenceType() || 14931 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14932 LSI->addPotentialCapture(E->IgnoreParens()); 14933 } 14934 } 14935 } 14936 } 14937 14938 /// \brief Mark a variable referenced, and check whether it is odr-used 14939 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14940 /// used directly for normal expressions referring to VarDecl. 14941 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14942 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14943 } 14944 14945 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14946 Decl *D, Expr *E, bool MightBeOdrUse) { 14947 if (SemaRef.isInOpenMPDeclareTargetContext()) 14948 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14949 14950 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14951 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14952 return; 14953 } 14954 14955 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14956 14957 // If this is a call to a method via a cast, also mark the method in the 14958 // derived class used in case codegen can devirtualize the call. 14959 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14960 if (!ME) 14961 return; 14962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14963 if (!MD) 14964 return; 14965 // Only attempt to devirtualize if this is truly a virtual call. 14966 bool IsVirtualCall = MD->isVirtual() && 14967 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14968 if (!IsVirtualCall) 14969 return; 14970 14971 // If it's possible to devirtualize the call, mark the called function 14972 // referenced. 14973 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14974 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14975 if (DM) 14976 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14977 } 14978 14979 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14980 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14981 // TODO: update this with DR# once a defect report is filed. 14982 // C++11 defect. The address of a pure member should not be an ODR use, even 14983 // if it's a qualified reference. 14984 bool OdrUse = true; 14985 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14986 if (Method->isVirtual() && 14987 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14988 OdrUse = false; 14989 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14990 } 14991 14992 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14993 void Sema::MarkMemberReferenced(MemberExpr *E) { 14994 // C++11 [basic.def.odr]p2: 14995 // A non-overloaded function whose name appears as a potentially-evaluated 14996 // expression or a member of a set of candidate functions, if selected by 14997 // overload resolution when referred to from a potentially-evaluated 14998 // expression, is odr-used, unless it is a pure virtual function and its 14999 // name is not explicitly qualified. 15000 bool MightBeOdrUse = true; 15001 if (E->performsVirtualDispatch(getLangOpts())) { 15002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15003 if (Method->isPure()) 15004 MightBeOdrUse = false; 15005 } 15006 SourceLocation Loc = E->getMemberLoc().isValid() ? 15007 E->getMemberLoc() : E->getLocStart(); 15008 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15009 } 15010 15011 /// \brief Perform marking for a reference to an arbitrary declaration. It 15012 /// marks the declaration referenced, and performs odr-use checking for 15013 /// functions and variables. This method should not be used when building a 15014 /// normal expression which refers to a variable. 15015 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15016 bool MightBeOdrUse) { 15017 if (MightBeOdrUse) { 15018 if (auto *VD = dyn_cast<VarDecl>(D)) { 15019 MarkVariableReferenced(Loc, VD); 15020 return; 15021 } 15022 } 15023 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15024 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15025 return; 15026 } 15027 D->setReferenced(); 15028 } 15029 15030 namespace { 15031 // Mark all of the declarations used by a type as referenced. 15032 // FIXME: Not fully implemented yet! We need to have a better understanding 15033 // of when we're entering a context we should not recurse into. 15034 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15035 // TreeTransforms rebuilding the type in a new context. Rather than 15036 // duplicating the TreeTransform logic, we should consider reusing it here. 15037 // Currently that causes problems when rebuilding LambdaExprs. 15038 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15039 Sema &S; 15040 SourceLocation Loc; 15041 15042 public: 15043 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15044 15045 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15046 15047 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15048 }; 15049 } 15050 15051 bool MarkReferencedDecls::TraverseTemplateArgument( 15052 const TemplateArgument &Arg) { 15053 { 15054 // A non-type template argument is a constant-evaluated context. 15055 EnterExpressionEvaluationContext Evaluated( 15056 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15057 if (Arg.getKind() == TemplateArgument::Declaration) { 15058 if (Decl *D = Arg.getAsDecl()) 15059 S.MarkAnyDeclReferenced(Loc, D, true); 15060 } else if (Arg.getKind() == TemplateArgument::Expression) { 15061 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15062 } 15063 } 15064 15065 return Inherited::TraverseTemplateArgument(Arg); 15066 } 15067 15068 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15069 MarkReferencedDecls Marker(*this, Loc); 15070 Marker.TraverseType(T); 15071 } 15072 15073 namespace { 15074 /// \brief Helper class that marks all of the declarations referenced by 15075 /// potentially-evaluated subexpressions as "referenced". 15076 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15077 Sema &S; 15078 bool SkipLocalVariables; 15079 15080 public: 15081 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15082 15083 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15084 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15085 15086 void VisitDeclRefExpr(DeclRefExpr *E) { 15087 // If we were asked not to visit local variables, don't. 15088 if (SkipLocalVariables) { 15089 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15090 if (VD->hasLocalStorage()) 15091 return; 15092 } 15093 15094 S.MarkDeclRefReferenced(E); 15095 } 15096 15097 void VisitMemberExpr(MemberExpr *E) { 15098 S.MarkMemberReferenced(E); 15099 Inherited::VisitMemberExpr(E); 15100 } 15101 15102 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15103 S.MarkFunctionReferenced(E->getLocStart(), 15104 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15105 Visit(E->getSubExpr()); 15106 } 15107 15108 void VisitCXXNewExpr(CXXNewExpr *E) { 15109 if (E->getOperatorNew()) 15110 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15111 if (E->getOperatorDelete()) 15112 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15113 Inherited::VisitCXXNewExpr(E); 15114 } 15115 15116 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15117 if (E->getOperatorDelete()) 15118 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15119 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15120 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15121 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15122 S.MarkFunctionReferenced(E->getLocStart(), 15123 S.LookupDestructor(Record)); 15124 } 15125 15126 Inherited::VisitCXXDeleteExpr(E); 15127 } 15128 15129 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15130 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15131 Inherited::VisitCXXConstructExpr(E); 15132 } 15133 15134 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15135 Visit(E->getExpr()); 15136 } 15137 15138 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15139 Inherited::VisitImplicitCastExpr(E); 15140 15141 if (E->getCastKind() == CK_LValueToRValue) 15142 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15143 } 15144 }; 15145 } 15146 15147 /// \brief Mark any declarations that appear within this expression or any 15148 /// potentially-evaluated subexpressions as "referenced". 15149 /// 15150 /// \param SkipLocalVariables If true, don't mark local variables as 15151 /// 'referenced'. 15152 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15153 bool SkipLocalVariables) { 15154 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15155 } 15156 15157 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15158 /// of the program being compiled. 15159 /// 15160 /// This routine emits the given diagnostic when the code currently being 15161 /// type-checked is "potentially evaluated", meaning that there is a 15162 /// possibility that the code will actually be executable. Code in sizeof() 15163 /// expressions, code used only during overload resolution, etc., are not 15164 /// potentially evaluated. This routine will suppress such diagnostics or, 15165 /// in the absolutely nutty case of potentially potentially evaluated 15166 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15167 /// later. 15168 /// 15169 /// This routine should be used for all diagnostics that describe the run-time 15170 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15171 /// Failure to do so will likely result in spurious diagnostics or failures 15172 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15173 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15174 const PartialDiagnostic &PD) { 15175 switch (ExprEvalContexts.back().Context) { 15176 case ExpressionEvaluationContext::Unevaluated: 15177 case ExpressionEvaluationContext::UnevaluatedList: 15178 case ExpressionEvaluationContext::UnevaluatedAbstract: 15179 case ExpressionEvaluationContext::DiscardedStatement: 15180 // The argument will never be evaluated, so don't complain. 15181 break; 15182 15183 case ExpressionEvaluationContext::ConstantEvaluated: 15184 // Relevant diagnostics should be produced by constant evaluation. 15185 break; 15186 15187 case ExpressionEvaluationContext::PotentiallyEvaluated: 15188 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15189 if (Statement && getCurFunctionOrMethodDecl()) { 15190 FunctionScopes.back()->PossiblyUnreachableDiags. 15191 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15192 return true; 15193 } 15194 15195 // The initializer of a constexpr variable or of the first declaration of a 15196 // static data member is not syntactically a constant evaluated constant, 15197 // but nonetheless is always required to be a constant expression, so we 15198 // can skip diagnosing. 15199 // FIXME: Using the mangling context here is a hack. 15200 if (auto *VD = dyn_cast_or_null<VarDecl>( 15201 ExprEvalContexts.back().ManglingContextDecl)) { 15202 if (VD->isConstexpr() || 15203 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15204 break; 15205 // FIXME: For any other kind of variable, we should build a CFG for its 15206 // initializer and check whether the context in question is reachable. 15207 } 15208 15209 Diag(Loc, PD); 15210 return true; 15211 } 15212 15213 return false; 15214 } 15215 15216 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15217 CallExpr *CE, FunctionDecl *FD) { 15218 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15219 return false; 15220 15221 // If we're inside a decltype's expression, don't check for a valid return 15222 // type or construct temporaries until we know whether this is the last call. 15223 if (ExprEvalContexts.back().IsDecltype) { 15224 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15225 return false; 15226 } 15227 15228 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15229 FunctionDecl *FD; 15230 CallExpr *CE; 15231 15232 public: 15233 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15234 : FD(FD), CE(CE) { } 15235 15236 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15237 if (!FD) { 15238 S.Diag(Loc, diag::err_call_incomplete_return) 15239 << T << CE->getSourceRange(); 15240 return; 15241 } 15242 15243 S.Diag(Loc, diag::err_call_function_incomplete_return) 15244 << CE->getSourceRange() << FD->getDeclName() << T; 15245 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15246 << FD->getDeclName(); 15247 } 15248 } Diagnoser(FD, CE); 15249 15250 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15251 return true; 15252 15253 return false; 15254 } 15255 15256 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15257 // will prevent this condition from triggering, which is what we want. 15258 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15259 SourceLocation Loc; 15260 15261 unsigned diagnostic = diag::warn_condition_is_assignment; 15262 bool IsOrAssign = false; 15263 15264 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15265 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15266 return; 15267 15268 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15269 15270 // Greylist some idioms by putting them into a warning subcategory. 15271 if (ObjCMessageExpr *ME 15272 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15273 Selector Sel = ME->getSelector(); 15274 15275 // self = [<foo> init...] 15276 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15277 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15278 15279 // <foo> = [<bar> nextObject] 15280 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15281 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15282 } 15283 15284 Loc = Op->getOperatorLoc(); 15285 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15286 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15287 return; 15288 15289 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15290 Loc = Op->getOperatorLoc(); 15291 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15292 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15293 else { 15294 // Not an assignment. 15295 return; 15296 } 15297 15298 Diag(Loc, diagnostic) << E->getSourceRange(); 15299 15300 SourceLocation Open = E->getLocStart(); 15301 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15302 Diag(Loc, diag::note_condition_assign_silence) 15303 << FixItHint::CreateInsertion(Open, "(") 15304 << FixItHint::CreateInsertion(Close, ")"); 15305 15306 if (IsOrAssign) 15307 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15308 << FixItHint::CreateReplacement(Loc, "!="); 15309 else 15310 Diag(Loc, diag::note_condition_assign_to_comparison) 15311 << FixItHint::CreateReplacement(Loc, "=="); 15312 } 15313 15314 /// \brief Redundant parentheses over an equality comparison can indicate 15315 /// that the user intended an assignment used as condition. 15316 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15317 // Don't warn if the parens came from a macro. 15318 SourceLocation parenLoc = ParenE->getLocStart(); 15319 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15320 return; 15321 // Don't warn for dependent expressions. 15322 if (ParenE->isTypeDependent()) 15323 return; 15324 15325 Expr *E = ParenE->IgnoreParens(); 15326 15327 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15328 if (opE->getOpcode() == BO_EQ && 15329 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15330 == Expr::MLV_Valid) { 15331 SourceLocation Loc = opE->getOperatorLoc(); 15332 15333 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15334 SourceRange ParenERange = ParenE->getSourceRange(); 15335 Diag(Loc, diag::note_equality_comparison_silence) 15336 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15337 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15338 Diag(Loc, diag::note_equality_comparison_to_assign) 15339 << FixItHint::CreateReplacement(Loc, "="); 15340 } 15341 } 15342 15343 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15344 bool IsConstexpr) { 15345 DiagnoseAssignmentAsCondition(E); 15346 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15347 DiagnoseEqualityWithExtraParens(parenE); 15348 15349 ExprResult result = CheckPlaceholderExpr(E); 15350 if (result.isInvalid()) return ExprError(); 15351 E = result.get(); 15352 15353 if (!E->isTypeDependent()) { 15354 if (getLangOpts().CPlusPlus) 15355 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15356 15357 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15358 if (ERes.isInvalid()) 15359 return ExprError(); 15360 E = ERes.get(); 15361 15362 QualType T = E->getType(); 15363 if (!T->isScalarType()) { // C99 6.8.4.1p1 15364 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15365 << T << E->getSourceRange(); 15366 return ExprError(); 15367 } 15368 CheckBoolLikeConversion(E, Loc); 15369 } 15370 15371 return E; 15372 } 15373 15374 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15375 Expr *SubExpr, ConditionKind CK) { 15376 // Empty conditions are valid in for-statements. 15377 if (!SubExpr) 15378 return ConditionResult(); 15379 15380 ExprResult Cond; 15381 switch (CK) { 15382 case ConditionKind::Boolean: 15383 Cond = CheckBooleanCondition(Loc, SubExpr); 15384 break; 15385 15386 case ConditionKind::ConstexprIf: 15387 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15388 break; 15389 15390 case ConditionKind::Switch: 15391 Cond = CheckSwitchCondition(Loc, SubExpr); 15392 break; 15393 } 15394 if (Cond.isInvalid()) 15395 return ConditionError(); 15396 15397 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15398 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15399 if (!FullExpr.get()) 15400 return ConditionError(); 15401 15402 return ConditionResult(*this, nullptr, FullExpr, 15403 CK == ConditionKind::ConstexprIf); 15404 } 15405 15406 namespace { 15407 /// A visitor for rebuilding a call to an __unknown_any expression 15408 /// to have an appropriate type. 15409 struct RebuildUnknownAnyFunction 15410 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15411 15412 Sema &S; 15413 15414 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15415 15416 ExprResult VisitStmt(Stmt *S) { 15417 llvm_unreachable("unexpected statement!"); 15418 } 15419 15420 ExprResult VisitExpr(Expr *E) { 15421 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15422 << E->getSourceRange(); 15423 return ExprError(); 15424 } 15425 15426 /// Rebuild an expression which simply semantically wraps another 15427 /// expression which it shares the type and value kind of. 15428 template <class T> ExprResult rebuildSugarExpr(T *E) { 15429 ExprResult SubResult = Visit(E->getSubExpr()); 15430 if (SubResult.isInvalid()) return ExprError(); 15431 15432 Expr *SubExpr = SubResult.get(); 15433 E->setSubExpr(SubExpr); 15434 E->setType(SubExpr->getType()); 15435 E->setValueKind(SubExpr->getValueKind()); 15436 assert(E->getObjectKind() == OK_Ordinary); 15437 return E; 15438 } 15439 15440 ExprResult VisitParenExpr(ParenExpr *E) { 15441 return rebuildSugarExpr(E); 15442 } 15443 15444 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15445 return rebuildSugarExpr(E); 15446 } 15447 15448 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15449 ExprResult SubResult = Visit(E->getSubExpr()); 15450 if (SubResult.isInvalid()) return ExprError(); 15451 15452 Expr *SubExpr = SubResult.get(); 15453 E->setSubExpr(SubExpr); 15454 E->setType(S.Context.getPointerType(SubExpr->getType())); 15455 assert(E->getValueKind() == VK_RValue); 15456 assert(E->getObjectKind() == OK_Ordinary); 15457 return E; 15458 } 15459 15460 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15461 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15462 15463 E->setType(VD->getType()); 15464 15465 assert(E->getValueKind() == VK_RValue); 15466 if (S.getLangOpts().CPlusPlus && 15467 !(isa<CXXMethodDecl>(VD) && 15468 cast<CXXMethodDecl>(VD)->isInstance())) 15469 E->setValueKind(VK_LValue); 15470 15471 return E; 15472 } 15473 15474 ExprResult VisitMemberExpr(MemberExpr *E) { 15475 return resolveDecl(E, E->getMemberDecl()); 15476 } 15477 15478 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15479 return resolveDecl(E, E->getDecl()); 15480 } 15481 }; 15482 } 15483 15484 /// Given a function expression of unknown-any type, try to rebuild it 15485 /// to have a function type. 15486 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15487 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15488 if (Result.isInvalid()) return ExprError(); 15489 return S.DefaultFunctionArrayConversion(Result.get()); 15490 } 15491 15492 namespace { 15493 /// A visitor for rebuilding an expression of type __unknown_anytype 15494 /// into one which resolves the type directly on the referring 15495 /// expression. Strict preservation of the original source 15496 /// structure is not a goal. 15497 struct RebuildUnknownAnyExpr 15498 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15499 15500 Sema &S; 15501 15502 /// The current destination type. 15503 QualType DestType; 15504 15505 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15506 : S(S), DestType(CastType) {} 15507 15508 ExprResult VisitStmt(Stmt *S) { 15509 llvm_unreachable("unexpected statement!"); 15510 } 15511 15512 ExprResult VisitExpr(Expr *E) { 15513 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15514 << E->getSourceRange(); 15515 return ExprError(); 15516 } 15517 15518 ExprResult VisitCallExpr(CallExpr *E); 15519 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15520 15521 /// Rebuild an expression which simply semantically wraps another 15522 /// expression which it shares the type and value kind of. 15523 template <class T> ExprResult rebuildSugarExpr(T *E) { 15524 ExprResult SubResult = Visit(E->getSubExpr()); 15525 if (SubResult.isInvalid()) return ExprError(); 15526 Expr *SubExpr = SubResult.get(); 15527 E->setSubExpr(SubExpr); 15528 E->setType(SubExpr->getType()); 15529 E->setValueKind(SubExpr->getValueKind()); 15530 assert(E->getObjectKind() == OK_Ordinary); 15531 return E; 15532 } 15533 15534 ExprResult VisitParenExpr(ParenExpr *E) { 15535 return rebuildSugarExpr(E); 15536 } 15537 15538 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15539 return rebuildSugarExpr(E); 15540 } 15541 15542 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15543 const PointerType *Ptr = DestType->getAs<PointerType>(); 15544 if (!Ptr) { 15545 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15546 << E->getSourceRange(); 15547 return ExprError(); 15548 } 15549 15550 if (isa<CallExpr>(E->getSubExpr())) { 15551 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15552 << E->getSourceRange(); 15553 return ExprError(); 15554 } 15555 15556 assert(E->getValueKind() == VK_RValue); 15557 assert(E->getObjectKind() == OK_Ordinary); 15558 E->setType(DestType); 15559 15560 // Build the sub-expression as if it were an object of the pointee type. 15561 DestType = Ptr->getPointeeType(); 15562 ExprResult SubResult = Visit(E->getSubExpr()); 15563 if (SubResult.isInvalid()) return ExprError(); 15564 E->setSubExpr(SubResult.get()); 15565 return E; 15566 } 15567 15568 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15569 15570 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15571 15572 ExprResult VisitMemberExpr(MemberExpr *E) { 15573 return resolveDecl(E, E->getMemberDecl()); 15574 } 15575 15576 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15577 return resolveDecl(E, E->getDecl()); 15578 } 15579 }; 15580 } 15581 15582 /// Rebuilds a call expression which yielded __unknown_anytype. 15583 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15584 Expr *CalleeExpr = E->getCallee(); 15585 15586 enum FnKind { 15587 FK_MemberFunction, 15588 FK_FunctionPointer, 15589 FK_BlockPointer 15590 }; 15591 15592 FnKind Kind; 15593 QualType CalleeType = CalleeExpr->getType(); 15594 if (CalleeType == S.Context.BoundMemberTy) { 15595 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15596 Kind = FK_MemberFunction; 15597 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15598 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15599 CalleeType = Ptr->getPointeeType(); 15600 Kind = FK_FunctionPointer; 15601 } else { 15602 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15603 Kind = FK_BlockPointer; 15604 } 15605 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15606 15607 // Verify that this is a legal result type of a function. 15608 if (DestType->isArrayType() || DestType->isFunctionType()) { 15609 unsigned diagID = diag::err_func_returning_array_function; 15610 if (Kind == FK_BlockPointer) 15611 diagID = diag::err_block_returning_array_function; 15612 15613 S.Diag(E->getExprLoc(), diagID) 15614 << DestType->isFunctionType() << DestType; 15615 return ExprError(); 15616 } 15617 15618 // Otherwise, go ahead and set DestType as the call's result. 15619 E->setType(DestType.getNonLValueExprType(S.Context)); 15620 E->setValueKind(Expr::getValueKindForType(DestType)); 15621 assert(E->getObjectKind() == OK_Ordinary); 15622 15623 // Rebuild the function type, replacing the result type with DestType. 15624 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15625 if (Proto) { 15626 // __unknown_anytype(...) is a special case used by the debugger when 15627 // it has no idea what a function's signature is. 15628 // 15629 // We want to build this call essentially under the K&R 15630 // unprototyped rules, but making a FunctionNoProtoType in C++ 15631 // would foul up all sorts of assumptions. However, we cannot 15632 // simply pass all arguments as variadic arguments, nor can we 15633 // portably just call the function under a non-variadic type; see 15634 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15635 // However, it turns out that in practice it is generally safe to 15636 // call a function declared as "A foo(B,C,D);" under the prototype 15637 // "A foo(B,C,D,...);". The only known exception is with the 15638 // Windows ABI, where any variadic function is implicitly cdecl 15639 // regardless of its normal CC. Therefore we change the parameter 15640 // types to match the types of the arguments. 15641 // 15642 // This is a hack, but it is far superior to moving the 15643 // corresponding target-specific code from IR-gen to Sema/AST. 15644 15645 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15646 SmallVector<QualType, 8> ArgTypes; 15647 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15648 ArgTypes.reserve(E->getNumArgs()); 15649 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15650 Expr *Arg = E->getArg(i); 15651 QualType ArgType = Arg->getType(); 15652 if (E->isLValue()) { 15653 ArgType = S.Context.getLValueReferenceType(ArgType); 15654 } else if (E->isXValue()) { 15655 ArgType = S.Context.getRValueReferenceType(ArgType); 15656 } 15657 ArgTypes.push_back(ArgType); 15658 } 15659 ParamTypes = ArgTypes; 15660 } 15661 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15662 Proto->getExtProtoInfo()); 15663 } else { 15664 DestType = S.Context.getFunctionNoProtoType(DestType, 15665 FnType->getExtInfo()); 15666 } 15667 15668 // Rebuild the appropriate pointer-to-function type. 15669 switch (Kind) { 15670 case FK_MemberFunction: 15671 // Nothing to do. 15672 break; 15673 15674 case FK_FunctionPointer: 15675 DestType = S.Context.getPointerType(DestType); 15676 break; 15677 15678 case FK_BlockPointer: 15679 DestType = S.Context.getBlockPointerType(DestType); 15680 break; 15681 } 15682 15683 // Finally, we can recurse. 15684 ExprResult CalleeResult = Visit(CalleeExpr); 15685 if (!CalleeResult.isUsable()) return ExprError(); 15686 E->setCallee(CalleeResult.get()); 15687 15688 // Bind a temporary if necessary. 15689 return S.MaybeBindToTemporary(E); 15690 } 15691 15692 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15693 // Verify that this is a legal result type of a call. 15694 if (DestType->isArrayType() || DestType->isFunctionType()) { 15695 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15696 << DestType->isFunctionType() << DestType; 15697 return ExprError(); 15698 } 15699 15700 // Rewrite the method result type if available. 15701 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15702 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15703 Method->setReturnType(DestType); 15704 } 15705 15706 // Change the type of the message. 15707 E->setType(DestType.getNonReferenceType()); 15708 E->setValueKind(Expr::getValueKindForType(DestType)); 15709 15710 return S.MaybeBindToTemporary(E); 15711 } 15712 15713 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15714 // The only case we should ever see here is a function-to-pointer decay. 15715 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15716 assert(E->getValueKind() == VK_RValue); 15717 assert(E->getObjectKind() == OK_Ordinary); 15718 15719 E->setType(DestType); 15720 15721 // Rebuild the sub-expression as the pointee (function) type. 15722 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15723 15724 ExprResult Result = Visit(E->getSubExpr()); 15725 if (!Result.isUsable()) return ExprError(); 15726 15727 E->setSubExpr(Result.get()); 15728 return E; 15729 } else if (E->getCastKind() == CK_LValueToRValue) { 15730 assert(E->getValueKind() == VK_RValue); 15731 assert(E->getObjectKind() == OK_Ordinary); 15732 15733 assert(isa<BlockPointerType>(E->getType())); 15734 15735 E->setType(DestType); 15736 15737 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15738 DestType = S.Context.getLValueReferenceType(DestType); 15739 15740 ExprResult Result = Visit(E->getSubExpr()); 15741 if (!Result.isUsable()) return ExprError(); 15742 15743 E->setSubExpr(Result.get()); 15744 return E; 15745 } else { 15746 llvm_unreachable("Unhandled cast type!"); 15747 } 15748 } 15749 15750 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15751 ExprValueKind ValueKind = VK_LValue; 15752 QualType Type = DestType; 15753 15754 // We know how to make this work for certain kinds of decls: 15755 15756 // - functions 15757 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15758 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15759 DestType = Ptr->getPointeeType(); 15760 ExprResult Result = resolveDecl(E, VD); 15761 if (Result.isInvalid()) return ExprError(); 15762 return S.ImpCastExprToType(Result.get(), Type, 15763 CK_FunctionToPointerDecay, VK_RValue); 15764 } 15765 15766 if (!Type->isFunctionType()) { 15767 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15768 << VD << E->getSourceRange(); 15769 return ExprError(); 15770 } 15771 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15772 // We must match the FunctionDecl's type to the hack introduced in 15773 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15774 // type. See the lengthy commentary in that routine. 15775 QualType FDT = FD->getType(); 15776 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15777 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15778 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15779 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15780 SourceLocation Loc = FD->getLocation(); 15781 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15782 FD->getDeclContext(), 15783 Loc, Loc, FD->getNameInfo().getName(), 15784 DestType, FD->getTypeSourceInfo(), 15785 SC_None, false/*isInlineSpecified*/, 15786 FD->hasPrototype(), 15787 false/*isConstexprSpecified*/); 15788 15789 if (FD->getQualifier()) 15790 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15791 15792 SmallVector<ParmVarDecl*, 16> Params; 15793 for (const auto &AI : FT->param_types()) { 15794 ParmVarDecl *Param = 15795 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15796 Param->setScopeInfo(0, Params.size()); 15797 Params.push_back(Param); 15798 } 15799 NewFD->setParams(Params); 15800 DRE->setDecl(NewFD); 15801 VD = DRE->getDecl(); 15802 } 15803 } 15804 15805 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15806 if (MD->isInstance()) { 15807 ValueKind = VK_RValue; 15808 Type = S.Context.BoundMemberTy; 15809 } 15810 15811 // Function references aren't l-values in C. 15812 if (!S.getLangOpts().CPlusPlus) 15813 ValueKind = VK_RValue; 15814 15815 // - variables 15816 } else if (isa<VarDecl>(VD)) { 15817 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15818 Type = RefTy->getPointeeType(); 15819 } else if (Type->isFunctionType()) { 15820 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15821 << VD << E->getSourceRange(); 15822 return ExprError(); 15823 } 15824 15825 // - nothing else 15826 } else { 15827 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15828 << VD << E->getSourceRange(); 15829 return ExprError(); 15830 } 15831 15832 // Modifying the declaration like this is friendly to IR-gen but 15833 // also really dangerous. 15834 VD->setType(DestType); 15835 E->setType(Type); 15836 E->setValueKind(ValueKind); 15837 return E; 15838 } 15839 15840 /// Check a cast of an unknown-any type. We intentionally only 15841 /// trigger this for C-style casts. 15842 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15843 Expr *CastExpr, CastKind &CastKind, 15844 ExprValueKind &VK, CXXCastPath &Path) { 15845 // The type we're casting to must be either void or complete. 15846 if (!CastType->isVoidType() && 15847 RequireCompleteType(TypeRange.getBegin(), CastType, 15848 diag::err_typecheck_cast_to_incomplete)) 15849 return ExprError(); 15850 15851 // Rewrite the casted expression from scratch. 15852 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15853 if (!result.isUsable()) return ExprError(); 15854 15855 CastExpr = result.get(); 15856 VK = CastExpr->getValueKind(); 15857 CastKind = CK_NoOp; 15858 15859 return CastExpr; 15860 } 15861 15862 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15863 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15864 } 15865 15866 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15867 Expr *arg, QualType ¶mType) { 15868 // If the syntactic form of the argument is not an explicit cast of 15869 // any sort, just do default argument promotion. 15870 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15871 if (!castArg) { 15872 ExprResult result = DefaultArgumentPromotion(arg); 15873 if (result.isInvalid()) return ExprError(); 15874 paramType = result.get()->getType(); 15875 return result; 15876 } 15877 15878 // Otherwise, use the type that was written in the explicit cast. 15879 assert(!arg->hasPlaceholderType()); 15880 paramType = castArg->getTypeAsWritten(); 15881 15882 // Copy-initialize a parameter of that type. 15883 InitializedEntity entity = 15884 InitializedEntity::InitializeParameter(Context, paramType, 15885 /*consumed*/ false); 15886 return PerformCopyInitialization(entity, callLoc, arg); 15887 } 15888 15889 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15890 Expr *orig = E; 15891 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15892 while (true) { 15893 E = E->IgnoreParenImpCasts(); 15894 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15895 E = call->getCallee(); 15896 diagID = diag::err_uncasted_call_of_unknown_any; 15897 } else { 15898 break; 15899 } 15900 } 15901 15902 SourceLocation loc; 15903 NamedDecl *d; 15904 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15905 loc = ref->getLocation(); 15906 d = ref->getDecl(); 15907 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15908 loc = mem->getMemberLoc(); 15909 d = mem->getMemberDecl(); 15910 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15911 diagID = diag::err_uncasted_call_of_unknown_any; 15912 loc = msg->getSelectorStartLoc(); 15913 d = msg->getMethodDecl(); 15914 if (!d) { 15915 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15916 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15917 << orig->getSourceRange(); 15918 return ExprError(); 15919 } 15920 } else { 15921 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15922 << E->getSourceRange(); 15923 return ExprError(); 15924 } 15925 15926 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15927 15928 // Never recoverable. 15929 return ExprError(); 15930 } 15931 15932 /// Check for operands with placeholder types and complain if found. 15933 /// Returns ExprError() if there was an error and no recovery was possible. 15934 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15935 if (!getLangOpts().CPlusPlus) { 15936 // C cannot handle TypoExpr nodes on either side of a binop because it 15937 // doesn't handle dependent types properly, so make sure any TypoExprs have 15938 // been dealt with before checking the operands. 15939 ExprResult Result = CorrectDelayedTyposInExpr(E); 15940 if (!Result.isUsable()) return ExprError(); 15941 E = Result.get(); 15942 } 15943 15944 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15945 if (!placeholderType) return E; 15946 15947 switch (placeholderType->getKind()) { 15948 15949 // Overloaded expressions. 15950 case BuiltinType::Overload: { 15951 // Try to resolve a single function template specialization. 15952 // This is obligatory. 15953 ExprResult Result = E; 15954 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15955 return Result; 15956 15957 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15958 // leaves Result unchanged on failure. 15959 Result = E; 15960 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15961 return Result; 15962 15963 // If that failed, try to recover with a call. 15964 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15965 /*complain*/ true); 15966 return Result; 15967 } 15968 15969 // Bound member functions. 15970 case BuiltinType::BoundMember: { 15971 ExprResult result = E; 15972 const Expr *BME = E->IgnoreParens(); 15973 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15974 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15975 if (isa<CXXPseudoDestructorExpr>(BME)) { 15976 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15977 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15978 if (ME->getMemberNameInfo().getName().getNameKind() == 15979 DeclarationName::CXXDestructorName) 15980 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15981 } 15982 tryToRecoverWithCall(result, PD, 15983 /*complain*/ true); 15984 return result; 15985 } 15986 15987 // ARC unbridged casts. 15988 case BuiltinType::ARCUnbridgedCast: { 15989 Expr *realCast = stripARCUnbridgedCast(E); 15990 diagnoseARCUnbridgedCast(realCast); 15991 return realCast; 15992 } 15993 15994 // Expressions of unknown type. 15995 case BuiltinType::UnknownAny: 15996 return diagnoseUnknownAnyExpr(*this, E); 15997 15998 // Pseudo-objects. 15999 case BuiltinType::PseudoObject: 16000 return checkPseudoObjectRValue(E); 16001 16002 case BuiltinType::BuiltinFn: { 16003 // Accept __noop without parens by implicitly converting it to a call expr. 16004 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16005 if (DRE) { 16006 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16007 if (FD->getBuiltinID() == Builtin::BI__noop) { 16008 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16009 CK_BuiltinFnToFnPtr).get(); 16010 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16011 VK_RValue, SourceLocation()); 16012 } 16013 } 16014 16015 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16016 return ExprError(); 16017 } 16018 16019 // Expressions of unknown type. 16020 case BuiltinType::OMPArraySection: 16021 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16022 return ExprError(); 16023 16024 // Everything else should be impossible. 16025 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16026 case BuiltinType::Id: 16027 #include "clang/Basic/OpenCLImageTypes.def" 16028 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16029 #define PLACEHOLDER_TYPE(Id, SingletonId) 16030 #include "clang/AST/BuiltinTypes.def" 16031 break; 16032 } 16033 16034 llvm_unreachable("invalid placeholder type!"); 16035 } 16036 16037 bool Sema::CheckCaseExpression(Expr *E) { 16038 if (E->isTypeDependent()) 16039 return true; 16040 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16041 return E->getType()->isIntegralOrEnumerationType(); 16042 return false; 16043 } 16044 16045 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16046 ExprResult 16047 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16048 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16049 "Unknown Objective-C Boolean value!"); 16050 QualType BoolT = Context.ObjCBuiltinBoolTy; 16051 if (!Context.getBOOLDecl()) { 16052 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16053 Sema::LookupOrdinaryName); 16054 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16055 NamedDecl *ND = Result.getFoundDecl(); 16056 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16057 Context.setBOOLDecl(TD); 16058 } 16059 } 16060 if (Context.getBOOLDecl()) 16061 BoolT = Context.getBOOLType(); 16062 return new (Context) 16063 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16064 } 16065 16066 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16067 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16068 SourceLocation RParen) { 16069 16070 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16071 16072 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16073 [&](const AvailabilitySpec &Spec) { 16074 return Spec.getPlatform() == Platform; 16075 }); 16076 16077 VersionTuple Version; 16078 if (Spec != AvailSpecs.end()) 16079 Version = Spec->getVersion(); 16080 16081 // The use of `@available` in the enclosing function should be analyzed to 16082 // warn when it's used inappropriately (i.e. not if(@available)). 16083 if (getCurFunctionOrMethodDecl()) 16084 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16085 else if (getCurBlock() || getCurLambda()) 16086 getCurFunction()->HasPotentialAvailabilityViolations = true; 16087 16088 return new (Context) 16089 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16090 } 16091