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 // If the common expression is a class or array prvalue, materialize it 7246 // so that we can safely refer to it multiple times. 7247 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7248 commonExpr->getType()->isArrayType())) { 7249 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7250 if (MatExpr.isInvalid()) 7251 return ExprError(); 7252 commonExpr = MatExpr.get(); 7253 } 7254 7255 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7256 commonExpr->getType(), 7257 commonExpr->getValueKind(), 7258 commonExpr->getObjectKind(), 7259 commonExpr); 7260 LHSExpr = CondExpr = opaqueValue; 7261 } 7262 7263 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7264 ExprValueKind VK = VK_RValue; 7265 ExprObjectKind OK = OK_Ordinary; 7266 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7267 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7268 VK, OK, QuestionLoc); 7269 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7270 RHS.isInvalid()) 7271 return ExprError(); 7272 7273 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7274 RHS.get()); 7275 7276 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7277 7278 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7279 Context); 7280 7281 if (!commonExpr) 7282 return new (Context) 7283 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7284 RHS.get(), result, VK, OK); 7285 7286 return new (Context) BinaryConditionalOperator( 7287 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7288 ColonLoc, result, VK, OK); 7289 } 7290 7291 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7292 // being closely modeled after the C99 spec:-). The odd characteristic of this 7293 // routine is it effectively iqnores the qualifiers on the top level pointee. 7294 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7295 // FIXME: add a couple examples in this comment. 7296 static Sema::AssignConvertType 7297 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7298 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7299 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7300 7301 // get the "pointed to" type (ignoring qualifiers at the top level) 7302 const Type *lhptee, *rhptee; 7303 Qualifiers lhq, rhq; 7304 std::tie(lhptee, lhq) = 7305 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7306 std::tie(rhptee, rhq) = 7307 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7308 7309 Sema::AssignConvertType ConvTy = Sema::Compatible; 7310 7311 // C99 6.5.16.1p1: This following citation is common to constraints 7312 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7313 // qualifiers of the type *pointed to* by the right; 7314 7315 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7316 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7317 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7318 // Ignore lifetime for further calculation. 7319 lhq.removeObjCLifetime(); 7320 rhq.removeObjCLifetime(); 7321 } 7322 7323 if (!lhq.compatiblyIncludes(rhq)) { 7324 // Treat address-space mismatches as fatal. TODO: address subspaces 7325 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7326 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7327 7328 // It's okay to add or remove GC or lifetime qualifiers when converting to 7329 // and from void*. 7330 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7331 .compatiblyIncludes( 7332 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7333 && (lhptee->isVoidType() || rhptee->isVoidType())) 7334 ; // keep old 7335 7336 // Treat lifetime mismatches as fatal. 7337 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7338 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7339 7340 // For GCC/MS compatibility, other qualifier mismatches are treated 7341 // as still compatible in C. 7342 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7343 } 7344 7345 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7346 // incomplete type and the other is a pointer to a qualified or unqualified 7347 // version of void... 7348 if (lhptee->isVoidType()) { 7349 if (rhptee->isIncompleteOrObjectType()) 7350 return ConvTy; 7351 7352 // As an extension, we allow cast to/from void* to function pointer. 7353 assert(rhptee->isFunctionType()); 7354 return Sema::FunctionVoidPointer; 7355 } 7356 7357 if (rhptee->isVoidType()) { 7358 if (lhptee->isIncompleteOrObjectType()) 7359 return ConvTy; 7360 7361 // As an extension, we allow cast to/from void* to function pointer. 7362 assert(lhptee->isFunctionType()); 7363 return Sema::FunctionVoidPointer; 7364 } 7365 7366 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7367 // unqualified versions of compatible types, ... 7368 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7369 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7370 // Check if the pointee types are compatible ignoring the sign. 7371 // We explicitly check for char so that we catch "char" vs 7372 // "unsigned char" on systems where "char" is unsigned. 7373 if (lhptee->isCharType()) 7374 ltrans = S.Context.UnsignedCharTy; 7375 else if (lhptee->hasSignedIntegerRepresentation()) 7376 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7377 7378 if (rhptee->isCharType()) 7379 rtrans = S.Context.UnsignedCharTy; 7380 else if (rhptee->hasSignedIntegerRepresentation()) 7381 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7382 7383 if (ltrans == rtrans) { 7384 // Types are compatible ignoring the sign. Qualifier incompatibility 7385 // takes priority over sign incompatibility because the sign 7386 // warning can be disabled. 7387 if (ConvTy != Sema::Compatible) 7388 return ConvTy; 7389 7390 return Sema::IncompatiblePointerSign; 7391 } 7392 7393 // If we are a multi-level pointer, it's possible that our issue is simply 7394 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7395 // the eventual target type is the same and the pointers have the same 7396 // level of indirection, this must be the issue. 7397 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7398 do { 7399 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7400 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7401 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7402 7403 if (lhptee == rhptee) 7404 return Sema::IncompatibleNestedPointerQualifiers; 7405 } 7406 7407 // General pointer incompatibility takes priority over qualifiers. 7408 return Sema::IncompatiblePointer; 7409 } 7410 if (!S.getLangOpts().CPlusPlus && 7411 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7412 return Sema::IncompatiblePointer; 7413 return ConvTy; 7414 } 7415 7416 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7417 /// block pointer types are compatible or whether a block and normal pointer 7418 /// are compatible. It is more restrict than comparing two function pointer 7419 // types. 7420 static Sema::AssignConvertType 7421 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7422 QualType RHSType) { 7423 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7424 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7425 7426 QualType lhptee, rhptee; 7427 7428 // get the "pointed to" type (ignoring qualifiers at the top level) 7429 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7430 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7431 7432 // In C++, the types have to match exactly. 7433 if (S.getLangOpts().CPlusPlus) 7434 return Sema::IncompatibleBlockPointer; 7435 7436 Sema::AssignConvertType ConvTy = Sema::Compatible; 7437 7438 // For blocks we enforce that qualifiers are identical. 7439 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7440 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7441 if (S.getLangOpts().OpenCL) { 7442 LQuals.removeAddressSpace(); 7443 RQuals.removeAddressSpace(); 7444 } 7445 if (LQuals != RQuals) 7446 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7447 7448 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7449 // assignment. 7450 // The current behavior is similar to C++ lambdas. A block might be 7451 // assigned to a variable iff its return type and parameters are compatible 7452 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7453 // an assignment. Presumably it should behave in way that a function pointer 7454 // assignment does in C, so for each parameter and return type: 7455 // * CVR and address space of LHS should be a superset of CVR and address 7456 // space of RHS. 7457 // * unqualified types should be compatible. 7458 if (S.getLangOpts().OpenCL) { 7459 if (!S.Context.typesAreBlockPointerCompatible( 7460 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7461 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7462 return Sema::IncompatibleBlockPointer; 7463 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7464 return Sema::IncompatibleBlockPointer; 7465 7466 return ConvTy; 7467 } 7468 7469 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7470 /// for assignment compatibility. 7471 static Sema::AssignConvertType 7472 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7473 QualType RHSType) { 7474 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7475 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7476 7477 if (LHSType->isObjCBuiltinType()) { 7478 // Class is not compatible with ObjC object pointers. 7479 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7480 !RHSType->isObjCQualifiedClassType()) 7481 return Sema::IncompatiblePointer; 7482 return Sema::Compatible; 7483 } 7484 if (RHSType->isObjCBuiltinType()) { 7485 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7486 !LHSType->isObjCQualifiedClassType()) 7487 return Sema::IncompatiblePointer; 7488 return Sema::Compatible; 7489 } 7490 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7491 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7492 7493 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7494 // make an exception for id<P> 7495 !LHSType->isObjCQualifiedIdType()) 7496 return Sema::CompatiblePointerDiscardsQualifiers; 7497 7498 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7499 return Sema::Compatible; 7500 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7501 return Sema::IncompatibleObjCQualifiedId; 7502 return Sema::IncompatiblePointer; 7503 } 7504 7505 Sema::AssignConvertType 7506 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7507 QualType LHSType, QualType RHSType) { 7508 // Fake up an opaque expression. We don't actually care about what 7509 // cast operations are required, so if CheckAssignmentConstraints 7510 // adds casts to this they'll be wasted, but fortunately that doesn't 7511 // usually happen on valid code. 7512 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7513 ExprResult RHSPtr = &RHSExpr; 7514 CastKind K = CK_Invalid; 7515 7516 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7517 } 7518 7519 /// This helper function returns true if QT is a vector type that has element 7520 /// type ElementType. 7521 static bool isVector(QualType QT, QualType ElementType) { 7522 if (const VectorType *VT = QT->getAs<VectorType>()) 7523 return VT->getElementType() == ElementType; 7524 return false; 7525 } 7526 7527 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7528 /// has code to accommodate several GCC extensions when type checking 7529 /// pointers. Here are some objectionable examples that GCC considers warnings: 7530 /// 7531 /// int a, *pint; 7532 /// short *pshort; 7533 /// struct foo *pfoo; 7534 /// 7535 /// pint = pshort; // warning: assignment from incompatible pointer type 7536 /// a = pint; // warning: assignment makes integer from pointer without a cast 7537 /// pint = a; // warning: assignment makes pointer from integer without a cast 7538 /// pint = pfoo; // warning: assignment from incompatible pointer type 7539 /// 7540 /// As a result, the code for dealing with pointers is more complex than the 7541 /// C99 spec dictates. 7542 /// 7543 /// Sets 'Kind' for any result kind except Incompatible. 7544 Sema::AssignConvertType 7545 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7546 CastKind &Kind, bool ConvertRHS) { 7547 QualType RHSType = RHS.get()->getType(); 7548 QualType OrigLHSType = LHSType; 7549 7550 // Get canonical types. We're not formatting these types, just comparing 7551 // them. 7552 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7553 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7554 7555 // Common case: no conversion required. 7556 if (LHSType == RHSType) { 7557 Kind = CK_NoOp; 7558 return Compatible; 7559 } 7560 7561 // If we have an atomic type, try a non-atomic assignment, then just add an 7562 // atomic qualification step. 7563 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7564 Sema::AssignConvertType result = 7565 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7566 if (result != Compatible) 7567 return result; 7568 if (Kind != CK_NoOp && ConvertRHS) 7569 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7570 Kind = CK_NonAtomicToAtomic; 7571 return Compatible; 7572 } 7573 7574 // If the left-hand side is a reference type, then we are in a 7575 // (rare!) case where we've allowed the use of references in C, 7576 // e.g., as a parameter type in a built-in function. In this case, 7577 // just make sure that the type referenced is compatible with the 7578 // right-hand side type. The caller is responsible for adjusting 7579 // LHSType so that the resulting expression does not have reference 7580 // type. 7581 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7582 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7583 Kind = CK_LValueBitCast; 7584 return Compatible; 7585 } 7586 return Incompatible; 7587 } 7588 7589 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7590 // to the same ExtVector type. 7591 if (LHSType->isExtVectorType()) { 7592 if (RHSType->isExtVectorType()) 7593 return Incompatible; 7594 if (RHSType->isArithmeticType()) { 7595 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7596 if (ConvertRHS) 7597 RHS = prepareVectorSplat(LHSType, RHS.get()); 7598 Kind = CK_VectorSplat; 7599 return Compatible; 7600 } 7601 } 7602 7603 // Conversions to or from vector type. 7604 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7605 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7606 // Allow assignments of an AltiVec vector type to an equivalent GCC 7607 // vector type and vice versa 7608 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7609 Kind = CK_BitCast; 7610 return Compatible; 7611 } 7612 7613 // If we are allowing lax vector conversions, and LHS and RHS are both 7614 // vectors, the total size only needs to be the same. This is a bitcast; 7615 // no bits are changed but the result type is different. 7616 if (isLaxVectorConversion(RHSType, LHSType)) { 7617 Kind = CK_BitCast; 7618 return IncompatibleVectors; 7619 } 7620 } 7621 7622 // When the RHS comes from another lax conversion (e.g. binops between 7623 // scalars and vectors) the result is canonicalized as a vector. When the 7624 // LHS is also a vector, the lax is allowed by the condition above. Handle 7625 // the case where LHS is a scalar. 7626 if (LHSType->isScalarType()) { 7627 const VectorType *VecType = RHSType->getAs<VectorType>(); 7628 if (VecType && VecType->getNumElements() == 1 && 7629 isLaxVectorConversion(RHSType, LHSType)) { 7630 ExprResult *VecExpr = &RHS; 7631 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7632 Kind = CK_BitCast; 7633 return Compatible; 7634 } 7635 } 7636 7637 return Incompatible; 7638 } 7639 7640 // Diagnose attempts to convert between __float128 and long double where 7641 // such conversions currently can't be handled. 7642 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7643 return Incompatible; 7644 7645 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7646 // discards the imaginary part. 7647 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7648 !LHSType->getAs<ComplexType>()) 7649 return Incompatible; 7650 7651 // Arithmetic conversions. 7652 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7653 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7654 if (ConvertRHS) 7655 Kind = PrepareScalarCast(RHS, LHSType); 7656 return Compatible; 7657 } 7658 7659 // Conversions to normal pointers. 7660 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7661 // U* -> T* 7662 if (isa<PointerType>(RHSType)) { 7663 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7664 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7665 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7666 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7667 } 7668 7669 // int -> T* 7670 if (RHSType->isIntegerType()) { 7671 Kind = CK_IntegralToPointer; // FIXME: null? 7672 return IntToPointer; 7673 } 7674 7675 // C pointers are not compatible with ObjC object pointers, 7676 // with two exceptions: 7677 if (isa<ObjCObjectPointerType>(RHSType)) { 7678 // - conversions to void* 7679 if (LHSPointer->getPointeeType()->isVoidType()) { 7680 Kind = CK_BitCast; 7681 return Compatible; 7682 } 7683 7684 // - conversions from 'Class' to the redefinition type 7685 if (RHSType->isObjCClassType() && 7686 Context.hasSameType(LHSType, 7687 Context.getObjCClassRedefinitionType())) { 7688 Kind = CK_BitCast; 7689 return Compatible; 7690 } 7691 7692 Kind = CK_BitCast; 7693 return IncompatiblePointer; 7694 } 7695 7696 // U^ -> void* 7697 if (RHSType->getAs<BlockPointerType>()) { 7698 if (LHSPointer->getPointeeType()->isVoidType()) { 7699 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7700 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7701 ->getPointeeType() 7702 .getAddressSpace(); 7703 Kind = 7704 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7705 return Compatible; 7706 } 7707 } 7708 7709 return Incompatible; 7710 } 7711 7712 // Conversions to block pointers. 7713 if (isa<BlockPointerType>(LHSType)) { 7714 // U^ -> T^ 7715 if (RHSType->isBlockPointerType()) { 7716 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7717 ->getPointeeType() 7718 .getAddressSpace(); 7719 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7720 ->getPointeeType() 7721 .getAddressSpace(); 7722 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7723 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7724 } 7725 7726 // int or null -> T^ 7727 if (RHSType->isIntegerType()) { 7728 Kind = CK_IntegralToPointer; // FIXME: null 7729 return IntToBlockPointer; 7730 } 7731 7732 // id -> T^ 7733 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7734 Kind = CK_AnyPointerToBlockPointerCast; 7735 return Compatible; 7736 } 7737 7738 // void* -> T^ 7739 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7740 if (RHSPT->getPointeeType()->isVoidType()) { 7741 Kind = CK_AnyPointerToBlockPointerCast; 7742 return Compatible; 7743 } 7744 7745 return Incompatible; 7746 } 7747 7748 // Conversions to Objective-C pointers. 7749 if (isa<ObjCObjectPointerType>(LHSType)) { 7750 // A* -> B* 7751 if (RHSType->isObjCObjectPointerType()) { 7752 Kind = CK_BitCast; 7753 Sema::AssignConvertType result = 7754 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7755 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7756 result == Compatible && 7757 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7758 result = IncompatibleObjCWeakRef; 7759 return result; 7760 } 7761 7762 // int or null -> A* 7763 if (RHSType->isIntegerType()) { 7764 Kind = CK_IntegralToPointer; // FIXME: null 7765 return IntToPointer; 7766 } 7767 7768 // In general, C pointers are not compatible with ObjC object pointers, 7769 // with two exceptions: 7770 if (isa<PointerType>(RHSType)) { 7771 Kind = CK_CPointerToObjCPointerCast; 7772 7773 // - conversions from 'void*' 7774 if (RHSType->isVoidPointerType()) { 7775 return Compatible; 7776 } 7777 7778 // - conversions to 'Class' from its redefinition type 7779 if (LHSType->isObjCClassType() && 7780 Context.hasSameType(RHSType, 7781 Context.getObjCClassRedefinitionType())) { 7782 return Compatible; 7783 } 7784 7785 return IncompatiblePointer; 7786 } 7787 7788 // Only under strict condition T^ is compatible with an Objective-C pointer. 7789 if (RHSType->isBlockPointerType() && 7790 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7791 if (ConvertRHS) 7792 maybeExtendBlockObject(RHS); 7793 Kind = CK_BlockPointerToObjCPointerCast; 7794 return Compatible; 7795 } 7796 7797 return Incompatible; 7798 } 7799 7800 // Conversions from pointers that are not covered by the above. 7801 if (isa<PointerType>(RHSType)) { 7802 // T* -> _Bool 7803 if (LHSType == Context.BoolTy) { 7804 Kind = CK_PointerToBoolean; 7805 return Compatible; 7806 } 7807 7808 // T* -> int 7809 if (LHSType->isIntegerType()) { 7810 Kind = CK_PointerToIntegral; 7811 return PointerToInt; 7812 } 7813 7814 return Incompatible; 7815 } 7816 7817 // Conversions from Objective-C pointers that are not covered by the above. 7818 if (isa<ObjCObjectPointerType>(RHSType)) { 7819 // T* -> _Bool 7820 if (LHSType == Context.BoolTy) { 7821 Kind = CK_PointerToBoolean; 7822 return Compatible; 7823 } 7824 7825 // T* -> int 7826 if (LHSType->isIntegerType()) { 7827 Kind = CK_PointerToIntegral; 7828 return PointerToInt; 7829 } 7830 7831 return Incompatible; 7832 } 7833 7834 // struct A -> struct B 7835 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7836 if (Context.typesAreCompatible(LHSType, RHSType)) { 7837 Kind = CK_NoOp; 7838 return Compatible; 7839 } 7840 } 7841 7842 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7843 Kind = CK_IntToOCLSampler; 7844 return Compatible; 7845 } 7846 7847 return Incompatible; 7848 } 7849 7850 /// \brief Constructs a transparent union from an expression that is 7851 /// used to initialize the transparent union. 7852 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7853 ExprResult &EResult, QualType UnionType, 7854 FieldDecl *Field) { 7855 // Build an initializer list that designates the appropriate member 7856 // of the transparent union. 7857 Expr *E = EResult.get(); 7858 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7859 E, SourceLocation()); 7860 Initializer->setType(UnionType); 7861 Initializer->setInitializedFieldInUnion(Field); 7862 7863 // Build a compound literal constructing a value of the transparent 7864 // union type from this initializer list. 7865 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7866 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7867 VK_RValue, Initializer, false); 7868 } 7869 7870 Sema::AssignConvertType 7871 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7872 ExprResult &RHS) { 7873 QualType RHSType = RHS.get()->getType(); 7874 7875 // If the ArgType is a Union type, we want to handle a potential 7876 // transparent_union GCC extension. 7877 const RecordType *UT = ArgType->getAsUnionType(); 7878 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7879 return Incompatible; 7880 7881 // The field to initialize within the transparent union. 7882 RecordDecl *UD = UT->getDecl(); 7883 FieldDecl *InitField = nullptr; 7884 // It's compatible if the expression matches any of the fields. 7885 for (auto *it : UD->fields()) { 7886 if (it->getType()->isPointerType()) { 7887 // If the transparent union contains a pointer type, we allow: 7888 // 1) void pointer 7889 // 2) null pointer constant 7890 if (RHSType->isPointerType()) 7891 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7892 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7893 InitField = it; 7894 break; 7895 } 7896 7897 if (RHS.get()->isNullPointerConstant(Context, 7898 Expr::NPC_ValueDependentIsNull)) { 7899 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7900 CK_NullToPointer); 7901 InitField = it; 7902 break; 7903 } 7904 } 7905 7906 CastKind Kind = CK_Invalid; 7907 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7908 == Compatible) { 7909 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7910 InitField = it; 7911 break; 7912 } 7913 } 7914 7915 if (!InitField) 7916 return Incompatible; 7917 7918 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7919 return Compatible; 7920 } 7921 7922 Sema::AssignConvertType 7923 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7924 bool Diagnose, 7925 bool DiagnoseCFAudited, 7926 bool ConvertRHS) { 7927 // We need to be able to tell the caller whether we diagnosed a problem, if 7928 // they ask us to issue diagnostics. 7929 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7930 7931 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7932 // we can't avoid *all* modifications at the moment, so we need some somewhere 7933 // to put the updated value. 7934 ExprResult LocalRHS = CallerRHS; 7935 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7936 7937 if (getLangOpts().CPlusPlus) { 7938 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7939 // C++ 5.17p3: If the left operand is not of class type, the 7940 // expression is implicitly converted (C++ 4) to the 7941 // cv-unqualified type of the left operand. 7942 QualType RHSType = RHS.get()->getType(); 7943 if (Diagnose) { 7944 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7945 AA_Assigning); 7946 } else { 7947 ImplicitConversionSequence ICS = 7948 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7949 /*SuppressUserConversions=*/false, 7950 /*AllowExplicit=*/false, 7951 /*InOverloadResolution=*/false, 7952 /*CStyle=*/false, 7953 /*AllowObjCWritebackConversion=*/false); 7954 if (ICS.isFailure()) 7955 return Incompatible; 7956 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7957 ICS, AA_Assigning); 7958 } 7959 if (RHS.isInvalid()) 7960 return Incompatible; 7961 Sema::AssignConvertType result = Compatible; 7962 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7963 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7964 result = IncompatibleObjCWeakRef; 7965 return result; 7966 } 7967 7968 // FIXME: Currently, we fall through and treat C++ classes like C 7969 // structures. 7970 // FIXME: We also fall through for atomics; not sure what should 7971 // happen there, though. 7972 } else if (RHS.get()->getType() == Context.OverloadTy) { 7973 // As a set of extensions to C, we support overloading on functions. These 7974 // functions need to be resolved here. 7975 DeclAccessPair DAP; 7976 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7977 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7978 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7979 else 7980 return Incompatible; 7981 } 7982 7983 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7984 // a null pointer constant. 7985 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7986 LHSType->isBlockPointerType()) && 7987 RHS.get()->isNullPointerConstant(Context, 7988 Expr::NPC_ValueDependentIsNull)) { 7989 if (Diagnose || ConvertRHS) { 7990 CastKind Kind; 7991 CXXCastPath Path; 7992 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7993 /*IgnoreBaseAccess=*/false, Diagnose); 7994 if (ConvertRHS) 7995 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7996 } 7997 return Compatible; 7998 } 7999 8000 // This check seems unnatural, however it is necessary to ensure the proper 8001 // conversion of functions/arrays. If the conversion were done for all 8002 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8003 // expressions that suppress this implicit conversion (&, sizeof). 8004 // 8005 // Suppress this for references: C++ 8.5.3p5. 8006 if (!LHSType->isReferenceType()) { 8007 // FIXME: We potentially allocate here even if ConvertRHS is false. 8008 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8009 if (RHS.isInvalid()) 8010 return Incompatible; 8011 } 8012 8013 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8014 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8015 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8016 if (PDecl && !PDecl->hasDefinition()) { 8017 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 8018 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8019 } 8020 } 8021 8022 CastKind Kind = CK_Invalid; 8023 Sema::AssignConvertType result = 8024 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8025 8026 // C99 6.5.16.1p2: The value of the right operand is converted to the 8027 // type of the assignment expression. 8028 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8029 // so that we can use references in built-in functions even in C. 8030 // The getNonReferenceType() call makes sure that the resulting expression 8031 // does not have reference type. 8032 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8033 QualType Ty = LHSType.getNonLValueExprType(Context); 8034 Expr *E = RHS.get(); 8035 8036 // Check for various Objective-C errors. If we are not reporting 8037 // diagnostics and just checking for errors, e.g., during overload 8038 // resolution, return Incompatible to indicate the failure. 8039 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8040 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8041 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8042 if (!Diagnose) 8043 return Incompatible; 8044 } 8045 if (getLangOpts().ObjC1 && 8046 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8047 E->getType(), E, Diagnose) || 8048 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8049 if (!Diagnose) 8050 return Incompatible; 8051 // Replace the expression with a corrected version and continue so we 8052 // can find further errors. 8053 RHS = E; 8054 return Compatible; 8055 } 8056 8057 if (ConvertRHS) 8058 RHS = ImpCastExprToType(E, Ty, Kind); 8059 } 8060 return result; 8061 } 8062 8063 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8064 ExprResult &RHS) { 8065 Diag(Loc, diag::err_typecheck_invalid_operands) 8066 << LHS.get()->getType() << RHS.get()->getType() 8067 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8068 return QualType(); 8069 } 8070 8071 // Diagnose cases where a scalar was implicitly converted to a vector and 8072 // diagnose the underlying types. Otherwise, diagnose the error 8073 // as invalid vector logical operands for non-C++ cases. 8074 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8075 ExprResult &RHS) { 8076 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8077 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8078 8079 bool LHSNatVec = LHSType->isVectorType(); 8080 bool RHSNatVec = RHSType->isVectorType(); 8081 8082 if (!(LHSNatVec && RHSNatVec)) { 8083 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8084 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8085 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8086 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8087 << Vector->getSourceRange(); 8088 return QualType(); 8089 } 8090 8091 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8092 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8093 << RHS.get()->getSourceRange(); 8094 8095 return QualType(); 8096 } 8097 8098 /// Try to convert a value of non-vector type to a vector type by converting 8099 /// the type to the element type of the vector and then performing a splat. 8100 /// If the language is OpenCL, we only use conversions that promote scalar 8101 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8102 /// for float->int. 8103 /// 8104 /// OpenCL V2.0 6.2.6.p2: 8105 /// An error shall occur if any scalar operand type has greater rank 8106 /// than the type of the vector element. 8107 /// 8108 /// \param scalar - if non-null, actually perform the conversions 8109 /// \return true if the operation fails (but without diagnosing the failure) 8110 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8111 QualType scalarTy, 8112 QualType vectorEltTy, 8113 QualType vectorTy, 8114 unsigned &DiagID) { 8115 // The conversion to apply to the scalar before splatting it, 8116 // if necessary. 8117 CastKind scalarCast = CK_Invalid; 8118 8119 if (vectorEltTy->isIntegralType(S.Context)) { 8120 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8121 (scalarTy->isIntegerType() && 8122 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8123 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8124 return true; 8125 } 8126 if (!scalarTy->isIntegralType(S.Context)) 8127 return true; 8128 scalarCast = CK_IntegralCast; 8129 } else if (vectorEltTy->isRealFloatingType()) { 8130 if (scalarTy->isRealFloatingType()) { 8131 if (S.getLangOpts().OpenCL && 8132 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8133 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8134 return true; 8135 } 8136 scalarCast = CK_FloatingCast; 8137 } 8138 else if (scalarTy->isIntegralType(S.Context)) 8139 scalarCast = CK_IntegralToFloating; 8140 else 8141 return true; 8142 } else { 8143 return true; 8144 } 8145 8146 // Adjust scalar if desired. 8147 if (scalar) { 8148 if (scalarCast != CK_Invalid) 8149 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8150 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8151 } 8152 return false; 8153 } 8154 8155 /// Convert vector E to a vector with the same number of elements but different 8156 /// element type. 8157 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8158 const auto *VecTy = E->getType()->getAs<VectorType>(); 8159 assert(VecTy && "Expression E must be a vector"); 8160 QualType NewVecTy = S.Context.getVectorType(ElementType, 8161 VecTy->getNumElements(), 8162 VecTy->getVectorKind()); 8163 8164 // Look through the implicit cast. Return the subexpression if its type is 8165 // NewVecTy. 8166 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8167 if (ICE->getSubExpr()->getType() == NewVecTy) 8168 return ICE->getSubExpr(); 8169 8170 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8171 return S.ImpCastExprToType(E, NewVecTy, Cast); 8172 } 8173 8174 /// Test if a (constant) integer Int can be casted to another integer type 8175 /// IntTy without losing precision. 8176 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8177 QualType OtherIntTy) { 8178 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8179 8180 // Reject cases where the value of the Int is unknown as that would 8181 // possibly cause truncation, but accept cases where the scalar can be 8182 // demoted without loss of precision. 8183 llvm::APSInt Result; 8184 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8185 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8186 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8187 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8188 8189 if (CstInt) { 8190 // If the scalar is constant and is of a higher order and has more active 8191 // bits that the vector element type, reject it. 8192 unsigned NumBits = IntSigned 8193 ? (Result.isNegative() ? Result.getMinSignedBits() 8194 : Result.getActiveBits()) 8195 : Result.getActiveBits(); 8196 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8197 return true; 8198 8199 // If the signedness of the scalar type and the vector element type 8200 // differs and the number of bits is greater than that of the vector 8201 // element reject it. 8202 return (IntSigned != OtherIntSigned && 8203 NumBits > S.Context.getIntWidth(OtherIntTy)); 8204 } 8205 8206 // Reject cases where the value of the scalar is not constant and it's 8207 // order is greater than that of the vector element type. 8208 return (Order < 0); 8209 } 8210 8211 /// Test if a (constant) integer Int can be casted to floating point type 8212 /// FloatTy without losing precision. 8213 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8214 QualType FloatTy) { 8215 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8216 8217 // Determine if the integer constant can be expressed as a floating point 8218 // number of the appropiate type. 8219 llvm::APSInt Result; 8220 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8221 uint64_t Bits = 0; 8222 if (CstInt) { 8223 // Reject constants that would be truncated if they were converted to 8224 // the floating point type. Test by simple to/from conversion. 8225 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8226 // could be avoided if there was a convertFromAPInt method 8227 // which could signal back if implicit truncation occurred. 8228 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8229 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8230 llvm::APFloat::rmTowardZero); 8231 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8232 !IntTy->hasSignedIntegerRepresentation()); 8233 bool Ignored = false; 8234 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8235 &Ignored); 8236 if (Result != ConvertBack) 8237 return true; 8238 } else { 8239 // Reject types that cannot be fully encoded into the mantissa of 8240 // the float. 8241 Bits = S.Context.getTypeSize(IntTy); 8242 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8243 S.Context.getFloatTypeSemantics(FloatTy)); 8244 if (Bits > FloatPrec) 8245 return true; 8246 } 8247 8248 return false; 8249 } 8250 8251 /// Attempt to convert and splat Scalar into a vector whose types matches 8252 /// Vector following GCC conversion rules. The rule is that implicit 8253 /// conversion can occur when Scalar can be casted to match Vector's element 8254 /// type without causing truncation of Scalar. 8255 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8256 ExprResult *Vector) { 8257 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8258 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8259 const VectorType *VT = VectorTy->getAs<VectorType>(); 8260 8261 assert(!isa<ExtVectorType>(VT) && 8262 "ExtVectorTypes should not be handled here!"); 8263 8264 QualType VectorEltTy = VT->getElementType(); 8265 8266 // Reject cases where the vector element type or the scalar element type are 8267 // not integral or floating point types. 8268 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8269 return true; 8270 8271 // The conversion to apply to the scalar before splatting it, 8272 // if necessary. 8273 CastKind ScalarCast = CK_NoOp; 8274 8275 // Accept cases where the vector elements are integers and the scalar is 8276 // an integer. 8277 // FIXME: Notionally if the scalar was a floating point value with a precise 8278 // integral representation, we could cast it to an appropriate integer 8279 // type and then perform the rest of the checks here. GCC will perform 8280 // this conversion in some cases as determined by the input language. 8281 // We should accept it on a language independent basis. 8282 if (VectorEltTy->isIntegralType(S.Context) && 8283 ScalarTy->isIntegralType(S.Context) && 8284 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8285 8286 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8287 return true; 8288 8289 ScalarCast = CK_IntegralCast; 8290 } else if (VectorEltTy->isRealFloatingType()) { 8291 if (ScalarTy->isRealFloatingType()) { 8292 8293 // Reject cases where the scalar type is not a constant and has a higher 8294 // Order than the vector element type. 8295 llvm::APFloat Result(0.0); 8296 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8297 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8298 if (!CstScalar && Order < 0) 8299 return true; 8300 8301 // If the scalar cannot be safely casted to the vector element type, 8302 // reject it. 8303 if (CstScalar) { 8304 bool Truncated = false; 8305 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8306 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8307 if (Truncated) 8308 return true; 8309 } 8310 8311 ScalarCast = CK_FloatingCast; 8312 } else if (ScalarTy->isIntegralType(S.Context)) { 8313 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8314 return true; 8315 8316 ScalarCast = CK_IntegralToFloating; 8317 } else 8318 return true; 8319 } 8320 8321 // Adjust scalar if desired. 8322 if (Scalar) { 8323 if (ScalarCast != CK_NoOp) 8324 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8325 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8326 } 8327 return false; 8328 } 8329 8330 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8331 SourceLocation Loc, bool IsCompAssign, 8332 bool AllowBothBool, 8333 bool AllowBoolConversions) { 8334 if (!IsCompAssign) { 8335 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8336 if (LHS.isInvalid()) 8337 return QualType(); 8338 } 8339 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8340 if (RHS.isInvalid()) 8341 return QualType(); 8342 8343 // For conversion purposes, we ignore any qualifiers. 8344 // For example, "const float" and "float" are equivalent. 8345 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8346 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8347 8348 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8349 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8350 assert(LHSVecType || RHSVecType); 8351 8352 // AltiVec-style "vector bool op vector bool" combinations are allowed 8353 // for some operators but not others. 8354 if (!AllowBothBool && 8355 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8356 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8357 return InvalidOperands(Loc, LHS, RHS); 8358 8359 // If the vector types are identical, return. 8360 if (Context.hasSameType(LHSType, RHSType)) 8361 return LHSType; 8362 8363 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8364 if (LHSVecType && RHSVecType && 8365 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8366 if (isa<ExtVectorType>(LHSVecType)) { 8367 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8368 return LHSType; 8369 } 8370 8371 if (!IsCompAssign) 8372 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8373 return RHSType; 8374 } 8375 8376 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8377 // can be mixed, with the result being the non-bool type. The non-bool 8378 // operand must have integer element type. 8379 if (AllowBoolConversions && LHSVecType && RHSVecType && 8380 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8381 (Context.getTypeSize(LHSVecType->getElementType()) == 8382 Context.getTypeSize(RHSVecType->getElementType()))) { 8383 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8384 LHSVecType->getElementType()->isIntegerType() && 8385 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8386 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8387 return LHSType; 8388 } 8389 if (!IsCompAssign && 8390 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8391 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8392 RHSVecType->getElementType()->isIntegerType()) { 8393 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8394 return RHSType; 8395 } 8396 } 8397 8398 // If there's a vector type and a scalar, try to convert the scalar to 8399 // the vector element type and splat. 8400 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8401 if (!RHSVecType) { 8402 if (isa<ExtVectorType>(LHSVecType)) { 8403 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8404 LHSVecType->getElementType(), LHSType, 8405 DiagID)) 8406 return LHSType; 8407 } else { 8408 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8409 return LHSType; 8410 } 8411 } 8412 if (!LHSVecType) { 8413 if (isa<ExtVectorType>(RHSVecType)) { 8414 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8415 LHSType, RHSVecType->getElementType(), 8416 RHSType, DiagID)) 8417 return RHSType; 8418 } else { 8419 if (LHS.get()->getValueKind() == VK_LValue || 8420 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8421 return RHSType; 8422 } 8423 } 8424 8425 // FIXME: The code below also handles conversion between vectors and 8426 // non-scalars, we should break this down into fine grained specific checks 8427 // and emit proper diagnostics. 8428 QualType VecType = LHSVecType ? LHSType : RHSType; 8429 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8430 QualType OtherType = LHSVecType ? RHSType : LHSType; 8431 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8432 if (isLaxVectorConversion(OtherType, VecType)) { 8433 // If we're allowing lax vector conversions, only the total (data) size 8434 // needs to be the same. For non compound assignment, if one of the types is 8435 // scalar, the result is always the vector type. 8436 if (!IsCompAssign) { 8437 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8438 return VecType; 8439 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8440 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8441 // type. Note that this is already done by non-compound assignments in 8442 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8443 // <1 x T> -> T. The result is also a vector type. 8444 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8445 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8446 ExprResult *RHSExpr = &RHS; 8447 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8448 return VecType; 8449 } 8450 } 8451 8452 // Okay, the expression is invalid. 8453 8454 // If there's a non-vector, non-real operand, diagnose that. 8455 if ((!RHSVecType && !RHSType->isRealType()) || 8456 (!LHSVecType && !LHSType->isRealType())) { 8457 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8458 << LHSType << RHSType 8459 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8460 return QualType(); 8461 } 8462 8463 // OpenCL V1.1 6.2.6.p1: 8464 // If the operands are of more than one vector type, then an error shall 8465 // occur. Implicit conversions between vector types are not permitted, per 8466 // section 6.2.1. 8467 if (getLangOpts().OpenCL && 8468 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8469 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8470 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8471 << RHSType; 8472 return QualType(); 8473 } 8474 8475 8476 // If there is a vector type that is not a ExtVector and a scalar, we reach 8477 // this point if scalar could not be converted to the vector's element type 8478 // without truncation. 8479 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8480 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8481 QualType Scalar = LHSVecType ? RHSType : LHSType; 8482 QualType Vector = LHSVecType ? LHSType : RHSType; 8483 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8484 Diag(Loc, 8485 diag::err_typecheck_vector_not_convertable_implict_truncation) 8486 << ScalarOrVector << Scalar << Vector; 8487 8488 return QualType(); 8489 } 8490 8491 // Otherwise, use the generic diagnostic. 8492 Diag(Loc, DiagID) 8493 << LHSType << RHSType 8494 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8495 return QualType(); 8496 } 8497 8498 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8499 // expression. These are mainly cases where the null pointer is used as an 8500 // integer instead of a pointer. 8501 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8502 SourceLocation Loc, bool IsCompare) { 8503 // The canonical way to check for a GNU null is with isNullPointerConstant, 8504 // but we use a bit of a hack here for speed; this is a relatively 8505 // hot path, and isNullPointerConstant is slow. 8506 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8507 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8508 8509 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8510 8511 // Avoid analyzing cases where the result will either be invalid (and 8512 // diagnosed as such) or entirely valid and not something to warn about. 8513 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8514 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8515 return; 8516 8517 // Comparison operations would not make sense with a null pointer no matter 8518 // what the other expression is. 8519 if (!IsCompare) { 8520 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8521 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8522 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8523 return; 8524 } 8525 8526 // The rest of the operations only make sense with a null pointer 8527 // if the other expression is a pointer. 8528 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8529 NonNullType->canDecayToPointerType()) 8530 return; 8531 8532 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8533 << LHSNull /* LHS is NULL */ << NonNullType 8534 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8535 } 8536 8537 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8538 ExprResult &RHS, 8539 SourceLocation Loc, bool IsDiv) { 8540 // Check for division/remainder by zero. 8541 llvm::APSInt RHSValue; 8542 if (!RHS.get()->isValueDependent() && 8543 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8544 S.DiagRuntimeBehavior(Loc, RHS.get(), 8545 S.PDiag(diag::warn_remainder_division_by_zero) 8546 << IsDiv << RHS.get()->getSourceRange()); 8547 } 8548 8549 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8550 SourceLocation Loc, 8551 bool IsCompAssign, bool IsDiv) { 8552 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8553 8554 if (LHS.get()->getType()->isVectorType() || 8555 RHS.get()->getType()->isVectorType()) 8556 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8557 /*AllowBothBool*/getLangOpts().AltiVec, 8558 /*AllowBoolConversions*/false); 8559 8560 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8561 if (LHS.isInvalid() || RHS.isInvalid()) 8562 return QualType(); 8563 8564 8565 if (compType.isNull() || !compType->isArithmeticType()) 8566 return InvalidOperands(Loc, LHS, RHS); 8567 if (IsDiv) 8568 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8569 return compType; 8570 } 8571 8572 QualType Sema::CheckRemainderOperands( 8573 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8574 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8575 8576 if (LHS.get()->getType()->isVectorType() || 8577 RHS.get()->getType()->isVectorType()) { 8578 if (LHS.get()->getType()->hasIntegerRepresentation() && 8579 RHS.get()->getType()->hasIntegerRepresentation()) 8580 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8581 /*AllowBothBool*/getLangOpts().AltiVec, 8582 /*AllowBoolConversions*/false); 8583 return InvalidOperands(Loc, LHS, RHS); 8584 } 8585 8586 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8587 if (LHS.isInvalid() || RHS.isInvalid()) 8588 return QualType(); 8589 8590 if (compType.isNull() || !compType->isIntegerType()) 8591 return InvalidOperands(Loc, LHS, RHS); 8592 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8593 return compType; 8594 } 8595 8596 /// \brief Diagnose invalid arithmetic on two void pointers. 8597 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8598 Expr *LHSExpr, Expr *RHSExpr) { 8599 S.Diag(Loc, S.getLangOpts().CPlusPlus 8600 ? diag::err_typecheck_pointer_arith_void_type 8601 : diag::ext_gnu_void_ptr) 8602 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8603 << RHSExpr->getSourceRange(); 8604 } 8605 8606 /// \brief Diagnose invalid arithmetic on a void pointer. 8607 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8608 Expr *Pointer) { 8609 S.Diag(Loc, S.getLangOpts().CPlusPlus 8610 ? diag::err_typecheck_pointer_arith_void_type 8611 : diag::ext_gnu_void_ptr) 8612 << 0 /* one pointer */ << Pointer->getSourceRange(); 8613 } 8614 8615 /// \brief Diagnose invalid arithmetic on a null pointer. 8616 /// 8617 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8618 /// idiom, which we recognize as a GNU extension. 8619 /// 8620 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8621 Expr *Pointer, bool IsGNUIdiom) { 8622 if (IsGNUIdiom) 8623 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8624 << Pointer->getSourceRange(); 8625 else 8626 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8627 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8628 } 8629 8630 /// \brief Diagnose invalid arithmetic on two function pointers. 8631 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8632 Expr *LHS, Expr *RHS) { 8633 assert(LHS->getType()->isAnyPointerType()); 8634 assert(RHS->getType()->isAnyPointerType()); 8635 S.Diag(Loc, S.getLangOpts().CPlusPlus 8636 ? diag::err_typecheck_pointer_arith_function_type 8637 : diag::ext_gnu_ptr_func_arith) 8638 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8639 // We only show the second type if it differs from the first. 8640 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8641 RHS->getType()) 8642 << RHS->getType()->getPointeeType() 8643 << LHS->getSourceRange() << RHS->getSourceRange(); 8644 } 8645 8646 /// \brief Diagnose invalid arithmetic on a function pointer. 8647 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8648 Expr *Pointer) { 8649 assert(Pointer->getType()->isAnyPointerType()); 8650 S.Diag(Loc, S.getLangOpts().CPlusPlus 8651 ? diag::err_typecheck_pointer_arith_function_type 8652 : diag::ext_gnu_ptr_func_arith) 8653 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8654 << 0 /* one pointer, so only one type */ 8655 << Pointer->getSourceRange(); 8656 } 8657 8658 /// \brief Emit error if Operand is incomplete pointer type 8659 /// 8660 /// \returns True if pointer has incomplete type 8661 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8662 Expr *Operand) { 8663 QualType ResType = Operand->getType(); 8664 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8665 ResType = ResAtomicType->getValueType(); 8666 8667 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8668 QualType PointeeTy = ResType->getPointeeType(); 8669 return S.RequireCompleteType(Loc, PointeeTy, 8670 diag::err_typecheck_arithmetic_incomplete_type, 8671 PointeeTy, Operand->getSourceRange()); 8672 } 8673 8674 /// \brief Check the validity of an arithmetic pointer operand. 8675 /// 8676 /// If the operand has pointer type, this code will check for pointer types 8677 /// which are invalid in arithmetic operations. These will be diagnosed 8678 /// appropriately, including whether or not the use is supported as an 8679 /// extension. 8680 /// 8681 /// \returns True when the operand is valid to use (even if as an extension). 8682 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8683 Expr *Operand) { 8684 QualType ResType = Operand->getType(); 8685 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8686 ResType = ResAtomicType->getValueType(); 8687 8688 if (!ResType->isAnyPointerType()) return true; 8689 8690 QualType PointeeTy = ResType->getPointeeType(); 8691 if (PointeeTy->isVoidType()) { 8692 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8693 return !S.getLangOpts().CPlusPlus; 8694 } 8695 if (PointeeTy->isFunctionType()) { 8696 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8697 return !S.getLangOpts().CPlusPlus; 8698 } 8699 8700 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8701 8702 return true; 8703 } 8704 8705 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8706 /// operands. 8707 /// 8708 /// This routine will diagnose any invalid arithmetic on pointer operands much 8709 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8710 /// for emitting a single diagnostic even for operations where both LHS and RHS 8711 /// are (potentially problematic) pointers. 8712 /// 8713 /// \returns True when the operand is valid to use (even if as an extension). 8714 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8715 Expr *LHSExpr, Expr *RHSExpr) { 8716 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8717 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8718 if (!isLHSPointer && !isRHSPointer) return true; 8719 8720 QualType LHSPointeeTy, RHSPointeeTy; 8721 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8722 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8723 8724 // if both are pointers check if operation is valid wrt address spaces 8725 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8726 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8727 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8728 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8729 S.Diag(Loc, 8730 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8731 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8732 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8733 return false; 8734 } 8735 } 8736 8737 // Check for arithmetic on pointers to incomplete types. 8738 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8739 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8740 if (isLHSVoidPtr || isRHSVoidPtr) { 8741 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8742 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8743 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8744 8745 return !S.getLangOpts().CPlusPlus; 8746 } 8747 8748 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8749 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8750 if (isLHSFuncPtr || isRHSFuncPtr) { 8751 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8752 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8753 RHSExpr); 8754 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8755 8756 return !S.getLangOpts().CPlusPlus; 8757 } 8758 8759 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8760 return false; 8761 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8762 return false; 8763 8764 return true; 8765 } 8766 8767 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8768 /// literal. 8769 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8770 Expr *LHSExpr, Expr *RHSExpr) { 8771 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8772 Expr* IndexExpr = RHSExpr; 8773 if (!StrExpr) { 8774 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8775 IndexExpr = LHSExpr; 8776 } 8777 8778 bool IsStringPlusInt = StrExpr && 8779 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8780 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8781 return; 8782 8783 llvm::APSInt index; 8784 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8785 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8786 if (index.isNonNegative() && 8787 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8788 index.isUnsigned())) 8789 return; 8790 } 8791 8792 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8793 Self.Diag(OpLoc, diag::warn_string_plus_int) 8794 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8795 8796 // Only print a fixit for "str" + int, not for int + "str". 8797 if (IndexExpr == RHSExpr) { 8798 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8799 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8800 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8801 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8802 << FixItHint::CreateInsertion(EndLoc, "]"); 8803 } else 8804 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8805 } 8806 8807 /// \brief Emit a warning when adding a char literal to a string. 8808 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8809 Expr *LHSExpr, Expr *RHSExpr) { 8810 const Expr *StringRefExpr = LHSExpr; 8811 const CharacterLiteral *CharExpr = 8812 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8813 8814 if (!CharExpr) { 8815 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8816 StringRefExpr = RHSExpr; 8817 } 8818 8819 if (!CharExpr || !StringRefExpr) 8820 return; 8821 8822 const QualType StringType = StringRefExpr->getType(); 8823 8824 // Return if not a PointerType. 8825 if (!StringType->isAnyPointerType()) 8826 return; 8827 8828 // Return if not a CharacterType. 8829 if (!StringType->getPointeeType()->isAnyCharacterType()) 8830 return; 8831 8832 ASTContext &Ctx = Self.getASTContext(); 8833 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8834 8835 const QualType CharType = CharExpr->getType(); 8836 if (!CharType->isAnyCharacterType() && 8837 CharType->isIntegerType() && 8838 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8839 Self.Diag(OpLoc, diag::warn_string_plus_char) 8840 << DiagRange << Ctx.CharTy; 8841 } else { 8842 Self.Diag(OpLoc, diag::warn_string_plus_char) 8843 << DiagRange << CharExpr->getType(); 8844 } 8845 8846 // Only print a fixit for str + char, not for char + str. 8847 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8848 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8849 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8850 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8851 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8852 << FixItHint::CreateInsertion(EndLoc, "]"); 8853 } else { 8854 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8855 } 8856 } 8857 8858 /// \brief Emit error when two pointers are incompatible. 8859 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8860 Expr *LHSExpr, Expr *RHSExpr) { 8861 assert(LHSExpr->getType()->isAnyPointerType()); 8862 assert(RHSExpr->getType()->isAnyPointerType()); 8863 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8864 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8865 << RHSExpr->getSourceRange(); 8866 } 8867 8868 // C99 6.5.6 8869 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8870 SourceLocation Loc, BinaryOperatorKind Opc, 8871 QualType* CompLHSTy) { 8872 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8873 8874 if (LHS.get()->getType()->isVectorType() || 8875 RHS.get()->getType()->isVectorType()) { 8876 QualType compType = CheckVectorOperands( 8877 LHS, RHS, Loc, CompLHSTy, 8878 /*AllowBothBool*/getLangOpts().AltiVec, 8879 /*AllowBoolConversions*/getLangOpts().ZVector); 8880 if (CompLHSTy) *CompLHSTy = compType; 8881 return compType; 8882 } 8883 8884 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8885 if (LHS.isInvalid() || RHS.isInvalid()) 8886 return QualType(); 8887 8888 // Diagnose "string literal" '+' int and string '+' "char literal". 8889 if (Opc == BO_Add) { 8890 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8891 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8892 } 8893 8894 // handle the common case first (both operands are arithmetic). 8895 if (!compType.isNull() && compType->isArithmeticType()) { 8896 if (CompLHSTy) *CompLHSTy = compType; 8897 return compType; 8898 } 8899 8900 // Type-checking. Ultimately the pointer's going to be in PExp; 8901 // note that we bias towards the LHS being the pointer. 8902 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8903 8904 bool isObjCPointer; 8905 if (PExp->getType()->isPointerType()) { 8906 isObjCPointer = false; 8907 } else if (PExp->getType()->isObjCObjectPointerType()) { 8908 isObjCPointer = true; 8909 } else { 8910 std::swap(PExp, IExp); 8911 if (PExp->getType()->isPointerType()) { 8912 isObjCPointer = false; 8913 } else if (PExp->getType()->isObjCObjectPointerType()) { 8914 isObjCPointer = true; 8915 } else { 8916 return InvalidOperands(Loc, LHS, RHS); 8917 } 8918 } 8919 assert(PExp->getType()->isAnyPointerType()); 8920 8921 if (!IExp->getType()->isIntegerType()) 8922 return InvalidOperands(Loc, LHS, RHS); 8923 8924 // Adding to a null pointer results in undefined behavior. 8925 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8926 Context, Expr::NPC_ValueDependentIsNotNull)) { 8927 // In C++ adding zero to a null pointer is defined. 8928 llvm::APSInt KnownVal; 8929 if (!getLangOpts().CPlusPlus || 8930 (!IExp->isValueDependent() && 8931 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8932 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8933 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8934 Context, BO_Add, PExp, IExp); 8935 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8936 } 8937 } 8938 8939 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8940 return QualType(); 8941 8942 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8943 return QualType(); 8944 8945 // Check array bounds for pointer arithemtic 8946 CheckArrayAccess(PExp, IExp); 8947 8948 if (CompLHSTy) { 8949 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8950 if (LHSTy.isNull()) { 8951 LHSTy = LHS.get()->getType(); 8952 if (LHSTy->isPromotableIntegerType()) 8953 LHSTy = Context.getPromotedIntegerType(LHSTy); 8954 } 8955 *CompLHSTy = LHSTy; 8956 } 8957 8958 return PExp->getType(); 8959 } 8960 8961 // C99 6.5.6 8962 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8963 SourceLocation Loc, 8964 QualType* CompLHSTy) { 8965 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8966 8967 if (LHS.get()->getType()->isVectorType() || 8968 RHS.get()->getType()->isVectorType()) { 8969 QualType compType = CheckVectorOperands( 8970 LHS, RHS, Loc, CompLHSTy, 8971 /*AllowBothBool*/getLangOpts().AltiVec, 8972 /*AllowBoolConversions*/getLangOpts().ZVector); 8973 if (CompLHSTy) *CompLHSTy = compType; 8974 return compType; 8975 } 8976 8977 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8978 if (LHS.isInvalid() || RHS.isInvalid()) 8979 return QualType(); 8980 8981 // Enforce type constraints: C99 6.5.6p3. 8982 8983 // Handle the common case first (both operands are arithmetic). 8984 if (!compType.isNull() && compType->isArithmeticType()) { 8985 if (CompLHSTy) *CompLHSTy = compType; 8986 return compType; 8987 } 8988 8989 // Either ptr - int or ptr - ptr. 8990 if (LHS.get()->getType()->isAnyPointerType()) { 8991 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8992 8993 // Diagnose bad cases where we step over interface counts. 8994 if (LHS.get()->getType()->isObjCObjectPointerType() && 8995 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8996 return QualType(); 8997 8998 // The result type of a pointer-int computation is the pointer type. 8999 if (RHS.get()->getType()->isIntegerType()) { 9000 // Subtracting from a null pointer should produce a warning. 9001 // The last argument to the diagnose call says this doesn't match the 9002 // GNU int-to-pointer idiom. 9003 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9004 Expr::NPC_ValueDependentIsNotNull)) { 9005 // In C++ adding zero to a null pointer is defined. 9006 llvm::APSInt KnownVal; 9007 if (!getLangOpts().CPlusPlus || 9008 (!RHS.get()->isValueDependent() && 9009 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9010 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9011 } 9012 } 9013 9014 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9015 return QualType(); 9016 9017 // Check array bounds for pointer arithemtic 9018 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9019 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9020 9021 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9022 return LHS.get()->getType(); 9023 } 9024 9025 // Handle pointer-pointer subtractions. 9026 if (const PointerType *RHSPTy 9027 = RHS.get()->getType()->getAs<PointerType>()) { 9028 QualType rpointee = RHSPTy->getPointeeType(); 9029 9030 if (getLangOpts().CPlusPlus) { 9031 // Pointee types must be the same: C++ [expr.add] 9032 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9033 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9034 } 9035 } else { 9036 // Pointee types must be compatible C99 6.5.6p3 9037 if (!Context.typesAreCompatible( 9038 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9039 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9040 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9041 return QualType(); 9042 } 9043 } 9044 9045 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9046 LHS.get(), RHS.get())) 9047 return QualType(); 9048 9049 // FIXME: Add warnings for nullptr - ptr. 9050 9051 // The pointee type may have zero size. As an extension, a structure or 9052 // union may have zero size or an array may have zero length. In this 9053 // case subtraction does not make sense. 9054 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9055 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9056 if (ElementSize.isZero()) { 9057 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9058 << rpointee.getUnqualifiedType() 9059 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9060 } 9061 } 9062 9063 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9064 return Context.getPointerDiffType(); 9065 } 9066 } 9067 9068 return InvalidOperands(Loc, LHS, RHS); 9069 } 9070 9071 static bool isScopedEnumerationType(QualType T) { 9072 if (const EnumType *ET = T->getAs<EnumType>()) 9073 return ET->getDecl()->isScoped(); 9074 return false; 9075 } 9076 9077 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9078 SourceLocation Loc, BinaryOperatorKind Opc, 9079 QualType LHSType) { 9080 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9081 // so skip remaining warnings as we don't want to modify values within Sema. 9082 if (S.getLangOpts().OpenCL) 9083 return; 9084 9085 llvm::APSInt Right; 9086 // Check right/shifter operand 9087 if (RHS.get()->isValueDependent() || 9088 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9089 return; 9090 9091 if (Right.isNegative()) { 9092 S.DiagRuntimeBehavior(Loc, RHS.get(), 9093 S.PDiag(diag::warn_shift_negative) 9094 << RHS.get()->getSourceRange()); 9095 return; 9096 } 9097 llvm::APInt LeftBits(Right.getBitWidth(), 9098 S.Context.getTypeSize(LHS.get()->getType())); 9099 if (Right.uge(LeftBits)) { 9100 S.DiagRuntimeBehavior(Loc, RHS.get(), 9101 S.PDiag(diag::warn_shift_gt_typewidth) 9102 << RHS.get()->getSourceRange()); 9103 return; 9104 } 9105 if (Opc != BO_Shl) 9106 return; 9107 9108 // When left shifting an ICE which is signed, we can check for overflow which 9109 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9110 // integers have defined behavior modulo one more than the maximum value 9111 // representable in the result type, so never warn for those. 9112 llvm::APSInt Left; 9113 if (LHS.get()->isValueDependent() || 9114 LHSType->hasUnsignedIntegerRepresentation() || 9115 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9116 return; 9117 9118 // If LHS does not have a signed type and non-negative value 9119 // then, the behavior is undefined. Warn about it. 9120 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9121 S.DiagRuntimeBehavior(Loc, LHS.get(), 9122 S.PDiag(diag::warn_shift_lhs_negative) 9123 << LHS.get()->getSourceRange()); 9124 return; 9125 } 9126 9127 llvm::APInt ResultBits = 9128 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9129 if (LeftBits.uge(ResultBits)) 9130 return; 9131 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9132 Result = Result.shl(Right); 9133 9134 // Print the bit representation of the signed integer as an unsigned 9135 // hexadecimal number. 9136 SmallString<40> HexResult; 9137 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9138 9139 // If we are only missing a sign bit, this is less likely to result in actual 9140 // bugs -- if the result is cast back to an unsigned type, it will have the 9141 // expected value. Thus we place this behind a different warning that can be 9142 // turned off separately if needed. 9143 if (LeftBits == ResultBits - 1) { 9144 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9145 << HexResult << LHSType 9146 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9147 return; 9148 } 9149 9150 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9151 << HexResult.str() << Result.getMinSignedBits() << LHSType 9152 << Left.getBitWidth() << LHS.get()->getSourceRange() 9153 << RHS.get()->getSourceRange(); 9154 } 9155 9156 /// \brief Return the resulting type when a vector is shifted 9157 /// by a scalar or vector shift amount. 9158 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9159 SourceLocation Loc, bool IsCompAssign) { 9160 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9161 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9162 !LHS.get()->getType()->isVectorType()) { 9163 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9164 << RHS.get()->getType() << LHS.get()->getType() 9165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9166 return QualType(); 9167 } 9168 9169 if (!IsCompAssign) { 9170 LHS = S.UsualUnaryConversions(LHS.get()); 9171 if (LHS.isInvalid()) return QualType(); 9172 } 9173 9174 RHS = S.UsualUnaryConversions(RHS.get()); 9175 if (RHS.isInvalid()) return QualType(); 9176 9177 QualType LHSType = LHS.get()->getType(); 9178 // Note that LHS might be a scalar because the routine calls not only in 9179 // OpenCL case. 9180 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9181 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9182 9183 // Note that RHS might not be a vector. 9184 QualType RHSType = RHS.get()->getType(); 9185 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9186 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9187 9188 // The operands need to be integers. 9189 if (!LHSEleType->isIntegerType()) { 9190 S.Diag(Loc, diag::err_typecheck_expect_int) 9191 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9192 return QualType(); 9193 } 9194 9195 if (!RHSEleType->isIntegerType()) { 9196 S.Diag(Loc, diag::err_typecheck_expect_int) 9197 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9198 return QualType(); 9199 } 9200 9201 if (!LHSVecTy) { 9202 assert(RHSVecTy); 9203 if (IsCompAssign) 9204 return RHSType; 9205 if (LHSEleType != RHSEleType) { 9206 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9207 LHSEleType = RHSEleType; 9208 } 9209 QualType VecTy = 9210 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9211 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9212 LHSType = VecTy; 9213 } else if (RHSVecTy) { 9214 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9215 // are applied component-wise. So if RHS is a vector, then ensure 9216 // that the number of elements is the same as LHS... 9217 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9218 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9219 << LHS.get()->getType() << RHS.get()->getType() 9220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9221 return QualType(); 9222 } 9223 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9224 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9225 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9226 if (LHSBT != RHSBT && 9227 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9228 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9229 << LHS.get()->getType() << RHS.get()->getType() 9230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9231 } 9232 } 9233 } else { 9234 // ...else expand RHS to match the number of elements in LHS. 9235 QualType VecTy = 9236 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9237 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9238 } 9239 9240 return LHSType; 9241 } 9242 9243 // C99 6.5.7 9244 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9245 SourceLocation Loc, BinaryOperatorKind Opc, 9246 bool IsCompAssign) { 9247 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9248 9249 // Vector shifts promote their scalar inputs to vector type. 9250 if (LHS.get()->getType()->isVectorType() || 9251 RHS.get()->getType()->isVectorType()) { 9252 if (LangOpts.ZVector) { 9253 // The shift operators for the z vector extensions work basically 9254 // like general shifts, except that neither the LHS nor the RHS is 9255 // allowed to be a "vector bool". 9256 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9257 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9258 return InvalidOperands(Loc, LHS, RHS); 9259 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9260 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9261 return InvalidOperands(Loc, LHS, RHS); 9262 } 9263 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9264 } 9265 9266 // Shifts don't perform usual arithmetic conversions, they just do integer 9267 // promotions on each operand. C99 6.5.7p3 9268 9269 // For the LHS, do usual unary conversions, but then reset them away 9270 // if this is a compound assignment. 9271 ExprResult OldLHS = LHS; 9272 LHS = UsualUnaryConversions(LHS.get()); 9273 if (LHS.isInvalid()) 9274 return QualType(); 9275 QualType LHSType = LHS.get()->getType(); 9276 if (IsCompAssign) LHS = OldLHS; 9277 9278 // The RHS is simpler. 9279 RHS = UsualUnaryConversions(RHS.get()); 9280 if (RHS.isInvalid()) 9281 return QualType(); 9282 QualType RHSType = RHS.get()->getType(); 9283 9284 // C99 6.5.7p2: Each of the operands shall have integer type. 9285 if (!LHSType->hasIntegerRepresentation() || 9286 !RHSType->hasIntegerRepresentation()) 9287 return InvalidOperands(Loc, LHS, RHS); 9288 9289 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9290 // hasIntegerRepresentation() above instead of this. 9291 if (isScopedEnumerationType(LHSType) || 9292 isScopedEnumerationType(RHSType)) { 9293 return InvalidOperands(Loc, LHS, RHS); 9294 } 9295 // Sanity-check shift operands 9296 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9297 9298 // "The type of the result is that of the promoted left operand." 9299 return LHSType; 9300 } 9301 9302 static bool IsWithinTemplateSpecialization(Decl *D) { 9303 if (DeclContext *DC = D->getDeclContext()) { 9304 if (isa<ClassTemplateSpecializationDecl>(DC)) 9305 return true; 9306 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9307 return FD->isFunctionTemplateSpecialization(); 9308 } 9309 return false; 9310 } 9311 9312 /// If two different enums are compared, raise a warning. 9313 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9314 Expr *RHS) { 9315 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9316 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9317 9318 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9319 if (!LHSEnumType) 9320 return; 9321 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9322 if (!RHSEnumType) 9323 return; 9324 9325 // Ignore anonymous enums. 9326 if (!LHSEnumType->getDecl()->getIdentifier() && 9327 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9328 return; 9329 if (!RHSEnumType->getDecl()->getIdentifier() && 9330 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9331 return; 9332 9333 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9334 return; 9335 9336 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9337 << LHSStrippedType << RHSStrippedType 9338 << LHS->getSourceRange() << RHS->getSourceRange(); 9339 } 9340 9341 /// \brief Diagnose bad pointer comparisons. 9342 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9343 ExprResult &LHS, ExprResult &RHS, 9344 bool IsError) { 9345 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9346 : diag::ext_typecheck_comparison_of_distinct_pointers) 9347 << LHS.get()->getType() << RHS.get()->getType() 9348 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9349 } 9350 9351 /// \brief Returns false if the pointers are converted to a composite type, 9352 /// true otherwise. 9353 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9354 ExprResult &LHS, ExprResult &RHS) { 9355 // C++ [expr.rel]p2: 9356 // [...] Pointer conversions (4.10) and qualification 9357 // conversions (4.4) are performed on pointer operands (or on 9358 // a pointer operand and a null pointer constant) to bring 9359 // them to their composite pointer type. [...] 9360 // 9361 // C++ [expr.eq]p1 uses the same notion for (in)equality 9362 // comparisons of pointers. 9363 9364 QualType LHSType = LHS.get()->getType(); 9365 QualType RHSType = RHS.get()->getType(); 9366 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9367 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9368 9369 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9370 if (T.isNull()) { 9371 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9372 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9373 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9374 else 9375 S.InvalidOperands(Loc, LHS, RHS); 9376 return true; 9377 } 9378 9379 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9380 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9381 return false; 9382 } 9383 9384 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9385 ExprResult &LHS, 9386 ExprResult &RHS, 9387 bool IsError) { 9388 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9389 : diag::ext_typecheck_comparison_of_fptr_to_void) 9390 << LHS.get()->getType() << RHS.get()->getType() 9391 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9392 } 9393 9394 static bool isObjCObjectLiteral(ExprResult &E) { 9395 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9396 case Stmt::ObjCArrayLiteralClass: 9397 case Stmt::ObjCDictionaryLiteralClass: 9398 case Stmt::ObjCStringLiteralClass: 9399 case Stmt::ObjCBoxedExprClass: 9400 return true; 9401 default: 9402 // Note that ObjCBoolLiteral is NOT an object literal! 9403 return false; 9404 } 9405 } 9406 9407 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9408 const ObjCObjectPointerType *Type = 9409 LHS->getType()->getAs<ObjCObjectPointerType>(); 9410 9411 // If this is not actually an Objective-C object, bail out. 9412 if (!Type) 9413 return false; 9414 9415 // Get the LHS object's interface type. 9416 QualType InterfaceType = Type->getPointeeType(); 9417 9418 // If the RHS isn't an Objective-C object, bail out. 9419 if (!RHS->getType()->isObjCObjectPointerType()) 9420 return false; 9421 9422 // Try to find the -isEqual: method. 9423 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9424 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9425 InterfaceType, 9426 /*instance=*/true); 9427 if (!Method) { 9428 if (Type->isObjCIdType()) { 9429 // For 'id', just check the global pool. 9430 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9431 /*receiverId=*/true); 9432 } else { 9433 // Check protocols. 9434 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9435 /*instance=*/true); 9436 } 9437 } 9438 9439 if (!Method) 9440 return false; 9441 9442 QualType T = Method->parameters()[0]->getType(); 9443 if (!T->isObjCObjectPointerType()) 9444 return false; 9445 9446 QualType R = Method->getReturnType(); 9447 if (!R->isScalarType()) 9448 return false; 9449 9450 return true; 9451 } 9452 9453 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9454 FromE = FromE->IgnoreParenImpCasts(); 9455 switch (FromE->getStmtClass()) { 9456 default: 9457 break; 9458 case Stmt::ObjCStringLiteralClass: 9459 // "string literal" 9460 return LK_String; 9461 case Stmt::ObjCArrayLiteralClass: 9462 // "array literal" 9463 return LK_Array; 9464 case Stmt::ObjCDictionaryLiteralClass: 9465 // "dictionary literal" 9466 return LK_Dictionary; 9467 case Stmt::BlockExprClass: 9468 return LK_Block; 9469 case Stmt::ObjCBoxedExprClass: { 9470 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9471 switch (Inner->getStmtClass()) { 9472 case Stmt::IntegerLiteralClass: 9473 case Stmt::FloatingLiteralClass: 9474 case Stmt::CharacterLiteralClass: 9475 case Stmt::ObjCBoolLiteralExprClass: 9476 case Stmt::CXXBoolLiteralExprClass: 9477 // "numeric literal" 9478 return LK_Numeric; 9479 case Stmt::ImplicitCastExprClass: { 9480 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9481 // Boolean literals can be represented by implicit casts. 9482 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9483 return LK_Numeric; 9484 break; 9485 } 9486 default: 9487 break; 9488 } 9489 return LK_Boxed; 9490 } 9491 } 9492 return LK_None; 9493 } 9494 9495 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9496 ExprResult &LHS, ExprResult &RHS, 9497 BinaryOperator::Opcode Opc){ 9498 Expr *Literal; 9499 Expr *Other; 9500 if (isObjCObjectLiteral(LHS)) { 9501 Literal = LHS.get(); 9502 Other = RHS.get(); 9503 } else { 9504 Literal = RHS.get(); 9505 Other = LHS.get(); 9506 } 9507 9508 // Don't warn on comparisons against nil. 9509 Other = Other->IgnoreParenCasts(); 9510 if (Other->isNullPointerConstant(S.getASTContext(), 9511 Expr::NPC_ValueDependentIsNotNull)) 9512 return; 9513 9514 // This should be kept in sync with warn_objc_literal_comparison. 9515 // LK_String should always be after the other literals, since it has its own 9516 // warning flag. 9517 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9518 assert(LiteralKind != Sema::LK_Block); 9519 if (LiteralKind == Sema::LK_None) { 9520 llvm_unreachable("Unknown Objective-C object literal kind"); 9521 } 9522 9523 if (LiteralKind == Sema::LK_String) 9524 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9525 << Literal->getSourceRange(); 9526 else 9527 S.Diag(Loc, diag::warn_objc_literal_comparison) 9528 << LiteralKind << Literal->getSourceRange(); 9529 9530 if (BinaryOperator::isEqualityOp(Opc) && 9531 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9532 SourceLocation Start = LHS.get()->getLocStart(); 9533 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9534 CharSourceRange OpRange = 9535 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9536 9537 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9538 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9539 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9540 << FixItHint::CreateInsertion(End, "]"); 9541 } 9542 } 9543 9544 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9545 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9546 ExprResult &RHS, SourceLocation Loc, 9547 BinaryOperatorKind Opc) { 9548 // Check that left hand side is !something. 9549 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9550 if (!UO || UO->getOpcode() != UO_LNot) return; 9551 9552 // Only check if the right hand side is non-bool arithmetic type. 9553 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9554 9555 // Make sure that the something in !something is not bool. 9556 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9557 if (SubExpr->isKnownToHaveBooleanValue()) return; 9558 9559 // Emit warning. 9560 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9561 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9562 << Loc << IsBitwiseOp; 9563 9564 // First note suggest !(x < y) 9565 SourceLocation FirstOpen = SubExpr->getLocStart(); 9566 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9567 FirstClose = S.getLocForEndOfToken(FirstClose); 9568 if (FirstClose.isInvalid()) 9569 FirstOpen = SourceLocation(); 9570 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9571 << IsBitwiseOp 9572 << FixItHint::CreateInsertion(FirstOpen, "(") 9573 << FixItHint::CreateInsertion(FirstClose, ")"); 9574 9575 // Second note suggests (!x) < y 9576 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9577 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9578 SecondClose = S.getLocForEndOfToken(SecondClose); 9579 if (SecondClose.isInvalid()) 9580 SecondOpen = SourceLocation(); 9581 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9582 << FixItHint::CreateInsertion(SecondOpen, "(") 9583 << FixItHint::CreateInsertion(SecondClose, ")"); 9584 } 9585 9586 // Get the decl for a simple expression: a reference to a variable, 9587 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9588 static ValueDecl *getCompareDecl(Expr *E) { 9589 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9590 return DR->getDecl(); 9591 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9592 if (Ivar->isFreeIvar()) 9593 return Ivar->getDecl(); 9594 } 9595 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9596 if (Mem->isImplicitAccess()) 9597 return Mem->getMemberDecl(); 9598 } 9599 return nullptr; 9600 } 9601 9602 // C99 6.5.8, C++ [expr.rel] 9603 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9604 SourceLocation Loc, BinaryOperatorKind Opc, 9605 bool IsRelational) { 9606 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9607 9608 // Handle vector comparisons separately. 9609 if (LHS.get()->getType()->isVectorType() || 9610 RHS.get()->getType()->isVectorType()) 9611 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9612 9613 QualType LHSType = LHS.get()->getType(); 9614 QualType RHSType = RHS.get()->getType(); 9615 9616 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9617 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9618 9619 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9620 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9621 9622 if (!LHSType->hasFloatingRepresentation() && 9623 !(LHSType->isBlockPointerType() && IsRelational) && 9624 !LHS.get()->getLocStart().isMacroID() && 9625 !RHS.get()->getLocStart().isMacroID() && 9626 !inTemplateInstantiation()) { 9627 // For non-floating point types, check for self-comparisons of the form 9628 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9629 // often indicate logic errors in the program. 9630 // 9631 // NOTE: Don't warn about comparison expressions resulting from macro 9632 // expansion. Also don't warn about comparisons which are only self 9633 // comparisons within a template specialization. The warnings should catch 9634 // obvious cases in the definition of the template anyways. The idea is to 9635 // warn when the typed comparison operator will always evaluate to the same 9636 // result. 9637 ValueDecl *DL = getCompareDecl(LHSStripped); 9638 ValueDecl *DR = getCompareDecl(RHSStripped); 9639 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9640 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9641 << 0 // self- 9642 << (Opc == BO_EQ 9643 || Opc == BO_LE 9644 || Opc == BO_GE)); 9645 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9646 !DL->getType()->isReferenceType() && 9647 !DR->getType()->isReferenceType()) { 9648 // what is it always going to eval to? 9649 char always_evals_to; 9650 switch(Opc) { 9651 case BO_EQ: // e.g. array1 == array2 9652 always_evals_to = 0; // false 9653 break; 9654 case BO_NE: // e.g. array1 != array2 9655 always_evals_to = 1; // true 9656 break; 9657 default: 9658 // best we can say is 'a constant' 9659 always_evals_to = 2; // e.g. array1 <= array2 9660 break; 9661 } 9662 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9663 << 1 // array 9664 << always_evals_to); 9665 } 9666 9667 if (isa<CastExpr>(LHSStripped)) 9668 LHSStripped = LHSStripped->IgnoreParenCasts(); 9669 if (isa<CastExpr>(RHSStripped)) 9670 RHSStripped = RHSStripped->IgnoreParenCasts(); 9671 9672 // Warn about comparisons against a string constant (unless the other 9673 // operand is null), the user probably wants strcmp. 9674 Expr *literalString = nullptr; 9675 Expr *literalStringStripped = nullptr; 9676 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9677 !RHSStripped->isNullPointerConstant(Context, 9678 Expr::NPC_ValueDependentIsNull)) { 9679 literalString = LHS.get(); 9680 literalStringStripped = LHSStripped; 9681 } else if ((isa<StringLiteral>(RHSStripped) || 9682 isa<ObjCEncodeExpr>(RHSStripped)) && 9683 !LHSStripped->isNullPointerConstant(Context, 9684 Expr::NPC_ValueDependentIsNull)) { 9685 literalString = RHS.get(); 9686 literalStringStripped = RHSStripped; 9687 } 9688 9689 if (literalString) { 9690 DiagRuntimeBehavior(Loc, nullptr, 9691 PDiag(diag::warn_stringcompare) 9692 << isa<ObjCEncodeExpr>(literalStringStripped) 9693 << literalString->getSourceRange()); 9694 } 9695 } 9696 9697 // C99 6.5.8p3 / C99 6.5.9p4 9698 UsualArithmeticConversions(LHS, RHS); 9699 if (LHS.isInvalid() || RHS.isInvalid()) 9700 return QualType(); 9701 9702 LHSType = LHS.get()->getType(); 9703 RHSType = RHS.get()->getType(); 9704 9705 // The result of comparisons is 'bool' in C++, 'int' in C. 9706 QualType ResultTy = Context.getLogicalOperationType(); 9707 9708 if (IsRelational) { 9709 if (LHSType->isRealType() && RHSType->isRealType()) 9710 return ResultTy; 9711 } else { 9712 // Check for comparisons of floating point operands using != and ==. 9713 if (LHSType->hasFloatingRepresentation()) 9714 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9715 9716 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9717 return ResultTy; 9718 } 9719 9720 const Expr::NullPointerConstantKind LHSNullKind = 9721 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9722 const Expr::NullPointerConstantKind RHSNullKind = 9723 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9724 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9725 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9726 9727 if (!IsRelational && LHSIsNull != RHSIsNull) { 9728 bool IsEquality = Opc == BO_EQ; 9729 if (RHSIsNull) 9730 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9731 RHS.get()->getSourceRange()); 9732 else 9733 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9734 LHS.get()->getSourceRange()); 9735 } 9736 9737 if ((LHSType->isIntegerType() && !LHSIsNull) || 9738 (RHSType->isIntegerType() && !RHSIsNull)) { 9739 // Skip normal pointer conversion checks in this case; we have better 9740 // diagnostics for this below. 9741 } else if (getLangOpts().CPlusPlus) { 9742 // Equality comparison of a function pointer to a void pointer is invalid, 9743 // but we allow it as an extension. 9744 // FIXME: If we really want to allow this, should it be part of composite 9745 // pointer type computation so it works in conditionals too? 9746 if (!IsRelational && 9747 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9748 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9749 // This is a gcc extension compatibility comparison. 9750 // In a SFINAE context, we treat this as a hard error to maintain 9751 // conformance with the C++ standard. 9752 diagnoseFunctionPointerToVoidComparison( 9753 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9754 9755 if (isSFINAEContext()) 9756 return QualType(); 9757 9758 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9759 return ResultTy; 9760 } 9761 9762 // C++ [expr.eq]p2: 9763 // If at least one operand is a pointer [...] bring them to their 9764 // composite pointer type. 9765 // C++ [expr.rel]p2: 9766 // If both operands are pointers, [...] bring them to their composite 9767 // pointer type. 9768 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9769 (IsRelational ? 2 : 1) && 9770 (!LangOpts.ObjCAutoRefCount || 9771 !(LHSType->isObjCObjectPointerType() || 9772 RHSType->isObjCObjectPointerType()))) { 9773 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9774 return QualType(); 9775 else 9776 return ResultTy; 9777 } 9778 } else if (LHSType->isPointerType() && 9779 RHSType->isPointerType()) { // C99 6.5.8p2 9780 // All of the following pointer-related warnings are GCC extensions, except 9781 // when handling null pointer constants. 9782 QualType LCanPointeeTy = 9783 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9784 QualType RCanPointeeTy = 9785 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9786 9787 // C99 6.5.9p2 and C99 6.5.8p2 9788 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9789 RCanPointeeTy.getUnqualifiedType())) { 9790 // Valid unless a relational comparison of function pointers 9791 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9792 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9793 << LHSType << RHSType << LHS.get()->getSourceRange() 9794 << RHS.get()->getSourceRange(); 9795 } 9796 } else if (!IsRelational && 9797 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9798 // Valid unless comparison between non-null pointer and function pointer 9799 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9800 && !LHSIsNull && !RHSIsNull) 9801 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9802 /*isError*/false); 9803 } else { 9804 // Invalid 9805 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9806 } 9807 if (LCanPointeeTy != RCanPointeeTy) { 9808 // Treat NULL constant as a special case in OpenCL. 9809 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9810 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9811 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9812 Diag(Loc, 9813 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9814 << LHSType << RHSType << 0 /* comparison */ 9815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9816 } 9817 } 9818 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9819 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9820 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9821 : CK_BitCast; 9822 if (LHSIsNull && !RHSIsNull) 9823 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9824 else 9825 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9826 } 9827 return ResultTy; 9828 } 9829 9830 if (getLangOpts().CPlusPlus) { 9831 // C++ [expr.eq]p4: 9832 // Two operands of type std::nullptr_t or one operand of type 9833 // std::nullptr_t and the other a null pointer constant compare equal. 9834 if (!IsRelational && LHSIsNull && RHSIsNull) { 9835 if (LHSType->isNullPtrType()) { 9836 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9837 return ResultTy; 9838 } 9839 if (RHSType->isNullPtrType()) { 9840 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9841 return ResultTy; 9842 } 9843 } 9844 9845 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9846 // These aren't covered by the composite pointer type rules. 9847 if (!IsRelational && RHSType->isNullPtrType() && 9848 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9849 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9850 return ResultTy; 9851 } 9852 if (!IsRelational && LHSType->isNullPtrType() && 9853 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9854 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9855 return ResultTy; 9856 } 9857 9858 if (IsRelational && 9859 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9860 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9861 // HACK: Relational comparison of nullptr_t against a pointer type is 9862 // invalid per DR583, but we allow it within std::less<> and friends, 9863 // since otherwise common uses of it break. 9864 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9865 // friends to have std::nullptr_t overload candidates. 9866 DeclContext *DC = CurContext; 9867 if (isa<FunctionDecl>(DC)) 9868 DC = DC->getParent(); 9869 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9870 if (CTSD->isInStdNamespace() && 9871 llvm::StringSwitch<bool>(CTSD->getName()) 9872 .Cases("less", "less_equal", "greater", "greater_equal", true) 9873 .Default(false)) { 9874 if (RHSType->isNullPtrType()) 9875 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9876 else 9877 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9878 return ResultTy; 9879 } 9880 } 9881 } 9882 9883 // C++ [expr.eq]p2: 9884 // If at least one operand is a pointer to member, [...] bring them to 9885 // their composite pointer type. 9886 if (!IsRelational && 9887 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9888 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9889 return QualType(); 9890 else 9891 return ResultTy; 9892 } 9893 9894 // Handle scoped enumeration types specifically, since they don't promote 9895 // to integers. 9896 if (LHS.get()->getType()->isEnumeralType() && 9897 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9898 RHS.get()->getType())) 9899 return ResultTy; 9900 } 9901 9902 // Handle block pointer types. 9903 if (!IsRelational && LHSType->isBlockPointerType() && 9904 RHSType->isBlockPointerType()) { 9905 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9906 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9907 9908 if (!LHSIsNull && !RHSIsNull && 9909 !Context.typesAreCompatible(lpointee, rpointee)) { 9910 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9911 << LHSType << RHSType << LHS.get()->getSourceRange() 9912 << RHS.get()->getSourceRange(); 9913 } 9914 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9915 return ResultTy; 9916 } 9917 9918 // Allow block pointers to be compared with null pointer constants. 9919 if (!IsRelational 9920 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9921 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9922 if (!LHSIsNull && !RHSIsNull) { 9923 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9924 ->getPointeeType()->isVoidType()) 9925 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9926 ->getPointeeType()->isVoidType()))) 9927 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9928 << LHSType << RHSType << LHS.get()->getSourceRange() 9929 << RHS.get()->getSourceRange(); 9930 } 9931 if (LHSIsNull && !RHSIsNull) 9932 LHS = ImpCastExprToType(LHS.get(), RHSType, 9933 RHSType->isPointerType() ? CK_BitCast 9934 : CK_AnyPointerToBlockPointerCast); 9935 else 9936 RHS = ImpCastExprToType(RHS.get(), LHSType, 9937 LHSType->isPointerType() ? CK_BitCast 9938 : CK_AnyPointerToBlockPointerCast); 9939 return ResultTy; 9940 } 9941 9942 if (LHSType->isObjCObjectPointerType() || 9943 RHSType->isObjCObjectPointerType()) { 9944 const PointerType *LPT = LHSType->getAs<PointerType>(); 9945 const PointerType *RPT = RHSType->getAs<PointerType>(); 9946 if (LPT || RPT) { 9947 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9948 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9949 9950 if (!LPtrToVoid && !RPtrToVoid && 9951 !Context.typesAreCompatible(LHSType, RHSType)) { 9952 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9953 /*isError*/false); 9954 } 9955 if (LHSIsNull && !RHSIsNull) { 9956 Expr *E = LHS.get(); 9957 if (getLangOpts().ObjCAutoRefCount) 9958 CheckObjCConversion(SourceRange(), RHSType, E, 9959 CCK_ImplicitConversion); 9960 LHS = ImpCastExprToType(E, RHSType, 9961 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9962 } 9963 else { 9964 Expr *E = RHS.get(); 9965 if (getLangOpts().ObjCAutoRefCount) 9966 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9967 /*Diagnose=*/true, 9968 /*DiagnoseCFAudited=*/false, Opc); 9969 RHS = ImpCastExprToType(E, LHSType, 9970 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9971 } 9972 return ResultTy; 9973 } 9974 if (LHSType->isObjCObjectPointerType() && 9975 RHSType->isObjCObjectPointerType()) { 9976 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9977 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9978 /*isError*/false); 9979 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9980 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9981 9982 if (LHSIsNull && !RHSIsNull) 9983 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9984 else 9985 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9986 return ResultTy; 9987 } 9988 } 9989 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9990 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9991 unsigned DiagID = 0; 9992 bool isError = false; 9993 if (LangOpts.DebuggerSupport) { 9994 // Under a debugger, allow the comparison of pointers to integers, 9995 // since users tend to want to compare addresses. 9996 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9997 (RHSIsNull && RHSType->isIntegerType())) { 9998 if (IsRelational) { 9999 isError = getLangOpts().CPlusPlus; 10000 DiagID = 10001 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10002 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10003 } 10004 } else if (getLangOpts().CPlusPlus) { 10005 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10006 isError = true; 10007 } else if (IsRelational) 10008 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10009 else 10010 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10011 10012 if (DiagID) { 10013 Diag(Loc, DiagID) 10014 << LHSType << RHSType << LHS.get()->getSourceRange() 10015 << RHS.get()->getSourceRange(); 10016 if (isError) 10017 return QualType(); 10018 } 10019 10020 if (LHSType->isIntegerType()) 10021 LHS = ImpCastExprToType(LHS.get(), RHSType, 10022 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10023 else 10024 RHS = ImpCastExprToType(RHS.get(), LHSType, 10025 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10026 return ResultTy; 10027 } 10028 10029 // Handle block pointers. 10030 if (!IsRelational && RHSIsNull 10031 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10032 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10033 return ResultTy; 10034 } 10035 if (!IsRelational && LHSIsNull 10036 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10037 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10038 return ResultTy; 10039 } 10040 10041 if (getLangOpts().OpenCLVersion >= 200) { 10042 if (LHSIsNull && RHSType->isQueueT()) { 10043 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10044 return ResultTy; 10045 } 10046 10047 if (LHSType->isQueueT() && RHSIsNull) { 10048 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10049 return ResultTy; 10050 } 10051 } 10052 10053 return InvalidOperands(Loc, LHS, RHS); 10054 } 10055 10056 // Return a signed ext_vector_type that is of identical size and number of 10057 // elements. For floating point vectors, return an integer type of identical 10058 // size and number of elements. In the non ext_vector_type case, search from 10059 // the largest type to the smallest type to avoid cases where long long == long, 10060 // where long gets picked over long long. 10061 QualType Sema::GetSignedVectorType(QualType V) { 10062 const VectorType *VTy = V->getAs<VectorType>(); 10063 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10064 10065 if (isa<ExtVectorType>(VTy)) { 10066 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10067 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10068 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10069 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10070 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10071 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10072 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10073 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10074 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10075 "Unhandled vector element size in vector compare"); 10076 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10077 } 10078 10079 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10080 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10081 VectorType::GenericVector); 10082 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10083 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10084 VectorType::GenericVector); 10085 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10086 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10087 VectorType::GenericVector); 10088 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10089 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10090 VectorType::GenericVector); 10091 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10092 "Unhandled vector element size in vector compare"); 10093 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10094 VectorType::GenericVector); 10095 } 10096 10097 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10098 /// operates on extended vector types. Instead of producing an IntTy result, 10099 /// like a scalar comparison, a vector comparison produces a vector of integer 10100 /// types. 10101 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10102 SourceLocation Loc, 10103 bool IsRelational) { 10104 // Check to make sure we're operating on vectors of the same type and width, 10105 // Allowing one side to be a scalar of element type. 10106 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10107 /*AllowBothBool*/true, 10108 /*AllowBoolConversions*/getLangOpts().ZVector); 10109 if (vType.isNull()) 10110 return vType; 10111 10112 QualType LHSType = LHS.get()->getType(); 10113 10114 // If AltiVec, the comparison results in a numeric type, i.e. 10115 // bool for C++, int for C 10116 if (getLangOpts().AltiVec && 10117 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10118 return Context.getLogicalOperationType(); 10119 10120 // For non-floating point types, check for self-comparisons of the form 10121 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10122 // often indicate logic errors in the program. 10123 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10124 if (DeclRefExpr* DRL 10125 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10126 if (DeclRefExpr* DRR 10127 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10128 if (DRL->getDecl() == DRR->getDecl()) 10129 DiagRuntimeBehavior(Loc, nullptr, 10130 PDiag(diag::warn_comparison_always) 10131 << 0 // self- 10132 << 2 // "a constant" 10133 ); 10134 } 10135 10136 // Check for comparisons of floating point operands using != and ==. 10137 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10138 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10139 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10140 } 10141 10142 // Return a signed type for the vector. 10143 return GetSignedVectorType(vType); 10144 } 10145 10146 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10147 SourceLocation Loc) { 10148 // Ensure that either both operands are of the same vector type, or 10149 // one operand is of a vector type and the other is of its element type. 10150 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10151 /*AllowBothBool*/true, 10152 /*AllowBoolConversions*/false); 10153 if (vType.isNull()) 10154 return InvalidOperands(Loc, LHS, RHS); 10155 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10156 vType->hasFloatingRepresentation()) 10157 return InvalidOperands(Loc, LHS, RHS); 10158 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10159 // usage of the logical operators && and || with vectors in C. This 10160 // check could be notionally dropped. 10161 if (!getLangOpts().CPlusPlus && 10162 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10163 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10164 10165 return GetSignedVectorType(LHS.get()->getType()); 10166 } 10167 10168 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10169 SourceLocation Loc, 10170 BinaryOperatorKind Opc) { 10171 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10172 10173 bool IsCompAssign = 10174 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10175 10176 if (LHS.get()->getType()->isVectorType() || 10177 RHS.get()->getType()->isVectorType()) { 10178 if (LHS.get()->getType()->hasIntegerRepresentation() && 10179 RHS.get()->getType()->hasIntegerRepresentation()) 10180 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10181 /*AllowBothBool*/true, 10182 /*AllowBoolConversions*/getLangOpts().ZVector); 10183 return InvalidOperands(Loc, LHS, RHS); 10184 } 10185 10186 if (Opc == BO_And) 10187 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10188 10189 ExprResult LHSResult = LHS, RHSResult = RHS; 10190 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10191 IsCompAssign); 10192 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10193 return QualType(); 10194 LHS = LHSResult.get(); 10195 RHS = RHSResult.get(); 10196 10197 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10198 return compType; 10199 return InvalidOperands(Loc, LHS, RHS); 10200 } 10201 10202 // C99 6.5.[13,14] 10203 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10204 SourceLocation Loc, 10205 BinaryOperatorKind Opc) { 10206 // Check vector operands differently. 10207 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10208 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10209 10210 // Diagnose cases where the user write a logical and/or but probably meant a 10211 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10212 // is a constant. 10213 if (LHS.get()->getType()->isIntegerType() && 10214 !LHS.get()->getType()->isBooleanType() && 10215 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10216 // Don't warn in macros or template instantiations. 10217 !Loc.isMacroID() && !inTemplateInstantiation()) { 10218 // If the RHS can be constant folded, and if it constant folds to something 10219 // that isn't 0 or 1 (which indicate a potential logical operation that 10220 // happened to fold to true/false) then warn. 10221 // Parens on the RHS are ignored. 10222 llvm::APSInt Result; 10223 if (RHS.get()->EvaluateAsInt(Result, Context)) 10224 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10225 !RHS.get()->getExprLoc().isMacroID()) || 10226 (Result != 0 && Result != 1)) { 10227 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10228 << RHS.get()->getSourceRange() 10229 << (Opc == BO_LAnd ? "&&" : "||"); 10230 // Suggest replacing the logical operator with the bitwise version 10231 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10232 << (Opc == BO_LAnd ? "&" : "|") 10233 << FixItHint::CreateReplacement(SourceRange( 10234 Loc, getLocForEndOfToken(Loc)), 10235 Opc == BO_LAnd ? "&" : "|"); 10236 if (Opc == BO_LAnd) 10237 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10238 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10239 << FixItHint::CreateRemoval( 10240 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10241 RHS.get()->getLocEnd())); 10242 } 10243 } 10244 10245 if (!Context.getLangOpts().CPlusPlus) { 10246 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10247 // not operate on the built-in scalar and vector float types. 10248 if (Context.getLangOpts().OpenCL && 10249 Context.getLangOpts().OpenCLVersion < 120) { 10250 if (LHS.get()->getType()->isFloatingType() || 10251 RHS.get()->getType()->isFloatingType()) 10252 return InvalidOperands(Loc, LHS, RHS); 10253 } 10254 10255 LHS = UsualUnaryConversions(LHS.get()); 10256 if (LHS.isInvalid()) 10257 return QualType(); 10258 10259 RHS = UsualUnaryConversions(RHS.get()); 10260 if (RHS.isInvalid()) 10261 return QualType(); 10262 10263 if (!LHS.get()->getType()->isScalarType() || 10264 !RHS.get()->getType()->isScalarType()) 10265 return InvalidOperands(Loc, LHS, RHS); 10266 10267 return Context.IntTy; 10268 } 10269 10270 // The following is safe because we only use this method for 10271 // non-overloadable operands. 10272 10273 // C++ [expr.log.and]p1 10274 // C++ [expr.log.or]p1 10275 // The operands are both contextually converted to type bool. 10276 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10277 if (LHSRes.isInvalid()) 10278 return InvalidOperands(Loc, LHS, RHS); 10279 LHS = LHSRes; 10280 10281 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10282 if (RHSRes.isInvalid()) 10283 return InvalidOperands(Loc, LHS, RHS); 10284 RHS = RHSRes; 10285 10286 // C++ [expr.log.and]p2 10287 // C++ [expr.log.or]p2 10288 // The result is a bool. 10289 return Context.BoolTy; 10290 } 10291 10292 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10293 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10294 if (!ME) return false; 10295 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10296 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10297 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10298 if (!Base) return false; 10299 return Base->getMethodDecl() != nullptr; 10300 } 10301 10302 /// Is the given expression (which must be 'const') a reference to a 10303 /// variable which was originally non-const, but which has become 10304 /// 'const' due to being captured within a block? 10305 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10306 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10307 assert(E->isLValue() && E->getType().isConstQualified()); 10308 E = E->IgnoreParens(); 10309 10310 // Must be a reference to a declaration from an enclosing scope. 10311 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10312 if (!DRE) return NCCK_None; 10313 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10314 10315 // The declaration must be a variable which is not declared 'const'. 10316 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10317 if (!var) return NCCK_None; 10318 if (var->getType().isConstQualified()) return NCCK_None; 10319 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10320 10321 // Decide whether the first capture was for a block or a lambda. 10322 DeclContext *DC = S.CurContext, *Prev = nullptr; 10323 // Decide whether the first capture was for a block or a lambda. 10324 while (DC) { 10325 // For init-capture, it is possible that the variable belongs to the 10326 // template pattern of the current context. 10327 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10328 if (var->isInitCapture() && 10329 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10330 break; 10331 if (DC == var->getDeclContext()) 10332 break; 10333 Prev = DC; 10334 DC = DC->getParent(); 10335 } 10336 // Unless we have an init-capture, we've gone one step too far. 10337 if (!var->isInitCapture()) 10338 DC = Prev; 10339 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10340 } 10341 10342 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10343 Ty = Ty.getNonReferenceType(); 10344 if (IsDereference && Ty->isPointerType()) 10345 Ty = Ty->getPointeeType(); 10346 return !Ty.isConstQualified(); 10347 } 10348 10349 // Update err_typecheck_assign_const and note_typecheck_assign_const 10350 // when this enum is changed. 10351 enum { 10352 ConstFunction, 10353 ConstVariable, 10354 ConstMember, 10355 ConstMethod, 10356 NestedConstMember, 10357 ConstUnknown, // Keep as last element 10358 }; 10359 10360 /// Emit the "read-only variable not assignable" error and print notes to give 10361 /// more information about why the variable is not assignable, such as pointing 10362 /// to the declaration of a const variable, showing that a method is const, or 10363 /// that the function is returning a const reference. 10364 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10365 SourceLocation Loc) { 10366 SourceRange ExprRange = E->getSourceRange(); 10367 10368 // Only emit one error on the first const found. All other consts will emit 10369 // a note to the error. 10370 bool DiagnosticEmitted = false; 10371 10372 // Track if the current expression is the result of a dereference, and if the 10373 // next checked expression is the result of a dereference. 10374 bool IsDereference = false; 10375 bool NextIsDereference = false; 10376 10377 // Loop to process MemberExpr chains. 10378 while (true) { 10379 IsDereference = NextIsDereference; 10380 10381 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10382 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10383 NextIsDereference = ME->isArrow(); 10384 const ValueDecl *VD = ME->getMemberDecl(); 10385 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10386 // Mutable fields can be modified even if the class is const. 10387 if (Field->isMutable()) { 10388 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10389 break; 10390 } 10391 10392 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10393 if (!DiagnosticEmitted) { 10394 S.Diag(Loc, diag::err_typecheck_assign_const) 10395 << ExprRange << ConstMember << false /*static*/ << Field 10396 << Field->getType(); 10397 DiagnosticEmitted = true; 10398 } 10399 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10400 << ConstMember << false /*static*/ << Field << Field->getType() 10401 << Field->getSourceRange(); 10402 } 10403 E = ME->getBase(); 10404 continue; 10405 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10406 if (VDecl->getType().isConstQualified()) { 10407 if (!DiagnosticEmitted) { 10408 S.Diag(Loc, diag::err_typecheck_assign_const) 10409 << ExprRange << ConstMember << true /*static*/ << VDecl 10410 << VDecl->getType(); 10411 DiagnosticEmitted = true; 10412 } 10413 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10414 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10415 << VDecl->getSourceRange(); 10416 } 10417 // Static fields do not inherit constness from parents. 10418 break; 10419 } 10420 break; 10421 } // End MemberExpr 10422 break; 10423 } 10424 10425 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10426 // Function calls 10427 const FunctionDecl *FD = CE->getDirectCallee(); 10428 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10429 if (!DiagnosticEmitted) { 10430 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10431 << ConstFunction << FD; 10432 DiagnosticEmitted = true; 10433 } 10434 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10435 diag::note_typecheck_assign_const) 10436 << ConstFunction << FD << FD->getReturnType() 10437 << FD->getReturnTypeSourceRange(); 10438 } 10439 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10440 // Point to variable declaration. 10441 if (const ValueDecl *VD = DRE->getDecl()) { 10442 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10443 if (!DiagnosticEmitted) { 10444 S.Diag(Loc, diag::err_typecheck_assign_const) 10445 << ExprRange << ConstVariable << VD << VD->getType(); 10446 DiagnosticEmitted = true; 10447 } 10448 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10449 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10450 } 10451 } 10452 } else if (isa<CXXThisExpr>(E)) { 10453 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10454 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10455 if (MD->isConst()) { 10456 if (!DiagnosticEmitted) { 10457 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10458 << ConstMethod << MD; 10459 DiagnosticEmitted = true; 10460 } 10461 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10462 << ConstMethod << MD << MD->getSourceRange(); 10463 } 10464 } 10465 } 10466 } 10467 10468 if (DiagnosticEmitted) 10469 return; 10470 10471 // Can't determine a more specific message, so display the generic error. 10472 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10473 } 10474 10475 enum OriginalExprKind { 10476 OEK_Variable, 10477 OEK_Member, 10478 OEK_LValue 10479 }; 10480 10481 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10482 const RecordType *Ty, 10483 SourceLocation Loc, SourceRange Range, 10484 OriginalExprKind OEK, 10485 bool &DiagnosticEmitted, 10486 bool IsNested = false) { 10487 // We walk the record hierarchy breadth-first to ensure that we print 10488 // diagnostics in field nesting order. 10489 // First, check every field for constness. 10490 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10491 if (Field->getType().isConstQualified()) { 10492 if (!DiagnosticEmitted) { 10493 S.Diag(Loc, diag::err_typecheck_assign_const) 10494 << Range << NestedConstMember << OEK << VD 10495 << IsNested << Field; 10496 DiagnosticEmitted = true; 10497 } 10498 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10499 << NestedConstMember << IsNested << Field 10500 << Field->getType() << Field->getSourceRange(); 10501 } 10502 } 10503 // Then, recurse. 10504 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10505 QualType FTy = Field->getType(); 10506 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10507 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10508 OEK, DiagnosticEmitted, true); 10509 } 10510 } 10511 10512 /// Emit an error for the case where a record we are trying to assign to has a 10513 /// const-qualified field somewhere in its hierarchy. 10514 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10515 SourceLocation Loc) { 10516 QualType Ty = E->getType(); 10517 assert(Ty->isRecordType() && "lvalue was not record?"); 10518 SourceRange Range = E->getSourceRange(); 10519 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10520 bool DiagEmitted = false; 10521 10522 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10523 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10524 Range, OEK_Member, DiagEmitted); 10525 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10526 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10527 Range, OEK_Variable, DiagEmitted); 10528 else 10529 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10530 Range, OEK_LValue, DiagEmitted); 10531 if (!DiagEmitted) 10532 DiagnoseConstAssignment(S, E, Loc); 10533 } 10534 10535 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10536 /// emit an error and return true. If so, return false. 10537 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10538 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10539 10540 S.CheckShadowingDeclModification(E, Loc); 10541 10542 SourceLocation OrigLoc = Loc; 10543 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10544 &Loc); 10545 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10546 IsLV = Expr::MLV_InvalidMessageExpression; 10547 if (IsLV == Expr::MLV_Valid) 10548 return false; 10549 10550 unsigned DiagID = 0; 10551 bool NeedType = false; 10552 switch (IsLV) { // C99 6.5.16p2 10553 case Expr::MLV_ConstQualified: 10554 // Use a specialized diagnostic when we're assigning to an object 10555 // from an enclosing function or block. 10556 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10557 if (NCCK == NCCK_Block) 10558 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10559 else 10560 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10561 break; 10562 } 10563 10564 // In ARC, use some specialized diagnostics for occasions where we 10565 // infer 'const'. These are always pseudo-strong variables. 10566 if (S.getLangOpts().ObjCAutoRefCount) { 10567 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10568 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10569 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10570 10571 // Use the normal diagnostic if it's pseudo-__strong but the 10572 // user actually wrote 'const'. 10573 if (var->isARCPseudoStrong() && 10574 (!var->getTypeSourceInfo() || 10575 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10576 // There are two pseudo-strong cases: 10577 // - self 10578 ObjCMethodDecl *method = S.getCurMethodDecl(); 10579 if (method && var == method->getSelfDecl()) 10580 DiagID = method->isClassMethod() 10581 ? diag::err_typecheck_arc_assign_self_class_method 10582 : diag::err_typecheck_arc_assign_self; 10583 10584 // - fast enumeration variables 10585 else 10586 DiagID = diag::err_typecheck_arr_assign_enumeration; 10587 10588 SourceRange Assign; 10589 if (Loc != OrigLoc) 10590 Assign = SourceRange(OrigLoc, OrigLoc); 10591 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10592 // We need to preserve the AST regardless, so migration tool 10593 // can do its job. 10594 return false; 10595 } 10596 } 10597 } 10598 10599 // If none of the special cases above are triggered, then this is a 10600 // simple const assignment. 10601 if (DiagID == 0) { 10602 DiagnoseConstAssignment(S, E, Loc); 10603 return true; 10604 } 10605 10606 break; 10607 case Expr::MLV_ConstAddrSpace: 10608 DiagnoseConstAssignment(S, E, Loc); 10609 return true; 10610 case Expr::MLV_ConstQualifiedField: 10611 DiagnoseRecursiveConstFields(S, E, Loc); 10612 return true; 10613 case Expr::MLV_ArrayType: 10614 case Expr::MLV_ArrayTemporary: 10615 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10616 NeedType = true; 10617 break; 10618 case Expr::MLV_NotObjectType: 10619 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10620 NeedType = true; 10621 break; 10622 case Expr::MLV_LValueCast: 10623 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10624 break; 10625 case Expr::MLV_Valid: 10626 llvm_unreachable("did not take early return for MLV_Valid"); 10627 case Expr::MLV_InvalidExpression: 10628 case Expr::MLV_MemberFunction: 10629 case Expr::MLV_ClassTemporary: 10630 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10631 break; 10632 case Expr::MLV_IncompleteType: 10633 case Expr::MLV_IncompleteVoidType: 10634 return S.RequireCompleteType(Loc, E->getType(), 10635 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10636 case Expr::MLV_DuplicateVectorComponents: 10637 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10638 break; 10639 case Expr::MLV_NoSetterProperty: 10640 llvm_unreachable("readonly properties should be processed differently"); 10641 case Expr::MLV_InvalidMessageExpression: 10642 DiagID = diag::err_readonly_message_assignment; 10643 break; 10644 case Expr::MLV_SubObjCPropertySetting: 10645 DiagID = diag::err_no_subobject_property_setting; 10646 break; 10647 } 10648 10649 SourceRange Assign; 10650 if (Loc != OrigLoc) 10651 Assign = SourceRange(OrigLoc, OrigLoc); 10652 if (NeedType) 10653 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10654 else 10655 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10656 return true; 10657 } 10658 10659 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10660 SourceLocation Loc, 10661 Sema &Sema) { 10662 // C / C++ fields 10663 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10664 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10665 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10666 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10667 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10668 } 10669 10670 // Objective-C instance variables 10671 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10672 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10673 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10674 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10675 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10676 if (RL && RR && RL->getDecl() == RR->getDecl()) 10677 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10678 } 10679 } 10680 10681 // C99 6.5.16.1 10682 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10683 SourceLocation Loc, 10684 QualType CompoundType) { 10685 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10686 10687 // Verify that LHS is a modifiable lvalue, and emit error if not. 10688 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10689 return QualType(); 10690 10691 QualType LHSType = LHSExpr->getType(); 10692 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10693 CompoundType; 10694 // OpenCL v1.2 s6.1.1.1 p2: 10695 // The half data type can only be used to declare a pointer to a buffer that 10696 // contains half values 10697 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10698 LHSType->isHalfType()) { 10699 Diag(Loc, diag::err_opencl_half_load_store) << 1 10700 << LHSType.getUnqualifiedType(); 10701 return QualType(); 10702 } 10703 10704 AssignConvertType ConvTy; 10705 if (CompoundType.isNull()) { 10706 Expr *RHSCheck = RHS.get(); 10707 10708 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10709 10710 QualType LHSTy(LHSType); 10711 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10712 if (RHS.isInvalid()) 10713 return QualType(); 10714 // Special case of NSObject attributes on c-style pointer types. 10715 if (ConvTy == IncompatiblePointer && 10716 ((Context.isObjCNSObjectType(LHSType) && 10717 RHSType->isObjCObjectPointerType()) || 10718 (Context.isObjCNSObjectType(RHSType) && 10719 LHSType->isObjCObjectPointerType()))) 10720 ConvTy = Compatible; 10721 10722 if (ConvTy == Compatible && 10723 LHSType->isObjCObjectType()) 10724 Diag(Loc, diag::err_objc_object_assignment) 10725 << LHSType; 10726 10727 // If the RHS is a unary plus or minus, check to see if they = and + are 10728 // right next to each other. If so, the user may have typo'd "x =+ 4" 10729 // instead of "x += 4". 10730 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10731 RHSCheck = ICE->getSubExpr(); 10732 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10733 if ((UO->getOpcode() == UO_Plus || 10734 UO->getOpcode() == UO_Minus) && 10735 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10736 // Only if the two operators are exactly adjacent. 10737 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10738 // And there is a space or other character before the subexpr of the 10739 // unary +/-. We don't want to warn on "x=-1". 10740 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10741 UO->getSubExpr()->getLocStart().isFileID()) { 10742 Diag(Loc, diag::warn_not_compound_assign) 10743 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10744 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10745 } 10746 } 10747 10748 if (ConvTy == Compatible) { 10749 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10750 // Warn about retain cycles where a block captures the LHS, but 10751 // not if the LHS is a simple variable into which the block is 10752 // being stored...unless that variable can be captured by reference! 10753 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10754 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10755 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10756 checkRetainCycles(LHSExpr, RHS.get()); 10757 } 10758 10759 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10760 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10761 // It is safe to assign a weak reference into a strong variable. 10762 // Although this code can still have problems: 10763 // id x = self.weakProp; 10764 // id y = self.weakProp; 10765 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10766 // paths through the function. This should be revisited if 10767 // -Wrepeated-use-of-weak is made flow-sensitive. 10768 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10769 // variable, which will be valid for the current autorelease scope. 10770 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10771 RHS.get()->getLocStart())) 10772 getCurFunction()->markSafeWeakUse(RHS.get()); 10773 10774 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10775 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10776 } 10777 } 10778 } else { 10779 // Compound assignment "x += y" 10780 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10781 } 10782 10783 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10784 RHS.get(), AA_Assigning)) 10785 return QualType(); 10786 10787 CheckForNullPointerDereference(*this, LHSExpr); 10788 10789 // C99 6.5.16p3: The type of an assignment expression is the type of the 10790 // left operand unless the left operand has qualified type, in which case 10791 // it is the unqualified version of the type of the left operand. 10792 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10793 // is converted to the type of the assignment expression (above). 10794 // C++ 5.17p1: the type of the assignment expression is that of its left 10795 // operand. 10796 return (getLangOpts().CPlusPlus 10797 ? LHSType : LHSType.getUnqualifiedType()); 10798 } 10799 10800 // Only ignore explicit casts to void. 10801 static bool IgnoreCommaOperand(const Expr *E) { 10802 E = E->IgnoreParens(); 10803 10804 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10805 if (CE->getCastKind() == CK_ToVoid) { 10806 return true; 10807 } 10808 } 10809 10810 return false; 10811 } 10812 10813 // Look for instances where it is likely the comma operator is confused with 10814 // another operator. There is a whitelist of acceptable expressions for the 10815 // left hand side of the comma operator, otherwise emit a warning. 10816 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10817 // No warnings in macros 10818 if (Loc.isMacroID()) 10819 return; 10820 10821 // Don't warn in template instantiations. 10822 if (inTemplateInstantiation()) 10823 return; 10824 10825 // Scope isn't fine-grained enough to whitelist the specific cases, so 10826 // instead, skip more than needed, then call back into here with the 10827 // CommaVisitor in SemaStmt.cpp. 10828 // The whitelisted locations are the initialization and increment portions 10829 // of a for loop. The additional checks are on the condition of 10830 // if statements, do/while loops, and for loops. 10831 const unsigned ForIncrementFlags = 10832 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10833 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10834 const unsigned ScopeFlags = getCurScope()->getFlags(); 10835 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10836 (ScopeFlags & ForInitFlags) == ForInitFlags) 10837 return; 10838 10839 // If there are multiple comma operators used together, get the RHS of the 10840 // of the comma operator as the LHS. 10841 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10842 if (BO->getOpcode() != BO_Comma) 10843 break; 10844 LHS = BO->getRHS(); 10845 } 10846 10847 // Only allow some expressions on LHS to not warn. 10848 if (IgnoreCommaOperand(LHS)) 10849 return; 10850 10851 Diag(Loc, diag::warn_comma_operator); 10852 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10853 << LHS->getSourceRange() 10854 << FixItHint::CreateInsertion(LHS->getLocStart(), 10855 LangOpts.CPlusPlus ? "static_cast<void>(" 10856 : "(void)(") 10857 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10858 ")"); 10859 } 10860 10861 // C99 6.5.17 10862 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10863 SourceLocation Loc) { 10864 LHS = S.CheckPlaceholderExpr(LHS.get()); 10865 RHS = S.CheckPlaceholderExpr(RHS.get()); 10866 if (LHS.isInvalid() || RHS.isInvalid()) 10867 return QualType(); 10868 10869 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10870 // operands, but not unary promotions. 10871 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10872 10873 // So we treat the LHS as a ignored value, and in C++ we allow the 10874 // containing site to determine what should be done with the RHS. 10875 LHS = S.IgnoredValueConversions(LHS.get()); 10876 if (LHS.isInvalid()) 10877 return QualType(); 10878 10879 S.DiagnoseUnusedExprResult(LHS.get()); 10880 10881 if (!S.getLangOpts().CPlusPlus) { 10882 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10883 if (RHS.isInvalid()) 10884 return QualType(); 10885 if (!RHS.get()->getType()->isVoidType()) 10886 S.RequireCompleteType(Loc, RHS.get()->getType(), 10887 diag::err_incomplete_type); 10888 } 10889 10890 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10891 S.DiagnoseCommaOperator(LHS.get(), Loc); 10892 10893 return RHS.get()->getType(); 10894 } 10895 10896 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10897 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10898 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10899 ExprValueKind &VK, 10900 ExprObjectKind &OK, 10901 SourceLocation OpLoc, 10902 bool IsInc, bool IsPrefix) { 10903 if (Op->isTypeDependent()) 10904 return S.Context.DependentTy; 10905 10906 QualType ResType = Op->getType(); 10907 // Atomic types can be used for increment / decrement where the non-atomic 10908 // versions can, so ignore the _Atomic() specifier for the purpose of 10909 // checking. 10910 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10911 ResType = ResAtomicType->getValueType(); 10912 10913 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10914 10915 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10916 // Decrement of bool is not allowed. 10917 if (!IsInc) { 10918 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10919 return QualType(); 10920 } 10921 // Increment of bool sets it to true, but is deprecated. 10922 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10923 : diag::warn_increment_bool) 10924 << Op->getSourceRange(); 10925 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10926 // Error on enum increments and decrements in C++ mode 10927 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10928 return QualType(); 10929 } else if (ResType->isRealType()) { 10930 // OK! 10931 } else if (ResType->isPointerType()) { 10932 // C99 6.5.2.4p2, 6.5.6p2 10933 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10934 return QualType(); 10935 } else if (ResType->isObjCObjectPointerType()) { 10936 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10937 // Otherwise, we just need a complete type. 10938 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10939 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10940 return QualType(); 10941 } else if (ResType->isAnyComplexType()) { 10942 // C99 does not support ++/-- on complex types, we allow as an extension. 10943 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10944 << ResType << Op->getSourceRange(); 10945 } else if (ResType->isPlaceholderType()) { 10946 ExprResult PR = S.CheckPlaceholderExpr(Op); 10947 if (PR.isInvalid()) return QualType(); 10948 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10949 IsInc, IsPrefix); 10950 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10951 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10952 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10953 (ResType->getAs<VectorType>()->getVectorKind() != 10954 VectorType::AltiVecBool)) { 10955 // The z vector extensions allow ++ and -- for non-bool vectors. 10956 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10957 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10958 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10959 } else { 10960 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10961 << ResType << int(IsInc) << Op->getSourceRange(); 10962 return QualType(); 10963 } 10964 // At this point, we know we have a real, complex or pointer type. 10965 // Now make sure the operand is a modifiable lvalue. 10966 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10967 return QualType(); 10968 // In C++, a prefix increment is the same type as the operand. Otherwise 10969 // (in C or with postfix), the increment is the unqualified type of the 10970 // operand. 10971 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10972 VK = VK_LValue; 10973 OK = Op->getObjectKind(); 10974 return ResType; 10975 } else { 10976 VK = VK_RValue; 10977 return ResType.getUnqualifiedType(); 10978 } 10979 } 10980 10981 10982 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10983 /// This routine allows us to typecheck complex/recursive expressions 10984 /// where the declaration is needed for type checking. We only need to 10985 /// handle cases when the expression references a function designator 10986 /// or is an lvalue. Here are some examples: 10987 /// - &(x) => x 10988 /// - &*****f => f for f a function designator. 10989 /// - &s.xx => s 10990 /// - &s.zz[1].yy -> s, if zz is an array 10991 /// - *(x + 1) -> x, if x is an array 10992 /// - &"123"[2] -> 0 10993 /// - & __real__ x -> x 10994 static ValueDecl *getPrimaryDecl(Expr *E) { 10995 switch (E->getStmtClass()) { 10996 case Stmt::DeclRefExprClass: 10997 return cast<DeclRefExpr>(E)->getDecl(); 10998 case Stmt::MemberExprClass: 10999 // If this is an arrow operator, the address is an offset from 11000 // the base's value, so the object the base refers to is 11001 // irrelevant. 11002 if (cast<MemberExpr>(E)->isArrow()) 11003 return nullptr; 11004 // Otherwise, the expression refers to a part of the base 11005 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11006 case Stmt::ArraySubscriptExprClass: { 11007 // FIXME: This code shouldn't be necessary! We should catch the implicit 11008 // promotion of register arrays earlier. 11009 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11010 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11011 if (ICE->getSubExpr()->getType()->isArrayType()) 11012 return getPrimaryDecl(ICE->getSubExpr()); 11013 } 11014 return nullptr; 11015 } 11016 case Stmt::UnaryOperatorClass: { 11017 UnaryOperator *UO = cast<UnaryOperator>(E); 11018 11019 switch(UO->getOpcode()) { 11020 case UO_Real: 11021 case UO_Imag: 11022 case UO_Extension: 11023 return getPrimaryDecl(UO->getSubExpr()); 11024 default: 11025 return nullptr; 11026 } 11027 } 11028 case Stmt::ParenExprClass: 11029 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11030 case Stmt::ImplicitCastExprClass: 11031 // If the result of an implicit cast is an l-value, we care about 11032 // the sub-expression; otherwise, the result here doesn't matter. 11033 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11034 default: 11035 return nullptr; 11036 } 11037 } 11038 11039 namespace { 11040 enum { 11041 AO_Bit_Field = 0, 11042 AO_Vector_Element = 1, 11043 AO_Property_Expansion = 2, 11044 AO_Register_Variable = 3, 11045 AO_No_Error = 4 11046 }; 11047 } 11048 /// \brief Diagnose invalid operand for address of operations. 11049 /// 11050 /// \param Type The type of operand which cannot have its address taken. 11051 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11052 Expr *E, unsigned Type) { 11053 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11054 } 11055 11056 /// CheckAddressOfOperand - The operand of & must be either a function 11057 /// designator or an lvalue designating an object. If it is an lvalue, the 11058 /// object cannot be declared with storage class register or be a bit field. 11059 /// Note: The usual conversions are *not* applied to the operand of the & 11060 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11061 /// In C++, the operand might be an overloaded function name, in which case 11062 /// we allow the '&' but retain the overloaded-function type. 11063 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11064 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11065 if (PTy->getKind() == BuiltinType::Overload) { 11066 Expr *E = OrigOp.get()->IgnoreParens(); 11067 if (!isa<OverloadExpr>(E)) { 11068 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11069 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11070 << OrigOp.get()->getSourceRange(); 11071 return QualType(); 11072 } 11073 11074 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11075 if (isa<UnresolvedMemberExpr>(Ovl)) 11076 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11077 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11078 << OrigOp.get()->getSourceRange(); 11079 return QualType(); 11080 } 11081 11082 return Context.OverloadTy; 11083 } 11084 11085 if (PTy->getKind() == BuiltinType::UnknownAny) 11086 return Context.UnknownAnyTy; 11087 11088 if (PTy->getKind() == BuiltinType::BoundMember) { 11089 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11090 << OrigOp.get()->getSourceRange(); 11091 return QualType(); 11092 } 11093 11094 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11095 if (OrigOp.isInvalid()) return QualType(); 11096 } 11097 11098 if (OrigOp.get()->isTypeDependent()) 11099 return Context.DependentTy; 11100 11101 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11102 11103 // Make sure to ignore parentheses in subsequent checks 11104 Expr *op = OrigOp.get()->IgnoreParens(); 11105 11106 // In OpenCL captures for blocks called as lambda functions 11107 // are located in the private address space. Blocks used in 11108 // enqueue_kernel can be located in a different address space 11109 // depending on a vendor implementation. Thus preventing 11110 // taking an address of the capture to avoid invalid AS casts. 11111 if (LangOpts.OpenCL) { 11112 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11113 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11114 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11115 return QualType(); 11116 } 11117 } 11118 11119 if (getLangOpts().C99) { 11120 // Implement C99-only parts of addressof rules. 11121 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11122 if (uOp->getOpcode() == UO_Deref) 11123 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11124 // (assuming the deref expression is valid). 11125 return uOp->getSubExpr()->getType(); 11126 } 11127 // Technically, there should be a check for array subscript 11128 // expressions here, but the result of one is always an lvalue anyway. 11129 } 11130 ValueDecl *dcl = getPrimaryDecl(op); 11131 11132 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11133 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11134 op->getLocStart())) 11135 return QualType(); 11136 11137 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11138 unsigned AddressOfError = AO_No_Error; 11139 11140 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11141 bool sfinae = (bool)isSFINAEContext(); 11142 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11143 : diag::ext_typecheck_addrof_temporary) 11144 << op->getType() << op->getSourceRange(); 11145 if (sfinae) 11146 return QualType(); 11147 // Materialize the temporary as an lvalue so that we can take its address. 11148 OrigOp = op = 11149 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11150 } else if (isa<ObjCSelectorExpr>(op)) { 11151 return Context.getPointerType(op->getType()); 11152 } else if (lval == Expr::LV_MemberFunction) { 11153 // If it's an instance method, make a member pointer. 11154 // The expression must have exactly the form &A::foo. 11155 11156 // If the underlying expression isn't a decl ref, give up. 11157 if (!isa<DeclRefExpr>(op)) { 11158 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11159 << OrigOp.get()->getSourceRange(); 11160 return QualType(); 11161 } 11162 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11163 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11164 11165 // The id-expression was parenthesized. 11166 if (OrigOp.get() != DRE) { 11167 Diag(OpLoc, diag::err_parens_pointer_member_function) 11168 << OrigOp.get()->getSourceRange(); 11169 11170 // The method was named without a qualifier. 11171 } else if (!DRE->getQualifier()) { 11172 if (MD->getParent()->getName().empty()) 11173 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11174 << op->getSourceRange(); 11175 else { 11176 SmallString<32> Str; 11177 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11178 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11179 << op->getSourceRange() 11180 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11181 } 11182 } 11183 11184 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11185 if (isa<CXXDestructorDecl>(MD)) 11186 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11187 11188 QualType MPTy = Context.getMemberPointerType( 11189 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11190 // Under the MS ABI, lock down the inheritance model now. 11191 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11192 (void)isCompleteType(OpLoc, MPTy); 11193 return MPTy; 11194 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11195 // C99 6.5.3.2p1 11196 // The operand must be either an l-value or a function designator 11197 if (!op->getType()->isFunctionType()) { 11198 // Use a special diagnostic for loads from property references. 11199 if (isa<PseudoObjectExpr>(op)) { 11200 AddressOfError = AO_Property_Expansion; 11201 } else { 11202 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11203 << op->getType() << op->getSourceRange(); 11204 return QualType(); 11205 } 11206 } 11207 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11208 // The operand cannot be a bit-field 11209 AddressOfError = AO_Bit_Field; 11210 } else if (op->getObjectKind() == OK_VectorComponent) { 11211 // The operand cannot be an element of a vector 11212 AddressOfError = AO_Vector_Element; 11213 } else if (dcl) { // C99 6.5.3.2p1 11214 // We have an lvalue with a decl. Make sure the decl is not declared 11215 // with the register storage-class specifier. 11216 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11217 // in C++ it is not error to take address of a register 11218 // variable (c++03 7.1.1P3) 11219 if (vd->getStorageClass() == SC_Register && 11220 !getLangOpts().CPlusPlus) { 11221 AddressOfError = AO_Register_Variable; 11222 } 11223 } else if (isa<MSPropertyDecl>(dcl)) { 11224 AddressOfError = AO_Property_Expansion; 11225 } else if (isa<FunctionTemplateDecl>(dcl)) { 11226 return Context.OverloadTy; 11227 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11228 // Okay: we can take the address of a field. 11229 // Could be a pointer to member, though, if there is an explicit 11230 // scope qualifier for the class. 11231 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11232 DeclContext *Ctx = dcl->getDeclContext(); 11233 if (Ctx && Ctx->isRecord()) { 11234 if (dcl->getType()->isReferenceType()) { 11235 Diag(OpLoc, 11236 diag::err_cannot_form_pointer_to_member_of_reference_type) 11237 << dcl->getDeclName() << dcl->getType(); 11238 return QualType(); 11239 } 11240 11241 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11242 Ctx = Ctx->getParent(); 11243 11244 QualType MPTy = Context.getMemberPointerType( 11245 op->getType(), 11246 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11247 // Under the MS ABI, lock down the inheritance model now. 11248 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11249 (void)isCompleteType(OpLoc, MPTy); 11250 return MPTy; 11251 } 11252 } 11253 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11254 !isa<BindingDecl>(dcl)) 11255 llvm_unreachable("Unknown/unexpected decl type"); 11256 } 11257 11258 if (AddressOfError != AO_No_Error) { 11259 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11260 return QualType(); 11261 } 11262 11263 if (lval == Expr::LV_IncompleteVoidType) { 11264 // Taking the address of a void variable is technically illegal, but we 11265 // allow it in cases which are otherwise valid. 11266 // Example: "extern void x; void* y = &x;". 11267 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11268 } 11269 11270 // If the operand has type "type", the result has type "pointer to type". 11271 if (op->getType()->isObjCObjectType()) 11272 return Context.getObjCObjectPointerType(op->getType()); 11273 11274 CheckAddressOfPackedMember(op); 11275 11276 return Context.getPointerType(op->getType()); 11277 } 11278 11279 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11280 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11281 if (!DRE) 11282 return; 11283 const Decl *D = DRE->getDecl(); 11284 if (!D) 11285 return; 11286 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11287 if (!Param) 11288 return; 11289 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11290 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11291 return; 11292 if (FunctionScopeInfo *FD = S.getCurFunction()) 11293 if (!FD->ModifiedNonNullParams.count(Param)) 11294 FD->ModifiedNonNullParams.insert(Param); 11295 } 11296 11297 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11298 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11299 SourceLocation OpLoc) { 11300 if (Op->isTypeDependent()) 11301 return S.Context.DependentTy; 11302 11303 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11304 if (ConvResult.isInvalid()) 11305 return QualType(); 11306 Op = ConvResult.get(); 11307 QualType OpTy = Op->getType(); 11308 QualType Result; 11309 11310 if (isa<CXXReinterpretCastExpr>(Op)) { 11311 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11312 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11313 Op->getSourceRange()); 11314 } 11315 11316 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11317 { 11318 Result = PT->getPointeeType(); 11319 } 11320 else if (const ObjCObjectPointerType *OPT = 11321 OpTy->getAs<ObjCObjectPointerType>()) 11322 Result = OPT->getPointeeType(); 11323 else { 11324 ExprResult PR = S.CheckPlaceholderExpr(Op); 11325 if (PR.isInvalid()) return QualType(); 11326 if (PR.get() != Op) 11327 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11328 } 11329 11330 if (Result.isNull()) { 11331 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11332 << OpTy << Op->getSourceRange(); 11333 return QualType(); 11334 } 11335 11336 // Note that per both C89 and C99, indirection is always legal, even if Result 11337 // is an incomplete type or void. It would be possible to warn about 11338 // dereferencing a void pointer, but it's completely well-defined, and such a 11339 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11340 // for pointers to 'void' but is fine for any other pointer type: 11341 // 11342 // C++ [expr.unary.op]p1: 11343 // [...] the expression to which [the unary * operator] is applied shall 11344 // be a pointer to an object type, or a pointer to a function type 11345 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11346 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11347 << OpTy << Op->getSourceRange(); 11348 11349 // Dereferences are usually l-values... 11350 VK = VK_LValue; 11351 11352 // ...except that certain expressions are never l-values in C. 11353 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11354 VK = VK_RValue; 11355 11356 return Result; 11357 } 11358 11359 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11360 BinaryOperatorKind Opc; 11361 switch (Kind) { 11362 default: llvm_unreachable("Unknown binop!"); 11363 case tok::periodstar: Opc = BO_PtrMemD; break; 11364 case tok::arrowstar: Opc = BO_PtrMemI; break; 11365 case tok::star: Opc = BO_Mul; break; 11366 case tok::slash: Opc = BO_Div; break; 11367 case tok::percent: Opc = BO_Rem; break; 11368 case tok::plus: Opc = BO_Add; break; 11369 case tok::minus: Opc = BO_Sub; break; 11370 case tok::lessless: Opc = BO_Shl; break; 11371 case tok::greatergreater: Opc = BO_Shr; break; 11372 case tok::lessequal: Opc = BO_LE; break; 11373 case tok::less: Opc = BO_LT; break; 11374 case tok::greaterequal: Opc = BO_GE; break; 11375 case tok::greater: Opc = BO_GT; break; 11376 case tok::exclaimequal: Opc = BO_NE; break; 11377 case tok::equalequal: Opc = BO_EQ; break; 11378 case tok::amp: Opc = BO_And; break; 11379 case tok::caret: Opc = BO_Xor; break; 11380 case tok::pipe: Opc = BO_Or; break; 11381 case tok::ampamp: Opc = BO_LAnd; break; 11382 case tok::pipepipe: Opc = BO_LOr; break; 11383 case tok::equal: Opc = BO_Assign; break; 11384 case tok::starequal: Opc = BO_MulAssign; break; 11385 case tok::slashequal: Opc = BO_DivAssign; break; 11386 case tok::percentequal: Opc = BO_RemAssign; break; 11387 case tok::plusequal: Opc = BO_AddAssign; break; 11388 case tok::minusequal: Opc = BO_SubAssign; break; 11389 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11390 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11391 case tok::ampequal: Opc = BO_AndAssign; break; 11392 case tok::caretequal: Opc = BO_XorAssign; break; 11393 case tok::pipeequal: Opc = BO_OrAssign; break; 11394 case tok::comma: Opc = BO_Comma; break; 11395 } 11396 return Opc; 11397 } 11398 11399 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11400 tok::TokenKind Kind) { 11401 UnaryOperatorKind Opc; 11402 switch (Kind) { 11403 default: llvm_unreachable("Unknown unary op!"); 11404 case tok::plusplus: Opc = UO_PreInc; break; 11405 case tok::minusminus: Opc = UO_PreDec; break; 11406 case tok::amp: Opc = UO_AddrOf; break; 11407 case tok::star: Opc = UO_Deref; break; 11408 case tok::plus: Opc = UO_Plus; break; 11409 case tok::minus: Opc = UO_Minus; break; 11410 case tok::tilde: Opc = UO_Not; break; 11411 case tok::exclaim: Opc = UO_LNot; break; 11412 case tok::kw___real: Opc = UO_Real; break; 11413 case tok::kw___imag: Opc = UO_Imag; break; 11414 case tok::kw___extension__: Opc = UO_Extension; break; 11415 } 11416 return Opc; 11417 } 11418 11419 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11420 /// This warning is only emitted for builtin assignment operations. It is also 11421 /// suppressed in the event of macro expansions. 11422 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11423 SourceLocation OpLoc) { 11424 if (S.inTemplateInstantiation()) 11425 return; 11426 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11427 return; 11428 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11429 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11430 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11431 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11432 if (!LHSDeclRef || !RHSDeclRef || 11433 LHSDeclRef->getLocation().isMacroID() || 11434 RHSDeclRef->getLocation().isMacroID()) 11435 return; 11436 const ValueDecl *LHSDecl = 11437 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11438 const ValueDecl *RHSDecl = 11439 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11440 if (LHSDecl != RHSDecl) 11441 return; 11442 if (LHSDecl->getType().isVolatileQualified()) 11443 return; 11444 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11445 if (RefTy->getPointeeType().isVolatileQualified()) 11446 return; 11447 11448 S.Diag(OpLoc, diag::warn_self_assignment) 11449 << LHSDeclRef->getType() 11450 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11451 } 11452 11453 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11454 /// is usually indicative of introspection within the Objective-C pointer. 11455 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11456 SourceLocation OpLoc) { 11457 if (!S.getLangOpts().ObjC1) 11458 return; 11459 11460 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11461 const Expr *LHS = L.get(); 11462 const Expr *RHS = R.get(); 11463 11464 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11465 ObjCPointerExpr = LHS; 11466 OtherExpr = RHS; 11467 } 11468 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11469 ObjCPointerExpr = RHS; 11470 OtherExpr = LHS; 11471 } 11472 11473 // This warning is deliberately made very specific to reduce false 11474 // positives with logic that uses '&' for hashing. This logic mainly 11475 // looks for code trying to introspect into tagged pointers, which 11476 // code should generally never do. 11477 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11478 unsigned Diag = diag::warn_objc_pointer_masking; 11479 // Determine if we are introspecting the result of performSelectorXXX. 11480 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11481 // Special case messages to -performSelector and friends, which 11482 // can return non-pointer values boxed in a pointer value. 11483 // Some clients may wish to silence warnings in this subcase. 11484 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11485 Selector S = ME->getSelector(); 11486 StringRef SelArg0 = S.getNameForSlot(0); 11487 if (SelArg0.startswith("performSelector")) 11488 Diag = diag::warn_objc_pointer_masking_performSelector; 11489 } 11490 11491 S.Diag(OpLoc, Diag) 11492 << ObjCPointerExpr->getSourceRange(); 11493 } 11494 } 11495 11496 static NamedDecl *getDeclFromExpr(Expr *E) { 11497 if (!E) 11498 return nullptr; 11499 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11500 return DRE->getDecl(); 11501 if (auto *ME = dyn_cast<MemberExpr>(E)) 11502 return ME->getMemberDecl(); 11503 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11504 return IRE->getDecl(); 11505 return nullptr; 11506 } 11507 11508 // This helper function promotes a binary operator's operands (which are of a 11509 // half vector type) to a vector of floats and then truncates the result to 11510 // a vector of either half or short. 11511 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11512 BinaryOperatorKind Opc, QualType ResultTy, 11513 ExprValueKind VK, ExprObjectKind OK, 11514 bool IsCompAssign, SourceLocation OpLoc, 11515 FPOptions FPFeatures) { 11516 auto &Context = S.getASTContext(); 11517 assert((isVector(ResultTy, Context.HalfTy) || 11518 isVector(ResultTy, Context.ShortTy)) && 11519 "Result must be a vector of half or short"); 11520 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11521 isVector(RHS.get()->getType(), Context.HalfTy) && 11522 "both operands expected to be a half vector"); 11523 11524 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11525 QualType BinOpResTy = RHS.get()->getType(); 11526 11527 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11528 // change BinOpResTy to a vector of ints. 11529 if (isVector(ResultTy, Context.ShortTy)) 11530 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11531 11532 if (IsCompAssign) 11533 return new (Context) CompoundAssignOperator( 11534 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11535 OpLoc, FPFeatures); 11536 11537 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11538 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11539 VK, OK, OpLoc, FPFeatures); 11540 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11541 } 11542 11543 static std::pair<ExprResult, ExprResult> 11544 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11545 Expr *RHSExpr) { 11546 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11547 if (!S.getLangOpts().CPlusPlus) { 11548 // C cannot handle TypoExpr nodes on either side of a binop because it 11549 // doesn't handle dependent types properly, so make sure any TypoExprs have 11550 // been dealt with before checking the operands. 11551 LHS = S.CorrectDelayedTyposInExpr(LHS); 11552 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11553 if (Opc != BO_Assign) 11554 return ExprResult(E); 11555 // Avoid correcting the RHS to the same Expr as the LHS. 11556 Decl *D = getDeclFromExpr(E); 11557 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11558 }); 11559 } 11560 return std::make_pair(LHS, RHS); 11561 } 11562 11563 /// Returns true if conversion between vectors of halfs and vectors of floats 11564 /// is needed. 11565 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11566 QualType SrcType) { 11567 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11568 Ctx.getLangOpts().HalfArgsAndReturns && isVector(SrcType, Ctx.HalfTy); 11569 } 11570 11571 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11572 /// operator @p Opc at location @c TokLoc. This routine only supports 11573 /// built-in operations; ActOnBinOp handles overloaded operators. 11574 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11575 BinaryOperatorKind Opc, 11576 Expr *LHSExpr, Expr *RHSExpr) { 11577 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11578 // The syntax only allows initializer lists on the RHS of assignment, 11579 // so we don't need to worry about accepting invalid code for 11580 // non-assignment operators. 11581 // C++11 5.17p9: 11582 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11583 // of x = {} is x = T(). 11584 InitializationKind Kind = 11585 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11586 InitializedEntity Entity = 11587 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11588 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11589 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11590 if (Init.isInvalid()) 11591 return Init; 11592 RHSExpr = Init.get(); 11593 } 11594 11595 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11596 QualType ResultTy; // Result type of the binary operator. 11597 // The following two variables are used for compound assignment operators 11598 QualType CompLHSTy; // Type of LHS after promotions for computation 11599 QualType CompResultTy; // Type of computation result 11600 ExprValueKind VK = VK_RValue; 11601 ExprObjectKind OK = OK_Ordinary; 11602 bool ConvertHalfVec = false; 11603 11604 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11605 if (!LHS.isUsable() || !RHS.isUsable()) 11606 return ExprError(); 11607 11608 if (getLangOpts().OpenCL) { 11609 QualType LHSTy = LHSExpr->getType(); 11610 QualType RHSTy = RHSExpr->getType(); 11611 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11612 // the ATOMIC_VAR_INIT macro. 11613 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11614 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11615 if (BO_Assign == Opc) 11616 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11617 else 11618 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11619 return ExprError(); 11620 } 11621 11622 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11623 // only with a builtin functions and therefore should be disallowed here. 11624 if (LHSTy->isImageType() || RHSTy->isImageType() || 11625 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11626 LHSTy->isPipeType() || RHSTy->isPipeType() || 11627 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11628 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11629 return ExprError(); 11630 } 11631 } 11632 11633 switch (Opc) { 11634 case BO_Assign: 11635 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11636 if (getLangOpts().CPlusPlus && 11637 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11638 VK = LHS.get()->getValueKind(); 11639 OK = LHS.get()->getObjectKind(); 11640 } 11641 if (!ResultTy.isNull()) { 11642 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11643 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11644 } 11645 RecordModifiableNonNullParam(*this, LHS.get()); 11646 break; 11647 case BO_PtrMemD: 11648 case BO_PtrMemI: 11649 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11650 Opc == BO_PtrMemI); 11651 break; 11652 case BO_Mul: 11653 case BO_Div: 11654 ConvertHalfVec = true; 11655 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11656 Opc == BO_Div); 11657 break; 11658 case BO_Rem: 11659 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11660 break; 11661 case BO_Add: 11662 ConvertHalfVec = true; 11663 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11664 break; 11665 case BO_Sub: 11666 ConvertHalfVec = true; 11667 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11668 break; 11669 case BO_Shl: 11670 case BO_Shr: 11671 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11672 break; 11673 case BO_LE: 11674 case BO_LT: 11675 case BO_GE: 11676 case BO_GT: 11677 ConvertHalfVec = true; 11678 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11679 break; 11680 case BO_EQ: 11681 case BO_NE: 11682 ConvertHalfVec = true; 11683 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11684 break; 11685 case BO_And: 11686 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11687 LLVM_FALLTHROUGH; 11688 case BO_Xor: 11689 case BO_Or: 11690 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11691 break; 11692 case BO_LAnd: 11693 case BO_LOr: 11694 ConvertHalfVec = true; 11695 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11696 break; 11697 case BO_MulAssign: 11698 case BO_DivAssign: 11699 ConvertHalfVec = true; 11700 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11701 Opc == BO_DivAssign); 11702 CompLHSTy = CompResultTy; 11703 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11704 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11705 break; 11706 case BO_RemAssign: 11707 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11708 CompLHSTy = CompResultTy; 11709 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11710 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11711 break; 11712 case BO_AddAssign: 11713 ConvertHalfVec = true; 11714 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11715 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11716 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11717 break; 11718 case BO_SubAssign: 11719 ConvertHalfVec = true; 11720 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11721 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11722 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11723 break; 11724 case BO_ShlAssign: 11725 case BO_ShrAssign: 11726 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11727 CompLHSTy = CompResultTy; 11728 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11729 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11730 break; 11731 case BO_AndAssign: 11732 case BO_OrAssign: // fallthrough 11733 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11734 LLVM_FALLTHROUGH; 11735 case BO_XorAssign: 11736 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11737 CompLHSTy = CompResultTy; 11738 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11739 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11740 break; 11741 case BO_Comma: 11742 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11743 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11744 VK = RHS.get()->getValueKind(); 11745 OK = RHS.get()->getObjectKind(); 11746 } 11747 break; 11748 } 11749 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11750 return ExprError(); 11751 11752 // Some of the binary operations require promoting operands of half vector to 11753 // float vectors and truncating the result back to half vector. For now, we do 11754 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11755 // arm64). 11756 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11757 isVector(LHS.get()->getType(), Context.HalfTy) && 11758 "both sides are half vectors or neither sides are"); 11759 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11760 LHS.get()->getType()); 11761 11762 // Check for array bounds violations for both sides of the BinaryOperator 11763 CheckArrayAccess(LHS.get()); 11764 CheckArrayAccess(RHS.get()); 11765 11766 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11767 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11768 &Context.Idents.get("object_setClass"), 11769 SourceLocation(), LookupOrdinaryName); 11770 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11771 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11772 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11773 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11774 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11775 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11776 } 11777 else 11778 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11779 } 11780 else if (const ObjCIvarRefExpr *OIRE = 11781 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11782 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11783 11784 // Opc is not a compound assignment if CompResultTy is null. 11785 if (CompResultTy.isNull()) { 11786 if (ConvertHalfVec) 11787 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11788 OpLoc, FPFeatures); 11789 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11790 OK, OpLoc, FPFeatures); 11791 } 11792 11793 // Handle compound assignments. 11794 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11795 OK_ObjCProperty) { 11796 VK = VK_LValue; 11797 OK = LHS.get()->getObjectKind(); 11798 } 11799 11800 if (ConvertHalfVec) 11801 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11802 OpLoc, FPFeatures); 11803 11804 return new (Context) CompoundAssignOperator( 11805 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11806 OpLoc, FPFeatures); 11807 } 11808 11809 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11810 /// operators are mixed in a way that suggests that the programmer forgot that 11811 /// comparison operators have higher precedence. The most typical example of 11812 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11813 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11814 SourceLocation OpLoc, Expr *LHSExpr, 11815 Expr *RHSExpr) { 11816 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11817 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11818 11819 // Check that one of the sides is a comparison operator and the other isn't. 11820 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11821 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11822 if (isLeftComp == isRightComp) 11823 return; 11824 11825 // Bitwise operations are sometimes used as eager logical ops. 11826 // Don't diagnose this. 11827 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11828 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11829 if (isLeftBitwise || isRightBitwise) 11830 return; 11831 11832 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11833 OpLoc) 11834 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11835 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11836 SourceRange ParensRange = isLeftComp ? 11837 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11838 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11839 11840 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11841 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11842 SuggestParentheses(Self, OpLoc, 11843 Self.PDiag(diag::note_precedence_silence) << OpStr, 11844 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11845 SuggestParentheses(Self, OpLoc, 11846 Self.PDiag(diag::note_precedence_bitwise_first) 11847 << BinaryOperator::getOpcodeStr(Opc), 11848 ParensRange); 11849 } 11850 11851 /// \brief It accepts a '&&' expr that is inside a '||' one. 11852 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11853 /// in parentheses. 11854 static void 11855 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11856 BinaryOperator *Bop) { 11857 assert(Bop->getOpcode() == BO_LAnd); 11858 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11859 << Bop->getSourceRange() << OpLoc; 11860 SuggestParentheses(Self, Bop->getOperatorLoc(), 11861 Self.PDiag(diag::note_precedence_silence) 11862 << Bop->getOpcodeStr(), 11863 Bop->getSourceRange()); 11864 } 11865 11866 /// \brief Returns true if the given expression can be evaluated as a constant 11867 /// 'true'. 11868 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11869 bool Res; 11870 return !E->isValueDependent() && 11871 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11872 } 11873 11874 /// \brief Returns true if the given expression can be evaluated as a constant 11875 /// 'false'. 11876 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11877 bool Res; 11878 return !E->isValueDependent() && 11879 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11880 } 11881 11882 /// \brief Look for '&&' in the left hand of a '||' expr. 11883 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11884 Expr *LHSExpr, Expr *RHSExpr) { 11885 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11886 if (Bop->getOpcode() == BO_LAnd) { 11887 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11888 if (EvaluatesAsFalse(S, RHSExpr)) 11889 return; 11890 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11891 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11892 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11893 } else if (Bop->getOpcode() == BO_LOr) { 11894 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11895 // If it's "a || b && 1 || c" we didn't warn earlier for 11896 // "a || b && 1", but warn now. 11897 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11898 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11899 } 11900 } 11901 } 11902 } 11903 11904 /// \brief Look for '&&' in the right hand of a '||' expr. 11905 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11906 Expr *LHSExpr, Expr *RHSExpr) { 11907 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11908 if (Bop->getOpcode() == BO_LAnd) { 11909 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11910 if (EvaluatesAsFalse(S, LHSExpr)) 11911 return; 11912 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11913 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11914 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11915 } 11916 } 11917 } 11918 11919 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11920 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11921 /// the '&' expression in parentheses. 11922 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11923 SourceLocation OpLoc, Expr *SubExpr) { 11924 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11925 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11926 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11927 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11928 << Bop->getSourceRange() << OpLoc; 11929 SuggestParentheses(S, Bop->getOperatorLoc(), 11930 S.PDiag(diag::note_precedence_silence) 11931 << Bop->getOpcodeStr(), 11932 Bop->getSourceRange()); 11933 } 11934 } 11935 } 11936 11937 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11938 Expr *SubExpr, StringRef Shift) { 11939 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11940 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11941 StringRef Op = Bop->getOpcodeStr(); 11942 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11943 << Bop->getSourceRange() << OpLoc << Shift << Op; 11944 SuggestParentheses(S, Bop->getOperatorLoc(), 11945 S.PDiag(diag::note_precedence_silence) << Op, 11946 Bop->getSourceRange()); 11947 } 11948 } 11949 } 11950 11951 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11952 Expr *LHSExpr, Expr *RHSExpr) { 11953 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11954 if (!OCE) 11955 return; 11956 11957 FunctionDecl *FD = OCE->getDirectCallee(); 11958 if (!FD || !FD->isOverloadedOperator()) 11959 return; 11960 11961 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11962 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11963 return; 11964 11965 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11966 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11967 << (Kind == OO_LessLess); 11968 SuggestParentheses(S, OCE->getOperatorLoc(), 11969 S.PDiag(diag::note_precedence_silence) 11970 << (Kind == OO_LessLess ? "<<" : ">>"), 11971 OCE->getSourceRange()); 11972 SuggestParentheses(S, OpLoc, 11973 S.PDiag(diag::note_evaluate_comparison_first), 11974 SourceRange(OCE->getArg(1)->getLocStart(), 11975 RHSExpr->getLocEnd())); 11976 } 11977 11978 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11979 /// precedence. 11980 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11981 SourceLocation OpLoc, Expr *LHSExpr, 11982 Expr *RHSExpr){ 11983 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11984 if (BinaryOperator::isBitwiseOp(Opc)) 11985 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11986 11987 // Diagnose "arg1 & arg2 | arg3" 11988 if ((Opc == BO_Or || Opc == BO_Xor) && 11989 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11990 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11991 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11992 } 11993 11994 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11995 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11996 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11997 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11998 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11999 } 12000 12001 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12002 || Opc == BO_Shr) { 12003 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12004 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12005 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12006 } 12007 12008 // Warn on overloaded shift operators and comparisons, such as: 12009 // cout << 5 == 4; 12010 if (BinaryOperator::isComparisonOp(Opc)) 12011 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12012 } 12013 12014 // Binary Operators. 'Tok' is the token for the operator. 12015 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12016 tok::TokenKind Kind, 12017 Expr *LHSExpr, Expr *RHSExpr) { 12018 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12019 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12020 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12021 12022 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12023 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12024 12025 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12026 } 12027 12028 /// Build an overloaded binary operator expression in the given scope. 12029 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12030 BinaryOperatorKind Opc, 12031 Expr *LHS, Expr *RHS) { 12032 // Find all of the overloaded operators visible from this 12033 // point. We perform both an operator-name lookup from the local 12034 // scope and an argument-dependent lookup based on the types of 12035 // the arguments. 12036 UnresolvedSet<16> Functions; 12037 OverloadedOperatorKind OverOp 12038 = BinaryOperator::getOverloadedOperator(Opc); 12039 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12040 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12041 RHS->getType(), Functions); 12042 12043 // Build the (potentially-overloaded, potentially-dependent) 12044 // binary operation. 12045 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12046 } 12047 12048 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12049 BinaryOperatorKind Opc, 12050 Expr *LHSExpr, Expr *RHSExpr) { 12051 ExprResult LHS, RHS; 12052 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12053 if (!LHS.isUsable() || !RHS.isUsable()) 12054 return ExprError(); 12055 LHSExpr = LHS.get(); 12056 RHSExpr = RHS.get(); 12057 12058 // We want to end up calling one of checkPseudoObjectAssignment 12059 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12060 // both expressions are overloadable or either is type-dependent), 12061 // or CreateBuiltinBinOp (in any other case). We also want to get 12062 // any placeholder types out of the way. 12063 12064 // Handle pseudo-objects in the LHS. 12065 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12066 // Assignments with a pseudo-object l-value need special analysis. 12067 if (pty->getKind() == BuiltinType::PseudoObject && 12068 BinaryOperator::isAssignmentOp(Opc)) 12069 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12070 12071 // Don't resolve overloads if the other type is overloadable. 12072 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12073 // We can't actually test that if we still have a placeholder, 12074 // though. Fortunately, none of the exceptions we see in that 12075 // code below are valid when the LHS is an overload set. Note 12076 // that an overload set can be dependently-typed, but it never 12077 // instantiates to having an overloadable type. 12078 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12079 if (resolvedRHS.isInvalid()) return ExprError(); 12080 RHSExpr = resolvedRHS.get(); 12081 12082 if (RHSExpr->isTypeDependent() || 12083 RHSExpr->getType()->isOverloadableType()) 12084 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12085 } 12086 12087 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12088 // template, diagnose the missing 'template' keyword instead of diagnosing 12089 // an invalid use of a bound member function. 12090 // 12091 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12092 // to C++1z [over.over]/1.4, but we already checked for that case above. 12093 if (Opc == BO_LT && inTemplateInstantiation() && 12094 (pty->getKind() == BuiltinType::BoundMember || 12095 pty->getKind() == BuiltinType::Overload)) { 12096 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12097 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12098 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12099 return isa<FunctionTemplateDecl>(ND); 12100 })) { 12101 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12102 : OE->getNameLoc(), 12103 diag::err_template_kw_missing) 12104 << OE->getName().getAsString() << ""; 12105 return ExprError(); 12106 } 12107 } 12108 12109 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12110 if (LHS.isInvalid()) return ExprError(); 12111 LHSExpr = LHS.get(); 12112 } 12113 12114 // Handle pseudo-objects in the RHS. 12115 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12116 // An overload in the RHS can potentially be resolved by the type 12117 // being assigned to. 12118 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12119 if (getLangOpts().CPlusPlus && 12120 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12121 LHSExpr->getType()->isOverloadableType())) 12122 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12123 12124 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12125 } 12126 12127 // Don't resolve overloads if the other type is overloadable. 12128 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12129 LHSExpr->getType()->isOverloadableType()) 12130 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12131 12132 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12133 if (!resolvedRHS.isUsable()) return ExprError(); 12134 RHSExpr = resolvedRHS.get(); 12135 } 12136 12137 if (getLangOpts().CPlusPlus) { 12138 // If either expression is type-dependent, always build an 12139 // overloaded op. 12140 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12141 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12142 12143 // Otherwise, build an overloaded op if either expression has an 12144 // overloadable type. 12145 if (LHSExpr->getType()->isOverloadableType() || 12146 RHSExpr->getType()->isOverloadableType()) 12147 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12148 } 12149 12150 // Build a built-in binary operation. 12151 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12152 } 12153 12154 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12155 UnaryOperatorKind Opc, 12156 Expr *InputExpr) { 12157 ExprResult Input = InputExpr; 12158 ExprValueKind VK = VK_RValue; 12159 ExprObjectKind OK = OK_Ordinary; 12160 QualType resultType; 12161 bool ConvertHalfVec = false; 12162 if (getLangOpts().OpenCL) { 12163 QualType Ty = InputExpr->getType(); 12164 // The only legal unary operation for atomics is '&'. 12165 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12166 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12167 // only with a builtin functions and therefore should be disallowed here. 12168 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12169 || Ty->isBlockPointerType())) { 12170 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12171 << InputExpr->getType() 12172 << Input.get()->getSourceRange()); 12173 } 12174 } 12175 switch (Opc) { 12176 case UO_PreInc: 12177 case UO_PreDec: 12178 case UO_PostInc: 12179 case UO_PostDec: 12180 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12181 OpLoc, 12182 Opc == UO_PreInc || 12183 Opc == UO_PostInc, 12184 Opc == UO_PreInc || 12185 Opc == UO_PreDec); 12186 break; 12187 case UO_AddrOf: 12188 resultType = CheckAddressOfOperand(Input, OpLoc); 12189 RecordModifiableNonNullParam(*this, InputExpr); 12190 break; 12191 case UO_Deref: { 12192 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12193 if (Input.isInvalid()) return ExprError(); 12194 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12195 break; 12196 } 12197 case UO_Plus: 12198 case UO_Minus: 12199 Input = UsualUnaryConversions(Input.get()); 12200 if (Input.isInvalid()) return ExprError(); 12201 // Unary plus and minus require promoting an operand of half vector to a 12202 // float vector and truncating the result back to a half vector. For now, we 12203 // do this only when HalfArgsAndReturns is set (that is, when the target is 12204 // arm or arm64). 12205 ConvertHalfVec = 12206 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12207 12208 // If the operand is a half vector, promote it to a float vector. 12209 if (ConvertHalfVec) 12210 Input = convertVector(Input.get(), Context.FloatTy, *this); 12211 resultType = Input.get()->getType(); 12212 if (resultType->isDependentType()) 12213 break; 12214 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12215 break; 12216 else if (resultType->isVectorType() && 12217 // The z vector extensions don't allow + or - with bool vectors. 12218 (!Context.getLangOpts().ZVector || 12219 resultType->getAs<VectorType>()->getVectorKind() != 12220 VectorType::AltiVecBool)) 12221 break; 12222 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12223 Opc == UO_Plus && 12224 resultType->isPointerType()) 12225 break; 12226 12227 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12228 << resultType << Input.get()->getSourceRange()); 12229 12230 case UO_Not: // bitwise complement 12231 Input = UsualUnaryConversions(Input.get()); 12232 if (Input.isInvalid()) 12233 return ExprError(); 12234 resultType = Input.get()->getType(); 12235 if (resultType->isDependentType()) 12236 break; 12237 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12238 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12239 // C99 does not support '~' for complex conjugation. 12240 Diag(OpLoc, diag::ext_integer_complement_complex) 12241 << resultType << Input.get()->getSourceRange(); 12242 else if (resultType->hasIntegerRepresentation()) 12243 break; 12244 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12245 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12246 // on vector float types. 12247 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12248 if (!T->isIntegerType()) 12249 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12250 << resultType << Input.get()->getSourceRange()); 12251 } else { 12252 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12253 << resultType << Input.get()->getSourceRange()); 12254 } 12255 break; 12256 12257 case UO_LNot: // logical negation 12258 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12259 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12260 if (Input.isInvalid()) return ExprError(); 12261 resultType = Input.get()->getType(); 12262 12263 // Though we still have to promote half FP to float... 12264 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12265 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12266 resultType = Context.FloatTy; 12267 } 12268 12269 if (resultType->isDependentType()) 12270 break; 12271 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12272 // C99 6.5.3.3p1: ok, fallthrough; 12273 if (Context.getLangOpts().CPlusPlus) { 12274 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12275 // operand contextually converted to bool. 12276 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12277 ScalarTypeToBooleanCastKind(resultType)); 12278 } else if (Context.getLangOpts().OpenCL && 12279 Context.getLangOpts().OpenCLVersion < 120) { 12280 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12281 // operate on scalar float types. 12282 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12283 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12284 << resultType << Input.get()->getSourceRange()); 12285 } 12286 } else if (resultType->isExtVectorType()) { 12287 if (Context.getLangOpts().OpenCL && 12288 Context.getLangOpts().OpenCLVersion < 120) { 12289 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12290 // operate on vector float types. 12291 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12292 if (!T->isIntegerType()) 12293 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12294 << resultType << Input.get()->getSourceRange()); 12295 } 12296 // Vector logical not returns the signed variant of the operand type. 12297 resultType = GetSignedVectorType(resultType); 12298 break; 12299 } else { 12300 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12301 // type in C++. We should allow that here too. 12302 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12303 << resultType << Input.get()->getSourceRange()); 12304 } 12305 12306 // LNot always has type int. C99 6.5.3.3p5. 12307 // In C++, it's bool. C++ 5.3.1p8 12308 resultType = Context.getLogicalOperationType(); 12309 break; 12310 case UO_Real: 12311 case UO_Imag: 12312 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12313 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12314 // complex l-values to ordinary l-values and all other values to r-values. 12315 if (Input.isInvalid()) return ExprError(); 12316 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12317 if (Input.get()->getValueKind() != VK_RValue && 12318 Input.get()->getObjectKind() == OK_Ordinary) 12319 VK = Input.get()->getValueKind(); 12320 } else if (!getLangOpts().CPlusPlus) { 12321 // In C, a volatile scalar is read by __imag. In C++, it is not. 12322 Input = DefaultLvalueConversion(Input.get()); 12323 } 12324 break; 12325 case UO_Extension: 12326 resultType = Input.get()->getType(); 12327 VK = Input.get()->getValueKind(); 12328 OK = Input.get()->getObjectKind(); 12329 break; 12330 case UO_Coawait: 12331 // It's unnessesary to represent the pass-through operator co_await in the 12332 // AST; just return the input expression instead. 12333 assert(!Input.get()->getType()->isDependentType() && 12334 "the co_await expression must be non-dependant before " 12335 "building operator co_await"); 12336 return Input; 12337 } 12338 if (resultType.isNull() || Input.isInvalid()) 12339 return ExprError(); 12340 12341 // Check for array bounds violations in the operand of the UnaryOperator, 12342 // except for the '*' and '&' operators that have to be handled specially 12343 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12344 // that are explicitly defined as valid by the standard). 12345 if (Opc != UO_AddrOf && Opc != UO_Deref) 12346 CheckArrayAccess(Input.get()); 12347 12348 auto *UO = new (Context) 12349 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12350 // Convert the result back to a half vector. 12351 if (ConvertHalfVec) 12352 return convertVector(UO, Context.HalfTy, *this); 12353 return UO; 12354 } 12355 12356 /// \brief Determine whether the given expression is a qualified member 12357 /// access expression, of a form that could be turned into a pointer to member 12358 /// with the address-of operator. 12359 static bool isQualifiedMemberAccess(Expr *E) { 12360 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12361 if (!DRE->getQualifier()) 12362 return false; 12363 12364 ValueDecl *VD = DRE->getDecl(); 12365 if (!VD->isCXXClassMember()) 12366 return false; 12367 12368 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12369 return true; 12370 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12371 return Method->isInstance(); 12372 12373 return false; 12374 } 12375 12376 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12377 if (!ULE->getQualifier()) 12378 return false; 12379 12380 for (NamedDecl *D : ULE->decls()) { 12381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12382 if (Method->isInstance()) 12383 return true; 12384 } else { 12385 // Overload set does not contain methods. 12386 break; 12387 } 12388 } 12389 12390 return false; 12391 } 12392 12393 return false; 12394 } 12395 12396 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12397 UnaryOperatorKind Opc, Expr *Input) { 12398 // First things first: handle placeholders so that the 12399 // overloaded-operator check considers the right type. 12400 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12401 // Increment and decrement of pseudo-object references. 12402 if (pty->getKind() == BuiltinType::PseudoObject && 12403 UnaryOperator::isIncrementDecrementOp(Opc)) 12404 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12405 12406 // extension is always a builtin operator. 12407 if (Opc == UO_Extension) 12408 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12409 12410 // & gets special logic for several kinds of placeholder. 12411 // The builtin code knows what to do. 12412 if (Opc == UO_AddrOf && 12413 (pty->getKind() == BuiltinType::Overload || 12414 pty->getKind() == BuiltinType::UnknownAny || 12415 pty->getKind() == BuiltinType::BoundMember)) 12416 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12417 12418 // Anything else needs to be handled now. 12419 ExprResult Result = CheckPlaceholderExpr(Input); 12420 if (Result.isInvalid()) return ExprError(); 12421 Input = Result.get(); 12422 } 12423 12424 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12425 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12426 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12427 // Find all of the overloaded operators visible from this 12428 // point. We perform both an operator-name lookup from the local 12429 // scope and an argument-dependent lookup based on the types of 12430 // the arguments. 12431 UnresolvedSet<16> Functions; 12432 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12433 if (S && OverOp != OO_None) 12434 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12435 Functions); 12436 12437 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12438 } 12439 12440 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12441 } 12442 12443 // Unary Operators. 'Tok' is the token for the operator. 12444 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12445 tok::TokenKind Op, Expr *Input) { 12446 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12447 } 12448 12449 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12450 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12451 LabelDecl *TheDecl) { 12452 TheDecl->markUsed(Context); 12453 // Create the AST node. The address of a label always has type 'void*'. 12454 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12455 Context.getPointerType(Context.VoidTy)); 12456 } 12457 12458 /// Given the last statement in a statement-expression, check whether 12459 /// the result is a producing expression (like a call to an 12460 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12461 /// release out of the full-expression. Otherwise, return null. 12462 /// Cannot fail. 12463 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12464 // Should always be wrapped with one of these. 12465 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12466 if (!cleanups) return nullptr; 12467 12468 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12469 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12470 return nullptr; 12471 12472 // Splice out the cast. This shouldn't modify any interesting 12473 // features of the statement. 12474 Expr *producer = cast->getSubExpr(); 12475 assert(producer->getType() == cast->getType()); 12476 assert(producer->getValueKind() == cast->getValueKind()); 12477 cleanups->setSubExpr(producer); 12478 return cleanups; 12479 } 12480 12481 void Sema::ActOnStartStmtExpr() { 12482 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12483 } 12484 12485 void Sema::ActOnStmtExprError() { 12486 // Note that function is also called by TreeTransform when leaving a 12487 // StmtExpr scope without rebuilding anything. 12488 12489 DiscardCleanupsInEvaluationContext(); 12490 PopExpressionEvaluationContext(); 12491 } 12492 12493 ExprResult 12494 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12495 SourceLocation RPLoc) { // "({..})" 12496 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12497 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12498 12499 if (hasAnyUnrecoverableErrorsInThisFunction()) 12500 DiscardCleanupsInEvaluationContext(); 12501 assert(!Cleanup.exprNeedsCleanups() && 12502 "cleanups within StmtExpr not correctly bound!"); 12503 PopExpressionEvaluationContext(); 12504 12505 // FIXME: there are a variety of strange constraints to enforce here, for 12506 // example, it is not possible to goto into a stmt expression apparently. 12507 // More semantic analysis is needed. 12508 12509 // If there are sub-stmts in the compound stmt, take the type of the last one 12510 // as the type of the stmtexpr. 12511 QualType Ty = Context.VoidTy; 12512 bool StmtExprMayBindToTemp = false; 12513 if (!Compound->body_empty()) { 12514 Stmt *LastStmt = Compound->body_back(); 12515 LabelStmt *LastLabelStmt = nullptr; 12516 // If LastStmt is a label, skip down through into the body. 12517 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12518 LastLabelStmt = Label; 12519 LastStmt = Label->getSubStmt(); 12520 } 12521 12522 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12523 // Do function/array conversion on the last expression, but not 12524 // lvalue-to-rvalue. However, initialize an unqualified type. 12525 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12526 if (LastExpr.isInvalid()) 12527 return ExprError(); 12528 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12529 12530 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12531 // In ARC, if the final expression ends in a consume, splice 12532 // the consume out and bind it later. In the alternate case 12533 // (when dealing with a retainable type), the result 12534 // initialization will create a produce. In both cases the 12535 // result will be +1, and we'll need to balance that out with 12536 // a bind. 12537 if (Expr *rebuiltLastStmt 12538 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12539 LastExpr = rebuiltLastStmt; 12540 } else { 12541 LastExpr = PerformCopyInitialization( 12542 InitializedEntity::InitializeResult(LPLoc, 12543 Ty, 12544 false), 12545 SourceLocation(), 12546 LastExpr); 12547 } 12548 12549 if (LastExpr.isInvalid()) 12550 return ExprError(); 12551 if (LastExpr.get() != nullptr) { 12552 if (!LastLabelStmt) 12553 Compound->setLastStmt(LastExpr.get()); 12554 else 12555 LastLabelStmt->setSubStmt(LastExpr.get()); 12556 StmtExprMayBindToTemp = true; 12557 } 12558 } 12559 } 12560 } 12561 12562 // FIXME: Check that expression type is complete/non-abstract; statement 12563 // expressions are not lvalues. 12564 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12565 if (StmtExprMayBindToTemp) 12566 return MaybeBindToTemporary(ResStmtExpr); 12567 return ResStmtExpr; 12568 } 12569 12570 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12571 TypeSourceInfo *TInfo, 12572 ArrayRef<OffsetOfComponent> Components, 12573 SourceLocation RParenLoc) { 12574 QualType ArgTy = TInfo->getType(); 12575 bool Dependent = ArgTy->isDependentType(); 12576 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12577 12578 // We must have at least one component that refers to the type, and the first 12579 // one is known to be a field designator. Verify that the ArgTy represents 12580 // a struct/union/class. 12581 if (!Dependent && !ArgTy->isRecordType()) 12582 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12583 << ArgTy << TypeRange); 12584 12585 // Type must be complete per C99 7.17p3 because a declaring a variable 12586 // with an incomplete type would be ill-formed. 12587 if (!Dependent 12588 && RequireCompleteType(BuiltinLoc, ArgTy, 12589 diag::err_offsetof_incomplete_type, TypeRange)) 12590 return ExprError(); 12591 12592 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12593 // GCC extension, diagnose them. 12594 // FIXME: This diagnostic isn't actually visible because the location is in 12595 // a system header! 12596 if (Components.size() != 1) 12597 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12598 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12599 12600 bool DidWarnAboutNonPOD = false; 12601 QualType CurrentType = ArgTy; 12602 SmallVector<OffsetOfNode, 4> Comps; 12603 SmallVector<Expr*, 4> Exprs; 12604 for (const OffsetOfComponent &OC : Components) { 12605 if (OC.isBrackets) { 12606 // Offset of an array sub-field. TODO: Should we allow vector elements? 12607 if (!CurrentType->isDependentType()) { 12608 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12609 if(!AT) 12610 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12611 << CurrentType); 12612 CurrentType = AT->getElementType(); 12613 } else 12614 CurrentType = Context.DependentTy; 12615 12616 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12617 if (IdxRval.isInvalid()) 12618 return ExprError(); 12619 Expr *Idx = IdxRval.get(); 12620 12621 // The expression must be an integral expression. 12622 // FIXME: An integral constant expression? 12623 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12624 !Idx->getType()->isIntegerType()) 12625 return ExprError(Diag(Idx->getLocStart(), 12626 diag::err_typecheck_subscript_not_integer) 12627 << Idx->getSourceRange()); 12628 12629 // Record this array index. 12630 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12631 Exprs.push_back(Idx); 12632 continue; 12633 } 12634 12635 // Offset of a field. 12636 if (CurrentType->isDependentType()) { 12637 // We have the offset of a field, but we can't look into the dependent 12638 // type. Just record the identifier of the field. 12639 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12640 CurrentType = Context.DependentTy; 12641 continue; 12642 } 12643 12644 // We need to have a complete type to look into. 12645 if (RequireCompleteType(OC.LocStart, CurrentType, 12646 diag::err_offsetof_incomplete_type)) 12647 return ExprError(); 12648 12649 // Look for the designated field. 12650 const RecordType *RC = CurrentType->getAs<RecordType>(); 12651 if (!RC) 12652 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12653 << CurrentType); 12654 RecordDecl *RD = RC->getDecl(); 12655 12656 // C++ [lib.support.types]p5: 12657 // The macro offsetof accepts a restricted set of type arguments in this 12658 // International Standard. type shall be a POD structure or a POD union 12659 // (clause 9). 12660 // C++11 [support.types]p4: 12661 // If type is not a standard-layout class (Clause 9), the results are 12662 // undefined. 12663 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12664 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12665 unsigned DiagID = 12666 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12667 : diag::ext_offsetof_non_pod_type; 12668 12669 if (!IsSafe && !DidWarnAboutNonPOD && 12670 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12671 PDiag(DiagID) 12672 << SourceRange(Components[0].LocStart, OC.LocEnd) 12673 << CurrentType)) 12674 DidWarnAboutNonPOD = true; 12675 } 12676 12677 // Look for the field. 12678 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12679 LookupQualifiedName(R, RD); 12680 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12681 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12682 if (!MemberDecl) { 12683 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12684 MemberDecl = IndirectMemberDecl->getAnonField(); 12685 } 12686 12687 if (!MemberDecl) 12688 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12689 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12690 OC.LocEnd)); 12691 12692 // C99 7.17p3: 12693 // (If the specified member is a bit-field, the behavior is undefined.) 12694 // 12695 // We diagnose this as an error. 12696 if (MemberDecl->isBitField()) { 12697 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12698 << MemberDecl->getDeclName() 12699 << SourceRange(BuiltinLoc, RParenLoc); 12700 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12701 return ExprError(); 12702 } 12703 12704 RecordDecl *Parent = MemberDecl->getParent(); 12705 if (IndirectMemberDecl) 12706 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12707 12708 // If the member was found in a base class, introduce OffsetOfNodes for 12709 // the base class indirections. 12710 CXXBasePaths Paths; 12711 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12712 Paths)) { 12713 if (Paths.getDetectedVirtual()) { 12714 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12715 << MemberDecl->getDeclName() 12716 << SourceRange(BuiltinLoc, RParenLoc); 12717 return ExprError(); 12718 } 12719 12720 CXXBasePath &Path = Paths.front(); 12721 for (const CXXBasePathElement &B : Path) 12722 Comps.push_back(OffsetOfNode(B.Base)); 12723 } 12724 12725 if (IndirectMemberDecl) { 12726 for (auto *FI : IndirectMemberDecl->chain()) { 12727 assert(isa<FieldDecl>(FI)); 12728 Comps.push_back(OffsetOfNode(OC.LocStart, 12729 cast<FieldDecl>(FI), OC.LocEnd)); 12730 } 12731 } else 12732 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12733 12734 CurrentType = MemberDecl->getType().getNonReferenceType(); 12735 } 12736 12737 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12738 Comps, Exprs, RParenLoc); 12739 } 12740 12741 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12742 SourceLocation BuiltinLoc, 12743 SourceLocation TypeLoc, 12744 ParsedType ParsedArgTy, 12745 ArrayRef<OffsetOfComponent> Components, 12746 SourceLocation RParenLoc) { 12747 12748 TypeSourceInfo *ArgTInfo; 12749 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12750 if (ArgTy.isNull()) 12751 return ExprError(); 12752 12753 if (!ArgTInfo) 12754 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12755 12756 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12757 } 12758 12759 12760 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12761 Expr *CondExpr, 12762 Expr *LHSExpr, Expr *RHSExpr, 12763 SourceLocation RPLoc) { 12764 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12765 12766 ExprValueKind VK = VK_RValue; 12767 ExprObjectKind OK = OK_Ordinary; 12768 QualType resType; 12769 bool ValueDependent = false; 12770 bool CondIsTrue = false; 12771 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12772 resType = Context.DependentTy; 12773 ValueDependent = true; 12774 } else { 12775 // The conditional expression is required to be a constant expression. 12776 llvm::APSInt condEval(32); 12777 ExprResult CondICE 12778 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12779 diag::err_typecheck_choose_expr_requires_constant, false); 12780 if (CondICE.isInvalid()) 12781 return ExprError(); 12782 CondExpr = CondICE.get(); 12783 CondIsTrue = condEval.getZExtValue(); 12784 12785 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12786 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12787 12788 resType = ActiveExpr->getType(); 12789 ValueDependent = ActiveExpr->isValueDependent(); 12790 VK = ActiveExpr->getValueKind(); 12791 OK = ActiveExpr->getObjectKind(); 12792 } 12793 12794 return new (Context) 12795 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12796 CondIsTrue, resType->isDependentType(), ValueDependent); 12797 } 12798 12799 //===----------------------------------------------------------------------===// 12800 // Clang Extensions. 12801 //===----------------------------------------------------------------------===// 12802 12803 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12804 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12805 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12806 12807 if (LangOpts.CPlusPlus) { 12808 Decl *ManglingContextDecl; 12809 if (MangleNumberingContext *MCtx = 12810 getCurrentMangleNumberContext(Block->getDeclContext(), 12811 ManglingContextDecl)) { 12812 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12813 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12814 } 12815 } 12816 12817 PushBlockScope(CurScope, Block); 12818 CurContext->addDecl(Block); 12819 if (CurScope) 12820 PushDeclContext(CurScope, Block); 12821 else 12822 CurContext = Block; 12823 12824 getCurBlock()->HasImplicitReturnType = true; 12825 12826 // Enter a new evaluation context to insulate the block from any 12827 // cleanups from the enclosing full-expression. 12828 PushExpressionEvaluationContext( 12829 ExpressionEvaluationContext::PotentiallyEvaluated); 12830 } 12831 12832 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12833 Scope *CurScope) { 12834 assert(ParamInfo.getIdentifier() == nullptr && 12835 "block-id should have no identifier!"); 12836 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12837 BlockScopeInfo *CurBlock = getCurBlock(); 12838 12839 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12840 QualType T = Sig->getType(); 12841 12842 // FIXME: We should allow unexpanded parameter packs here, but that would, 12843 // in turn, make the block expression contain unexpanded parameter packs. 12844 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12845 // Drop the parameters. 12846 FunctionProtoType::ExtProtoInfo EPI; 12847 EPI.HasTrailingReturn = false; 12848 EPI.TypeQuals |= DeclSpec::TQ_const; 12849 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12850 Sig = Context.getTrivialTypeSourceInfo(T); 12851 } 12852 12853 // GetTypeForDeclarator always produces a function type for a block 12854 // literal signature. Furthermore, it is always a FunctionProtoType 12855 // unless the function was written with a typedef. 12856 assert(T->isFunctionType() && 12857 "GetTypeForDeclarator made a non-function block signature"); 12858 12859 // Look for an explicit signature in that function type. 12860 FunctionProtoTypeLoc ExplicitSignature; 12861 12862 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12863 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12864 12865 // Check whether that explicit signature was synthesized by 12866 // GetTypeForDeclarator. If so, don't save that as part of the 12867 // written signature. 12868 if (ExplicitSignature.getLocalRangeBegin() == 12869 ExplicitSignature.getLocalRangeEnd()) { 12870 // This would be much cheaper if we stored TypeLocs instead of 12871 // TypeSourceInfos. 12872 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12873 unsigned Size = Result.getFullDataSize(); 12874 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12875 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12876 12877 ExplicitSignature = FunctionProtoTypeLoc(); 12878 } 12879 } 12880 12881 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12882 CurBlock->FunctionType = T; 12883 12884 const FunctionType *Fn = T->getAs<FunctionType>(); 12885 QualType RetTy = Fn->getReturnType(); 12886 bool isVariadic = 12887 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12888 12889 CurBlock->TheDecl->setIsVariadic(isVariadic); 12890 12891 // Context.DependentTy is used as a placeholder for a missing block 12892 // return type. TODO: what should we do with declarators like: 12893 // ^ * { ... } 12894 // If the answer is "apply template argument deduction".... 12895 if (RetTy != Context.DependentTy) { 12896 CurBlock->ReturnType = RetTy; 12897 CurBlock->TheDecl->setBlockMissingReturnType(false); 12898 CurBlock->HasImplicitReturnType = false; 12899 } 12900 12901 // Push block parameters from the declarator if we had them. 12902 SmallVector<ParmVarDecl*, 8> Params; 12903 if (ExplicitSignature) { 12904 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12905 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12906 if (Param->getIdentifier() == nullptr && 12907 !Param->isImplicit() && 12908 !Param->isInvalidDecl() && 12909 !getLangOpts().CPlusPlus) 12910 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12911 Params.push_back(Param); 12912 } 12913 12914 // Fake up parameter variables if we have a typedef, like 12915 // ^ fntype { ... } 12916 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12917 for (const auto &I : Fn->param_types()) { 12918 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12919 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12920 Params.push_back(Param); 12921 } 12922 } 12923 12924 // Set the parameters on the block decl. 12925 if (!Params.empty()) { 12926 CurBlock->TheDecl->setParams(Params); 12927 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12928 /*CheckParameterNames=*/false); 12929 } 12930 12931 // Finally we can process decl attributes. 12932 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12933 12934 // Put the parameter variables in scope. 12935 for (auto AI : CurBlock->TheDecl->parameters()) { 12936 AI->setOwningFunction(CurBlock->TheDecl); 12937 12938 // If this has an identifier, add it to the scope stack. 12939 if (AI->getIdentifier()) { 12940 CheckShadow(CurBlock->TheScope, AI); 12941 12942 PushOnScopeChains(AI, CurBlock->TheScope); 12943 } 12944 } 12945 } 12946 12947 /// ActOnBlockError - If there is an error parsing a block, this callback 12948 /// is invoked to pop the information about the block from the action impl. 12949 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12950 // Leave the expression-evaluation context. 12951 DiscardCleanupsInEvaluationContext(); 12952 PopExpressionEvaluationContext(); 12953 12954 // Pop off CurBlock, handle nested blocks. 12955 PopDeclContext(); 12956 PopFunctionScopeInfo(); 12957 } 12958 12959 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12960 /// literal was successfully completed. ^(int x){...} 12961 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12962 Stmt *Body, Scope *CurScope) { 12963 // If blocks are disabled, emit an error. 12964 if (!LangOpts.Blocks) 12965 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12966 12967 // Leave the expression-evaluation context. 12968 if (hasAnyUnrecoverableErrorsInThisFunction()) 12969 DiscardCleanupsInEvaluationContext(); 12970 assert(!Cleanup.exprNeedsCleanups() && 12971 "cleanups within block not correctly bound!"); 12972 PopExpressionEvaluationContext(); 12973 12974 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12975 12976 if (BSI->HasImplicitReturnType) 12977 deduceClosureReturnType(*BSI); 12978 12979 PopDeclContext(); 12980 12981 QualType RetTy = Context.VoidTy; 12982 if (!BSI->ReturnType.isNull()) 12983 RetTy = BSI->ReturnType; 12984 12985 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12986 QualType BlockTy; 12987 12988 // Set the captured variables on the block. 12989 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12990 SmallVector<BlockDecl::Capture, 4> Captures; 12991 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12992 if (Cap.isThisCapture()) 12993 continue; 12994 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12995 Cap.isNested(), Cap.getInitExpr()); 12996 Captures.push_back(NewCap); 12997 } 12998 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12999 13000 // If the user wrote a function type in some form, try to use that. 13001 if (!BSI->FunctionType.isNull()) { 13002 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13003 13004 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13005 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13006 13007 // Turn protoless block types into nullary block types. 13008 if (isa<FunctionNoProtoType>(FTy)) { 13009 FunctionProtoType::ExtProtoInfo EPI; 13010 EPI.ExtInfo = Ext; 13011 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13012 13013 // Otherwise, if we don't need to change anything about the function type, 13014 // preserve its sugar structure. 13015 } else if (FTy->getReturnType() == RetTy && 13016 (!NoReturn || FTy->getNoReturnAttr())) { 13017 BlockTy = BSI->FunctionType; 13018 13019 // Otherwise, make the minimal modifications to the function type. 13020 } else { 13021 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13022 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13023 EPI.TypeQuals = 0; // FIXME: silently? 13024 EPI.ExtInfo = Ext; 13025 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13026 } 13027 13028 // If we don't have a function type, just build one from nothing. 13029 } else { 13030 FunctionProtoType::ExtProtoInfo EPI; 13031 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13032 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13033 } 13034 13035 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13036 BlockTy = Context.getBlockPointerType(BlockTy); 13037 13038 // If needed, diagnose invalid gotos and switches in the block. 13039 if (getCurFunction()->NeedsScopeChecking() && 13040 !PP.isCodeCompletionEnabled()) 13041 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13042 13043 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13044 13045 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13046 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13047 13048 // Try to apply the named return value optimization. We have to check again 13049 // if we can do this, though, because blocks keep return statements around 13050 // to deduce an implicit return type. 13051 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13052 !BSI->TheDecl->isDependentContext()) 13053 computeNRVO(Body, BSI); 13054 13055 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13056 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13057 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13058 13059 // If the block isn't obviously global, i.e. it captures anything at 13060 // all, then we need to do a few things in the surrounding context: 13061 if (Result->getBlockDecl()->hasCaptures()) { 13062 // First, this expression has a new cleanup object. 13063 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13064 Cleanup.setExprNeedsCleanups(true); 13065 13066 // It also gets a branch-protected scope if any of the captured 13067 // variables needs destruction. 13068 for (const auto &CI : Result->getBlockDecl()->captures()) { 13069 const VarDecl *var = CI.getVariable(); 13070 if (var->getType().isDestructedType() != QualType::DK_none) { 13071 getCurFunction()->setHasBranchProtectedScope(); 13072 break; 13073 } 13074 } 13075 } 13076 13077 return Result; 13078 } 13079 13080 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13081 SourceLocation RPLoc) { 13082 TypeSourceInfo *TInfo; 13083 GetTypeFromParser(Ty, &TInfo); 13084 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13085 } 13086 13087 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13088 Expr *E, TypeSourceInfo *TInfo, 13089 SourceLocation RPLoc) { 13090 Expr *OrigExpr = E; 13091 bool IsMS = false; 13092 13093 // CUDA device code does not support varargs. 13094 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13095 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13096 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13097 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13098 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13099 } 13100 } 13101 13102 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13103 // as Microsoft ABI on an actual Microsoft platform, where 13104 // __builtin_ms_va_list and __builtin_va_list are the same.) 13105 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13106 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13107 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13108 if (Context.hasSameType(MSVaListType, E->getType())) { 13109 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13110 return ExprError(); 13111 IsMS = true; 13112 } 13113 } 13114 13115 // Get the va_list type 13116 QualType VaListType = Context.getBuiltinVaListType(); 13117 if (!IsMS) { 13118 if (VaListType->isArrayType()) { 13119 // Deal with implicit array decay; for example, on x86-64, 13120 // va_list is an array, but it's supposed to decay to 13121 // a pointer for va_arg. 13122 VaListType = Context.getArrayDecayedType(VaListType); 13123 // Make sure the input expression also decays appropriately. 13124 ExprResult Result = UsualUnaryConversions(E); 13125 if (Result.isInvalid()) 13126 return ExprError(); 13127 E = Result.get(); 13128 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13129 // If va_list is a record type and we are compiling in C++ mode, 13130 // check the argument using reference binding. 13131 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13132 Context, Context.getLValueReferenceType(VaListType), false); 13133 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13134 if (Init.isInvalid()) 13135 return ExprError(); 13136 E = Init.getAs<Expr>(); 13137 } else { 13138 // Otherwise, the va_list argument must be an l-value because 13139 // it is modified by va_arg. 13140 if (!E->isTypeDependent() && 13141 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13142 return ExprError(); 13143 } 13144 } 13145 13146 if (!IsMS && !E->isTypeDependent() && 13147 !Context.hasSameType(VaListType, E->getType())) 13148 return ExprError(Diag(E->getLocStart(), 13149 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13150 << OrigExpr->getType() << E->getSourceRange()); 13151 13152 if (!TInfo->getType()->isDependentType()) { 13153 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13154 diag::err_second_parameter_to_va_arg_incomplete, 13155 TInfo->getTypeLoc())) 13156 return ExprError(); 13157 13158 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13159 TInfo->getType(), 13160 diag::err_second_parameter_to_va_arg_abstract, 13161 TInfo->getTypeLoc())) 13162 return ExprError(); 13163 13164 if (!TInfo->getType().isPODType(Context)) { 13165 Diag(TInfo->getTypeLoc().getBeginLoc(), 13166 TInfo->getType()->isObjCLifetimeType() 13167 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13168 : diag::warn_second_parameter_to_va_arg_not_pod) 13169 << TInfo->getType() 13170 << TInfo->getTypeLoc().getSourceRange(); 13171 } 13172 13173 // Check for va_arg where arguments of the given type will be promoted 13174 // (i.e. this va_arg is guaranteed to have undefined behavior). 13175 QualType PromoteType; 13176 if (TInfo->getType()->isPromotableIntegerType()) { 13177 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13178 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13179 PromoteType = QualType(); 13180 } 13181 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13182 PromoteType = Context.DoubleTy; 13183 if (!PromoteType.isNull()) 13184 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13185 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13186 << TInfo->getType() 13187 << PromoteType 13188 << TInfo->getTypeLoc().getSourceRange()); 13189 } 13190 13191 QualType T = TInfo->getType().getNonLValueExprType(Context); 13192 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13193 } 13194 13195 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13196 // The type of __null will be int or long, depending on the size of 13197 // pointers on the target. 13198 QualType Ty; 13199 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13200 if (pw == Context.getTargetInfo().getIntWidth()) 13201 Ty = Context.IntTy; 13202 else if (pw == Context.getTargetInfo().getLongWidth()) 13203 Ty = Context.LongTy; 13204 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13205 Ty = Context.LongLongTy; 13206 else { 13207 llvm_unreachable("I don't know size of pointer!"); 13208 } 13209 13210 return new (Context) GNUNullExpr(Ty, TokenLoc); 13211 } 13212 13213 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13214 bool Diagnose) { 13215 if (!getLangOpts().ObjC1) 13216 return false; 13217 13218 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13219 if (!PT) 13220 return false; 13221 13222 if (!PT->isObjCIdType()) { 13223 // Check if the destination is the 'NSString' interface. 13224 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13225 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13226 return false; 13227 } 13228 13229 // Ignore any parens, implicit casts (should only be 13230 // array-to-pointer decays), and not-so-opaque values. The last is 13231 // important for making this trigger for property assignments. 13232 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13233 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13234 if (OV->getSourceExpr()) 13235 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13236 13237 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13238 if (!SL || !SL->isAscii()) 13239 return false; 13240 if (Diagnose) { 13241 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13242 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13243 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13244 } 13245 return true; 13246 } 13247 13248 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13249 const Expr *SrcExpr) { 13250 if (!DstType->isFunctionPointerType() || 13251 !SrcExpr->getType()->isFunctionType()) 13252 return false; 13253 13254 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13255 if (!DRE) 13256 return false; 13257 13258 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13259 if (!FD) 13260 return false; 13261 13262 return !S.checkAddressOfFunctionIsAvailable(FD, 13263 /*Complain=*/true, 13264 SrcExpr->getLocStart()); 13265 } 13266 13267 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13268 SourceLocation Loc, 13269 QualType DstType, QualType SrcType, 13270 Expr *SrcExpr, AssignmentAction Action, 13271 bool *Complained) { 13272 if (Complained) 13273 *Complained = false; 13274 13275 // Decode the result (notice that AST's are still created for extensions). 13276 bool CheckInferredResultType = false; 13277 bool isInvalid = false; 13278 unsigned DiagKind = 0; 13279 FixItHint Hint; 13280 ConversionFixItGenerator ConvHints; 13281 bool MayHaveConvFixit = false; 13282 bool MayHaveFunctionDiff = false; 13283 const ObjCInterfaceDecl *IFace = nullptr; 13284 const ObjCProtocolDecl *PDecl = nullptr; 13285 13286 switch (ConvTy) { 13287 case Compatible: 13288 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13289 return false; 13290 13291 case PointerToInt: 13292 DiagKind = diag::ext_typecheck_convert_pointer_int; 13293 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13294 MayHaveConvFixit = true; 13295 break; 13296 case IntToPointer: 13297 DiagKind = diag::ext_typecheck_convert_int_pointer; 13298 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13299 MayHaveConvFixit = true; 13300 break; 13301 case IncompatiblePointer: 13302 if (Action == AA_Passing_CFAudited) 13303 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13304 else if (SrcType->isFunctionPointerType() && 13305 DstType->isFunctionPointerType()) 13306 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13307 else 13308 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13309 13310 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13311 SrcType->isObjCObjectPointerType(); 13312 if (Hint.isNull() && !CheckInferredResultType) { 13313 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13314 } 13315 else if (CheckInferredResultType) { 13316 SrcType = SrcType.getUnqualifiedType(); 13317 DstType = DstType.getUnqualifiedType(); 13318 } 13319 MayHaveConvFixit = true; 13320 break; 13321 case IncompatiblePointerSign: 13322 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13323 break; 13324 case FunctionVoidPointer: 13325 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13326 break; 13327 case IncompatiblePointerDiscardsQualifiers: { 13328 // Perform array-to-pointer decay if necessary. 13329 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13330 13331 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13332 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13333 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13334 DiagKind = diag::err_typecheck_incompatible_address_space; 13335 break; 13336 13337 13338 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13339 DiagKind = diag::err_typecheck_incompatible_ownership; 13340 break; 13341 } 13342 13343 llvm_unreachable("unknown error case for discarding qualifiers!"); 13344 // fallthrough 13345 } 13346 case CompatiblePointerDiscardsQualifiers: 13347 // If the qualifiers lost were because we were applying the 13348 // (deprecated) C++ conversion from a string literal to a char* 13349 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13350 // Ideally, this check would be performed in 13351 // checkPointerTypesForAssignment. However, that would require a 13352 // bit of refactoring (so that the second argument is an 13353 // expression, rather than a type), which should be done as part 13354 // of a larger effort to fix checkPointerTypesForAssignment for 13355 // C++ semantics. 13356 if (getLangOpts().CPlusPlus && 13357 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13358 return false; 13359 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13360 break; 13361 case IncompatibleNestedPointerQualifiers: 13362 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13363 break; 13364 case IntToBlockPointer: 13365 DiagKind = diag::err_int_to_block_pointer; 13366 break; 13367 case IncompatibleBlockPointer: 13368 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13369 break; 13370 case IncompatibleObjCQualifiedId: { 13371 if (SrcType->isObjCQualifiedIdType()) { 13372 const ObjCObjectPointerType *srcOPT = 13373 SrcType->getAs<ObjCObjectPointerType>(); 13374 for (auto *srcProto : srcOPT->quals()) { 13375 PDecl = srcProto; 13376 break; 13377 } 13378 if (const ObjCInterfaceType *IFaceT = 13379 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13380 IFace = IFaceT->getDecl(); 13381 } 13382 else if (DstType->isObjCQualifiedIdType()) { 13383 const ObjCObjectPointerType *dstOPT = 13384 DstType->getAs<ObjCObjectPointerType>(); 13385 for (auto *dstProto : dstOPT->quals()) { 13386 PDecl = dstProto; 13387 break; 13388 } 13389 if (const ObjCInterfaceType *IFaceT = 13390 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13391 IFace = IFaceT->getDecl(); 13392 } 13393 DiagKind = diag::warn_incompatible_qualified_id; 13394 break; 13395 } 13396 case IncompatibleVectors: 13397 DiagKind = diag::warn_incompatible_vectors; 13398 break; 13399 case IncompatibleObjCWeakRef: 13400 DiagKind = diag::err_arc_weak_unavailable_assign; 13401 break; 13402 case Incompatible: 13403 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13404 if (Complained) 13405 *Complained = true; 13406 return true; 13407 } 13408 13409 DiagKind = diag::err_typecheck_convert_incompatible; 13410 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13411 MayHaveConvFixit = true; 13412 isInvalid = true; 13413 MayHaveFunctionDiff = true; 13414 break; 13415 } 13416 13417 QualType FirstType, SecondType; 13418 switch (Action) { 13419 case AA_Assigning: 13420 case AA_Initializing: 13421 // The destination type comes first. 13422 FirstType = DstType; 13423 SecondType = SrcType; 13424 break; 13425 13426 case AA_Returning: 13427 case AA_Passing: 13428 case AA_Passing_CFAudited: 13429 case AA_Converting: 13430 case AA_Sending: 13431 case AA_Casting: 13432 // The source type comes first. 13433 FirstType = SrcType; 13434 SecondType = DstType; 13435 break; 13436 } 13437 13438 PartialDiagnostic FDiag = PDiag(DiagKind); 13439 if (Action == AA_Passing_CFAudited) 13440 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13441 else 13442 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13443 13444 // If we can fix the conversion, suggest the FixIts. 13445 assert(ConvHints.isNull() || Hint.isNull()); 13446 if (!ConvHints.isNull()) { 13447 for (FixItHint &H : ConvHints.Hints) 13448 FDiag << H; 13449 } else { 13450 FDiag << Hint; 13451 } 13452 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13453 13454 if (MayHaveFunctionDiff) 13455 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13456 13457 Diag(Loc, FDiag); 13458 if (DiagKind == diag::warn_incompatible_qualified_id && 13459 PDecl && IFace && !IFace->hasDefinition()) 13460 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13461 << IFace->getName() << PDecl->getName(); 13462 13463 if (SecondType == Context.OverloadTy) 13464 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13465 FirstType, /*TakingAddress=*/true); 13466 13467 if (CheckInferredResultType) 13468 EmitRelatedResultTypeNote(SrcExpr); 13469 13470 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13471 EmitRelatedResultTypeNoteForReturn(DstType); 13472 13473 if (Complained) 13474 *Complained = true; 13475 return isInvalid; 13476 } 13477 13478 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13479 llvm::APSInt *Result) { 13480 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13481 public: 13482 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13483 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13484 } 13485 } Diagnoser; 13486 13487 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13488 } 13489 13490 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13491 llvm::APSInt *Result, 13492 unsigned DiagID, 13493 bool AllowFold) { 13494 class IDDiagnoser : public VerifyICEDiagnoser { 13495 unsigned DiagID; 13496 13497 public: 13498 IDDiagnoser(unsigned DiagID) 13499 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13500 13501 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13502 S.Diag(Loc, DiagID) << SR; 13503 } 13504 } Diagnoser(DiagID); 13505 13506 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13507 } 13508 13509 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13510 SourceRange SR) { 13511 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13512 } 13513 13514 ExprResult 13515 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13516 VerifyICEDiagnoser &Diagnoser, 13517 bool AllowFold) { 13518 SourceLocation DiagLoc = E->getLocStart(); 13519 13520 if (getLangOpts().CPlusPlus11) { 13521 // C++11 [expr.const]p5: 13522 // If an expression of literal class type is used in a context where an 13523 // integral constant expression is required, then that class type shall 13524 // have a single non-explicit conversion function to an integral or 13525 // unscoped enumeration type 13526 ExprResult Converted; 13527 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13528 public: 13529 CXX11ConvertDiagnoser(bool Silent) 13530 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13531 Silent, true) {} 13532 13533 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13534 QualType T) override { 13535 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13536 } 13537 13538 SemaDiagnosticBuilder diagnoseIncomplete( 13539 Sema &S, SourceLocation Loc, QualType T) override { 13540 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13541 } 13542 13543 SemaDiagnosticBuilder diagnoseExplicitConv( 13544 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13545 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13546 } 13547 13548 SemaDiagnosticBuilder noteExplicitConv( 13549 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13550 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13551 << ConvTy->isEnumeralType() << ConvTy; 13552 } 13553 13554 SemaDiagnosticBuilder diagnoseAmbiguous( 13555 Sema &S, SourceLocation Loc, QualType T) override { 13556 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13557 } 13558 13559 SemaDiagnosticBuilder noteAmbiguous( 13560 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13561 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13562 << ConvTy->isEnumeralType() << ConvTy; 13563 } 13564 13565 SemaDiagnosticBuilder diagnoseConversion( 13566 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13567 llvm_unreachable("conversion functions are permitted"); 13568 } 13569 } ConvertDiagnoser(Diagnoser.Suppress); 13570 13571 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13572 ConvertDiagnoser); 13573 if (Converted.isInvalid()) 13574 return Converted; 13575 E = Converted.get(); 13576 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13577 return ExprError(); 13578 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13579 // An ICE must be of integral or unscoped enumeration type. 13580 if (!Diagnoser.Suppress) 13581 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13582 return ExprError(); 13583 } 13584 13585 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13586 // in the non-ICE case. 13587 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13588 if (Result) 13589 *Result = E->EvaluateKnownConstInt(Context); 13590 return E; 13591 } 13592 13593 Expr::EvalResult EvalResult; 13594 SmallVector<PartialDiagnosticAt, 8> Notes; 13595 EvalResult.Diag = &Notes; 13596 13597 // Try to evaluate the expression, and produce diagnostics explaining why it's 13598 // not a constant expression as a side-effect. 13599 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13600 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13601 13602 // In C++11, we can rely on diagnostics being produced for any expression 13603 // which is not a constant expression. If no diagnostics were produced, then 13604 // this is a constant expression. 13605 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13606 if (Result) 13607 *Result = EvalResult.Val.getInt(); 13608 return E; 13609 } 13610 13611 // If our only note is the usual "invalid subexpression" note, just point 13612 // the caret at its location rather than producing an essentially 13613 // redundant note. 13614 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13615 diag::note_invalid_subexpr_in_const_expr) { 13616 DiagLoc = Notes[0].first; 13617 Notes.clear(); 13618 } 13619 13620 if (!Folded || !AllowFold) { 13621 if (!Diagnoser.Suppress) { 13622 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13623 for (const PartialDiagnosticAt &Note : Notes) 13624 Diag(Note.first, Note.second); 13625 } 13626 13627 return ExprError(); 13628 } 13629 13630 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13631 for (const PartialDiagnosticAt &Note : Notes) 13632 Diag(Note.first, Note.second); 13633 13634 if (Result) 13635 *Result = EvalResult.Val.getInt(); 13636 return E; 13637 } 13638 13639 namespace { 13640 // Handle the case where we conclude a expression which we speculatively 13641 // considered to be unevaluated is actually evaluated. 13642 class TransformToPE : public TreeTransform<TransformToPE> { 13643 typedef TreeTransform<TransformToPE> BaseTransform; 13644 13645 public: 13646 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13647 13648 // Make sure we redo semantic analysis 13649 bool AlwaysRebuild() { return true; } 13650 13651 // Make sure we handle LabelStmts correctly. 13652 // FIXME: This does the right thing, but maybe we need a more general 13653 // fix to TreeTransform? 13654 StmtResult TransformLabelStmt(LabelStmt *S) { 13655 S->getDecl()->setStmt(nullptr); 13656 return BaseTransform::TransformLabelStmt(S); 13657 } 13658 13659 // We need to special-case DeclRefExprs referring to FieldDecls which 13660 // are not part of a member pointer formation; normal TreeTransforming 13661 // doesn't catch this case because of the way we represent them in the AST. 13662 // FIXME: This is a bit ugly; is it really the best way to handle this 13663 // case? 13664 // 13665 // Error on DeclRefExprs referring to FieldDecls. 13666 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13667 if (isa<FieldDecl>(E->getDecl()) && 13668 !SemaRef.isUnevaluatedContext()) 13669 return SemaRef.Diag(E->getLocation(), 13670 diag::err_invalid_non_static_member_use) 13671 << E->getDecl() << E->getSourceRange(); 13672 13673 return BaseTransform::TransformDeclRefExpr(E); 13674 } 13675 13676 // Exception: filter out member pointer formation 13677 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13678 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13679 return E; 13680 13681 return BaseTransform::TransformUnaryOperator(E); 13682 } 13683 13684 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13685 // Lambdas never need to be transformed. 13686 return E; 13687 } 13688 }; 13689 } 13690 13691 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13692 assert(isUnevaluatedContext() && 13693 "Should only transform unevaluated expressions"); 13694 ExprEvalContexts.back().Context = 13695 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13696 if (isUnevaluatedContext()) 13697 return E; 13698 return TransformToPE(*this).TransformExpr(E); 13699 } 13700 13701 void 13702 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13703 Decl *LambdaContextDecl, 13704 bool IsDecltype) { 13705 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13706 LambdaContextDecl, IsDecltype); 13707 Cleanup.reset(); 13708 if (!MaybeODRUseExprs.empty()) 13709 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13710 } 13711 13712 void 13713 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13714 ReuseLambdaContextDecl_t, 13715 bool IsDecltype) { 13716 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13717 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13718 } 13719 13720 void Sema::PopExpressionEvaluationContext() { 13721 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13722 unsigned NumTypos = Rec.NumTypos; 13723 13724 if (!Rec.Lambdas.empty()) { 13725 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13726 unsigned D; 13727 if (Rec.isUnevaluated()) { 13728 // C++11 [expr.prim.lambda]p2: 13729 // A lambda-expression shall not appear in an unevaluated operand 13730 // (Clause 5). 13731 D = diag::err_lambda_unevaluated_operand; 13732 } else { 13733 // C++1y [expr.const]p2: 13734 // A conditional-expression e is a core constant expression unless the 13735 // evaluation of e, following the rules of the abstract machine, would 13736 // evaluate [...] a lambda-expression. 13737 D = diag::err_lambda_in_constant_expression; 13738 } 13739 13740 // C++1z allows lambda expressions as core constant expressions. 13741 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13742 // 1607) from appearing within template-arguments and array-bounds that 13743 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13744 // unevaluated contexts) might lift some of these restrictions in a 13745 // future version. 13746 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13747 for (const auto *L : Rec.Lambdas) 13748 Diag(L->getLocStart(), D); 13749 } else { 13750 // Mark the capture expressions odr-used. This was deferred 13751 // during lambda expression creation. 13752 for (auto *Lambda : Rec.Lambdas) { 13753 for (auto *C : Lambda->capture_inits()) 13754 MarkDeclarationsReferencedInExpr(C); 13755 } 13756 } 13757 } 13758 13759 // When are coming out of an unevaluated context, clear out any 13760 // temporaries that we may have created as part of the evaluation of 13761 // the expression in that context: they aren't relevant because they 13762 // will never be constructed. 13763 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13764 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13765 ExprCleanupObjects.end()); 13766 Cleanup = Rec.ParentCleanup; 13767 CleanupVarDeclMarking(); 13768 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13769 // Otherwise, merge the contexts together. 13770 } else { 13771 Cleanup.mergeFrom(Rec.ParentCleanup); 13772 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13773 Rec.SavedMaybeODRUseExprs.end()); 13774 } 13775 13776 // Pop the current expression evaluation context off the stack. 13777 ExprEvalContexts.pop_back(); 13778 13779 if (!ExprEvalContexts.empty()) 13780 ExprEvalContexts.back().NumTypos += NumTypos; 13781 else 13782 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13783 "last ExpressionEvaluationContextRecord"); 13784 } 13785 13786 void Sema::DiscardCleanupsInEvaluationContext() { 13787 ExprCleanupObjects.erase( 13788 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13789 ExprCleanupObjects.end()); 13790 Cleanup.reset(); 13791 MaybeODRUseExprs.clear(); 13792 } 13793 13794 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13795 if (!E->getType()->isVariablyModifiedType()) 13796 return E; 13797 return TransformToPotentiallyEvaluated(E); 13798 } 13799 13800 /// Are we within a context in which some evaluation could be performed (be it 13801 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13802 /// captured by C++'s idea of an "unevaluated context". 13803 static bool isEvaluatableContext(Sema &SemaRef) { 13804 switch (SemaRef.ExprEvalContexts.back().Context) { 13805 case Sema::ExpressionEvaluationContext::Unevaluated: 13806 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13807 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13808 // Expressions in this context are never evaluated. 13809 return false; 13810 13811 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13812 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13813 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13814 // Expressions in this context could be evaluated. 13815 return true; 13816 13817 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13818 // Referenced declarations will only be used if the construct in the 13819 // containing expression is used, at which point we'll be given another 13820 // turn to mark them. 13821 return false; 13822 } 13823 llvm_unreachable("Invalid context"); 13824 } 13825 13826 /// Are we within a context in which references to resolved functions or to 13827 /// variables result in odr-use? 13828 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13829 // An expression in a template is not really an expression until it's been 13830 // instantiated, so it doesn't trigger odr-use. 13831 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13832 return false; 13833 13834 switch (SemaRef.ExprEvalContexts.back().Context) { 13835 case Sema::ExpressionEvaluationContext::Unevaluated: 13836 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13837 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13838 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13839 return false; 13840 13841 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13842 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13843 return true; 13844 13845 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13846 return false; 13847 } 13848 llvm_unreachable("Invalid context"); 13849 } 13850 13851 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13852 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13853 return Func->isConstexpr() && 13854 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13855 } 13856 13857 /// \brief Mark a function referenced, and check whether it is odr-used 13858 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13859 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13860 bool MightBeOdrUse) { 13861 assert(Func && "No function?"); 13862 13863 Func->setReferenced(); 13864 13865 // C++11 [basic.def.odr]p3: 13866 // A function whose name appears as a potentially-evaluated expression is 13867 // odr-used if it is the unique lookup result or the selected member of a 13868 // set of overloaded functions [...]. 13869 // 13870 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13871 // can just check that here. 13872 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13873 13874 // Determine whether we require a function definition to exist, per 13875 // C++11 [temp.inst]p3: 13876 // Unless a function template specialization has been explicitly 13877 // instantiated or explicitly specialized, the function template 13878 // specialization is implicitly instantiated when the specialization is 13879 // referenced in a context that requires a function definition to exist. 13880 // 13881 // That is either when this is an odr-use, or when a usage of a constexpr 13882 // function occurs within an evaluatable context. 13883 bool NeedDefinition = 13884 OdrUse || (isEvaluatableContext(*this) && 13885 isImplicitlyDefinableConstexprFunction(Func)); 13886 13887 // C++14 [temp.expl.spec]p6: 13888 // If a template [...] is explicitly specialized then that specialization 13889 // shall be declared before the first use of that specialization that would 13890 // cause an implicit instantiation to take place, in every translation unit 13891 // in which such a use occurs 13892 if (NeedDefinition && 13893 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13894 Func->getMemberSpecializationInfo())) 13895 checkSpecializationVisibility(Loc, Func); 13896 13897 // C++14 [except.spec]p17: 13898 // An exception-specification is considered to be needed when: 13899 // - the function is odr-used or, if it appears in an unevaluated operand, 13900 // would be odr-used if the expression were potentially-evaluated; 13901 // 13902 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13903 // function is a pure virtual function we're calling, and in that case the 13904 // function was selected by overload resolution and we need to resolve its 13905 // exception specification for a different reason. 13906 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13907 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13908 ResolveExceptionSpec(Loc, FPT); 13909 13910 // If we don't need to mark the function as used, and we don't need to 13911 // try to provide a definition, there's nothing more to do. 13912 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13913 (!NeedDefinition || Func->getBody())) 13914 return; 13915 13916 // Note that this declaration has been used. 13917 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13918 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13919 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13920 if (Constructor->isDefaultConstructor()) { 13921 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13922 return; 13923 DefineImplicitDefaultConstructor(Loc, Constructor); 13924 } else if (Constructor->isCopyConstructor()) { 13925 DefineImplicitCopyConstructor(Loc, Constructor); 13926 } else if (Constructor->isMoveConstructor()) { 13927 DefineImplicitMoveConstructor(Loc, Constructor); 13928 } 13929 } else if (Constructor->getInheritedConstructor()) { 13930 DefineInheritingConstructor(Loc, Constructor); 13931 } 13932 } else if (CXXDestructorDecl *Destructor = 13933 dyn_cast<CXXDestructorDecl>(Func)) { 13934 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13935 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13936 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13937 return; 13938 DefineImplicitDestructor(Loc, Destructor); 13939 } 13940 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13941 MarkVTableUsed(Loc, Destructor->getParent()); 13942 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13943 if (MethodDecl->isOverloadedOperator() && 13944 MethodDecl->getOverloadedOperator() == OO_Equal) { 13945 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13946 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13947 if (MethodDecl->isCopyAssignmentOperator()) 13948 DefineImplicitCopyAssignment(Loc, MethodDecl); 13949 else if (MethodDecl->isMoveAssignmentOperator()) 13950 DefineImplicitMoveAssignment(Loc, MethodDecl); 13951 } 13952 } else if (isa<CXXConversionDecl>(MethodDecl) && 13953 MethodDecl->getParent()->isLambda()) { 13954 CXXConversionDecl *Conversion = 13955 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13956 if (Conversion->isLambdaToBlockPointerConversion()) 13957 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13958 else 13959 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13960 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13961 MarkVTableUsed(Loc, MethodDecl->getParent()); 13962 } 13963 13964 // Recursive functions should be marked when used from another function. 13965 // FIXME: Is this really right? 13966 if (CurContext == Func) return; 13967 13968 // Implicit instantiation of function templates and member functions of 13969 // class templates. 13970 if (Func->isImplicitlyInstantiable()) { 13971 bool AlreadyInstantiated = false; 13972 SourceLocation PointOfInstantiation = Loc; 13973 if (FunctionTemplateSpecializationInfo *SpecInfo 13974 = Func->getTemplateSpecializationInfo()) { 13975 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13976 SpecInfo->setPointOfInstantiation(Loc); 13977 else if (SpecInfo->getTemplateSpecializationKind() 13978 == TSK_ImplicitInstantiation) { 13979 AlreadyInstantiated = true; 13980 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13981 } 13982 } else if (MemberSpecializationInfo *MSInfo 13983 = Func->getMemberSpecializationInfo()) { 13984 if (MSInfo->getPointOfInstantiation().isInvalid()) 13985 MSInfo->setPointOfInstantiation(Loc); 13986 else if (MSInfo->getTemplateSpecializationKind() 13987 == TSK_ImplicitInstantiation) { 13988 AlreadyInstantiated = true; 13989 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13990 } 13991 } 13992 13993 if (!AlreadyInstantiated || Func->isConstexpr()) { 13994 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13995 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13996 CodeSynthesisContexts.size()) 13997 PendingLocalImplicitInstantiations.push_back( 13998 std::make_pair(Func, PointOfInstantiation)); 13999 else if (Func->isConstexpr()) 14000 // Do not defer instantiations of constexpr functions, to avoid the 14001 // expression evaluator needing to call back into Sema if it sees a 14002 // call to such a function. 14003 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14004 else { 14005 Func->setInstantiationIsPending(true); 14006 PendingInstantiations.push_back(std::make_pair(Func, 14007 PointOfInstantiation)); 14008 // Notify the consumer that a function was implicitly instantiated. 14009 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14010 } 14011 } 14012 } else { 14013 // Walk redefinitions, as some of them may be instantiable. 14014 for (auto i : Func->redecls()) { 14015 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14016 MarkFunctionReferenced(Loc, i, OdrUse); 14017 } 14018 } 14019 14020 if (!OdrUse) return; 14021 14022 // Keep track of used but undefined functions. 14023 if (!Func->isDefined()) { 14024 if (mightHaveNonExternalLinkage(Func)) 14025 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14026 else if (Func->getMostRecentDecl()->isInlined() && 14027 !LangOpts.GNUInline && 14028 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14029 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14030 else if (isExternalWithNoLinkageType(Func)) 14031 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14032 } 14033 14034 Func->markUsed(Context); 14035 } 14036 14037 static void 14038 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14039 ValueDecl *var, DeclContext *DC) { 14040 DeclContext *VarDC = var->getDeclContext(); 14041 14042 // If the parameter still belongs to the translation unit, then 14043 // we're actually just using one parameter in the declaration of 14044 // the next. 14045 if (isa<ParmVarDecl>(var) && 14046 isa<TranslationUnitDecl>(VarDC)) 14047 return; 14048 14049 // For C code, don't diagnose about capture if we're not actually in code 14050 // right now; it's impossible to write a non-constant expression outside of 14051 // function context, so we'll get other (more useful) diagnostics later. 14052 // 14053 // For C++, things get a bit more nasty... it would be nice to suppress this 14054 // diagnostic for certain cases like using a local variable in an array bound 14055 // for a member of a local class, but the correct predicate is not obvious. 14056 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14057 return; 14058 14059 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14060 unsigned ContextKind = 3; // unknown 14061 if (isa<CXXMethodDecl>(VarDC) && 14062 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14063 ContextKind = 2; 14064 } else if (isa<FunctionDecl>(VarDC)) { 14065 ContextKind = 0; 14066 } else if (isa<BlockDecl>(VarDC)) { 14067 ContextKind = 1; 14068 } 14069 14070 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14071 << var << ValueKind << ContextKind << VarDC; 14072 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14073 << var; 14074 14075 // FIXME: Add additional diagnostic info about class etc. which prevents 14076 // capture. 14077 } 14078 14079 14080 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14081 bool &SubCapturesAreNested, 14082 QualType &CaptureType, 14083 QualType &DeclRefType) { 14084 // Check whether we've already captured it. 14085 if (CSI->CaptureMap.count(Var)) { 14086 // If we found a capture, any subcaptures are nested. 14087 SubCapturesAreNested = true; 14088 14089 // Retrieve the capture type for this variable. 14090 CaptureType = CSI->getCapture(Var).getCaptureType(); 14091 14092 // Compute the type of an expression that refers to this variable. 14093 DeclRefType = CaptureType.getNonReferenceType(); 14094 14095 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14096 // are mutable in the sense that user can change their value - they are 14097 // private instances of the captured declarations. 14098 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 14099 if (Cap.isCopyCapture() && 14100 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14101 !(isa<CapturedRegionScopeInfo>(CSI) && 14102 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14103 DeclRefType.addConst(); 14104 return true; 14105 } 14106 return false; 14107 } 14108 14109 // Only block literals, captured statements, and lambda expressions can 14110 // capture; other scopes don't work. 14111 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14112 SourceLocation Loc, 14113 const bool Diagnose, Sema &S) { 14114 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14115 return getLambdaAwareParentOfDeclContext(DC); 14116 else if (Var->hasLocalStorage()) { 14117 if (Diagnose) 14118 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14119 } 14120 return nullptr; 14121 } 14122 14123 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14124 // certain types of variables (unnamed, variably modified types etc.) 14125 // so check for eligibility. 14126 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14127 SourceLocation Loc, 14128 const bool Diagnose, Sema &S) { 14129 14130 bool IsBlock = isa<BlockScopeInfo>(CSI); 14131 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14132 14133 // Lambdas are not allowed to capture unnamed variables 14134 // (e.g. anonymous unions). 14135 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14136 // assuming that's the intent. 14137 if (IsLambda && !Var->getDeclName()) { 14138 if (Diagnose) { 14139 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14140 S.Diag(Var->getLocation(), diag::note_declared_at); 14141 } 14142 return false; 14143 } 14144 14145 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14146 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14147 if (Diagnose) { 14148 S.Diag(Loc, diag::err_ref_vm_type); 14149 S.Diag(Var->getLocation(), diag::note_previous_decl) 14150 << Var->getDeclName(); 14151 } 14152 return false; 14153 } 14154 // Prohibit structs with flexible array members too. 14155 // We cannot capture what is in the tail end of the struct. 14156 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14157 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14158 if (Diagnose) { 14159 if (IsBlock) 14160 S.Diag(Loc, diag::err_ref_flexarray_type); 14161 else 14162 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14163 << Var->getDeclName(); 14164 S.Diag(Var->getLocation(), diag::note_previous_decl) 14165 << Var->getDeclName(); 14166 } 14167 return false; 14168 } 14169 } 14170 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14171 // Lambdas and captured statements are not allowed to capture __block 14172 // variables; they don't support the expected semantics. 14173 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14174 if (Diagnose) { 14175 S.Diag(Loc, diag::err_capture_block_variable) 14176 << Var->getDeclName() << !IsLambda; 14177 S.Diag(Var->getLocation(), diag::note_previous_decl) 14178 << Var->getDeclName(); 14179 } 14180 return false; 14181 } 14182 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14183 if (S.getLangOpts().OpenCL && IsBlock && 14184 Var->getType()->isBlockPointerType()) { 14185 if (Diagnose) 14186 S.Diag(Loc, diag::err_opencl_block_ref_block); 14187 return false; 14188 } 14189 14190 return true; 14191 } 14192 14193 // Returns true if the capture by block was successful. 14194 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14195 SourceLocation Loc, 14196 const bool BuildAndDiagnose, 14197 QualType &CaptureType, 14198 QualType &DeclRefType, 14199 const bool Nested, 14200 Sema &S) { 14201 Expr *CopyExpr = nullptr; 14202 bool ByRef = false; 14203 14204 // Blocks are not allowed to capture arrays. 14205 if (CaptureType->isArrayType()) { 14206 if (BuildAndDiagnose) { 14207 S.Diag(Loc, diag::err_ref_array_type); 14208 S.Diag(Var->getLocation(), diag::note_previous_decl) 14209 << Var->getDeclName(); 14210 } 14211 return false; 14212 } 14213 14214 // Forbid the block-capture of autoreleasing variables. 14215 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14216 if (BuildAndDiagnose) { 14217 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14218 << /*block*/ 0; 14219 S.Diag(Var->getLocation(), diag::note_previous_decl) 14220 << Var->getDeclName(); 14221 } 14222 return false; 14223 } 14224 14225 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14226 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14227 // This function finds out whether there is an AttributedType of kind 14228 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14229 // attr_objc_ownership implies __autoreleasing was explicitly specified 14230 // rather than being added implicitly by the compiler. 14231 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14232 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14233 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14234 return true; 14235 14236 // Peel off AttributedTypes that are not of kind objc_ownership. 14237 Ty = AttrTy->getModifiedType(); 14238 } 14239 14240 return false; 14241 }; 14242 14243 QualType PointeeTy = PT->getPointeeType(); 14244 14245 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14246 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14247 !IsObjCOwnershipAttributedType(PointeeTy)) { 14248 if (BuildAndDiagnose) { 14249 SourceLocation VarLoc = Var->getLocation(); 14250 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14251 { 14252 auto AddAutoreleaseNote = 14253 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14254 // Provide a fix-it for the '__autoreleasing' keyword at the 14255 // appropriate location in the variable's type. 14256 if (const auto *TSI = Var->getTypeSourceInfo()) { 14257 PointerTypeLoc PTL = 14258 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14259 if (PTL) { 14260 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14261 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14262 S.getLangOpts()); 14263 if (Loc.isValid()) { 14264 StringRef CharAtLoc = Lexer::getSourceText( 14265 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14266 S.getSourceManager(), S.getLangOpts()); 14267 AddAutoreleaseNote << FixItHint::CreateInsertion( 14268 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14269 ? " __autoreleasing " 14270 : " __autoreleasing"); 14271 } 14272 } 14273 } 14274 } 14275 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14276 } 14277 } 14278 } 14279 14280 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14281 if (HasBlocksAttr || CaptureType->isReferenceType() || 14282 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14283 // Block capture by reference does not change the capture or 14284 // declaration reference types. 14285 ByRef = true; 14286 } else { 14287 // Block capture by copy introduces 'const'. 14288 CaptureType = CaptureType.getNonReferenceType().withConst(); 14289 DeclRefType = CaptureType; 14290 14291 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14292 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14293 // The capture logic needs the destructor, so make sure we mark it. 14294 // Usually this is unnecessary because most local variables have 14295 // their destructors marked at declaration time, but parameters are 14296 // an exception because it's technically only the call site that 14297 // actually requires the destructor. 14298 if (isa<ParmVarDecl>(Var)) 14299 S.FinalizeVarWithDestructor(Var, Record); 14300 14301 // Enter a new evaluation context to insulate the copy 14302 // full-expression. 14303 EnterExpressionEvaluationContext scope( 14304 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14305 14306 // According to the blocks spec, the capture of a variable from 14307 // the stack requires a const copy constructor. This is not true 14308 // of the copy/move done to move a __block variable to the heap. 14309 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14310 DeclRefType.withConst(), 14311 VK_LValue, Loc); 14312 14313 ExprResult Result 14314 = S.PerformCopyInitialization( 14315 InitializedEntity::InitializeBlock(Var->getLocation(), 14316 CaptureType, false), 14317 Loc, DeclRef); 14318 14319 // Build a full-expression copy expression if initialization 14320 // succeeded and used a non-trivial constructor. Recover from 14321 // errors by pretending that the copy isn't necessary. 14322 if (!Result.isInvalid() && 14323 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14324 ->isTrivial()) { 14325 Result = S.MaybeCreateExprWithCleanups(Result); 14326 CopyExpr = Result.get(); 14327 } 14328 } 14329 } 14330 } 14331 14332 // Actually capture the variable. 14333 if (BuildAndDiagnose) 14334 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14335 SourceLocation(), CaptureType, CopyExpr); 14336 14337 return true; 14338 14339 } 14340 14341 14342 /// \brief Capture the given variable in the captured region. 14343 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14344 VarDecl *Var, 14345 SourceLocation Loc, 14346 const bool BuildAndDiagnose, 14347 QualType &CaptureType, 14348 QualType &DeclRefType, 14349 const bool RefersToCapturedVariable, 14350 Sema &S) { 14351 // By default, capture variables by reference. 14352 bool ByRef = true; 14353 // Using an LValue reference type is consistent with Lambdas (see below). 14354 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14355 if (S.IsOpenMPCapturedDecl(Var)) 14356 DeclRefType = DeclRefType.getUnqualifiedType(); 14357 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14358 } 14359 14360 if (ByRef) 14361 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14362 else 14363 CaptureType = DeclRefType; 14364 14365 Expr *CopyExpr = nullptr; 14366 if (BuildAndDiagnose) { 14367 // The current implementation assumes that all variables are captured 14368 // by references. Since there is no capture by copy, no expression 14369 // evaluation will be needed. 14370 RecordDecl *RD = RSI->TheRecordDecl; 14371 14372 FieldDecl *Field 14373 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14374 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14375 nullptr, false, ICIS_NoInit); 14376 Field->setImplicit(true); 14377 Field->setAccess(AS_private); 14378 RD->addDecl(Field); 14379 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14380 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14381 14382 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14383 DeclRefType, VK_LValue, Loc); 14384 Var->setReferenced(true); 14385 Var->markUsed(S.Context); 14386 } 14387 14388 // Actually capture the variable. 14389 if (BuildAndDiagnose) 14390 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14391 SourceLocation(), CaptureType, CopyExpr); 14392 14393 14394 return true; 14395 } 14396 14397 /// \brief Create a field within the lambda class for the variable 14398 /// being captured. 14399 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14400 QualType FieldType, QualType DeclRefType, 14401 SourceLocation Loc, 14402 bool RefersToCapturedVariable) { 14403 CXXRecordDecl *Lambda = LSI->Lambda; 14404 14405 // Build the non-static data member. 14406 FieldDecl *Field 14407 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14408 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14409 nullptr, false, ICIS_NoInit); 14410 Field->setImplicit(true); 14411 Field->setAccess(AS_private); 14412 Lambda->addDecl(Field); 14413 } 14414 14415 /// \brief Capture the given variable in the lambda. 14416 static bool captureInLambda(LambdaScopeInfo *LSI, 14417 VarDecl *Var, 14418 SourceLocation Loc, 14419 const bool BuildAndDiagnose, 14420 QualType &CaptureType, 14421 QualType &DeclRefType, 14422 const bool RefersToCapturedVariable, 14423 const Sema::TryCaptureKind Kind, 14424 SourceLocation EllipsisLoc, 14425 const bool IsTopScope, 14426 Sema &S) { 14427 14428 // Determine whether we are capturing by reference or by value. 14429 bool ByRef = false; 14430 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14431 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14432 } else { 14433 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14434 } 14435 14436 // Compute the type of the field that will capture this variable. 14437 if (ByRef) { 14438 // C++11 [expr.prim.lambda]p15: 14439 // An entity is captured by reference if it is implicitly or 14440 // explicitly captured but not captured by copy. It is 14441 // unspecified whether additional unnamed non-static data 14442 // members are declared in the closure type for entities 14443 // captured by reference. 14444 // 14445 // FIXME: It is not clear whether we want to build an lvalue reference 14446 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14447 // to do the former, while EDG does the latter. Core issue 1249 will 14448 // clarify, but for now we follow GCC because it's a more permissive and 14449 // easily defensible position. 14450 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14451 } else { 14452 // C++11 [expr.prim.lambda]p14: 14453 // For each entity captured by copy, an unnamed non-static 14454 // data member is declared in the closure type. The 14455 // declaration order of these members is unspecified. The type 14456 // of such a data member is the type of the corresponding 14457 // captured entity if the entity is not a reference to an 14458 // object, or the referenced type otherwise. [Note: If the 14459 // captured entity is a reference to a function, the 14460 // corresponding data member is also a reference to a 14461 // function. - end note ] 14462 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14463 if (!RefType->getPointeeType()->isFunctionType()) 14464 CaptureType = RefType->getPointeeType(); 14465 } 14466 14467 // Forbid the lambda copy-capture of autoreleasing variables. 14468 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14469 if (BuildAndDiagnose) { 14470 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14471 S.Diag(Var->getLocation(), diag::note_previous_decl) 14472 << Var->getDeclName(); 14473 } 14474 return false; 14475 } 14476 14477 // Make sure that by-copy captures are of a complete and non-abstract type. 14478 if (BuildAndDiagnose) { 14479 if (!CaptureType->isDependentType() && 14480 S.RequireCompleteType(Loc, CaptureType, 14481 diag::err_capture_of_incomplete_type, 14482 Var->getDeclName())) 14483 return false; 14484 14485 if (S.RequireNonAbstractType(Loc, CaptureType, 14486 diag::err_capture_of_abstract_type)) 14487 return false; 14488 } 14489 } 14490 14491 // Capture this variable in the lambda. 14492 if (BuildAndDiagnose) 14493 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14494 RefersToCapturedVariable); 14495 14496 // Compute the type of a reference to this captured variable. 14497 if (ByRef) 14498 DeclRefType = CaptureType.getNonReferenceType(); 14499 else { 14500 // C++ [expr.prim.lambda]p5: 14501 // The closure type for a lambda-expression has a public inline 14502 // function call operator [...]. This function call operator is 14503 // declared const (9.3.1) if and only if the lambda-expression's 14504 // parameter-declaration-clause is not followed by mutable. 14505 DeclRefType = CaptureType.getNonReferenceType(); 14506 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14507 DeclRefType.addConst(); 14508 } 14509 14510 // Add the capture. 14511 if (BuildAndDiagnose) 14512 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14513 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14514 14515 return true; 14516 } 14517 14518 bool Sema::tryCaptureVariable( 14519 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14520 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14521 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14522 // An init-capture is notionally from the context surrounding its 14523 // declaration, but its parent DC is the lambda class. 14524 DeclContext *VarDC = Var->getDeclContext(); 14525 if (Var->isInitCapture()) 14526 VarDC = VarDC->getParent(); 14527 14528 DeclContext *DC = CurContext; 14529 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14530 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14531 // We need to sync up the Declaration Context with the 14532 // FunctionScopeIndexToStopAt 14533 if (FunctionScopeIndexToStopAt) { 14534 unsigned FSIndex = FunctionScopes.size() - 1; 14535 while (FSIndex != MaxFunctionScopesIndex) { 14536 DC = getLambdaAwareParentOfDeclContext(DC); 14537 --FSIndex; 14538 } 14539 } 14540 14541 14542 // If the variable is declared in the current context, there is no need to 14543 // capture it. 14544 if (VarDC == DC) return true; 14545 14546 // Capture global variables if it is required to use private copy of this 14547 // variable. 14548 bool IsGlobal = !Var->hasLocalStorage(); 14549 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14550 return true; 14551 Var = Var->getCanonicalDecl(); 14552 14553 // Walk up the stack to determine whether we can capture the variable, 14554 // performing the "simple" checks that don't depend on type. We stop when 14555 // we've either hit the declared scope of the variable or find an existing 14556 // capture of that variable. We start from the innermost capturing-entity 14557 // (the DC) and ensure that all intervening capturing-entities 14558 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14559 // declcontext can either capture the variable or have already captured 14560 // the variable. 14561 CaptureType = Var->getType(); 14562 DeclRefType = CaptureType.getNonReferenceType(); 14563 bool Nested = false; 14564 bool Explicit = (Kind != TryCapture_Implicit); 14565 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14566 do { 14567 // Only block literals, captured statements, and lambda expressions can 14568 // capture; other scopes don't work. 14569 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14570 ExprLoc, 14571 BuildAndDiagnose, 14572 *this); 14573 // We need to check for the parent *first* because, if we *have* 14574 // private-captured a global variable, we need to recursively capture it in 14575 // intermediate blocks, lambdas, etc. 14576 if (!ParentDC) { 14577 if (IsGlobal) { 14578 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14579 break; 14580 } 14581 return true; 14582 } 14583 14584 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14585 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14586 14587 14588 // Check whether we've already captured it. 14589 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14590 DeclRefType)) { 14591 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14592 break; 14593 } 14594 // If we are instantiating a generic lambda call operator body, 14595 // we do not want to capture new variables. What was captured 14596 // during either a lambdas transformation or initial parsing 14597 // should be used. 14598 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14599 if (BuildAndDiagnose) { 14600 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14601 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14602 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14603 Diag(Var->getLocation(), diag::note_previous_decl) 14604 << Var->getDeclName(); 14605 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14606 } else 14607 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14608 } 14609 return true; 14610 } 14611 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14612 // certain types of variables (unnamed, variably modified types etc.) 14613 // so check for eligibility. 14614 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14615 return true; 14616 14617 // Try to capture variable-length arrays types. 14618 if (Var->getType()->isVariablyModifiedType()) { 14619 // We're going to walk down into the type and look for VLA 14620 // expressions. 14621 QualType QTy = Var->getType(); 14622 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14623 QTy = PVD->getOriginalType(); 14624 captureVariablyModifiedType(Context, QTy, CSI); 14625 } 14626 14627 if (getLangOpts().OpenMP) { 14628 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14629 // OpenMP private variables should not be captured in outer scope, so 14630 // just break here. Similarly, global variables that are captured in a 14631 // target region should not be captured outside the scope of the region. 14632 if (RSI->CapRegionKind == CR_OpenMP) { 14633 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14634 // When we detect target captures we are looking from inside the 14635 // target region, therefore we need to propagate the capture from the 14636 // enclosing region. Therefore, the capture is not initially nested. 14637 if (IsTargetCap) 14638 FunctionScopesIndex--; 14639 14640 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14641 Nested = !IsTargetCap; 14642 DeclRefType = DeclRefType.getUnqualifiedType(); 14643 CaptureType = Context.getLValueReferenceType(DeclRefType); 14644 break; 14645 } 14646 } 14647 } 14648 } 14649 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14650 // No capture-default, and this is not an explicit capture 14651 // so cannot capture this variable. 14652 if (BuildAndDiagnose) { 14653 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14654 Diag(Var->getLocation(), diag::note_previous_decl) 14655 << Var->getDeclName(); 14656 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14657 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14658 diag::note_lambda_decl); 14659 // FIXME: If we error out because an outer lambda can not implicitly 14660 // capture a variable that an inner lambda explicitly captures, we 14661 // should have the inner lambda do the explicit capture - because 14662 // it makes for cleaner diagnostics later. This would purely be done 14663 // so that the diagnostic does not misleadingly claim that a variable 14664 // can not be captured by a lambda implicitly even though it is captured 14665 // explicitly. Suggestion: 14666 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14667 // at the function head 14668 // - cache the StartingDeclContext - this must be a lambda 14669 // - captureInLambda in the innermost lambda the variable. 14670 } 14671 return true; 14672 } 14673 14674 FunctionScopesIndex--; 14675 DC = ParentDC; 14676 Explicit = false; 14677 } while (!VarDC->Equals(DC)); 14678 14679 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14680 // computing the type of the capture at each step, checking type-specific 14681 // requirements, and adding captures if requested. 14682 // If the variable had already been captured previously, we start capturing 14683 // at the lambda nested within that one. 14684 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14685 ++I) { 14686 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14687 14688 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14689 if (!captureInBlock(BSI, Var, ExprLoc, 14690 BuildAndDiagnose, CaptureType, 14691 DeclRefType, Nested, *this)) 14692 return true; 14693 Nested = true; 14694 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14695 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14696 BuildAndDiagnose, CaptureType, 14697 DeclRefType, Nested, *this)) 14698 return true; 14699 Nested = true; 14700 } else { 14701 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14702 if (!captureInLambda(LSI, Var, ExprLoc, 14703 BuildAndDiagnose, CaptureType, 14704 DeclRefType, Nested, Kind, EllipsisLoc, 14705 /*IsTopScope*/I == N - 1, *this)) 14706 return true; 14707 Nested = true; 14708 } 14709 } 14710 return false; 14711 } 14712 14713 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14714 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14715 QualType CaptureType; 14716 QualType DeclRefType; 14717 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14718 /*BuildAndDiagnose=*/true, CaptureType, 14719 DeclRefType, nullptr); 14720 } 14721 14722 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14723 QualType CaptureType; 14724 QualType DeclRefType; 14725 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14726 /*BuildAndDiagnose=*/false, CaptureType, 14727 DeclRefType, nullptr); 14728 } 14729 14730 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14731 QualType CaptureType; 14732 QualType DeclRefType; 14733 14734 // Determine whether we can capture this variable. 14735 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14736 /*BuildAndDiagnose=*/false, CaptureType, 14737 DeclRefType, nullptr)) 14738 return QualType(); 14739 14740 return DeclRefType; 14741 } 14742 14743 14744 14745 // If either the type of the variable or the initializer is dependent, 14746 // return false. Otherwise, determine whether the variable is a constant 14747 // expression. Use this if you need to know if a variable that might or 14748 // might not be dependent is truly a constant expression. 14749 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14750 ASTContext &Context) { 14751 14752 if (Var->getType()->isDependentType()) 14753 return false; 14754 const VarDecl *DefVD = nullptr; 14755 Var->getAnyInitializer(DefVD); 14756 if (!DefVD) 14757 return false; 14758 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14759 Expr *Init = cast<Expr>(Eval->Value); 14760 if (Init->isValueDependent()) 14761 return false; 14762 return IsVariableAConstantExpression(Var, Context); 14763 } 14764 14765 14766 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14767 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14768 // an object that satisfies the requirements for appearing in a 14769 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14770 // is immediately applied." This function handles the lvalue-to-rvalue 14771 // conversion part. 14772 MaybeODRUseExprs.erase(E->IgnoreParens()); 14773 14774 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14775 // to a variable that is a constant expression, and if so, identify it as 14776 // a reference to a variable that does not involve an odr-use of that 14777 // variable. 14778 if (LambdaScopeInfo *LSI = getCurLambda()) { 14779 Expr *SansParensExpr = E->IgnoreParens(); 14780 VarDecl *Var = nullptr; 14781 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14782 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14783 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14784 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14785 14786 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14787 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14788 } 14789 } 14790 14791 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14792 Res = CorrectDelayedTyposInExpr(Res); 14793 14794 if (!Res.isUsable()) 14795 return Res; 14796 14797 // If a constant-expression is a reference to a variable where we delay 14798 // deciding whether it is an odr-use, just assume we will apply the 14799 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14800 // (a non-type template argument), we have special handling anyway. 14801 UpdateMarkingForLValueToRValue(Res.get()); 14802 return Res; 14803 } 14804 14805 void Sema::CleanupVarDeclMarking() { 14806 for (Expr *E : MaybeODRUseExprs) { 14807 VarDecl *Var; 14808 SourceLocation Loc; 14809 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14810 Var = cast<VarDecl>(DRE->getDecl()); 14811 Loc = DRE->getLocation(); 14812 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14813 Var = cast<VarDecl>(ME->getMemberDecl()); 14814 Loc = ME->getMemberLoc(); 14815 } else { 14816 llvm_unreachable("Unexpected expression"); 14817 } 14818 14819 MarkVarDeclODRUsed(Var, Loc, *this, 14820 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14821 } 14822 14823 MaybeODRUseExprs.clear(); 14824 } 14825 14826 14827 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14828 VarDecl *Var, Expr *E) { 14829 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14830 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14831 Var->setReferenced(); 14832 14833 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14834 14835 bool OdrUseContext = isOdrUseContext(SemaRef); 14836 bool UsableInConstantExpr = 14837 Var->isUsableInConstantExpressions(SemaRef.Context); 14838 bool NeedDefinition = 14839 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14840 14841 VarTemplateSpecializationDecl *VarSpec = 14842 dyn_cast<VarTemplateSpecializationDecl>(Var); 14843 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14844 "Can't instantiate a partial template specialization."); 14845 14846 // If this might be a member specialization of a static data member, check 14847 // the specialization is visible. We already did the checks for variable 14848 // template specializations when we created them. 14849 if (NeedDefinition && TSK != TSK_Undeclared && 14850 !isa<VarTemplateSpecializationDecl>(Var)) 14851 SemaRef.checkSpecializationVisibility(Loc, Var); 14852 14853 // Perform implicit instantiation of static data members, static data member 14854 // templates of class templates, and variable template specializations. Delay 14855 // instantiations of variable templates, except for those that could be used 14856 // in a constant expression. 14857 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14858 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14859 // instantiation declaration if a variable is usable in a constant 14860 // expression (among other cases). 14861 bool TryInstantiating = 14862 TSK == TSK_ImplicitInstantiation || 14863 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14864 14865 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14866 if (Var->getPointOfInstantiation().isInvalid()) { 14867 // This is a modification of an existing AST node. Notify listeners. 14868 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14869 L->StaticDataMemberInstantiated(Var); 14870 } else if (!UsableInConstantExpr) 14871 // Don't bother trying to instantiate it again, unless we might need 14872 // its initializer before we get to the end of the TU. 14873 TryInstantiating = false; 14874 } 14875 14876 if (Var->getPointOfInstantiation().isInvalid()) 14877 Var->setTemplateSpecializationKind(TSK, Loc); 14878 14879 if (TryInstantiating) { 14880 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14881 bool InstantiationDependent = false; 14882 bool IsNonDependent = 14883 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14884 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14885 : true; 14886 14887 // Do not instantiate specializations that are still type-dependent. 14888 if (IsNonDependent) { 14889 if (UsableInConstantExpr) { 14890 // Do not defer instantiations of variables which could be used in a 14891 // constant expression. 14892 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14893 } else { 14894 SemaRef.PendingInstantiations 14895 .push_back(std::make_pair(Var, PointOfInstantiation)); 14896 } 14897 } 14898 } 14899 } 14900 14901 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14902 // the requirements for appearing in a constant expression (5.19) and, if 14903 // it is an object, the lvalue-to-rvalue conversion (4.1) 14904 // is immediately applied." We check the first part here, and 14905 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14906 // Note that we use the C++11 definition everywhere because nothing in 14907 // C++03 depends on whether we get the C++03 version correct. The second 14908 // part does not apply to references, since they are not objects. 14909 if (OdrUseContext && E && 14910 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14911 // A reference initialized by a constant expression can never be 14912 // odr-used, so simply ignore it. 14913 if (!Var->getType()->isReferenceType() || 14914 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14915 SemaRef.MaybeODRUseExprs.insert(E); 14916 } else if (OdrUseContext) { 14917 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14918 /*MaxFunctionScopeIndex ptr*/ nullptr); 14919 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14920 // If this is a dependent context, we don't need to mark variables as 14921 // odr-used, but we may still need to track them for lambda capture. 14922 // FIXME: Do we also need to do this inside dependent typeid expressions 14923 // (which are modeled as unevaluated at this point)? 14924 const bool RefersToEnclosingScope = 14925 (SemaRef.CurContext != Var->getDeclContext() && 14926 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14927 if (RefersToEnclosingScope) { 14928 LambdaScopeInfo *const LSI = 14929 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14930 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14931 // If a variable could potentially be odr-used, defer marking it so 14932 // until we finish analyzing the full expression for any 14933 // lvalue-to-rvalue 14934 // or discarded value conversions that would obviate odr-use. 14935 // Add it to the list of potential captures that will be analyzed 14936 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14937 // unless the variable is a reference that was initialized by a constant 14938 // expression (this will never need to be captured or odr-used). 14939 assert(E && "Capture variable should be used in an expression."); 14940 if (!Var->getType()->isReferenceType() || 14941 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14942 LSI->addPotentialCapture(E->IgnoreParens()); 14943 } 14944 } 14945 } 14946 } 14947 14948 /// \brief Mark a variable referenced, and check whether it is odr-used 14949 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14950 /// used directly for normal expressions referring to VarDecl. 14951 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14952 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14953 } 14954 14955 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14956 Decl *D, Expr *E, bool MightBeOdrUse) { 14957 if (SemaRef.isInOpenMPDeclareTargetContext()) 14958 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14959 14960 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14961 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14962 return; 14963 } 14964 14965 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14966 14967 // If this is a call to a method via a cast, also mark the method in the 14968 // derived class used in case codegen can devirtualize the call. 14969 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14970 if (!ME) 14971 return; 14972 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14973 if (!MD) 14974 return; 14975 // Only attempt to devirtualize if this is truly a virtual call. 14976 bool IsVirtualCall = MD->isVirtual() && 14977 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14978 if (!IsVirtualCall) 14979 return; 14980 14981 // If it's possible to devirtualize the call, mark the called function 14982 // referenced. 14983 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 14984 ME->getBase(), SemaRef.getLangOpts().AppleKext); 14985 if (DM) 14986 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14987 } 14988 14989 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14990 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 14991 // TODO: update this with DR# once a defect report is filed. 14992 // C++11 defect. The address of a pure member should not be an ODR use, even 14993 // if it's a qualified reference. 14994 bool OdrUse = true; 14995 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14996 if (Method->isVirtual() && 14997 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 14998 OdrUse = false; 14999 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15000 } 15001 15002 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15003 void Sema::MarkMemberReferenced(MemberExpr *E) { 15004 // C++11 [basic.def.odr]p2: 15005 // A non-overloaded function whose name appears as a potentially-evaluated 15006 // expression or a member of a set of candidate functions, if selected by 15007 // overload resolution when referred to from a potentially-evaluated 15008 // expression, is odr-used, unless it is a pure virtual function and its 15009 // name is not explicitly qualified. 15010 bool MightBeOdrUse = true; 15011 if (E->performsVirtualDispatch(getLangOpts())) { 15012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15013 if (Method->isPure()) 15014 MightBeOdrUse = false; 15015 } 15016 SourceLocation Loc = E->getMemberLoc().isValid() ? 15017 E->getMemberLoc() : E->getLocStart(); 15018 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15019 } 15020 15021 /// \brief Perform marking for a reference to an arbitrary declaration. It 15022 /// marks the declaration referenced, and performs odr-use checking for 15023 /// functions and variables. This method should not be used when building a 15024 /// normal expression which refers to a variable. 15025 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15026 bool MightBeOdrUse) { 15027 if (MightBeOdrUse) { 15028 if (auto *VD = dyn_cast<VarDecl>(D)) { 15029 MarkVariableReferenced(Loc, VD); 15030 return; 15031 } 15032 } 15033 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15034 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15035 return; 15036 } 15037 D->setReferenced(); 15038 } 15039 15040 namespace { 15041 // Mark all of the declarations used by a type as referenced. 15042 // FIXME: Not fully implemented yet! We need to have a better understanding 15043 // of when we're entering a context we should not recurse into. 15044 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15045 // TreeTransforms rebuilding the type in a new context. Rather than 15046 // duplicating the TreeTransform logic, we should consider reusing it here. 15047 // Currently that causes problems when rebuilding LambdaExprs. 15048 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15049 Sema &S; 15050 SourceLocation Loc; 15051 15052 public: 15053 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15054 15055 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15056 15057 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15058 }; 15059 } 15060 15061 bool MarkReferencedDecls::TraverseTemplateArgument( 15062 const TemplateArgument &Arg) { 15063 { 15064 // A non-type template argument is a constant-evaluated context. 15065 EnterExpressionEvaluationContext Evaluated( 15066 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15067 if (Arg.getKind() == TemplateArgument::Declaration) { 15068 if (Decl *D = Arg.getAsDecl()) 15069 S.MarkAnyDeclReferenced(Loc, D, true); 15070 } else if (Arg.getKind() == TemplateArgument::Expression) { 15071 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15072 } 15073 } 15074 15075 return Inherited::TraverseTemplateArgument(Arg); 15076 } 15077 15078 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15079 MarkReferencedDecls Marker(*this, Loc); 15080 Marker.TraverseType(T); 15081 } 15082 15083 namespace { 15084 /// \brief Helper class that marks all of the declarations referenced by 15085 /// potentially-evaluated subexpressions as "referenced". 15086 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15087 Sema &S; 15088 bool SkipLocalVariables; 15089 15090 public: 15091 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15092 15093 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15094 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15095 15096 void VisitDeclRefExpr(DeclRefExpr *E) { 15097 // If we were asked not to visit local variables, don't. 15098 if (SkipLocalVariables) { 15099 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15100 if (VD->hasLocalStorage()) 15101 return; 15102 } 15103 15104 S.MarkDeclRefReferenced(E); 15105 } 15106 15107 void VisitMemberExpr(MemberExpr *E) { 15108 S.MarkMemberReferenced(E); 15109 Inherited::VisitMemberExpr(E); 15110 } 15111 15112 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15113 S.MarkFunctionReferenced(E->getLocStart(), 15114 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15115 Visit(E->getSubExpr()); 15116 } 15117 15118 void VisitCXXNewExpr(CXXNewExpr *E) { 15119 if (E->getOperatorNew()) 15120 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15121 if (E->getOperatorDelete()) 15122 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15123 Inherited::VisitCXXNewExpr(E); 15124 } 15125 15126 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15127 if (E->getOperatorDelete()) 15128 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15129 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15130 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15131 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15132 S.MarkFunctionReferenced(E->getLocStart(), 15133 S.LookupDestructor(Record)); 15134 } 15135 15136 Inherited::VisitCXXDeleteExpr(E); 15137 } 15138 15139 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15140 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15141 Inherited::VisitCXXConstructExpr(E); 15142 } 15143 15144 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15145 Visit(E->getExpr()); 15146 } 15147 15148 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15149 Inherited::VisitImplicitCastExpr(E); 15150 15151 if (E->getCastKind() == CK_LValueToRValue) 15152 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15153 } 15154 }; 15155 } 15156 15157 /// \brief Mark any declarations that appear within this expression or any 15158 /// potentially-evaluated subexpressions as "referenced". 15159 /// 15160 /// \param SkipLocalVariables If true, don't mark local variables as 15161 /// 'referenced'. 15162 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15163 bool SkipLocalVariables) { 15164 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15165 } 15166 15167 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15168 /// of the program being compiled. 15169 /// 15170 /// This routine emits the given diagnostic when the code currently being 15171 /// type-checked is "potentially evaluated", meaning that there is a 15172 /// possibility that the code will actually be executable. Code in sizeof() 15173 /// expressions, code used only during overload resolution, etc., are not 15174 /// potentially evaluated. This routine will suppress such diagnostics or, 15175 /// in the absolutely nutty case of potentially potentially evaluated 15176 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15177 /// later. 15178 /// 15179 /// This routine should be used for all diagnostics that describe the run-time 15180 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15181 /// Failure to do so will likely result in spurious diagnostics or failures 15182 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15183 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15184 const PartialDiagnostic &PD) { 15185 switch (ExprEvalContexts.back().Context) { 15186 case ExpressionEvaluationContext::Unevaluated: 15187 case ExpressionEvaluationContext::UnevaluatedList: 15188 case ExpressionEvaluationContext::UnevaluatedAbstract: 15189 case ExpressionEvaluationContext::DiscardedStatement: 15190 // The argument will never be evaluated, so don't complain. 15191 break; 15192 15193 case ExpressionEvaluationContext::ConstantEvaluated: 15194 // Relevant diagnostics should be produced by constant evaluation. 15195 break; 15196 15197 case ExpressionEvaluationContext::PotentiallyEvaluated: 15198 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15199 if (Statement && getCurFunctionOrMethodDecl()) { 15200 FunctionScopes.back()->PossiblyUnreachableDiags. 15201 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15202 return true; 15203 } 15204 15205 // The initializer of a constexpr variable or of the first declaration of a 15206 // static data member is not syntactically a constant evaluated constant, 15207 // but nonetheless is always required to be a constant expression, so we 15208 // can skip diagnosing. 15209 // FIXME: Using the mangling context here is a hack. 15210 if (auto *VD = dyn_cast_or_null<VarDecl>( 15211 ExprEvalContexts.back().ManglingContextDecl)) { 15212 if (VD->isConstexpr() || 15213 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15214 break; 15215 // FIXME: For any other kind of variable, we should build a CFG for its 15216 // initializer and check whether the context in question is reachable. 15217 } 15218 15219 Diag(Loc, PD); 15220 return true; 15221 } 15222 15223 return false; 15224 } 15225 15226 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15227 CallExpr *CE, FunctionDecl *FD) { 15228 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15229 return false; 15230 15231 // If we're inside a decltype's expression, don't check for a valid return 15232 // type or construct temporaries until we know whether this is the last call. 15233 if (ExprEvalContexts.back().IsDecltype) { 15234 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15235 return false; 15236 } 15237 15238 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15239 FunctionDecl *FD; 15240 CallExpr *CE; 15241 15242 public: 15243 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15244 : FD(FD), CE(CE) { } 15245 15246 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15247 if (!FD) { 15248 S.Diag(Loc, diag::err_call_incomplete_return) 15249 << T << CE->getSourceRange(); 15250 return; 15251 } 15252 15253 S.Diag(Loc, diag::err_call_function_incomplete_return) 15254 << CE->getSourceRange() << FD->getDeclName() << T; 15255 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15256 << FD->getDeclName(); 15257 } 15258 } Diagnoser(FD, CE); 15259 15260 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15261 return true; 15262 15263 return false; 15264 } 15265 15266 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15267 // will prevent this condition from triggering, which is what we want. 15268 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15269 SourceLocation Loc; 15270 15271 unsigned diagnostic = diag::warn_condition_is_assignment; 15272 bool IsOrAssign = false; 15273 15274 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15275 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15276 return; 15277 15278 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15279 15280 // Greylist some idioms by putting them into a warning subcategory. 15281 if (ObjCMessageExpr *ME 15282 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15283 Selector Sel = ME->getSelector(); 15284 15285 // self = [<foo> init...] 15286 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15287 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15288 15289 // <foo> = [<bar> nextObject] 15290 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15291 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15292 } 15293 15294 Loc = Op->getOperatorLoc(); 15295 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15296 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15297 return; 15298 15299 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15300 Loc = Op->getOperatorLoc(); 15301 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15302 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15303 else { 15304 // Not an assignment. 15305 return; 15306 } 15307 15308 Diag(Loc, diagnostic) << E->getSourceRange(); 15309 15310 SourceLocation Open = E->getLocStart(); 15311 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15312 Diag(Loc, diag::note_condition_assign_silence) 15313 << FixItHint::CreateInsertion(Open, "(") 15314 << FixItHint::CreateInsertion(Close, ")"); 15315 15316 if (IsOrAssign) 15317 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15318 << FixItHint::CreateReplacement(Loc, "!="); 15319 else 15320 Diag(Loc, diag::note_condition_assign_to_comparison) 15321 << FixItHint::CreateReplacement(Loc, "=="); 15322 } 15323 15324 /// \brief Redundant parentheses over an equality comparison can indicate 15325 /// that the user intended an assignment used as condition. 15326 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15327 // Don't warn if the parens came from a macro. 15328 SourceLocation parenLoc = ParenE->getLocStart(); 15329 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15330 return; 15331 // Don't warn for dependent expressions. 15332 if (ParenE->isTypeDependent()) 15333 return; 15334 15335 Expr *E = ParenE->IgnoreParens(); 15336 15337 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15338 if (opE->getOpcode() == BO_EQ && 15339 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15340 == Expr::MLV_Valid) { 15341 SourceLocation Loc = opE->getOperatorLoc(); 15342 15343 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15344 SourceRange ParenERange = ParenE->getSourceRange(); 15345 Diag(Loc, diag::note_equality_comparison_silence) 15346 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15347 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15348 Diag(Loc, diag::note_equality_comparison_to_assign) 15349 << FixItHint::CreateReplacement(Loc, "="); 15350 } 15351 } 15352 15353 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15354 bool IsConstexpr) { 15355 DiagnoseAssignmentAsCondition(E); 15356 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15357 DiagnoseEqualityWithExtraParens(parenE); 15358 15359 ExprResult result = CheckPlaceholderExpr(E); 15360 if (result.isInvalid()) return ExprError(); 15361 E = result.get(); 15362 15363 if (!E->isTypeDependent()) { 15364 if (getLangOpts().CPlusPlus) 15365 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15366 15367 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15368 if (ERes.isInvalid()) 15369 return ExprError(); 15370 E = ERes.get(); 15371 15372 QualType T = E->getType(); 15373 if (!T->isScalarType()) { // C99 6.8.4.1p1 15374 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15375 << T << E->getSourceRange(); 15376 return ExprError(); 15377 } 15378 CheckBoolLikeConversion(E, Loc); 15379 } 15380 15381 return E; 15382 } 15383 15384 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15385 Expr *SubExpr, ConditionKind CK) { 15386 // Empty conditions are valid in for-statements. 15387 if (!SubExpr) 15388 return ConditionResult(); 15389 15390 ExprResult Cond; 15391 switch (CK) { 15392 case ConditionKind::Boolean: 15393 Cond = CheckBooleanCondition(Loc, SubExpr); 15394 break; 15395 15396 case ConditionKind::ConstexprIf: 15397 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15398 break; 15399 15400 case ConditionKind::Switch: 15401 Cond = CheckSwitchCondition(Loc, SubExpr); 15402 break; 15403 } 15404 if (Cond.isInvalid()) 15405 return ConditionError(); 15406 15407 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15408 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15409 if (!FullExpr.get()) 15410 return ConditionError(); 15411 15412 return ConditionResult(*this, nullptr, FullExpr, 15413 CK == ConditionKind::ConstexprIf); 15414 } 15415 15416 namespace { 15417 /// A visitor for rebuilding a call to an __unknown_any expression 15418 /// to have an appropriate type. 15419 struct RebuildUnknownAnyFunction 15420 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15421 15422 Sema &S; 15423 15424 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15425 15426 ExprResult VisitStmt(Stmt *S) { 15427 llvm_unreachable("unexpected statement!"); 15428 } 15429 15430 ExprResult VisitExpr(Expr *E) { 15431 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15432 << E->getSourceRange(); 15433 return ExprError(); 15434 } 15435 15436 /// Rebuild an expression which simply semantically wraps another 15437 /// expression which it shares the type and value kind of. 15438 template <class T> ExprResult rebuildSugarExpr(T *E) { 15439 ExprResult SubResult = Visit(E->getSubExpr()); 15440 if (SubResult.isInvalid()) return ExprError(); 15441 15442 Expr *SubExpr = SubResult.get(); 15443 E->setSubExpr(SubExpr); 15444 E->setType(SubExpr->getType()); 15445 E->setValueKind(SubExpr->getValueKind()); 15446 assert(E->getObjectKind() == OK_Ordinary); 15447 return E; 15448 } 15449 15450 ExprResult VisitParenExpr(ParenExpr *E) { 15451 return rebuildSugarExpr(E); 15452 } 15453 15454 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15455 return rebuildSugarExpr(E); 15456 } 15457 15458 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15459 ExprResult SubResult = Visit(E->getSubExpr()); 15460 if (SubResult.isInvalid()) return ExprError(); 15461 15462 Expr *SubExpr = SubResult.get(); 15463 E->setSubExpr(SubExpr); 15464 E->setType(S.Context.getPointerType(SubExpr->getType())); 15465 assert(E->getValueKind() == VK_RValue); 15466 assert(E->getObjectKind() == OK_Ordinary); 15467 return E; 15468 } 15469 15470 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15471 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15472 15473 E->setType(VD->getType()); 15474 15475 assert(E->getValueKind() == VK_RValue); 15476 if (S.getLangOpts().CPlusPlus && 15477 !(isa<CXXMethodDecl>(VD) && 15478 cast<CXXMethodDecl>(VD)->isInstance())) 15479 E->setValueKind(VK_LValue); 15480 15481 return E; 15482 } 15483 15484 ExprResult VisitMemberExpr(MemberExpr *E) { 15485 return resolveDecl(E, E->getMemberDecl()); 15486 } 15487 15488 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15489 return resolveDecl(E, E->getDecl()); 15490 } 15491 }; 15492 } 15493 15494 /// Given a function expression of unknown-any type, try to rebuild it 15495 /// to have a function type. 15496 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15497 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15498 if (Result.isInvalid()) return ExprError(); 15499 return S.DefaultFunctionArrayConversion(Result.get()); 15500 } 15501 15502 namespace { 15503 /// A visitor for rebuilding an expression of type __unknown_anytype 15504 /// into one which resolves the type directly on the referring 15505 /// expression. Strict preservation of the original source 15506 /// structure is not a goal. 15507 struct RebuildUnknownAnyExpr 15508 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15509 15510 Sema &S; 15511 15512 /// The current destination type. 15513 QualType DestType; 15514 15515 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15516 : S(S), DestType(CastType) {} 15517 15518 ExprResult VisitStmt(Stmt *S) { 15519 llvm_unreachable("unexpected statement!"); 15520 } 15521 15522 ExprResult VisitExpr(Expr *E) { 15523 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15524 << E->getSourceRange(); 15525 return ExprError(); 15526 } 15527 15528 ExprResult VisitCallExpr(CallExpr *E); 15529 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15530 15531 /// Rebuild an expression which simply semantically wraps another 15532 /// expression which it shares the type and value kind of. 15533 template <class T> ExprResult rebuildSugarExpr(T *E) { 15534 ExprResult SubResult = Visit(E->getSubExpr()); 15535 if (SubResult.isInvalid()) return ExprError(); 15536 Expr *SubExpr = SubResult.get(); 15537 E->setSubExpr(SubExpr); 15538 E->setType(SubExpr->getType()); 15539 E->setValueKind(SubExpr->getValueKind()); 15540 assert(E->getObjectKind() == OK_Ordinary); 15541 return E; 15542 } 15543 15544 ExprResult VisitParenExpr(ParenExpr *E) { 15545 return rebuildSugarExpr(E); 15546 } 15547 15548 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15549 return rebuildSugarExpr(E); 15550 } 15551 15552 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15553 const PointerType *Ptr = DestType->getAs<PointerType>(); 15554 if (!Ptr) { 15555 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15556 << E->getSourceRange(); 15557 return ExprError(); 15558 } 15559 15560 if (isa<CallExpr>(E->getSubExpr())) { 15561 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15562 << E->getSourceRange(); 15563 return ExprError(); 15564 } 15565 15566 assert(E->getValueKind() == VK_RValue); 15567 assert(E->getObjectKind() == OK_Ordinary); 15568 E->setType(DestType); 15569 15570 // Build the sub-expression as if it were an object of the pointee type. 15571 DestType = Ptr->getPointeeType(); 15572 ExprResult SubResult = Visit(E->getSubExpr()); 15573 if (SubResult.isInvalid()) return ExprError(); 15574 E->setSubExpr(SubResult.get()); 15575 return E; 15576 } 15577 15578 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15579 15580 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15581 15582 ExprResult VisitMemberExpr(MemberExpr *E) { 15583 return resolveDecl(E, E->getMemberDecl()); 15584 } 15585 15586 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15587 return resolveDecl(E, E->getDecl()); 15588 } 15589 }; 15590 } 15591 15592 /// Rebuilds a call expression which yielded __unknown_anytype. 15593 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15594 Expr *CalleeExpr = E->getCallee(); 15595 15596 enum FnKind { 15597 FK_MemberFunction, 15598 FK_FunctionPointer, 15599 FK_BlockPointer 15600 }; 15601 15602 FnKind Kind; 15603 QualType CalleeType = CalleeExpr->getType(); 15604 if (CalleeType == S.Context.BoundMemberTy) { 15605 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15606 Kind = FK_MemberFunction; 15607 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15608 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15609 CalleeType = Ptr->getPointeeType(); 15610 Kind = FK_FunctionPointer; 15611 } else { 15612 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15613 Kind = FK_BlockPointer; 15614 } 15615 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15616 15617 // Verify that this is a legal result type of a function. 15618 if (DestType->isArrayType() || DestType->isFunctionType()) { 15619 unsigned diagID = diag::err_func_returning_array_function; 15620 if (Kind == FK_BlockPointer) 15621 diagID = diag::err_block_returning_array_function; 15622 15623 S.Diag(E->getExprLoc(), diagID) 15624 << DestType->isFunctionType() << DestType; 15625 return ExprError(); 15626 } 15627 15628 // Otherwise, go ahead and set DestType as the call's result. 15629 E->setType(DestType.getNonLValueExprType(S.Context)); 15630 E->setValueKind(Expr::getValueKindForType(DestType)); 15631 assert(E->getObjectKind() == OK_Ordinary); 15632 15633 // Rebuild the function type, replacing the result type with DestType. 15634 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15635 if (Proto) { 15636 // __unknown_anytype(...) is a special case used by the debugger when 15637 // it has no idea what a function's signature is. 15638 // 15639 // We want to build this call essentially under the K&R 15640 // unprototyped rules, but making a FunctionNoProtoType in C++ 15641 // would foul up all sorts of assumptions. However, we cannot 15642 // simply pass all arguments as variadic arguments, nor can we 15643 // portably just call the function under a non-variadic type; see 15644 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15645 // However, it turns out that in practice it is generally safe to 15646 // call a function declared as "A foo(B,C,D);" under the prototype 15647 // "A foo(B,C,D,...);". The only known exception is with the 15648 // Windows ABI, where any variadic function is implicitly cdecl 15649 // regardless of its normal CC. Therefore we change the parameter 15650 // types to match the types of the arguments. 15651 // 15652 // This is a hack, but it is far superior to moving the 15653 // corresponding target-specific code from IR-gen to Sema/AST. 15654 15655 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15656 SmallVector<QualType, 8> ArgTypes; 15657 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15658 ArgTypes.reserve(E->getNumArgs()); 15659 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15660 Expr *Arg = E->getArg(i); 15661 QualType ArgType = Arg->getType(); 15662 if (E->isLValue()) { 15663 ArgType = S.Context.getLValueReferenceType(ArgType); 15664 } else if (E->isXValue()) { 15665 ArgType = S.Context.getRValueReferenceType(ArgType); 15666 } 15667 ArgTypes.push_back(ArgType); 15668 } 15669 ParamTypes = ArgTypes; 15670 } 15671 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15672 Proto->getExtProtoInfo()); 15673 } else { 15674 DestType = S.Context.getFunctionNoProtoType(DestType, 15675 FnType->getExtInfo()); 15676 } 15677 15678 // Rebuild the appropriate pointer-to-function type. 15679 switch (Kind) { 15680 case FK_MemberFunction: 15681 // Nothing to do. 15682 break; 15683 15684 case FK_FunctionPointer: 15685 DestType = S.Context.getPointerType(DestType); 15686 break; 15687 15688 case FK_BlockPointer: 15689 DestType = S.Context.getBlockPointerType(DestType); 15690 break; 15691 } 15692 15693 // Finally, we can recurse. 15694 ExprResult CalleeResult = Visit(CalleeExpr); 15695 if (!CalleeResult.isUsable()) return ExprError(); 15696 E->setCallee(CalleeResult.get()); 15697 15698 // Bind a temporary if necessary. 15699 return S.MaybeBindToTemporary(E); 15700 } 15701 15702 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15703 // Verify that this is a legal result type of a call. 15704 if (DestType->isArrayType() || DestType->isFunctionType()) { 15705 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15706 << DestType->isFunctionType() << DestType; 15707 return ExprError(); 15708 } 15709 15710 // Rewrite the method result type if available. 15711 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15712 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15713 Method->setReturnType(DestType); 15714 } 15715 15716 // Change the type of the message. 15717 E->setType(DestType.getNonReferenceType()); 15718 E->setValueKind(Expr::getValueKindForType(DestType)); 15719 15720 return S.MaybeBindToTemporary(E); 15721 } 15722 15723 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15724 // The only case we should ever see here is a function-to-pointer decay. 15725 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15726 assert(E->getValueKind() == VK_RValue); 15727 assert(E->getObjectKind() == OK_Ordinary); 15728 15729 E->setType(DestType); 15730 15731 // Rebuild the sub-expression as the pointee (function) type. 15732 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15733 15734 ExprResult Result = Visit(E->getSubExpr()); 15735 if (!Result.isUsable()) return ExprError(); 15736 15737 E->setSubExpr(Result.get()); 15738 return E; 15739 } else if (E->getCastKind() == CK_LValueToRValue) { 15740 assert(E->getValueKind() == VK_RValue); 15741 assert(E->getObjectKind() == OK_Ordinary); 15742 15743 assert(isa<BlockPointerType>(E->getType())); 15744 15745 E->setType(DestType); 15746 15747 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15748 DestType = S.Context.getLValueReferenceType(DestType); 15749 15750 ExprResult Result = Visit(E->getSubExpr()); 15751 if (!Result.isUsable()) return ExprError(); 15752 15753 E->setSubExpr(Result.get()); 15754 return E; 15755 } else { 15756 llvm_unreachable("Unhandled cast type!"); 15757 } 15758 } 15759 15760 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15761 ExprValueKind ValueKind = VK_LValue; 15762 QualType Type = DestType; 15763 15764 // We know how to make this work for certain kinds of decls: 15765 15766 // - functions 15767 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15768 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15769 DestType = Ptr->getPointeeType(); 15770 ExprResult Result = resolveDecl(E, VD); 15771 if (Result.isInvalid()) return ExprError(); 15772 return S.ImpCastExprToType(Result.get(), Type, 15773 CK_FunctionToPointerDecay, VK_RValue); 15774 } 15775 15776 if (!Type->isFunctionType()) { 15777 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15778 << VD << E->getSourceRange(); 15779 return ExprError(); 15780 } 15781 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15782 // We must match the FunctionDecl's type to the hack introduced in 15783 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15784 // type. See the lengthy commentary in that routine. 15785 QualType FDT = FD->getType(); 15786 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15787 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15788 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15789 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15790 SourceLocation Loc = FD->getLocation(); 15791 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15792 FD->getDeclContext(), 15793 Loc, Loc, FD->getNameInfo().getName(), 15794 DestType, FD->getTypeSourceInfo(), 15795 SC_None, false/*isInlineSpecified*/, 15796 FD->hasPrototype(), 15797 false/*isConstexprSpecified*/); 15798 15799 if (FD->getQualifier()) 15800 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15801 15802 SmallVector<ParmVarDecl*, 16> Params; 15803 for (const auto &AI : FT->param_types()) { 15804 ParmVarDecl *Param = 15805 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15806 Param->setScopeInfo(0, Params.size()); 15807 Params.push_back(Param); 15808 } 15809 NewFD->setParams(Params); 15810 DRE->setDecl(NewFD); 15811 VD = DRE->getDecl(); 15812 } 15813 } 15814 15815 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15816 if (MD->isInstance()) { 15817 ValueKind = VK_RValue; 15818 Type = S.Context.BoundMemberTy; 15819 } 15820 15821 // Function references aren't l-values in C. 15822 if (!S.getLangOpts().CPlusPlus) 15823 ValueKind = VK_RValue; 15824 15825 // - variables 15826 } else if (isa<VarDecl>(VD)) { 15827 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15828 Type = RefTy->getPointeeType(); 15829 } else if (Type->isFunctionType()) { 15830 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15831 << VD << E->getSourceRange(); 15832 return ExprError(); 15833 } 15834 15835 // - nothing else 15836 } else { 15837 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15838 << VD << E->getSourceRange(); 15839 return ExprError(); 15840 } 15841 15842 // Modifying the declaration like this is friendly to IR-gen but 15843 // also really dangerous. 15844 VD->setType(DestType); 15845 E->setType(Type); 15846 E->setValueKind(ValueKind); 15847 return E; 15848 } 15849 15850 /// Check a cast of an unknown-any type. We intentionally only 15851 /// trigger this for C-style casts. 15852 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15853 Expr *CastExpr, CastKind &CastKind, 15854 ExprValueKind &VK, CXXCastPath &Path) { 15855 // The type we're casting to must be either void or complete. 15856 if (!CastType->isVoidType() && 15857 RequireCompleteType(TypeRange.getBegin(), CastType, 15858 diag::err_typecheck_cast_to_incomplete)) 15859 return ExprError(); 15860 15861 // Rewrite the casted expression from scratch. 15862 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15863 if (!result.isUsable()) return ExprError(); 15864 15865 CastExpr = result.get(); 15866 VK = CastExpr->getValueKind(); 15867 CastKind = CK_NoOp; 15868 15869 return CastExpr; 15870 } 15871 15872 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15873 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15874 } 15875 15876 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15877 Expr *arg, QualType ¶mType) { 15878 // If the syntactic form of the argument is not an explicit cast of 15879 // any sort, just do default argument promotion. 15880 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15881 if (!castArg) { 15882 ExprResult result = DefaultArgumentPromotion(arg); 15883 if (result.isInvalid()) return ExprError(); 15884 paramType = result.get()->getType(); 15885 return result; 15886 } 15887 15888 // Otherwise, use the type that was written in the explicit cast. 15889 assert(!arg->hasPlaceholderType()); 15890 paramType = castArg->getTypeAsWritten(); 15891 15892 // Copy-initialize a parameter of that type. 15893 InitializedEntity entity = 15894 InitializedEntity::InitializeParameter(Context, paramType, 15895 /*consumed*/ false); 15896 return PerformCopyInitialization(entity, callLoc, arg); 15897 } 15898 15899 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15900 Expr *orig = E; 15901 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15902 while (true) { 15903 E = E->IgnoreParenImpCasts(); 15904 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15905 E = call->getCallee(); 15906 diagID = diag::err_uncasted_call_of_unknown_any; 15907 } else { 15908 break; 15909 } 15910 } 15911 15912 SourceLocation loc; 15913 NamedDecl *d; 15914 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15915 loc = ref->getLocation(); 15916 d = ref->getDecl(); 15917 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15918 loc = mem->getMemberLoc(); 15919 d = mem->getMemberDecl(); 15920 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15921 diagID = diag::err_uncasted_call_of_unknown_any; 15922 loc = msg->getSelectorStartLoc(); 15923 d = msg->getMethodDecl(); 15924 if (!d) { 15925 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15926 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15927 << orig->getSourceRange(); 15928 return ExprError(); 15929 } 15930 } else { 15931 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15932 << E->getSourceRange(); 15933 return ExprError(); 15934 } 15935 15936 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15937 15938 // Never recoverable. 15939 return ExprError(); 15940 } 15941 15942 /// Check for operands with placeholder types and complain if found. 15943 /// Returns ExprError() if there was an error and no recovery was possible. 15944 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15945 if (!getLangOpts().CPlusPlus) { 15946 // C cannot handle TypoExpr nodes on either side of a binop because it 15947 // doesn't handle dependent types properly, so make sure any TypoExprs have 15948 // been dealt with before checking the operands. 15949 ExprResult Result = CorrectDelayedTyposInExpr(E); 15950 if (!Result.isUsable()) return ExprError(); 15951 E = Result.get(); 15952 } 15953 15954 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15955 if (!placeholderType) return E; 15956 15957 switch (placeholderType->getKind()) { 15958 15959 // Overloaded expressions. 15960 case BuiltinType::Overload: { 15961 // Try to resolve a single function template specialization. 15962 // This is obligatory. 15963 ExprResult Result = E; 15964 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15965 return Result; 15966 15967 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15968 // leaves Result unchanged on failure. 15969 Result = E; 15970 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15971 return Result; 15972 15973 // If that failed, try to recover with a call. 15974 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15975 /*complain*/ true); 15976 return Result; 15977 } 15978 15979 // Bound member functions. 15980 case BuiltinType::BoundMember: { 15981 ExprResult result = E; 15982 const Expr *BME = E->IgnoreParens(); 15983 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15984 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15985 if (isa<CXXPseudoDestructorExpr>(BME)) { 15986 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15987 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15988 if (ME->getMemberNameInfo().getName().getNameKind() == 15989 DeclarationName::CXXDestructorName) 15990 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15991 } 15992 tryToRecoverWithCall(result, PD, 15993 /*complain*/ true); 15994 return result; 15995 } 15996 15997 // ARC unbridged casts. 15998 case BuiltinType::ARCUnbridgedCast: { 15999 Expr *realCast = stripARCUnbridgedCast(E); 16000 diagnoseARCUnbridgedCast(realCast); 16001 return realCast; 16002 } 16003 16004 // Expressions of unknown type. 16005 case BuiltinType::UnknownAny: 16006 return diagnoseUnknownAnyExpr(*this, E); 16007 16008 // Pseudo-objects. 16009 case BuiltinType::PseudoObject: 16010 return checkPseudoObjectRValue(E); 16011 16012 case BuiltinType::BuiltinFn: { 16013 // Accept __noop without parens by implicitly converting it to a call expr. 16014 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16015 if (DRE) { 16016 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16017 if (FD->getBuiltinID() == Builtin::BI__noop) { 16018 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16019 CK_BuiltinFnToFnPtr).get(); 16020 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16021 VK_RValue, SourceLocation()); 16022 } 16023 } 16024 16025 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16026 return ExprError(); 16027 } 16028 16029 // Expressions of unknown type. 16030 case BuiltinType::OMPArraySection: 16031 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16032 return ExprError(); 16033 16034 // Everything else should be impossible. 16035 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16036 case BuiltinType::Id: 16037 #include "clang/Basic/OpenCLImageTypes.def" 16038 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16039 #define PLACEHOLDER_TYPE(Id, SingletonId) 16040 #include "clang/AST/BuiltinTypes.def" 16041 break; 16042 } 16043 16044 llvm_unreachable("invalid placeholder type!"); 16045 } 16046 16047 bool Sema::CheckCaseExpression(Expr *E) { 16048 if (E->isTypeDependent()) 16049 return true; 16050 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16051 return E->getType()->isIntegralOrEnumerationType(); 16052 return false; 16053 } 16054 16055 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16056 ExprResult 16057 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16058 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16059 "Unknown Objective-C Boolean value!"); 16060 QualType BoolT = Context.ObjCBuiltinBoolTy; 16061 if (!Context.getBOOLDecl()) { 16062 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16063 Sema::LookupOrdinaryName); 16064 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16065 NamedDecl *ND = Result.getFoundDecl(); 16066 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16067 Context.setBOOLDecl(TD); 16068 } 16069 } 16070 if (Context.getBOOLDecl()) 16071 BoolT = Context.getBOOLType(); 16072 return new (Context) 16073 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16074 } 16075 16076 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16077 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16078 SourceLocation RParen) { 16079 16080 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16081 16082 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16083 [&](const AvailabilitySpec &Spec) { 16084 return Spec.getPlatform() == Platform; 16085 }); 16086 16087 VersionTuple Version; 16088 if (Spec != AvailSpecs.end()) 16089 Version = Spec->getVersion(); 16090 16091 // The use of `@available` in the enclosing function should be analyzed to 16092 // warn when it's used inappropriately (i.e. not if(@available)). 16093 if (getCurFunctionOrMethodDecl()) 16094 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16095 else if (getCurBlock() || getCurLambda()) 16096 getCurFunction()->HasPotentialAvailabilityViolations = true; 16097 16098 return new (Context) 16099 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16100 } 16101